The VS Code of video editing, built for agents.
TypeScript
Refactor asset and folder management to remove IndexedDB dependencies
konstantin-paulus641b6abde914
diff --git a/apps/web/src/components/engine/api/assets.ts b/apps/web/src/components/engine/api/assets.tsindex ca3b4169..b901cbdb 100644--- a/apps/web/src/components/engine/api/assets.ts+++ b/apps/web/src/components/engine/api/assets.ts@@ -10,7 +10,7 @@ import { BlobSource } from 'mediabunny';import { Input } from 'mediabunny';import { nanoid } from "nanoid";import Sqids from "sqids";-import { saveDirectoryHandle, retrieveDirectoryHandle, getProjectDB } from "../db";+import { saveDirectoryHandle, retrieveDirectoryHandle } from "../db";import { GeometryType, PaintType } from "../components";import { secondsToFrames } from "../utils/time";import { toast } from "somoto";@@ -45,7 +45,6 @@ type AssetState = {projectId: string;counter: number;directoryHandle: Promise<FileSystemDirectoryHandle>;- db: ReturnType<typeof getProjectDB>;version: Accessor<number>;setVersion: Setter<number>;selected: Accessor<Map<string, Asset>>;@@ -67,7 +66,6 @@ export function initAssets(world: EngineWorld, projectId: string): void {projectId,counter: 0,directoryHandle: retrieveDirectoryHandle(),- db: getProjectDB(projectId),version,setVersion,selected,@@ -470,9 +468,6 @@ export async function saveAsset(world: EngineWorld, asset: Asset): Promise<Assetstate.setSelected(next);}- const db = await state.db;- await db.put('assets', serializeAssetForPersist(asset));-invalidateAssets(world);return asset;@@ -485,21 +480,15 @@ export async function removeAsset(world: EngineWorld, ...ids: string[]): Promiseconst map = world.assets;for (const id of ids) map.delete(id);invalidateAssets(world);-- const db = await assetState(world).db;- for (const id of ids) {- db.delete('assets', id);- }}/**- * Restores assets from IndexedDB into the in-memory store.- * Call once during engine init.+ * Restores assets into the in-memory store. Call once during engine init.+ * Placeholder: projects are held purely in memory, so there is nothing to+ * load yet — wire the project (JSX package) loader in here.*/export async function restoreAssets(world: EngineWorld): Promise<void> {- const state = assetState(world);- const db = await state.db;- const records = await db.getAll('assets');+ const records: Asset[] = [];if (records.length === 0) return;const map = world.assets;@@ -708,15 +697,6 @@ function concatBytes(a: Uint8Array<ArrayBuffer>, b: Uint8Array<ArrayBuffer>): Uireturn out;}-function serializeAssetForPersist(asset: Asset): Asset {- // IndexedDB structured-clones records. ElectronFileHandle is a custom class- // whose methods don't survive cloning — serialize to the persisted shape.- if (asset.handle instanceof ElectronFileHandle) {- return { ...asset, handle: asset.handle.toJSON() } as unknown as Asset;- }- return asset;-}-function rehydrateAsset(asset: Asset): Asset {if (isSerializedElectronFileHandle(asset.handle)) {return { ...asset, handle: rehydrateElectronFileHandle(asset.handle) };diff --git a/apps/web/src/components/engine/api/base.ts b/apps/web/src/components/engine/api/base.tsindex f3ee34d6..95cc470e 100644--- a/apps/web/src/components/engine/api/base.ts+++ b/apps/web/src/components/engine/api/base.ts@@ -8,7 +8,6 @@ import { rgbToColor } from "@/utils/color";import { deserializeEntity } from "./serialize";import { ChildOf } from "../components/relations";import { restoreFonts } from "../font/utils";-import { WORLD_STATE_KEY } from "../db";import * as tl from '../timeline';import { createEntity, deleteEntity } from "./entities";import { assert } from "@/utils";@@ -18,6 +17,13 @@ import { restoreAssets } from "./assets";import { restoreFolders } from "./folders";import type { EngineWorld } from "./world";+import type { DBEntity, Camera2D } from "../types";++/** Serialized world-level state (camera + background). */+export type DBWorldState = {+ camera: Camera2D;+ background: number;+};export function getParentEntity(world: EngineWorld, eid: number | null | undefined): number | null {if (!eid) return null;@@ -37,22 +43,36 @@ export function getSiblingEntities(world: EngineWorld, eid: number, component: ureturn children;}-/** Persist the current camera + background to IndexedDB. */-export function persistWorldState(world: EngineWorld): void {- world.store.worldState.schedule(world);+/**+ * Placeholder: projects are held purely in memory. Hook project (JSX package)+ * persistence of camera + background in here once it lands.+ */+export function persistWorldState(_world: EngineWorld): void { }++/** Placeholder loader for entity records; projects are in memory only. */+async function loadEntityRecords(_world: EngineWorld): Promise<DBEntity[]> {+ return [];+}++/** Placeholder loader for the world record; projects are in memory only. */+async function loadWorldRecord(_world: EngineWorld): Promise<DBWorldState | undefined> {+ return undefined;}+/**+ * Restores a world from its persisted records. Projects are currently held+ * purely in memory, so this boots an empty world; `records` / `worldRecord`+ * are placeholders for the upcoming project (JSX package) loader.+ */export async function restoreWorld(world: EngineWorld) {assert(getAllEntities(world).length === 0, 'World is not empty');- const store = world.store;-- const db = await store.db;-- // Load entity records, world state, and previously loaded fonts in parallel.const [records, worldRecord] = await Promise.all([- db.getAll('entities'),- db.get('world', WORLD_STATE_KEY),+ loadEntityRecords(world),+ loadWorldRecord(world),+ ]);++ await Promise.all([restoreAssets(world),restoreFolders(world),restoreFonts(world),@@ -86,13 +106,13 @@ export async function restoreWorld(world: EngineWorld) {world.background = rgbToColor(r, g, b);}- // Bitecs hands out fresh sequential eids after resetWorld, but the DB key- // is the entity's eid — so to keep records stable across reloads we+ // Bitecs hands out fresh sequential eids after resetWorld, but the record+ // key is the entity's eid — so to keep records stable across reloads we// restore each entity at the exact eid it was saved under. Fill the gap// eids with placeholder entities up to the max stored eid, then remove// them once the real ones are deserialized.const liveEids = new Set(records.map(r => r.eid));- const maxEid = Math.max(...records.map(r => r.eid));+ const maxEid = records.length ? Math.max(...records.map(r => r.eid)) : 0;// Loading a project must never populate the undo stack: deserialize// untracked, then clear so the first undo can't unwind the boot.diff --git a/apps/web/src/components/engine/api/folders.ts b/apps/web/src/components/engine/api/folders.tsindex 259521f2..8d3be493 100644--- a/apps/web/src/components/engine/api/folders.ts+++ b/apps/web/src/components/engine/api/folders.ts@@ -4,7 +4,6 @@import { createSignal } from "solid-js";import { assert } from "@/utils";-import { getProjectDB } from "../db";import { allocateId, assetsVersion, invalidateAssets, raiseIdCounter, saveAsset, removeAsset } from "./assets";import type { Accessor, Setter } from "solid-js";@@ -12,7 +11,6 @@ import type { EngineWorld } from "./world";import type { Asset, Folder } from "../db";type FolderState = {- db: ReturnType<typeof getProjectDB>;currentId: Accessor<string | null>;setCurrentId: Setter<string | null>;};@@ -23,11 +21,10 @@ const folderStates = new WeakMap<object, FolderState>();* Initializes the folder subsystem for a world. Call once, right after the* world is created. `world.folders` must already be an (empty) Map.*/-export function initFolders(world: EngineWorld, projectId: string): void {+export function initFolders(world: EngineWorld, _projectId: string): void {const [currentId, setCurrentId] = createSignal<string | null>(null);folderStates.set(world, {- db: getProjectDB(projectId),currentId,setCurrentId,});@@ -211,9 +208,6 @@ export async function createFolder(world.folders.set(folder.id, folder);invalidateAssets(world);- const db = await folderState(world).db;- await db.put('folders', folder);-return folder;}@@ -227,9 +221,6 @@ export async function renameFolder(world: EngineWorld, id: string, name: string)const next = { ...folder, name };world.folders.set(id, next);invalidateAssets(world);-- const db = await folderState(world).db;- await db.put('folders', next);}/**@@ -271,9 +262,6 @@ export async function moveFolder(const next = { ...folder, parentId };world.folders.set(id, next);invalidateAssets(world);-- const db = await folderState(world).db;- await db.put('folders', next);return true;}@@ -312,10 +300,8 @@ export async function deleteFolder(world: EngineWorld, id: string) {await removeAsset(world, ...assetIds);}- const db = await state.db;for (const folderId of subtree) {world.folders.delete(folderId);- await db.delete('folders', folderId);}invalidateAssets(world);@@ -323,12 +309,12 @@ export async function deleteFolder(world: EngineWorld, id: string) {}/**- * Restores folders from IndexedDB into the in-memory store.- * Call once during engine init.+ * Restores folders into the in-memory store. Call once during engine init.+ * Placeholder: projects are held purely in memory, so there is nothing to+ * load yet — wire the project (JSX package) loader in here.*/export async function restoreFolders(world: EngineWorld): Promise<void> {- const db = await folderState(world).db;- const records = await db.getAll('folders');+ const records: Folder[] = [];if (records.length === 0) return;world.folders.clear();diff --git a/apps/web/src/components/engine/api/utils.ts b/apps/web/src/components/engine/api/utils.tsindex 76ea253e..d5c89b0e 100644--- a/apps/web/src/components/engine/api/utils.ts+++ b/apps/web/src/components/engine/api/utils.ts@@ -70,21 +70,25 @@ export function rebuildCaches(world: EngineWorld, eid: number, pid: number | nul}}+/**+ * Placeholder: projects are held purely in memory. Hook project (JSX package)+ * persistence in here once it lands.+ */export function persistEntity(world: EngineWorld, eid: number) {const c = world.components;if (world.mode !== 'realtime' || !entityExists(world, eid) || hasComponent(world, eid, c.Deleted)) return;-- world.store.queue.scheduleWrite(world, eid);}+/**+ * Placeholder counterpart to `persistEntity`.+ */export function unpersistEntity(world: EngineWorld, eid: number) {const c = world.components;if (world.mode !== 'realtime' || !entityExists(world, eid) || !hasComponent(world, eid, c.Deleted)) return;removeComponent(world, eid, c.Selected, false);- world.store.queue.scheduleDelete(world, eid);}export function findClosestParentGeometry(world: EngineWorld, eid: number) {diff --git a/apps/web/src/components/engine/api/world.ts b/apps/web/src/components/engine/api/world.tsindex b3f8ea38..dab0354d 100644--- a/apps/web/src/components/engine/api/world.ts+++ b/apps/web/src/components/engine/api/world.ts@@ -9,7 +9,6 @@ import { observeWorld } from "./observers";import { createComponents } from "./components";import { createHistory } from "../utils/history";import { createLiveMounts } from "../utils/live-mounts";-import { createStore } from "../db";import { initAssets } from "./assets";import { initFolders } from "./folders";import { buildTimelineLayers, type TimelineIndexValue } from "./timeline-index";@@ -60,7 +59,6 @@ export function createEngineWorld(projectId: string, audioContext: AudioContextaudio: audioContext,assets: new Map<string, Asset>(),folders: new Map<string, Folder>(),- store: createStore(projectId),promises: null as (Promise<unknown> | null)[] | null,timelineIndex,rebuildTimelineIndex: () => { },diff --git a/apps/web/src/components/engine/db/global-db.ts b/apps/web/src/components/engine/db/global-db.tsindex d788f5fb..a2e82784 100644--- a/apps/web/src/components/engine/db/global-db.ts+++ b/apps/web/src/components/engine/db/global-db.ts@@ -5,7 +5,8 @@import { openDB } from 'idb';import type * as idb from 'idb';import { nanoid } from 'nanoid';-import { DEFAULT_PROJECT_ID, deleteProjectDB, getProjectDB } from './project-db';++export const DEFAULT_PROJECT_ID = 'V1StGXR8_Z5jdHi6B-myT';const adjectives = ["Golden", "Silent", "Fast", "Bright", "Dark", "Wild", "Calm"];const nouns = ["River", "Mountain", "Dream", "Storm", "Sunset", "Forest", "Ocean"];@@ -48,14 +49,6 @@ export interface GlobalDBSchema extends idb.DBSchema {'by-last-accessed': string;};};- projects: {- value: ProjectEntry;- key: string;- indexes: {- 'by-name': string;- 'by-last-accessed': string;- };- };}const DB_NAME = 'global-db';@@ -70,19 +63,18 @@ const dbPromise = openDB<GlobalDBSchema>(DB_NAME, DB_VERSION, {store.createIndex('by-name', 'name');store.createIndex('by-last-accessed', 'lastAccessedAt');}-- if (!db.objectStoreNames.contains('projects')) {- const store = db.createObjectStore('projects', {- keyPath: 'id',- });- store.createIndex('by-name', 'name');- store.createIndex('by-last-accessed', 'lastAccessedAt');- }},});+/** Session-only project registry. */+const projects = new Map<string, ProjectEntry>();++function byLastAccessedDesc<T extends { lastAccessedAt: string }>(a: T, b: T): number {+ return b.lastAccessedAt.localeCompare(a.lastAccessedAt);+}+/**- * Saves a directory handle to the database.+ * Saves the root directory handle to the database.* If the same handle already exists, it will be updated.*/export async function saveDirectoryHandle(handle: FileSystemDirectoryHandle) {@@ -115,7 +107,7 @@ export async function saveDirectoryHandle(handle: FileSystemDirectoryHandle) {}/**- * Returns the most recently accessed directory handle, or null if none exists.+ * Returns the most recently accessed root directory, or null if none exists.*/export async function retrieveLastAccessedDirectory(): Promise<Directory | null> {const db = await dbPromise;@@ -128,8 +120,8 @@ export async function retrieveLastAccessedDirectory(): Promise<Directory | null>}/**- * Finds the last accessed directory handle, or creates a new one if none exists.- * Uses OPFS as a fallback if the indexeddb is not available.+ * Finds the last accessed directory handle, or falls back to the origin+ * private file system as a scratch location for asset files.* @returns The directory handle.*/export async function retrieveDirectoryHandle() {@@ -146,24 +138,19 @@ const PROJECT_ID_PATTERN = /^[A-Za-z0-9_-]{21}$/;export async function markProjectOpened(projectId: string): Promise<void> {if (!PROJECT_ID_PATTERN.test(projectId) || projectId === DEFAULT_PROJECT_ID) return;- const db = await dbPromise;const now = new Date().toISOString();- const tx = db.transaction('projects', 'readwrite');- const existing = await tx.store.get(projectId);+ const existing = projects.get(projectId);- const entry: ProjectEntry = {+ projects.set(projectId, {+ ...existing,id: projectId,name: existing?.name ?? generateProjectName(),createdAt: existing?.createdAt ?? now,lastAccessedAt: now,- };-- await tx.store.put(entry);- await tx.done;+ });}export async function createProject(name?: string): Promise<ProjectEntry> {- const db = await dbPromise;const now = new Date().toISOString();const entry: ProjectEntry = {id: nanoid(),@@ -171,14 +158,12 @@ export async function createProject(name?: string): Promise<ProjectEntry> {createdAt: now,lastAccessedAt: now,};- await db.put('projects', entry);+ projects.set(entry.id, entry);return entry;}export async function getProjectName(projectId: string): Promise<string> {- const db = await dbPromise;-- const project = await db.get('projects', projectId)+ const project = projects.get(projectId);if (!project) return generateProjectName();return project.name;@@ -186,96 +171,51 @@ export async function getProjectName(projectId: string): Promise<string> {export async function getProject(projectId: string): Promise<ProjectEntry | null> {if (!PROJECT_ID_PATTERN.test(projectId)) return null;- const db = await dbPromise;- return (await db.get('projects', projectId)) ?? null;+ return projects.get(projectId) ?? null;}export async function setProjectName(projectId: string, name: string): Promise<void> {if (!PROJECT_ID_PATTERN.test(projectId)) return;- const db = await dbPromise;- const tx = db.transaction('projects', 'readwrite');- const existing = await tx.store.get(projectId);+ const existing = projects.get(projectId);const now = new Date().toISOString();- const entry: ProjectEntry = {+ projects.set(projectId, {+ ...existing,id: projectId,name,createdAt: existing?.createdAt ?? now,lastAccessedAt: now,- };-- await tx.store.put(entry);- await tx.done;+ });}export async function listRecentProjects(limit = 10): Promise<ProjectEntry[]> {- const db = await dbPromise;-- const tx = db.transaction('projects', 'readonly');- let cursor = await tx.store.index('by-last-accessed').openCursor(null, 'prev');-- const entries: ProjectEntry[] = [];- while (cursor && entries.length < limit) {- entries.push(cursor.value);- cursor = await cursor.continue();- }-- await tx.done;- return entries;+ return Array.from(projects.values()).sort(byLastAccessedDesc).slice(0, limit);}export async function setProjectThumbnail(projectId: string, thumbnail: Blob): Promise<void> {if (!PROJECT_ID_PATTERN.test(projectId) || projectId === DEFAULT_PROJECT_ID) return;- const db = await dbPromise;- const tx = db.transaction('projects', 'readwrite');- const existing = await tx.store.get(projectId);- if (!existing) {- await tx.done;- return;- }+ const existing = projects.get(projectId);+ if (!existing) return;- existing.thumbnail = thumbnail;- await tx.store.put(existing);- await tx.done;+ projects.set(projectId, { ...existing, thumbnail });}export async function getProjectThumbnail(projectId: string): Promise<Blob | null> {- const db = await dbPromise;- const project = await db.get('projects', projectId);- return project?.thumbnail ?? null;+ return projects.get(projectId)?.thumbnail ?? null;}export async function duplicateProject(projectId: string): Promise<ProjectEntry | null> {if (!PROJECT_ID_PATTERN.test(projectId)) return null;- const db = await dbPromise;- const source = await db.get('projects', projectId);+ const source = projects.get(projectId);if (!source) return null;const newProjectId = nanoid();const now = new Date().toISOString();- const sourceDB = await getProjectDB(projectId);- const targetDB = await getProjectDB(newProjectId);-- const [entities, assets, folders, fonts] = await Promise.all([- sourceDB.getAll('entities'),- sourceDB.getAll('assets'),- sourceDB.getAll('folders'),- sourceDB.getAll('fonts'),- ]);-- const tx = targetDB.transaction(['entities', 'assets', 'folders', 'fonts'], 'readwrite');- await Promise.all([- ...entities.map((entity) => tx.objectStore('entities').put(entity)),- ...assets.map((asset) => tx.objectStore('assets').put(asset)),- ...folders.map((folder) => tx.objectStore('folders').put(folder)),- ...fonts.map((font) => tx.objectStore('fonts').put(font)),- tx.done,- ]);-+ // TODO: copy the project's package/JSX contents once projects live on disk.const entry: ProjectEntry = {id: newProjectId,name: `${source.name} (Copy)`,@@ -284,15 +224,12 @@ export async function duplicateProject(projectId: string): Promise<ProjectEntrythumbnail: source.thumbnail,};- await db.put('projects', entry);+ projects.set(newProjectId, entry);return entry;}export async function deleteProject(projectId: string): Promise<void> {if (!PROJECT_ID_PATTERN.test(projectId)) return;- const db = await dbPromise;- await db.delete('projects', projectId);-- await deleteProjectDB(projectId);+ projects.delete(projectId);}diff --git a/apps/web/src/components/engine/db/index.ts b/apps/web/src/components/engine/db/index.tsindex 01bc2ab7..73c36df6 100644--- a/apps/web/src/components/engine/db/index.ts+++ b/apps/web/src/components/engine/db/index.ts@@ -2,6 +2,5 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-export * from './project-db';export * from './global-db';export * from './schemas';diff --git a/apps/web/src/components/engine/db/migrations.ts b/apps/web/src/components/engine/db/migrations.tsdeleted file mode 100644index f7ecfceb..00000000--- a/apps/web/src/components/engine/db/migrations.ts+++ /dev/null@@ -1,439 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import type * as idb from 'idb';-import type { DBEntity } from '../types';-import type { EngineDBSchema } from './project-db';--type Transaction = idb.IDBPTransaction<EngineDBSchema, ("entities" | "assets" | "folders" | "fonts" | "world")[], "versionchange">;--const LEGACY_FPS = 30;--export async function migrateToV2(tx: Transaction) {- // v1 → v2: rename time/frame fields and convert seconds → frames.- // Mappings:- // Workarea.start (s) → Workarea.startFrame (f)- // Workarea.end (s) → Workarea.stopFrame (f)- // Time.delay (s) → Time.delayInFrames (f)- // Time.trimStart (s) → Time.trimStartFrame (f)- // Time.trimEnd (s) → Time.trimEndFrame (f)- // Timeline.currentTime (s) → Timeline.currentTimeInSeconds (rename only)- // Transition.duration (s) → Transition.durationInFrames (f)- // Animation.duration (s) → Animation.durationInFrames (f)- // Keyframe.time (s) → Keyframe.frame (f)- const store = tx.objectStore('entities');- let cursor = await store.openCursor();- while (cursor) {- const record = cursor.value as DBEntity & {- Workarea?: { start?: number; end?: number; startFrame?: number; stopFrame?: number };- Time?: {- delay?: number; trimStart?: number; trimEnd?: number;- delayInFrames?: number; trimStartFrame?: number; trimEndFrame?: number;- playbackRate?: number;- };- Timeline?: { currentTime?: number; currentTimeInSeconds?: number; loop?: number };- Transition?: { type?: number; duration?: number; durationInFrames?: number };- Animation?: { type?: number; duration?: number; durationInFrames?: number; phase?: number };- Keyframe?: { time?: number; frame?: number; value?: number; property?: string; easing?: string };- };- let changed = false;-- if (record.Workarea) {- if (record.Workarea.start !== undefined) {- record.Workarea.startFrame = Math.round(record.Workarea.start * LEGACY_FPS);- delete record.Workarea.start;- changed = true;- }- if (record.Workarea.end !== undefined) {- record.Workarea.stopFrame = Math.round(record.Workarea.end * LEGACY_FPS);- delete record.Workarea.end;- changed = true;- }- }-- if (record.Time) {- if (record.Time.delay !== undefined) {- record.Time.delayInFrames = Math.round(record.Time.delay * LEGACY_FPS);- delete record.Time.delay;- changed = true;- }- if (record.Time.trimStart !== undefined) {- record.Time.trimStartFrame = Math.round(record.Time.trimStart * LEGACY_FPS);- delete record.Time.trimStart;- changed = true;- }- if (record.Time.trimEnd !== undefined) {- record.Time.trimEndFrame = Math.round(record.Time.trimEnd * LEGACY_FPS);- delete record.Time.trimEnd;- changed = true;- }- }-- if (record.Timeline && record.Timeline.currentTime !== undefined) {- record.Timeline.currentTimeInSeconds = record.Timeline.currentTime;- delete record.Timeline.currentTime;- changed = true;- }-- if (record.Transition && record.Transition.duration !== undefined) {- record.Transition.durationInFrames = Math.round(record.Transition.duration * LEGACY_FPS);- delete record.Transition.duration;- changed = true;- }-- if (record.Animation && record.Animation.duration !== undefined) {- record.Animation.durationInFrames = Math.round(record.Animation.duration * LEGACY_FPS);- delete record.Animation.duration;- changed = true;- }-- if (record.Keyframe && record.Keyframe.time !== undefined) {- record.Keyframe.frame = Math.round(record.Keyframe.time * LEGACY_FPS);- delete record.Keyframe.time;- changed = true;- }-- if (changed) {- await cursor.update(record);- }- cursor = await cursor.continue();- }-}--/** Legacy stage entity id used before the v3 refactor. */-const LEGACY_STAGE_EID = 1;--/**- * v2 → v3: drop the deprecated stage entity (eid=1) and unparent anything- * that pointed at it. Removing STAGE=0 from the NodeType enum also shifts- * the remaining values down by one, so Node.type on every surviving record- * is decremented to match. Camera and background fall back to defaults on- * the next load — we don't bother carrying the stage's values over.- */-export async function migrateToV3(tx: Transaction) {- const entities = tx.objectStore('entities');-- let cursor = await entities.openCursor();- while (cursor) {- const record = cursor.value as DBEntity & { Node?: { type?: number } };-- if (record.eid === LEGACY_STAGE_EID) {- await cursor.delete();- } else {- let changed = false;- if (record.ChildOf === LEGACY_STAGE_EID) {- delete record.ChildOf;- changed = true;- }- if (record.Node?.type !== undefined && record.Node.type > 0) {- record.Node.type -= 1;- changed = true;- }- if (changed) await cursor.update(record);- }-- cursor = await cursor.continue();- }-}--/**- * v4 → v5: drop the Tracks model. Each clip becomes its own layer (motion-- * graphics style). For each entity record:- * - Rename `TrackIndex` → `ItemIndex` (preserving the integer value).- * - Drop the scene-level `Tracks` payload entirely — per-track mute/hide/- * volume/height are not preserved.- * - Assign `ClipHeight = DEFAULT_CLIP_HEIGHT` to every Node entity so the- * new render path has a height to fall back on.- * - Rename `Timeline` → `Playback`, keeping only `loop`. Time-tracking fields- * (currentTimeInSeconds, etc.) moved to Computed and are recomputed- * at runtime, so we drop any residual values from older shapes.- *- * Clips that previously shared a TrackIndex will share an ItemIndex after the- * rename. In the new model that means they stack on the same row visually- * (overlapping); the user can drag to fix.- */-const DEFAULT_CLIP_HEIGHT_V5 = 32;-/** NodeType.SCENE — pinned so this migration survives enum reordering. */-const SCENE_NODE_TYPE_V5 = 0;-type LegacyEntity = DBEntity & {- TrackIndex?: number;- Tracks?: unknown;- Timeline?: { loop?: number };- Workarea?: { startFrame?: number; stopFrame?: number };- Time?: {- delayInFrames?: number;- trimStartFrame?: number;- trimEndFrame?: number;- playbackRate?: number;- mode?: number;- };- Node?: { type?: number };- DelayInFrames?: number;- PlaybackRate?: number;- Trim?: { startFrame?: number; endFrame?: number };-};-export async function migrateToV5(tx: Transaction) {- const entities = tx.objectStore('entities');- let cursor = await entities.openCursor();- while (cursor) {- const record = cursor.value as LegacyEntity;- let changed = false;-- if (record.TrackIndex !== undefined) {- record.ItemIndex = record.TrackIndex;- delete record.TrackIndex;- changed = true;- }-- if (record.Tracks !== undefined) {- delete record.Tracks;- changed = true;- }-- if (record.Node !== undefined && record.ClipHeight === undefined) {- record.ClipHeight = DEFAULT_CLIP_HEIGHT_V5;- changed = true;- }-- if (record.Timeline !== undefined) {- record.Playback = { loop: record.Timeline.loop ?? 1 };- delete record.Timeline;- changed = true;- }-- // Split the old Time record into separate scalar components plus an- // optional Trim. The old Time held both placement (delay, rate) and- // explicit bounds (trimStart, trimEnd); bounds now live in Trim, whose- // absence means "auto-fit" (scenes) or "no inherent duration" (clips).- if (record.Time) {- record.DelayInFrames = record.Time.delayInFrames ?? 0;- record.PlaybackRate = record.Time.playbackRate ?? 1;- const isScene = record.Node?.type === SCENE_NODE_TYPE_V5;- const hasExplicitTrim =- !isScene ||- record.Workarea !== undefined ||- record.Time.mode === 0;- if (hasExplicitTrim) {- record.Trim = {- startFrame: record.Workarea?.startFrame ?? record.Time.trimStartFrame ?? 0,- endFrame: record.Workarea?.stopFrame ?? record.Time.trimEndFrame ?? 0,- };- }- delete record.Time;- changed = true;- }-- if (record.Workarea) {- delete record.Workarea;- changed = true;- }-- if (changed) await cursor.update(record);- cursor = await cursor.continue();- }-}--/** FillType enum value for SOLID — pinned to a constant so this migration- * keeps working if the runtime enum is later reordered. */-const SOLID_FILL_TYPE = 0;--/**- * v5 → v6: drop the `Node` and `Fill` typed components in favour of flat- * arrays and tag components.- *- * Node = { type } (NodeType enum) → Geometry = number (RECT|TEXT)- * + Group / Audio tags as needed- * + ClipsContent for scenes- * Fill = { type } (FillType enum) → Paint = number (PaintType enum)- *- * Old NodeType values are pinned below — they reflect the v5 enum order- * (SCENE=0, SHAPE=1, TEXT=2, AUDIO=3, CAPTION=4, GROUP=5) and won't move- * even if the live enum is later renamed/removed.- *- * The mapping (chosen with the user):- * SCENE → Geometry=RECT, +Scene, +ClipsContent- * SHAPE → Geometry=RECT- * TEXT → Geometry=TEXT- * AUDIO → Geometry=RECT, +Audio- * CAPTION → Geometry=TEXT, + ensure Caption preset component is present- * GROUP → Geometry=RECT, +Group- *- * FillType values transfer 1:1 (no reordering) — WAVEFORM is appended to- * PaintType but isn't emitted by any legacy data. We just copy the integer over.- */-const V6_NODE_TYPE_SCENE = 0;-const V6_NODE_TYPE_SHAPE = 1;-const V6_NODE_TYPE_TEXT = 2;-const V6_NODE_TYPE_AUDIO = 3;-const V6_NODE_TYPE_CAPTION = 4;-const V6_NODE_TYPE_GROUP = 5;--const V6_GEOMETRY_RECT = 0;-const V6_GEOMETRY_TEXT = 1;--export async function migrateToV6(tx: Transaction) {- const entities = tx.objectStore('entities');-- let cursor = await entities.openCursor();- while (cursor) {- const record = cursor.value as DBEntity & {- Node?: { type?: number };- Fill?: { type?: number };- };- let changed = false;-- if (record.Node !== undefined) {- const nodeType = record.Node.type ?? V6_NODE_TYPE_SHAPE;-- // Both TEXT and CAPTION nodes get a text geometry — captions are- // just text nodes with a Caption preset component attached.- record.Geometry = nodeType === V6_NODE_TYPE_TEXT || nodeType === V6_NODE_TYPE_CAPTION- ? V6_GEOMETRY_TEXT- : V6_GEOMETRY_RECT;-- if (nodeType === V6_NODE_TYPE_SCENE) {- record.Scene = {};- record.ClipsContent = true;- } else if (nodeType === V6_NODE_TYPE_GROUP) {- record.Group = {};- } else if (nodeType === V6_NODE_TYPE_AUDIO) {- record.Audio = {};- } else if (nodeType === V6_NODE_TYPE_CAPTION) {- // Caption preset config is added on-demand by the sidebar; ensure- // it's present so the new model can detect captions via hasComponent.- if (record.Caption === undefined) {- record.Caption = {};- }- }-- delete record.Node;- changed = true;- }-- if (record.Keyframe !== undefined) {- delete record.Keyframe;- changed = true;- }-- if (record.Fill !== undefined) {- record.Paint = record.Fill.type ?? 0;- delete record.Fill;- changed = true;- }-- if (changed) {- await cursor.update(record);- }- cursor = await cursor.continue();- }-}--/**- * v3 → v4: gradient fills changed shape. The old `ColorStops` aggregate (parallel- * positions/colors/opacities arrays on the fill entity) was replaced by per-stop- * `ColorStop` child entities. Rather than migrate the stops one-by-one (which- * would need to allocate fresh eids and add ChildOf relations), we degrade- * gradient fills to solid fills using the first stop's color. Users can rebuild- * the gradient in the picker if needed.- */-export async function migrateToV4(tx: Transaction) {- const entities = tx.objectStore('entities');-- let cursor = await entities.openCursor();- while (cursor) {- const record = cursor.value as DBEntity & {- ColorStops?: { positions?: number[]; colors?: number[]; opacities?: number[] };- Fill?: { type?: number };- };-- if (record.ColorStops !== undefined) {- const firstColor = record.ColorStops.colors?.[0] ?? 0xFFFFFF;- record.Color = firstColor;- record.Fill = { type: SOLID_FILL_TYPE };- delete record.ColorStops;- await cursor.update(record);- }-- cursor = await cursor.continue();- }-}--/**- * v6 → v7: drop the redundant `Frame`/`InFrames` unit suffix from time fields- * now that frames are the default unit. Pure key renames — values are already- * in frames, so no numeric conversion is needed.- * DelayInFrames → Delay- * Trim.startFrame → Trim.start- * Trim.endFrame → Trim.end- * Transition.durationInFrames → Transition.duration- * Animation.durationInFrames → Animation.duration- * Animation.delayInFrames → Animation.delay- * Keyframe.frame → Keyframe.time- */-export async function migrateToV7(tx: Transaction) {- const entities = tx.objectStore('entities');- let cursor = await entities.openCursor();- while (cursor) {- const record = cursor.value as DBEntity & {- DelayInFrames?: number;- Delay?: number;- Trim?: { startFrame?: number; endFrame?: number; start?: number; end?: number };- Transition?: { type?: number; durationInFrames?: number; duration?: number };- Animation?: {- type?: number; phase?: number;- durationInFrames?: number; delayInFrames?: number;- duration?: number; delay?: number;- };- Keyframe?: { frame?: number; time?: number; value?: number; easing?: string };- };- let changed = false;-- if (record.DelayInFrames !== undefined) {- record.Delay = record.DelayInFrames;- delete record.DelayInFrames;- changed = true;- }-- if (record.Trim) {- if (record.Trim.startFrame !== undefined) {- record.Trim.start = record.Trim.startFrame;- delete record.Trim.startFrame;- changed = true;- }- if (record.Trim.endFrame !== undefined) {- record.Trim.end = record.Trim.endFrame;- delete record.Trim.endFrame;- changed = true;- }- }-- if (record.Transition && record.Transition.durationInFrames !== undefined) {- record.Transition.duration = record.Transition.durationInFrames;- delete record.Transition.durationInFrames;- changed = true;- }-- if (record.Animation) {- if (record.Animation.durationInFrames !== undefined) {- record.Animation.duration = record.Animation.durationInFrames;- delete record.Animation.durationInFrames;- changed = true;- }- if (record.Animation.delayInFrames !== undefined) {- record.Animation.delay = record.Animation.delayInFrames;- delete record.Animation.delayInFrames;- changed = true;- }- }-- if (record.Keyframe && record.Keyframe.frame !== undefined) {- record.Keyframe.time = record.Keyframe.frame;- delete record.Keyframe.frame;- changed = true;- }-- if (changed) await cursor.update(record);- cursor = await cursor.continue();- }-}diff --git a/apps/web/src/components/engine/db/project-db.ts b/apps/web/src/components/engine/db/project-db.tsdeleted file mode 100644index 2aa4b0d9..00000000--- a/apps/web/src/components/engine/db/project-db.ts+++ /dev/null@@ -1,315 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--/**- * IndexedDB persistence for the ECS engine.- *- * Each project gets its own database (`db-{projectId}`).- * Entity records are stored as plain objects keyed by numeric eid- * (converted to string for IDB). World-level state (camera, background)- * lives in the `world` store under a single fixed key.- *- * A `WriteQueue` batches put/delete operations via requestIdleCallback- * so persistence never blocks the render loop.- */--import { deleteDB, openDB } from 'idb';-import { serializeEntity } from '../api';-import { migrateToV2, migrateToV3, migrateToV4, migrateToV5, migrateToV6, migrateToV7 } from './migrations';--import type * as idb from 'idb';-import type { DBEntity, Camera2D } from '../types';-import type { EngineWorld } from '../api/world';-import type { Asset, Folder } from './schemas';-import type { FontSource } from '../font';--if (typeof window !== 'undefined' && typeof requestIdleCallback !== 'function') {- Object.assign(window, { requestIdleCallback: requestAnimationFrame });-}--export const WORLD_STATE_KEY = 'world';-export const DEFAULT_PROJECT_ID = 'V1StGXR8_Z5jdHi6B-myT';--export type DBWorldState = {- id: string; // always WORLD_STATE_KEY- camera: Camera2D;- background: number;-};--export interface EngineDBSchema extends idb.DBSchema {- entities: {- value: DBEntity;- key: string;- };- assets: {- value: Asset;- key: string;- };- folders: {- value: Folder;- key: string;- };- fonts: {- value: FontSource;- key: string;- };- world: {- value: DBWorldState;- key: string;- };-}--const dbPromises = new Map<string, Promise<idb.IDBPDatabase<EngineDBSchema>>>();--const STORE_KEY_PATHS: Record<string, string> = {- entities: 'id',- assets: 'id',- folders: 'id',- fonts: 'source',- world: 'id',-};--/**- * In-memory stand-in for a project database, covering the subset of the idb- * API the engine uses. Backs the session-only default project.- */-function createMemoryDB(): idb.IDBPDatabase<EngineDBSchema> {- const stores = new Map<string, Map<string, unknown>>(- Object.keys(STORE_KEY_PATHS).map((name) => [name, new Map()]),- );-- const objectStore = (name: string) => {- const store = stores.get(name)!;- return {- put: async (value: Record<string, unknown>) => {- const key = String(value[STORE_KEY_PATHS[name]!]);- store.set(key, value);- return key;- },- delete: async (key: string) => {- store.delete(key);- },- };- };-- return {- get: async (name: string, key: string) => stores.get(name)!.get(key),- getAll: async (name: string) => Array.from(stores.get(name)!.values()),- put: (name: string, value: Record<string, unknown>) => objectStore(name).put(value),- delete: (name: string, key: string) => objectStore(name).delete(key),- transaction: () => ({ objectStore, done: Promise.resolve() }),- close: () => { },- } as unknown as idb.IDBPDatabase<EngineDBSchema>;-}--export function getProjectDB(projectId: string, version = 8) {- const dbName = `db-v2-${projectId}`;- let cacheKey = `${dbName}@${version}`;-- if (projectId === DEFAULT_PROJECT_ID) {- cacheKey = `${dbName}@memory`;- }-- const cached = dbPromises.get(cacheKey);- if (cached) return cached;-- if (projectId === DEFAULT_PROJECT_ID) {- const promise = Promise.resolve(createMemoryDB());- dbPromises.set(cacheKey, promise);- return promise;- }-- const promise = openDB<EngineDBSchema>(dbName, version, {- async upgrade(db, oldVersion, _newVersion, tx) {- if (!db.objectStoreNames.contains('entities')) {- db.createObjectStore('entities', { keyPath: 'id' });- }- if (!db.objectStoreNames.contains('assets')) {- db.createObjectStore('assets', { keyPath: 'id' });- }- if (!db.objectStoreNames.contains('folders')) {- db.createObjectStore('folders', { keyPath: 'id' });- }- if (!db.objectStoreNames.contains('fonts')) {- db.createObjectStore('fonts', { keyPath: 'source' });- }- if (!db.objectStoreNames.contains('world')) {- db.createObjectStore('world', { keyPath: 'id' });- }-- if (oldVersion < 2) {- await migrateToV2(tx);- }- if (oldVersion < 3) {- await migrateToV3(tx);- }- if (oldVersion < 4) {- await migrateToV4(tx);- }- if (oldVersion < 5) {- await migrateToV5(tx);- }- if (oldVersion < 6) {- await migrateToV6(tx);- }- if (oldVersion < 7) {- await migrateToV7(tx);- }- },- });-- dbPromises.set(cacheKey, promise);- return promise;-}--/**- * Deletes the per-project IndexedDB database and clears any cached DB handles.- */-export async function deleteProjectDB(projectId: string): Promise<void> {- const dbName = `db-v2-${projectId}`;- const cachePrefix = `${dbName}@`;-- for (const [cacheKey, dbPromise] of dbPromises) {- if (!cacheKey.startsWith(cachePrefix)) continue;-- try {- const db = await dbPromise;- db.close();- } catch {- // Ignore failed opens; cache still needs to be cleared.- }-- dbPromises.delete(cacheKey);- }-- await deleteDB(dbName);-}--// ─── Write queue ─────────────────────────────────────────────────--/**- * Batches put and delete operations into single IDB transactions.- * Uses requestIdleCallback so writes never block the main thread.- */-export class WriteQueue {- private puts = new Map<string, DBEntity>();- private deletes = new Set<string>();- private isWriting = false;- private db: Promise<idb.IDBPDatabase<EngineDBSchema>>;-- public constructor(db: Promise<idb.IDBPDatabase<EngineDBSchema>>) {- this.db = db;- }-- /** Enqueue an entity upsert. */- public scheduleWrite(world: EngineWorld, eid?: number): void {- if (!eid) return;-- this.deletes.delete(eid.toString());- this.puts.set(eid.toString(), serializeEntity(world, eid));- requestIdleCallback(this.flush.bind(this));- }-- /** Enqueue an entity deletion. */- public scheduleDelete(_world: EngineWorld, eid?: number): void {- if (!eid) return;-- this.puts.delete(eid.toString());- this.deletes.add(eid.toString());- requestIdleCallback(this.flush.bind(this));- }-- /** Flush all pending puts and deletes in one transaction. */- public async flush(): Promise<void> {- const db = await this.db;-- if (this.isWriting || (this.puts.size === 0 && this.deletes.size === 0)) {- return;- }-- try {- this.isWriting = true;-- const putData = Array.from(this.puts.values());- const deleteKeys = Array.from(this.deletes);- this.puts.clear();- this.deletes.clear();-- const tx = db.transaction('entities', 'readwrite');-- await Promise.all([- ...putData.map(data => tx.objectStore('entities').put(data)),- ...deleteKeys.map(key => tx.objectStore('entities').delete(key)),- tx.done,- ]);-- // Re-check in case new items were queued during the await- requestIdleCallback(this.flush.bind(this));- } catch (e) {- console.error('[engine] WriteQueue flush failed:', e);- } finally {- this.isWriting = false;- }- }-}--/**- * Persists the single world-state record (camera + background). Unlike the- * entity WriteQueue, there's no key-space to track — every schedule call- * replaces the same row, so we just remember which world is dirty and snapshot- * its current state at flush time.- */-export class WorldStateWriter {- private dirty: EngineWorld | null = null;- private isWriting = false;- private db: Promise<idb.IDBPDatabase<EngineDBSchema>>;-- public constructor(db: Promise<idb.IDBPDatabase<EngineDBSchema>>) {- this.db = db;- }-- /** Schedule a write of the current world state. Rapid calls coalesce. */- public schedule(world: EngineWorld): void {- this.dirty = world;- requestIdleCallback(this.flush.bind(this));- }-- private async flush(): Promise<void> {- if (this.isWriting || !this.dirty) return;-- const world = this.dirty;- this.dirty = null;- this.isWriting = true;-- try {- const db = await this.db;- await db.put('world', {- id: WORLD_STATE_KEY,- camera: { ...world.camera },- background: world.background,- });- } catch (e) {- console.error('[engine] WorldStateWriter flush failed:', e);- } finally {- this.isWriting = false;- // Something dirtied us during the await — re-queue.- if (this.dirty) requestIdleCallback(this.flush.bind(this));- }- }-}--export type Store = {- queue: WriteQueue;- worldState: WorldStateWriter;- db: Promise<idb.IDBPDatabase<EngineDBSchema>>;-};--export function createStore(projectId: string): Store {- const db = getProjectDB(projectId);- return {- queue: new WriteQueue(db),- worldState: new WorldStateWriter(db),- db,- };-}diff --git a/apps/web/src/components/engine/font/utils.ts b/apps/web/src/components/engine/font/utils.tsindex dda16a37..2be504fc 100644--- a/apps/web/src/components/engine/font/utils.ts+++ b/apps/web/src/components/engine/font/utils.ts@@ -105,15 +105,16 @@ export async function loadWebFont(reject(error);});});-- const db = await world.store.db;- await db.put('fonts', font);}+/**+ * Re-loads previously used fonts. Placeholder: projects are held purely in+ * memory, so there is nothing to restore yet.+ */export async function restoreFonts(world: EngineWorld): Promise<void> {- const db = await world.store.db;+ const fonts: types.FontSource[] = [];- for (const font of await db.getAll('fonts')) {+ for (const font of fonts) {if (font.family in WebFonts) {await loadWebFont(world,