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): New Script writes the file AND the line that makes it run
yhh478e2f6fc208
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 793bb166c..77f035ef0 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -27,6 +27,7 @@ import { syncAutosave, listAutosave, restoreAutosave, clearAutosave, type Autosaimport { listRecents, addRecent, removeRecent, listTemplates, createFromTemplate } from './launcher';import { buildProjectScripts } from './buildScripts';import { extractProjectSchemas } from './extractSchemas';+import { scaffoldScript, type ScriptKind } from './scriptScaffold';import { scanAssetDatabase, readCachedAssetIndex, updateAssetIndex } from './assetDb';import { cookAssets } from './cookAssets';import { startProjectWatch, stopProjectWatch } from './projectWatcher';@@ -855,6 +856,15 @@ ipcMain.handle('project:extractSchemas', async () => {return extractProjectSchemas(root, { entry: register, required: manifest.scripts?.register !== undefined });});+// Write a new project script and wire it into the entry its kind belongs to —+// the declaration entry for a component, the startup entry for a system. Both+// come from the SAME resolveScripts the extractor and the bundler read, so a+// project that renamed its entries is wired at its own (see scriptScaffold.ts).+ipcMain.handle('project:createScript', async (_e, kind: ScriptKind, name: string, dir?: string) => {+ const root = requireRoot();+ return scaffoldScript(root, { kind, name, dir, entries: resolveScripts(await readManifest(root)) });+});+// Scan the open project's `.meta` sidecars → the asset index (uuid↔path registry// + dependency graph) written to .esengine/cache/assets.json. The editor feeds// this into the engine Assets registry (one resolution path) and the Contentdiff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 7e6493055..34d215d7e 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -4,6 +4,7 @@ import { contextBridge, ipcRenderer, webUtils } from 'electron';import type { OpenedProject, WorkspaceState, DirEntry, RecentEntry, TemplateEntry, ExportPlatform } from '../src/project/format';import type { BuildScriptsResult } from './buildScripts';import type { ExtractSchemasResult } from './extractSchemas';+import type { ScaffoldScriptResult, ScriptKind } from './scriptScaffold';import type { ScanAssetsResult, AssetIndex, IncrementalScanResult } from './assetDb';import type { CookResult } from './cookAssets';import type { ExportGameResult } from './exportGame';@@ -101,6 +102,11 @@ const api = {buildScripts: (): Promise<BuildScriptsResult> => ipcRenderer.invoke('project:buildScripts'),/** Extract the project's component field schemas → .esengine/cache/schemas.json. */extractSchemas: (): Promise<ExtractSchemasResult> => ipcRenderer.invoke('project:extractSchemas'),+ /** Write a new script under the project's source root AND wire it into the entry+ * its kind belongs to (declaration entry for a component, startup entry for a+ * system) — an unwired module is one nothing bundles or inspects. */+ createScript: (kind: ScriptKind, name: string, dir?: string): Promise<ScaffoldScriptResult> =>+ ipcRenderer.invoke('project:createScript', kind, name, dir),/** Scan the project's .meta sidecars → the asset index (registry + dep graph). */scanAssets: (): Promise<ScanAssetsResult> => ipcRenderer.invoke('project:scanAssets'),/** The cached asset index (assets.json) without a tree walk, or null — the fastdiff --git a/desktop/electron/scriptScaffold.ts b/desktop/electron/scriptScaffold.tsnew file mode 100644index 000000000..604c8c4cb--- /dev/null+++ b/desktop/electron/scriptScaffold.ts@@ -0,0 +1,154 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file scriptScaffold.ts — write a new project script, already wired in.+ *+ * A project has exactly two script entries (format.ts `resolveScripts`): the+ * DECLARATION entry the editor reads to build inspectors, and the STARTUP entry+ * the play realm bundles. A `.ts` file neither of them reaches is dead — never+ * bundled, never extracted, its component never in Add Component. That is the+ * part nobody can be expected to know before they have seen a project laid out,+ * so the editor writes it: the module AND the one line in the entry that pulls+ * it in. Which entry depends on what the script IS, and the vocabulary for that+ * lives in ../src/project/scripts.ts, shared with the dialog that asks for it.+ *+ * The entries come from the caller, resolved from the manifest, so a project that+ * renamed them is wired at ITS entries and not at the defaults.+ *+ * Posture mirrors pluginScaffold.ts: validate first, never clobber a file that+ * exists, hand back paths rather than throwing.+ *+ * Pure Node → unit-testable; the IPC wiring lives in main.ts.+ */+import { existsSync } from 'node:fs';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import {+ scriptNameProblem, scriptTargetDir, scriptModulePath, scriptWiring,+ type ScriptEntries, type ScriptKind,+} from '../src/project/scripts';++export type { ScriptEntries, ScriptKind };++export interface ScaffoldScriptOptions {+ kind: ScriptKind;+ /** Identifier for the component/system AND the file stem (see `scriptNameProblem`). */+ name: string;+ /** Project-relative folder the user asked for; redirected into the source root+ * when it lies outside (see `scriptTargetDir`). */+ dir?: string;+ entries: ScriptEntries;+}++export interface ScaffoldScriptResult {+ ok: boolean;+ error?: string;+ /** Project-relative path of the new module. */+ path?: string;+ /** Project-relative path of the entry that now pulls it in. */+ wiredInto?: string;+ /** The line appended there — surfaced so the editor can say what it did. */+ wiredLine?: string;+}++// =============================================================================+// Templates+// =============================================================================++function componentTemplate(name: string, entries: ScriptEntries): string {+ return `// ${name} — a project component: data an entity carries, and a row in its inspector.+//+// Re-exported from ${entries.register}, the ONE module the editor reads to learn a+// project's components. It reads it WITHOUT running the game, so keep startup code+// out of the declaration graph — behaviour belongs in a system (${entries.main}).+import { defineComponent } from 'esengine';++export const ${name} = defineComponent('${name}', {+ // Each field's inspector control comes from the TYPE of its default: a number+ // is a number box, a boolean a checkbox, a string a text field, and an+ // { r, g, b, a } object a color picker.+ speed: 100,+});+`;+}++function systemTemplate(name: string, entries: ScriptEntries): string {+ const fn = `${name.charAt(0).toLowerCase()}${name.slice(1)}System`;+ return `// ${name} — a project system: behaviour that runs every frame while the scene plays.+//+// It registers itself at the bottom of this file, so the one \`import\` line in+// ${entries.main} is the whole of its wiring. Move that call into ${entries.main}+// instead if you would rather read every registration in one list.+import {+ addSystemToSchedule, defineSystem, Mut, Query, Res, Schedule, Time, Transform,+} from 'esengine';++export const ${fn} = defineSystem(+ // The query decides which entities this runs for. Add your own component to+ // narrow it — \`Query(Mut(Transform), MyComponent)\` — and read it from the same+ // tuple below. Mut() is what makes a component writable.+ [Query(Mut(Transform)), Res(Time)],+ (query, time) => {+ for (const [entity, transform] of query) {+ // Scale movement by time.delta (seconds since the last frame) so speed+ // does not depend on frame rate:+ //+ // transform.position.x += 120 * time.delta;+ }+ },+ { name: '${name}System' },+);++addSystemToSchedule(Schedule.Update, ${fn});+`;+}++// =============================================================================+// Scaffolding+// =============================================================================++/**+ * Append `line` to `entryRel`, creating the file if it is absent. Idempotent: an+ * entry that already carries the line is left byte-identical, so scaffolding over+ * a hand-wired module cannot duplicate its import.+ */+async function appendWiring(root: string, entryRel: string, line: string): Promise<void> {+ const abs = path.join(root, entryRel);+ const existing = existsSync(abs) ? await readFile(abs, 'utf8') : '';+ if (existing.split('\n').some((l) => l.trim() === line)) return;+ const gap = existing === '' || existing.endsWith('\n') ? '' : '\n';+ await mkdir(path.dirname(abs), { recursive: true });+ await writeFile(abs, `${existing}${gap}${line}\n`, 'utf8');+}++/**+ * Write `<dir>/<name>.ts` under `root` and wire it into the entry its kind+ * belongs to. Never clobbers: an existing module is an error, because the+ * alternative is overwriting someone's work with a template.+ */+export async function scaffoldScript(+ root: string,+ opts: ScaffoldScriptOptions,+): Promise<ScaffoldScriptResult> {+ const bad = scriptNameProblem(opts.name);+ if (bad) return { ok: false, error: bad };+ const name = opts.name.trim();++ const moduleRel = scriptModulePath(scriptTargetDir(opts.dir, opts.entries), name);+ const abs = path.join(root, moduleRel);+ if (existsSync(abs)) return { ok: false, error: `${moduleRel} already exists` };++ const { entry, line } = scriptWiring(opts.kind, opts.entries, moduleRel);+ const source = opts.kind === 'component'+ ? componentTemplate(name, opts.entries)+ : systemTemplate(name, opts.entries);++ try {+ await mkdir(path.dirname(abs), { recursive: true });+ await writeFile(abs, source, 'utf8');+ await appendWiring(root, entry, line);+ return { ok: true, path: moduleRel, wiredInto: entry, wiredLine: line };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 4916411cd..857241ce3 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -12,6 +12,7 @@ import '@/document/dirtyDocs'; // side effect: registers scene + asset docs on timport { Launcher } from '@/launcher/Launcher';import { Toaster } from '@/components/Toaster';import { ConfirmHost } from '@/components/ConfirmHost';+import { NewScriptHost } from '@/components/NewScriptHost';import { PrefabModeBanner } from '@/components/PrefabModeBanner';import { LoadingScreen } from '@/components/LoadingScreen';import { LoadGate } from '@/store/loadGate';@@ -305,6 +306,7 @@ export function App() {{paletteOpen && <CommandPalette onClose={() => useEditorStore.getState().setPaletteOpen(false)} />}<Toaster /><ConfirmHost />+ <NewScriptHost /><LoadingScreen /></div>);diff --git a/desktop/src/components/NewScriptDialog.tsx b/desktop/src/components/NewScriptDialog.tsxnew file mode 100644index 000000000..0c5b72b9e--- /dev/null+++ b/desktop/src/components/NewScriptDialog.tsx@@ -0,0 +1,147 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file NewScriptDialog — create a script the project already runs.+ *+ * The name is validated HERE with the same function the scaffolder uses, so the+ * dialog can never accept one the writer would reject (the handshake+ * NewPluginDialog has with `pluginIdProblem`).+ *+ * It asks for the name rather than dropping the file into the Content Browser's+ * inline rename the way every other creator does, because a script's name is not+ * only its file name: it is the exported identifier, the string a scene+ * serializes, and the specifier the entry imports it by. Renaming it afterwards+ * would leave three of those disagreeing.+ *+ * The two kinds are shown with what each ACTUALLY does to the project — which+ * entry gains a line — because that wiring is the difference between a script the+ * engine runs and a file nothing imports.+ */+import { useMemo, useState } from 'react';+import { Plus, AlertCircle } from 'lucide-react';+import { Modal } from '@/components/Modal';+import { Button } from '@/components/Button';+import { Segmented } from '@/components/Segmented';+import { ProjectStore } from '@/project/ProjectStore';+import {+ SCRIPT_KINDS, scriptNameProblem, scriptTargetDir, scriptModulePath, scriptWiring,+ type ScriptKind,+} from '@/project/scripts';+import { revealAsset } from '@/project/assetReveal';+import { Toasts } from '@/store/Toasts';+import { t, type MsgKey } from '@/i18n';++const KIND_LABEL: Record<ScriptKind, MsgKey> = {+ component: 'script.kind.component',+ system: 'script.kind.system',+};+const KIND_HINT: Record<ScriptKind, MsgKey> = {+ component: 'script.kind.componentHint',+ system: 'script.kind.systemHint',+};+const DEFAULT_NAME: Record<ScriptKind, string> = { component: 'MyComponent', system: 'MySystem' };++export function NewScriptDialog({ dir, onDone }: { dir: string; onDone: (path: string | null) => void }) {+ const [kind, setKind] = useState<ScriptKind>('component');+ const [name, setName] = useState('');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const entries = ProjectStore.scriptEntries();+ const effective = name.trim() || DEFAULT_NAME[kind];+ const problem = name.trim() ? scriptNameProblem(name) : null;++ // Shown live, so "where does this go and what does it change" is answered+ // before the file exists rather than discovered afterwards.+ const preview = useMemo(() => {+ if (problem) return null;+ const modulePath = scriptModulePath(scriptTargetDir(dir, entries), effective);+ return { modulePath, ...scriptWiring(kind, entries, modulePath) };+ }, [dir, entries, kind, effective, problem]);++ const create = async () => {+ setBusy(true);+ setError(null);+ const res = await window.estella.project.createScript(kind, effective, dir);+ if (!res.ok || !res.path) {+ setError(res.error ?? 'could not create the script');+ setBusy(false);+ return;+ }+ // Deterministic rather than waiting on the watcher: the door's contract is+ // "returned ⇒ usable", and for a component that means its schema is loaded,+ // so the inspector offers it in Add Component the moment the dialog closes.+ await ProjectStore.refreshUserSchemas();+ // Reveal rather than open: this editor has no code editor, and launching the+ // configured external one unbidden would end a successful create on someone+ // else's window — or, with none configured, on an error toast about a program.+ // Double-click takes it there when the user is ready.+ revealAsset(res.path);+ Toasts.push(t('script.created', { path: res.path, entry: res.wiredInto ?? '' }), 'success');+ onDone(res.path);+ };++ return (+ <Modal+ title={t('script.newTitle')}+ onClose={() => onDone(null)}+ width={470}+ footer={(+ <>+ <Button onClick={() => onDone(null)}>{t('ui.cancel')}</Button>+ <Button variant="primary" disabled={busy || !!problem} onClick={() => void create()}>+ <Plus size={13} /> {t('script.create')}+ </Button>+ </>+ )}+ >+ <div className="nsc">+ <div className="nsc__row">+ <span className="nsc__label">{t('script.field.kind')}</span>+ <Segmented+ value={kind}+ onChange={setKind}+ ariaLabel={t('script.field.kind')}+ options={SCRIPT_KINDS.map((k) => ({ value: k, label: t(KIND_LABEL[k]) }))}+ />+ </div>+ <div className="nsc__hint">{t(KIND_HINT[kind])}</div>++ <div className="nsc__row">+ <span className="nsc__label">{t('script.field.name')}</span>+ <input+ value={name}+ spellCheck={false}+ autoFocus+ placeholder={DEFAULT_NAME[kind]}+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !problem && !busy) void create();+ }}+ />+ </div>+ {problem && <div className="nsc__hint is-error">{problem}</div>}++ {preview && (+ <div className="nsc__plan">+ <div className="nsc__planRow">+ <span className="nsc__planKey">{t('script.willCreate')}</span>+ <code className="selectable">{preview.modulePath}</code>+ </div>+ <div className="nsc__planRow">+ <span className="nsc__planKey">{t('script.willWire')}</span>+ <code className="selectable">{preview.entry}</code>+ </div>+ <code className="nsc__planLine selectable">{preview.line}</code>+ </div>+ )}++ {error && (+ <div className="nsc__hint is-error">+ <AlertCircle size={12} strokeWidth={2} /> <span className="selectable">{error}</span>+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/desktop/src/components/NewScriptHost.tsx b/desktop/src/components/NewScriptHost.tsxnew file mode 100644index 000000000..8a6bcf446--- /dev/null+++ b/desktop/src/components/NewScriptHost.tsx@@ -0,0 +1,23 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file NewScriptHost.tsx — renders the NewScriptService queue's front request+ * as a NewScriptDialog. Mounted once in the editor shell (next to+ * ConfirmHost); queued requests show one at a time in arrival order.+ */+import { useSyncExternalStore } from 'react';+import { NewScriptService } from './newScript';+import { NewScriptDialog } from './NewScriptDialog';++export function NewScriptHost() {+ const queue = useSyncExternalStore(NewScriptService.subscribe, NewScriptService.getSnapshot);+ const cur = queue[0];+ if (!cur) return null;+ return (+ <NewScriptDialog+ key={cur.id}+ dir={cur.dir}+ onDone={(path) => NewScriptService.settle(cur.id, path)}+ />+ );+}diff --git a/desktop/src/components/newScript.ts b/desktop/src/components/newScript.tsnew file mode 100644index 000000000..229423ddf--- /dev/null+++ b/desktop/src/components/newScript.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file newScript.ts+ * @brief Imperative "New Script" request — `newScript(dir)` resolves with the+ * created module's project-relative path (or null if cancelled) once the+ * user answers the dialog <NewScriptHost> renders for it.+ *+ * Same shape as confirm.ts, and for the same reason: the caller is the+ * NEW_ASSET_TYPES registry, a plain module with no React of its own, and+ * a create entry that has to await a name cannot reach a component's+ * state. Concurrent requests queue; one dialog shows at a time.+ */+import { createStore } from 'zustand/vanilla';++export interface PendingNewScript {+ id: number;+ /** The Content Browser folder the request came from (a hint — the scaffold+ * redirects it into the project's source root when it lies outside). */+ dir: string;+}++class NewScriptServiceImpl {+ private readonly store = createStore<{ queue: PendingNewScript[] }>(() => ({ queue: [] }));+ private readonly resolvers = new Map<number, (path: string | null) => void>();+ private seq = 0;++ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getSnapshot = (): PendingNewScript[] => this.store.getState().queue;++ request(dir: string): Promise<string | null> {+ return new Promise((resolve) => {+ const id = ++this.seq;+ this.resolvers.set(id, resolve);+ this.store.setState((s) => ({ queue: [...s.queue, { id, dir }] }));+ });+ }++ /** Answer a pending request (the host calls this when the dialog closes). */+ settle(id: number, path: string | null): void {+ const resolve = this.resolvers.get(id);+ if (!resolve) return;+ this.resolvers.delete(id);+ this.store.setState((s) => ({ queue: s.queue.filter((r) => r.id !== id) }));+ resolve(path);+ }+}++export const NewScriptService = new NewScriptServiceImpl();++/** Ask for a new script in `dir`; resolves with its path, or null on cancel. */+export const newScript = (dir: string): Promise<string | null> => NewScriptService.request(dir);diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.tsindex c4d116740..fc821c910 100644--- a/desktop/src/i18n/messages/content.ts+++ b/desktop/src/i18n/messages/content.ts@@ -64,6 +64,7 @@ export const contentMessages = defineMessages({'cb.menuImport': { en: 'Import…', zh: '导入…' },'cb.menuNewFolder': { en: 'New Folder', zh: '新建文件夹' },'cb.menuNewScene': { en: 'New Scene', zh: '新建场景' },+ 'cb.menuNewScript': { en: 'New Script…', zh: '新建脚本…' },'cb.menuNewAnimation': { en: 'New Animation', zh: '新建动画' },'cb.menuNewInputMap': { en: 'New Input Map', zh: '新建输入映射' },'cb.menuNewLocaleTable': { en: 'New Locale Table', zh: '新建本地化表' },diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex ce6cd7ce3..cc82a8f9d 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -338,4 +338,23 @@ export const projectMessages = defineMessages({zh: '准备游戏运行环境超时(脚本打包器可能卡死)。请再次点击运行重试;若仍然如此,请重启编辑器。',},'proj.playRealmError': { en: 'play realm error', zh: '游戏运行环境错误' },++ // — New Script dialog (Content Browser → New Script) —+ 'script.newTitle': { en: 'New Script', zh: '新建脚本' },+ 'script.create': { en: 'Create', zh: '创建' },+ 'script.field.kind': { en: 'Kind', zh: '类型' },+ 'script.field.name': { en: 'Name', zh: '名称' },+ 'script.kind.component': { en: 'Component', zh: '组件' },+ 'script.kind.system': { en: 'System', zh: '系统' },+ 'script.kind.componentHint': {+ en: 'Data an entity carries. Declared for the editor to read, so it shows up in Add Component with a row per field.',+ zh: '实体携带的数据。声明后编辑器即可读取,会出现在「添加组件」里,每个字段一行。',+ },+ 'script.kind.systemHint': {+ en: 'Behaviour that runs every frame while the scene plays, over the entities its query matches.',+ zh: '场景运行时每帧执行的行为,作用于查询匹配到的实体。',+ },+ 'script.willCreate': { en: 'Creates', zh: '创建' },+ 'script.willWire': { en: 'Wires into', zh: '接入' },+ 'script.created': { en: 'Created {path} and wired it into {entry}', zh: '已创建 {path} 并接入 {entry}' },});diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 43ca80bcc..d56781aeb 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -37,7 +37,7 @@ import { assetTypeOf } from '@/project/assetMeta';import { ASSET_TYPES, assetTypeDef } from '@/project/assetTypes';import { ASSET_SLOTS, metaTypeToSlot } from '@/project/assetSlots';import type { AssetType } from '@/types';-import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenPreset, type ScreenOrientation, type CameraScaleMode, type ExportPlatform } from './format';+import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, resolveScripts, DEFAULT_SCRIPTS, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type ProjectScripts, type WorkspaceState, type DesignResolution, type ScreenPreset, type ScreenOrientation, type CameraScaleMode, type ExportPlatform } from './format';import { useEditorMode } from '@/store/editorModeStore';import { PlayRealms } from '@/engine/PlayRealm';import { PlayInspect } from '@/engine/PlayInspect';@@ -133,6 +133,10 @@ interface ProjectState {defaultScene?: string;/** Engine features (subsystems) the project enables; drives the play realm. */features?: ProjectFeatures;+ /** The manifest's script entries, resolved over the defaults — the same pair the+ * schema extractor and the play bundler read, so anything the editor wires into+ * a project's scripts wires into ITS entries and not the conventional ones. */+ scripts: Required<ProjectScripts>;/** Persisted Package Project settings (last target/config/output). */packaging?: ProjectPackaging;/** Reference resolution new Canvas entities seed from; per-scene Canvas stays authoritative. */@@ -448,6 +452,7 @@ class ProjectStoreImpl {packaging: opened.manifest.packaging,designResolution: opened.manifest.designResolution,screenPresets: opened.manifest.screenPresets,+ scripts: resolveScripts(opened.manifest),currentScene: null,},});@@ -612,6 +617,13 @@ class ProjectStoreImpl {return window.estella.project.createAsset(destDir, base, content, 'scene');}+ /** The open project's script entries — the declaration module the editor reads+ * schemas from and the startup module the play realm bundles. Falls back to the+ * conventional pair when no project is open (the dialog previews against it). */+ scriptEntries(): Required<ProjectScripts> {+ return this.state?.scripts ?? DEFAULT_SCRIPTS;+ }+/** Create a blank `.inputmap` asset (named input actions) under `destDir`. */async createInputMapFile(destDir: string): Promise<string> {const content = JSON.stringify(blankInputMap(), null, 2) + '\n';diff --git a/desktop/src/project/newAssetTypes.ts b/desktop/src/project/newAssetTypes.tsindex 08f88cbb0..d9ecf4b36 100644--- a/desktop/src/project/newAssetTypes.ts+++ b/desktop/src/project/newAssetTypes.ts@@ -23,6 +23,7 @@ import { createMaterialGraph } from '@/material/openMaterialGraph';import { createStateMachine } from '@/fsm/openStateMachine';import { createAnimatorController } from '@/animator/openAnimatorController';import { createBehaviorTree } from '@/bt/openBehaviorTree';+import { newScript } from '@/components/newScript';/** Create an asset in `dir`; a returned path means "reveal + rename me" (see file). */export type CreateAsset = (dir: string) => Promise<string | void> | string | void;@@ -42,6 +43,11 @@ const shaderTemplateMenu = (make: (dir: string, templateId: string) => Promise<vexport const NEW_ASSET_TYPES: NewAssetEntry[] = [{ labelKey: 'cb.menuNewScene', create: (dir) => ProjectStore.createSceneFile(dir), errorKey: 'cb.newSceneFailed' },+ // Returns void like the editor-backed creators: a script's editor is the one+ // configured for source files, which the dialog hands it to itself — and its+ // name is fixed at creation (it is also an identifier and an import specifier),+ // so it must not land in the Content Browser's inline rename.+ { labelKey: 'cb.menuNewScript', create: (dir) => void newScript(dir) },{ labelKey: 'cb.menuNewAnimation', create: createAnimationClip },{ labelKey: 'cb.menuNewInputMap', create: (dir) => ProjectStore.createInputMapFile(dir), errorKey: 'cb.newInputMapFailed' },{ labelKey: 'cb.menuNewLocaleTable', create: (dir) => ProjectStore.createLocaleTableFile(dir), errorKey: 'cb.newLocaleTableFailed' },diff --git a/desktop/src/project/scripts.ts b/desktop/src/project/scripts.tsnew file mode 100644index 000000000..538b6c6a0--- /dev/null+++ b/desktop/src/project/scripts.ts@@ -0,0 +1,125 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file scripts.ts+ * @brief What a project SCRIPT is, in the terms both sides of the editor need:+ * the two kinds, the rule for naming one, where a new one goes, and how an+ * entry imports it. Pure string work, no fs and no node imports — so the+ * main process (electron/scriptScaffold.ts, which writes the file) and the+ * renderer (the New Script dialog, which validates before asking it to)+ * answer from ONE source and cannot disagree about a name.+ *+ * The same direction pluginScaffold.ts takes with `pluginIdProblem`: the+ * rule lives with the UI that must not accept what the writer would reject.+ *+ * Script ENTRIES (which module is the declaration one, which the startup+ * one) are a manifest fact and stay in format.ts — `resolveScripts`.+ */++/**+ * What a new module IS, which decides both its template and which entry pulls it+ * in. The distinction is the project's own architecture, not a menu convenience:+ * a component is a DECLARATION the editor reads without running the game, a+ * system is BEHAVIOUR the play realm bundles and runs.+ */+export type ScriptKind = 'component' | 'system';++export const SCRIPT_KINDS: readonly ScriptKind[] = ['component', 'system'];++/** The project's script entries (project-relative), as `resolveScripts` returns them. */+export interface ScriptEntries {+ /** Declaration entry — the module the editor extracts component schemas from. */+ register: string;+ /** Startup entry — the module the play realm bundles. */+ main: string;+}++// Reserved words a declaration cannot be named. Not the full ECMAScript list:+// only the ones that are otherwise legal-looking identifiers someone might type.+const RESERVED = new Set([+ 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do',+ 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import',+ 'in', 'instanceof', 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true',+ 'try', 'typeof', 'var', 'void', 'while', 'with', 'let', 'static', 'yield', 'await',+ 'implements', 'interface', 'package', 'private', 'protected', 'public',+]);++/**+ * Why `name` cannot be used, or null when it can.+ *+ * One name plays three parts at once — the exported identifier, the module's file+ * stem, and (for a component) the string every scene serializes — so the+ * strictest of the three governs: a plain JS identifier.+ */+export function scriptNameProblem(name: string): string | null {+ const n = name.trim();+ if (!n) return 'name is required';+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)) {+ return 'use letters, digits, _ and $ only, and do not start with a digit';+ }+ if (RESERVED.has(n)) return `"${n}" is a reserved word`;+ return null;+}++/** Project-relative, forward-slashed, no leading `./` or trailing slash. */+function norm(p: string): string {+ return p.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '');+}++function dirOf(p: string): string {+ const i = p.lastIndexOf('/');+ return i < 0 ? '' : p.slice(0, i);+}++/** The project's source root — where its declaration entry lives. */+export function scriptSourceRoot(entries: ScriptEntries): string {+ return dirOf(norm(entries.register));+}++/**+ * Where a new module goes: the folder the user is browsing when it is inside the+ * source root, else the source root itself.+ *+ * A module outside the source tree is reached by neither entry's import graph nor+ * the watcher's schema re-extract, so honouring "create it here" for a folder+ * under `assets/` would hand back a file that silently does nothing. Derived from+ * the declaration entry rather than hard-coded, so a project that keeps its+ * scripts elsewhere gets them there.+ */+export function scriptTargetDir(dir: string | undefined, entries: ScriptEntries): string {+ const root = scriptSourceRoot(entries);+ const asked = norm(dir ?? '');+ if (!root) return asked;+ return asked === root || asked.startsWith(`${root}/`) ? asked : root;+}++/** The project-relative path a script of `name` gets under `dir`. */+export function scriptModulePath(dir: string, name: string): string {+ const d = norm(dir);+ return d ? `${d}/${name.trim()}.ts` : `${name.trim()}.ts`;+}++/** The specifier `entryRel` would import `moduleRel` by (relative, extensionless). */+export function importSpecifier(entryRel: string, moduleRel: string): string {+ const from = dirOf(norm(entryRel)).split('/').filter(Boolean);+ const to = norm(moduleRel).replace(/\.tsx?$/, '').split('/').filter(Boolean);+ let i = 0;+ while (i < from.length && i < to.length && from[i] === to[i]) i++;+ const rel = [...from.slice(i).map(() => '..'), ...to.slice(i)].join('/');+ return rel.startsWith('.') ? rel : `./${rel}`;+}++/**+ * The entry a kind wires into, and the line appended there. A component is+ * RE-EXPORTED (naming what the project declares is the declaration entry's whole+ * job); a system is IMPORTED for the registration side effect its module performs.+ */+export function scriptWiring(+ kind: ScriptKind,+ entries: ScriptEntries,+ moduleRel: string,+): { entry: string; line: string } {+ const entry = norm(kind === 'component' ? entries.register : entries.main);+ const spec = importSpecifier(entry, moduleRel);+ return { entry, line: kind === 'component' ? `export * from '${spec}';` : `import '${spec}';` };+}diff --git a/desktop/src/theme/content.css b/desktop/src/theme/content.cssindex 8a9caf51f..cf9616ea9 100644--- a/desktop/src/theme/content.css+++ b/desktop/src/theme/content.css@@ -168,3 +168,20 @@.cb-foot { display: flex; align-items: center; gap: 10px; height: 28px; padding: 0 12px; border-top: 1px solid var(--border); background: var(--srf-2); flex-shrink: 0; font-size: var(--fs-xs); color: var(--text-dim); }.cb-foot .sp { flex: 1; }.cb-foot input[type='range'] { width: 110px; accent-color: var(--acc); cursor: ew-resize; }++/* New-script dialog. Same one-column label/field rhythm as the new-plugin dialog+ (.npl), plus a plan block: what gets written and which entry gains a line. The+ plan is shown before the file exists because the wiring — not the file — is+ what makes a script one the engine runs. */+.nsc { display: flex; flex-direction: column; gap: 10px; }+.nsc__row { display: grid; grid-template-columns: 60px 1fr; align-items: center; gap: 8px; }+.nsc__label { font-size: var(--fs-xs); color: var(--text-dim); }+.nsc__row input { width: 100%; padding: 4px 7px; background: var(--srf-2); color: var(--text); border: 1px solid var(--border); border-radius: var(--r-sm); font-size: var(--fs-xs); font-family: var(--font-ui); }+.nsc__row input:focus { outline: none; border-color: var(--acc); }+.nsc__hint { display: flex; align-items: center; gap: 5px; font-size: var(--fs-2xs); color: var(--text-faint); line-height: 1.5; margin-left: 68px; }+.nsc__hint.is-error { color: #e0736a; }+.nsc__plan { display: flex; flex-direction: column; gap: 5px; padding: 9px 10px; background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-md); }+.nsc__planRow { display: flex; align-items: baseline; gap: 8px; min-width: 0; }+.nsc__planKey { flex: none; width: 52px; font-size: var(--fs-2xs); color: var(--text-faint); }+.nsc__plan code { font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-dim); word-break: break-all; }+.nsc__planLine { display: block; margin-top: 2px; padding-left: 60px; color: var(--star-hi) !important; }diff --git a/desktop/tests/new-asset-types.test.ts b/desktop/tests/new-asset-types.test.tsindex 9a1d8b754..ec9bcb36c 100644--- a/desktop/tests/new-asset-types.test.ts+++ b/desktop/tests/new-asset-types.test.ts@@ -37,6 +37,7 @@ describe('NEW_ASSET_TYPES', () => {it('covers the expected creatable types', () => {expect(NEW_ASSET_TYPES.map((a) => a.labelKey)).toEqual(['cb.menuNewScene',+ 'cb.menuNewScript','cb.menuNewAnimation','cb.menuNewInputMap','cb.menuNewLocaleTable',diff --git a/desktop/tests/script-scaffold.test.ts b/desktop/tests/script-scaffold.test.tsnew file mode 100644index 000000000..f52359931--- /dev/null+++ b/desktop/tests/script-scaffold.test.ts@@ -0,0 +1,164 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The New Script door: a scaffolded module lands in the project's SOURCE+ * root and the entry its kind belongs to gains the one line that pulls it+ * in. The wiring is the whole point — a `.ts` neither entry reaches is+ * never bundled and never extracted, so its component would never appear+ * in Add Component no matter how correct the file is.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { scaffoldScript } from '../electron/scriptScaffold';+import {+ importSpecifier, scriptModulePath, scriptNameProblem, scriptTargetDir, scriptWiring,+} from '@/project/scripts';++const ENTRIES = { register: 'src/components.ts', main: 'src/main.ts' };++let root: string;++beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-script-'));+ mkdirSync(path.join(root, 'src'), { recursive: true });+ writeFileSync(path.join(root, 'src/components.ts'), 'export {};\n');+ writeFileSync(path.join(root, 'src/main.ts'), "import './components';\n");+});+afterEach(() => rmSync(root, { recursive: true, force: true }));++const read = (rel: string): string => readFileSync(path.join(root, rel), 'utf8');++describe('scriptNameProblem', () => {+ it('accepts an identifier and rejects what cannot be one', () => {+ expect(scriptNameProblem('Patrol')).toBeNull();+ expect(scriptNameProblem(' Patrol ')).toBeNull();+ expect(scriptNameProblem('_private$1')).toBeNull();+ expect(scriptNameProblem('')).toMatch(/required/);+ expect(scriptNameProblem('2fast')).toMatch(/digit/);+ expect(scriptNameProblem('my component')).toMatch(/letters/);+ expect(scriptNameProblem('my-component')).toMatch(/letters/);+ expect(scriptNameProblem('class')).toMatch(/reserved/);+ });+});++describe('where a script goes', () => {+ it('honours the browsed folder when it is inside the source root', () => {+ expect(scriptTargetDir('src', ENTRIES)).toBe('src');+ expect(scriptTargetDir('src/systems', ENTRIES)).toBe('src/systems');+ });++ it('redirects a folder outside the source root — a module out there is never reached', () => {+ expect(scriptTargetDir('assets/spine', ENTRIES)).toBe('src');+ expect(scriptTargetDir('', ENTRIES)).toBe('src');+ expect(scriptTargetDir(undefined, ENTRIES)).toBe('src');+ // "srcish" must not pass as being under "src".+ expect(scriptTargetDir('srcish/deep', ENTRIES)).toBe('src');+ });++ it('follows a project that renamed its entries, rather than the convention', () => {+ const custom = { register: 'game/decl.ts', main: 'game/boot.ts' };+ expect(scriptTargetDir('assets', custom)).toBe('game');+ expect(scriptTargetDir('game/ai', custom)).toBe('game/ai');+ });+});++describe('importSpecifier', () => {+ it('is relative to the entry, extensionless, and always dot-prefixed', () => {+ expect(importSpecifier('src/components.ts', 'src/Patrol.ts')).toBe('./Patrol');+ expect(importSpecifier('src/main.ts', 'src/systems/Chase.ts')).toBe('./systems/Chase');+ expect(importSpecifier('src/deep/main.ts', 'src/Patrol.ts')).toBe('../Patrol');+ expect(importSpecifier('main.ts', 'src/Patrol.ts')).toBe('./src/Patrol');+ });+});++describe('scaffoldScript — component', () => {+ it('writes the module and re-exports it from the DECLARATION entry', async () => {+ const res = await scaffoldScript(root, { kind: 'component', name: 'Patrol', dir: 'src', entries: ENTRIES });+ expect(res.ok).toBe(true);+ expect(res.path).toBe('src/Patrol.ts');+ expect(res.wiredInto).toBe('src/components.ts');++ const src = read('src/Patrol.ts');+ expect(src).toContain("import { defineComponent } from 'esengine';");+ expect(src).toContain("export const Patrol = defineComponent('Patrol', {");+ expect(read('src/components.ts')).toContain("export * from './Patrol';");+ // The startup entry is not touched — a declaration is not behaviour.+ expect(read('src/main.ts')).toBe("import './components';\n");+ });++ it('redirects a create from an assets folder into the source root', async () => {+ const res = await scaffoldScript(root, { kind: 'component', name: 'Health', dir: 'assets/art', entries: ENTRIES });+ expect(res.path).toBe('src/Health.ts');+ expect(existsSync(path.join(root, 'assets/art/Health.ts'))).toBe(false);+ });++ it('wires a nested module by a path the entry can actually import', async () => {+ const res = await scaffoldScript(root, { kind: 'component', name: 'Ammo', dir: 'src/gameplay', entries: ENTRIES });+ expect(res.path).toBe('src/gameplay/Ammo.ts');+ expect(read('src/components.ts')).toContain("export * from './gameplay/Ammo';");+ });+});++describe('scaffoldScript — system', () => {+ it('writes a self-registering module and imports it from the STARTUP entry', async () => {+ const res = await scaffoldScript(root, { kind: 'system', name: 'Chase', dir: 'src', entries: ENTRIES });+ expect(res.ok).toBe(true);+ expect(res.wiredInto).toBe('src/main.ts');++ const src = read('src/Chase.ts');+ expect(src).toContain('export const chaseSystem = defineSystem(');+ expect(src).toContain('addSystemToSchedule(Schedule.Update, chaseSystem);');+ expect(read('src/main.ts')).toContain("import './Chase';");+ // The declaration entry is not touched — behaviour is not a declaration.+ expect(read('src/components.ts')).toBe('export {};\n');+ });+});++describe('scaffoldScript — safety', () => {+ it('refuses a name that cannot be an identifier, writing nothing', async () => {+ const res = await scaffoldScript(root, { kind: 'component', name: 'my comp', dir: 'src', entries: ENTRIES });+ expect(res.ok).toBe(false);+ expect(read('src/components.ts')).toBe('export {};\n');+ });++ it('never clobbers an existing module', async () => {+ writeFileSync(path.join(root, 'src/Patrol.ts'), '// mine\n');+ const res = await scaffoldScript(root, { kind: 'component', name: 'Patrol', dir: 'src', entries: ENTRIES });+ expect(res.ok).toBe(false);+ expect(res.error).toMatch(/already exists/);+ expect(read('src/Patrol.ts')).toBe('// mine\n');+ });++ it('does not duplicate a line the entry already carries (hand-wired module)', async () => {+ writeFileSync(path.join(root, 'src/components.ts'), "export {};\nexport * from './Patrol';\n");+ rmSync(path.join(root, 'src/Patrol.ts'), { force: true });+ await scaffoldScript(root, { kind: 'component', name: 'Patrol', dir: 'src', entries: ENTRIES });+ const wired = read('src/components.ts').split('\n').filter((l) => l.includes("'./Patrol'"));+ expect(wired).toHaveLength(1);+ });++ it('creates a missing entry rather than dropping the wiring on the floor', async () => {+ rmSync(path.join(root, 'src/components.ts'));+ const res = await scaffoldScript(root, { kind: 'component', name: 'Patrol', dir: 'src', entries: ENTRIES });+ expect(res.ok).toBe(true);+ expect(read('src/components.ts')).toBe("export * from './Patrol';\n");+ });++ it('separates the appended line from an entry that lacks a trailing newline', async () => {+ writeFileSync(path.join(root, 'src/components.ts'), 'export {};');+ await scaffoldScript(root, { kind: 'component', name: 'Patrol', dir: 'src', entries: ENTRIES });+ expect(read('src/components.ts')).toBe("export {};\nexport * from './Patrol';\n");+ });+});++describe('scriptWiring', () => {+ it('names the entry and the line each kind needs', () => {+ const modulePath = scriptModulePath(scriptTargetDir('src', ENTRIES), 'Patrol');+ expect(scriptWiring('component', ENTRIES, modulePath))+ .toEqual({ entry: 'src/components.ts', line: "export * from './Patrol';" });+ expect(scriptWiring('system', ENTRIES, modulePath))+ .toEqual({ entry: 'src/main.ts', line: "import './Patrol';" });+ });+});