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: extension lifecycle redesign with ExtensionContext
esengine99f1b534a017
diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex d034c043d..afba5f941 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -22,12 +22,16 @@ import {isAssetServerProvider,isAssetNavigable,isOutputAppendable,+ lockBuiltinPanels,+ clearExtensionPanels,+ isBuiltinPanel,} from './panels/PanelRegistry';import { registerBuiltinPanels } from './panels/builtinPanels';import { registerBuiltinEditors } from './property/editors';import { registerMaterialEditors } from './property/materialEditors';-import { registerBuiltinSchemas } from './schemas/ComponentSchemas';-import { initBoundsProviders, registerBoundsProvider } from './bounds';+import { lockBuiltinPropertyEditors, clearExtensionPropertyEditors } from './property/PropertyEditor';+import { registerBuiltinSchemas, lockBuiltinComponentSchemas, clearExtensionComponentSchemas } from './schemas/ComponentSchemas';+import { initBoundsProviders, registerBoundsProvider, lockBuiltinBoundsProviders, clearExtensionBoundsProviders } from './bounds';import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from './io/SceneSerializer';import { icons } from './utils/icons';import { ScriptLoader } from './scripting';@@ -38,10 +42,11 @@ import type { EditorAssetServer } from './asset/EditorAssetServer';import { setEditorInstance, getEditorContext, getEditorInstance } from './context/EditorContext';import { getAllMenus, getMenuItems, getAllStatusbarItems, registerBuiltinMenus } from './menus';import { ShortcutManager } from './menus/ShortcutManager';-import { registerBuiltinGizmos, registerGizmo } from './gizmos';+import { registerBuiltinGizmos, registerGizmo, lockBuiltinGizmos, clearExtensionGizmos } from './gizmos';import { registerBuiltinStatusbarItems } from './menus/builtinStatusbar';import { ExtensionLoader } from './extension';-import { registerMenu, registerMenuItem, registerStatusbarItem } from './menus/MenuRegistry';+import { setEditorAPI, clearEditorAPI } from './extension/editorAPI';+import { registerMenu, registerMenuItem, registerStatusbarItem, lockBuiltinMenus, clearExtensionMenus } from './menus/MenuRegistry';import { registerPropertyEditor } from './property';import { registerComponentSchema } from './schemas';import { showToast, showSuccessToast, showErrorToast } from './ui/Toast';@@ -70,6 +75,7 @@ export class Editor {private panelInstances_ = new Map<string, PanelInstance>();private statusbarInstances_: Array<{ dispose(): void; update?(): void }> = [];+ private baseAPI_: Record<string, unknown> | null = null;private scriptLoader_: ScriptLoader | null = null;private extensionLoader_: ExtensionLoader | null = null;private previewService_: PreviewService | null = null;@@ -93,6 +99,12 @@ export class Editor {onOpenScene: (scenePath) => this.openSceneFromPath(scenePath),});registerBuiltinMenus(this);+ lockBuiltinPanels();+ lockBuiltinMenus();+ lockBuiltinGizmos();+ lockBuiltinPropertyEditors();+ lockBuiltinComponentSchemas();+ lockBuiltinBoundsProviders();this.setupLayout();@@ -329,7 +341,7 @@ export class Editor {// =========================================================================private setupEditorGlobals(): void {- (window as any).__ESENGINE_EDITOR__ = {+ this.baseAPI_ = {registerPanel,registerMenuItem,registerMenu,@@ -360,33 +372,57 @@ export class Editor {unregisterDrawCallback,clearDrawCallbacks,};+ setEditorAPI(this.baseAPI_);}private async initializeExtensions(): Promise<void> {- if (!this.projectPath_) return;+ if (!this.projectPath_ || !this.baseAPI_) return;this.extensionLoader_ = new ExtensionLoader({projectPath: this.projectPath_,+ baseAPI: this.baseAPI_,onCompileError: (errors) => {console.error('Extension compilation errors:', errors);+ const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');+ showErrorToast(`Extension compile failed:\n${msg}`);},onCompileSuccess: () => {console.log('Extensions compiled successfully');},+ onCleanup: () => this.cleanupExtensionUI(),+ onAfterReload: () => this.applyExtensionUI(),});try {await this.extensionLoader_.initialize();- const compiled = await this.extensionLoader_.compile();- if (compiled) {- await this.extensionLoader_.execute();- this.applyExtensionUI();- }+ await this.extensionLoader_.reload();+ await this.extensionLoader_.watch();} catch (err) {console.error('Failed to initialize extensions:', err);}}+ private cleanupExtensionUI(): void {+ for (const [id, instance] of this.panelInstances_) {+ if (isBuiltinPanel(id)) continue;+ instance.dispose();+ this.panelInstances_.delete(id);+ this.container_.querySelector(`[data-panel-id="${id}"]`)?.remove();+ }++ this.container_.querySelectorAll('[data-statusbar-id^="toggle-"]').forEach(el => {+ const panelId = el.getAttribute('data-statusbar-id')?.replace('toggle-', '');+ if (panelId && !isBuiltinPanel(panelId)) el.remove();+ });++ clearExtensionPanels();+ clearExtensionMenus();+ clearExtensionGizmos();+ clearExtensionPropertyEditors();+ clearExtensionComponentSchemas();+ clearExtensionBoundsProviders();+ }+private applyExtensionUI(): void {this.instantiateExtensionPanels();this.addExtensionBottomPanelToggles();@@ -518,11 +554,7 @@ export class Editor {return false;}- const success = await this.extensionLoader_.reload();- if (success) {- this.applyExtensionUI();- }- return success;+ return this.extensionLoader_.reload();}// =========================================================================@@ -610,17 +642,48 @@ export class Editor {error: console.error.bind(console),};- const forward = (type: 'stdout' | 'stderr' | 'error', args: unknown[]) => {- const text = args.map(a =>- typeof a === 'string' ? a : JSON.stringify(a, null, 2) ?? String(a)- ).join(' ');+ const formatArg = (a: unknown): string => {+ if (typeof a === 'string') return a;+ if (a instanceof Error) return `${a.name}: ${a.message}`;+ return JSON.stringify(a, null, 2) ?? String(a);+ };+ const formatArgs = (args: unknown[]) => args.map(formatArg).join(' ');++ const cleanStack = (raw: string | undefined): string => {+ if (!raw) return '';+ return raw.split('\n')+ .filter(line => {+ const t = line.trim();+ if (!t || t === 'Error') return false;+ if (t.includes('/editor/dist/')) return false;+ return true;+ })+ .map(line => line+ .replace(/https?:\/\/[^/]+\/@fs/g, '')+ .replace(/blob:https?:\/\/[^/]+\/[a-f0-9-]+/g, '<extension>')+ )+ .join('\n');+ };++ const INTERNAL_PREFIXES = [+ '[TAURI]', '[INFO]', 'File change:',+ ];++ const forward = (type: 'stdout' | 'stderr' | 'error', args: unknown[], stack?: string) => {+ const first = typeof args[0] === 'string' ? args[0] : '';+ if (INTERNAL_PREFIXES.some(p => first.startsWith(p))) return;++ let text = formatArgs(args);+ if (stack) {+ text += '\n' + stack;+ }this.appendOutput(text + '\n', type);};console.log = (...args) => { original.log(...args); forward('stdout', args); };console.info = (...args) => { original.info(...args); forward('stdout', args); };- console.warn = (...args) => { original.warn(...args); forward('stderr', args); };- console.error = (...args) => { original.error(...args); forward('error', args); };+ console.warn = (...args) => { original.warn(...args); forward('stderr', args, cleanStack(new Error().stack)); };+ console.error = (...args) => { original.error(...args); forward('error', args, cleanStack(new Error().stack)); };}private appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {@@ -898,7 +961,7 @@ export class Editor {panel.dispose();}this.panelInstances_.clear();- delete (window as any).__ESENGINE_EDITOR__;+ clearEditorAPI();}}diff --git a/editor/src/bounds/BoundsRegistry.ts b/editor/src/bounds/BoundsRegistry.tsindex 76fa477de..1a894de4f 100644--- a/editor/src/bounds/BoundsRegistry.ts+++ b/editor/src/bounds/BoundsRegistry.ts@@ -11,6 +11,18 @@ export function registerBoundsProvider(componentType: string, provider: BoundsPrproviders.set(componentType, provider);}+const builtinProviderTypes = new Set<string>();++export function lockBuiltinBoundsProviders(): void {+ for (const type of providers.keys()) builtinProviderTypes.add(type);+}++export function clearExtensionBoundsProviders(): void {+ for (const type of providers.keys()) {+ if (!builtinProviderTypes.has(type)) providers.delete(type);+ }+}+export function getEntityBounds(components: { type: string; data: any }[]): Bounds {for (const comp of components) {const provider = providers.get(comp.type);diff --git a/editor/src/bounds/index.ts b/editor/src/bounds/index.tsindex 03ff0d2fe..58f0c90f3 100644--- a/editor/src/bounds/index.ts+++ b/editor/src/bounds/index.ts@@ -4,7 +4,7 @@*/export * from './BoundsProvider';-export * from './BoundsRegistry';+export { registerBoundsProvider, getEntityBounds, lockBuiltinBoundsProviders, clearExtensionBoundsProviders } from './BoundsRegistry';import { registerBoundsProvider } from './BoundsRegistry';import { spriteBoundsProvider } from './SpriteBoundsProvider';diff --git a/editor/src/extension/ExtensionContext.ts b/editor/src/extension/ExtensionContext.tsnew file mode 100644index 000000000..082b021e4--- /dev/null+++ b/editor/src/extension/ExtensionContext.ts@@ -0,0 +1,71 @@+import {+ PostProcess, Material,+ unregisterDrawCallback,+} from 'esengine';++export class ExtensionContext {+ createAPI(base: Record<string, unknown>): Record<string, unknown> {+ return {+ ...base,+ registerDrawCallback: (id: string, fn: Function) => {+ if (this.disposed_) return;+ (base.registerDrawCallback as Function)(id, fn);+ this.drawCallbackIds_.add(id);+ },+ unregisterDrawCallback: (id: string) => {+ (base.unregisterDrawCallback as Function)(id);+ this.drawCallbackIds_.delete(id);+ },+ clearDrawCallbacks: undefined,++ PostProcess: {+ ...(base.PostProcess as object),+ addPass: (name: string, shader: number) => {+ if (this.disposed_) return -1;+ const idx = (base.PostProcess as any).addPass(name, shader);+ this.postProcessPasses_.add(name);+ return idx;+ },+ },++ Material: {+ ...(base.Material as object),+ createShader: (vert: string, frag: string) => {+ if (this.disposed_) return 0;+ const handle = (base.Material as any).createShader(vert, frag);+ if (handle > 0) this.shaderHandles_.add(handle);+ return handle;+ },+ },++ onDispose: (fn: () => void) => { this.disposables_.push(fn); },+ };+ }++ dispose(): void {+ if (this.disposed_) return;+ this.disposed_ = true;++ for (let i = this.disposables_.length - 1; i >= 0; i--) {+ try { this.disposables_[i](); } catch {}+ }++ for (const id of this.drawCallbackIds_) {+ unregisterDrawCallback(id);+ }++ for (const name of this.postProcessPasses_) {+ try { PostProcess.removePass(name); } catch {}+ }++ for (const handle of this.shaderHandles_) {+ try { Material.releaseShader(handle); } catch {}+ }+ }++ private disposed_ = false;+ private drawCallbackIds_ = new Set<string>();+ private postProcessPasses_ = new Set<string>();+ private shaderHandles_ = new Set<number>();+ private disposables_: (() => void)[] = [];+}diff --git a/editor/src/extension/ExtensionLoader.ts b/editor/src/extension/ExtensionLoader.tsindex afe2230b7..7c616779a 100644--- a/editor/src/extension/ExtensionLoader.ts+++ b/editor/src/extension/ExtensionLoader.ts@@ -7,6 +7,8 @@ import * as esbuild from 'esbuild-wasm/esm/browser';import { editorShimPlugin, virtualFsPlugin } from '../scripting/esbuildPlugins';import type { NativeFS, CompileError } from '../scripting/types';import { getEditorContext } from '../context/EditorContext';+import { ExtensionContext } from './ExtensionContext';+import { setEditorAPI } from './editorAPI';// =============================================================================// Path Utilities@@ -40,16 +42,22 @@ function getNativeFS(): NativeFS | null {export interface ExtensionLoaderOptions {projectPath: string;+ baseAPI: Record<string, unknown>;onCompileError?: (errors: CompileError[]) => void;onCompileSuccess?: () => void;+ onCleanup?: () => void;+ onAfterReload?: () => void;}export class ExtensionLoader {constructor(options: ExtensionLoaderOptions) {this.projectPath_ = normalizePath(options.projectPath);this.projectDir_ = getProjectDir(this.projectPath_);+ this.baseAPI_ = options.baseAPI;this.onCompileError_ = options.onCompileError;this.onCompileSuccess_ = options.onCompileSuccess;+ this.onCleanup_ = options.onCleanup;+ this.onAfterReload_ = options.onAfterReload;}// =========================================================================@@ -73,15 +81,22 @@ export class ExtensionLoader {const fs = getNativeFS();if (!fs) return [];- const editorDir = joinPath(this.projectDir_, 'editor');-try {- if (!(await fs.exists(editorDir))) return [];+ const editorDirs = await this.findEditorDirs(fs, this.projectDir_);+ const results: string[] = [];++ for (const dir of editorDirs) {+ if (!await fs.exists(dir)) continue;+ const entries = await fs.listDirectoryDetailed(dir);+ for (const e of entries) {+ if (!e.isDirectory && e.name.endsWith('.ts')) {+ results.push(joinPath(dir, e.name));+ }+ }+ }- const entries = await fs.listDirectoryDetailed(editorDir);- return entries- .filter(e => !e.isDirectory && e.name.endsWith('.ts'))- .map(e => joinPath(editorDir, e.name));+ this.lastEditorDir_ = editorDirs[0] ?? null;+ return results;} catch (err) {console.error('ExtensionLoader: Failed to discover extensions:', err);return [];@@ -109,11 +124,12 @@ export class ExtensionLoader {stdin: {contents: entryContent,loader: 'ts',- resolveDir: joinPath(this.projectDir_, 'editor'),+ resolveDir: this.lastEditorDir_ ?? this.projectDir_,},bundle: true,format: 'esm',write: false,+ sourcemap: true,platform: 'browser',target: 'es2020',external: ['esengine'],@@ -135,47 +151,120 @@ export class ExtensionLoader {return false;}- this.lastCompiled_ = result.outputFiles?.[0]?.text ?? null;+ const outputFiles = result.outputFiles ?? [];+ const mapFile = outputFiles.find(f => f.path.endsWith('.map'));+ const jsFile = outputFiles.find(f => !f.path.endsWith('.map'));+ this.lastCompiled_ = jsFile?.text ?? null;+ this.lastSourcemap_ = mapFile?.text ?? null;console.log('ExtensionLoader: Extensions compiled successfully');this.onCompileSuccess_?.();return true;- } catch (err) {+ } catch (err: any) {console.error('ExtensionLoader: Compilation failed:', err);- const errors: CompileError[] = [{- file: 'unknown',- line: 0,- column: 0,- message: String(err),- }];+ const esbuildErrors = err?.errors as esbuild.Message[] | undefined;+ const errors: CompileError[] = esbuildErrors?.length+ ? esbuildErrors.map(e => ({+ file: e.location?.file || 'unknown',+ line: e.location?.line || 0,+ column: e.location?.column || 0,+ message: e.text,+ }))+ : [{ file: 'unknown', line: 0, column: 0, message: String(err) }];this.onCompileError_?.(errors);return false;}}async execute(): Promise<boolean> {- if (!this.lastCompiled_) return false;+ if (!this.lastCompiled_) {+ console.warn('ExtensionLoader: No compiled code to execute');+ return false;+ }this.disposeCurrentUrl();try {- const blob = new Blob([this.lastCompiled_], { type: 'application/javascript' });+ let code = this.lastCompiled_;+ if (this.lastSourcemap_) {+ const b64 = btoa(unescape(encodeURIComponent(this.lastSourcemap_)));+ code += '\n//# sourceMappingURL=data:application/json;base64,' + b64;+ }++ const blob = new Blob([code], { type: 'application/javascript' });this.currentBlobUrl_ = URL.createObjectURL(blob);await import(/* @vite-ignore */ this.currentBlobUrl_);console.log('ExtensionLoader: Extensions executed successfully');return true;} catch (err) {- console.error('ExtensionLoader: Extension execution failed:', err);+ const msg = err instanceof Error ? err.message : String(err);+ console.error('ExtensionLoader: Extension execution failed:', msg);return false;}}async reload(): Promise<boolean> {- const compiled = await this.compile();- if (!compiled) return false;- return this.execute();+ if (this.isReloading_) return false;+ this.isReloading_ = true;+ try {+ const compiled = await this.compile();+ if (this.currentContext_) {+ this.currentContext_.dispose();+ this.currentContext_ = null;+ this.onCleanup_?.();+ }+ if (!compiled) return false;+ this.currentContext_ = new ExtensionContext();+ setEditorAPI(this.currentContext_.createAPI(this.baseAPI_));+ const executed = await this.execute();+ if (executed) {+ this.onAfterReload_?.();+ }+ return executed;+ } finally {+ this.isReloading_ = false;+ }+ }++ async watch(): Promise<void> {+ const fs = getNativeFS();+ if (!fs) return;++ this.unwatch();++ this.unwatchFn_ = await fs.watchDirectory(+ this.projectDir_,+ (event) => {+ const hasEditorTs = event.paths.some(p => {+ const normalized = normalizePath(p);+ return /\/editor\/[^/]+\.ts$/.test(normalized);+ });+ if (!hasEditorTs) return;++ if (this.recompileTimer_ !== null) {+ clearTimeout(this.recompileTimer_);+ }+ this.recompileTimer_ = window.setTimeout(() => {+ this.recompileTimer_ = null;+ this.reload();+ }, 300);+ },+ { recursive: true },+ );+ }++ unwatch(): void {+ if (this.recompileTimer_ !== null) {+ clearTimeout(this.recompileTimer_);+ this.recompileTimer_ = null;+ }+ this.unwatchFn_?.();+ this.unwatchFn_ = null;}dispose(): void {+ this.unwatch();+ this.currentContext_?.dispose();+ this.currentContext_ = null;this.disposeCurrentUrl();}@@ -183,6 +272,30 @@ export class ExtensionLoader {// Private Methods// =========================================================================+ private static readonly IGNORED_DIRS = new Set([+ 'node_modules', '.git', '.esengine', 'dist', 'build', '.next', '.cache',+ ]);++ private async findEditorDirs(fs: NativeFS, dir: string): Promise<string[]> {+ const results: string[] = [];+ const entries = await fs.listDirectoryDetailed(dir);++ for (const e of entries) {+ if (!e.isDirectory) continue;+ if (ExtensionLoader.IGNORED_DIRS.has(e.name)) continue;++ const fullPath = joinPath(dir, e.name);+ if (e.name === 'editor') {+ results.push(fullPath);+ } else {+ const nested = await this.findEditorDirs(fs, fullPath);+ results.push(...nested);+ }+ }++ return results;+ }+private disposeCurrentUrl(): void {if (this.currentBlobUrl_) {URL.revokeObjectURL(this.currentBlobUrl_);@@ -196,9 +309,18 @@ export class ExtensionLoader {private projectPath_: string;private projectDir_: string;+ private baseAPI_: Record<string, unknown>;private initialized_ = false;+ private isReloading_ = false;+ private lastEditorDir_: string | null = null;private lastCompiled_: string | null = null;+ private lastSourcemap_: string | null = null;private currentBlobUrl_: string | null = null;+ private currentContext_: ExtensionContext | null = null;+ private unwatchFn_: (() => void) | null = null;+ private recompileTimer_: number | null = null;private onCompileError_?: (errors: CompileError[]) => void;private onCompileSuccess_?: () => void;+ private onCleanup_?: () => void;+ private onAfterReload_?: () => void;}diff --git a/editor/src/extension/editorAPI.ts b/editor/src/extension/editorAPI.tsnew file mode 100644index 000000000..4fd0a2f22--- /dev/null+++ b/editor/src/extension/editorAPI.ts@@ -0,0 +1,7 @@+export function setEditorAPI(api: Record<string, unknown>): void {+ window.__ESENGINE_EDITOR__ = api;+}++export function clearEditorAPI(): void {+ delete window.__ESENGINE_EDITOR__;+}diff --git a/editor/src/extension/index.ts b/editor/src/extension/index.tsindex e8e8bb639..b8b63cddb 100644--- a/editor/src/extension/index.ts+++ b/editor/src/extension/index.ts@@ -1,2 +1,3 @@export { ExtensionLoader, type ExtensionLoaderOptions } from './ExtensionLoader';+export { ExtensionContext } from './ExtensionContext';export { EditorExportService } from './EditorExportService';diff --git a/editor/src/globals.d.ts b/editor/src/globals.d.tsnew file mode 100644index 000000000..99dd779a9--- /dev/null+++ b/editor/src/globals.d.ts@@ -0,0 +1,11 @@+interface Window {+ __ESENGINE_EDITOR__?: Record<string, unknown>;+ __esengine_registerComponent?: (name: string, defaults: Record<string, unknown>, isTag: boolean) => void;+ showSaveFilePicker?: (options?: {+ suggestedName?: string;+ types?: Array<{+ description?: string;+ accept: Record<string, string[]>;+ }>;+ }) => Promise<FileSystemFileHandle>;+}diff --git a/editor/src/panels/PanelRegistry.ts b/editor/src/panels/PanelRegistry.tsindex ae47c13c1..98b755a0f 100644--- a/editor/src/panels/PanelRegistry.ts+++ b/editor/src/panels/PanelRegistry.ts@@ -72,11 +72,26 @@ export function isOutputAppendable(p: PanelInstance): p is PanelInstance & Outpu}const panels = new Map<string, PanelDescriptor>();+const builtinPanelIds = new Set<string>();export function registerPanel(descriptor: PanelDescriptor): void {panels.set(descriptor.id, descriptor);}+export function lockBuiltinPanels(): void {+ for (const id of panels.keys()) builtinPanelIds.add(id);+}++export function clearExtensionPanels(): void {+ for (const id of panels.keys()) {+ if (!builtinPanelIds.has(id)) panels.delete(id);+ }+}++export function isBuiltinPanel(id: string): boolean {+ return builtinPanelIds.has(id);+}+export function getPanel(id: string): PanelDescriptor | undefined {return panels.get(id);}diff --git a/editor/src/property/PropertyEditor.ts b/editor/src/property/PropertyEditor.tsindex 7b85208b7..015f19e02 100644--- a/editor/src/property/PropertyEditor.ts+++ b/editor/src/property/PropertyEditor.ts@@ -50,6 +50,18 @@ export function getPropertyEditor(type: string): PropertyEditorFactory | undefinreturn editorRegistry.get(type);}+const builtinEditorTypes = new Set<string>();++export function lockBuiltinPropertyEditors(): void {+ for (const type of editorRegistry.keys()) builtinEditorTypes.add(type);+}++export function clearExtensionPropertyEditors(): void {+ for (const type of editorRegistry.keys()) {+ if (!builtinEditorTypes.has(type)) editorRegistry.delete(type);+ }+}+export function createPropertyEditor(container: HTMLElement,ctx: PropertyEditorContextdiff --git a/editor/src/property/index.ts b/editor/src/property/index.tsindex c8a3eda82..f23348c40 100644--- a/editor/src/property/index.ts+++ b/editor/src/property/index.ts@@ -11,6 +11,8 @@ export {registerPropertyEditor,getPropertyEditor,createPropertyEditor,+ lockBuiltinPropertyEditors,+ clearExtensionPropertyEditors,} from './PropertyEditor';export { registerBuiltinEditors } from './editors';diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex d071b96fa..d37c55904 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -209,6 +209,18 @@ export function getComponentsByCategory(): ComponentsByCategory {return result;}+const builtinSchemaNames = new Set<string>();++export function lockBuiltinComponentSchemas(): void {+ for (const name of schemaRegistry.keys()) builtinSchemaNames.add(name);+}++export function clearExtensionComponentSchemas(): void {+ for (const name of schemaRegistry.keys()) {+ if (!builtinSchemaNames.has(name)) schemaRegistry.delete(name);+ }+}+export function clearScriptComponents(): void {for (const [name, schema] of schemaRegistry.entries()) {if (schema.category === 'script' || schema.category === 'tag') {@@ -244,7 +256,7 @@ function registerUserComponent(function exposeRegistrationAPI(): void {if (typeof window !== 'undefined') {- (window as any).__esengine_registerComponent = registerUserComponent;+ window.__esengine_registerComponent = registerUserComponent;}}diff --git a/editor/src/schemas/index.ts b/editor/src/schemas/index.tsindex df702d698..df275a885 100644--- a/editor/src/schemas/index.ts+++ b/editor/src/schemas/index.ts@@ -13,4 +13,6 @@ export {getComponentSchema,getAllComponentSchemas,registerBuiltinSchemas,+ lockBuiltinComponentSchemas,+ clearExtensionComponentSchemas,} from './ComponentSchemas';diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.tsindex 077ba0925..36652550a 100644--- a/editor/src/scripting/esbuildPlugins.ts+++ b/editor/src/scripting/esbuildPlugins.ts@@ -57,7 +57,8 @@ const EDITOR_SHIM_EXPORTS = ['getEditorInstance', 'getEditorStore','Draw', 'Geometry', 'Material', 'BlendMode', 'DataType', 'ShaderSources','PostProcess', 'Renderer', 'RenderStage',- 'registerDrawCallback', 'unregisterDrawCallback', 'clearDrawCallbacks',+ 'registerDrawCallback', 'unregisterDrawCallback',+ 'onDispose',] as const;const EDITOR_SHIM_CODE = EDITOR_SHIM_EXPORTS.map(