import { createRxDatabase, addRxPlugin, RxDatabase, RxCollection, RxJsonSchema } from 'rxdb'; import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie'; import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'; import { RxDBUpdatePlugin } from 'rxdb/plugins/update'; import { RxDBQueryBuilderPlugin } from 'rxdb/plugins/query-builder'; // Add plugins addRxPlugin(RxDBQueryBuilderPlugin); addRxPlugin(RxDBUpdatePlugin); if (import.meta.env.DEV) { addRxPlugin(RxDBDevModePlugin); } // Schema definitions const chatSchema: RxJsonSchema = { title: 'chat schema', version: 0, description: 'describes a chat message', primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, sessionId: { type: 'string' }, role: { type: 'string' }, content: { type: 'string' }, timestamp: { type: 'number' }, status: { type: 'string' }, // sent, pending, error metadata: { type: 'object' } }, required: ['id', 'sessionId', 'role', 'content', 'timestamp'], indexes: ['sessionId', 'timestamp'] }; const workflowSchema: RxJsonSchema = { title: 'workflow schema', version: 0, primaryKey: 'id', type: 'object', properties: { id: { type: 'string', maxLength: 100 }, name: { type: 'string' }, nodes: { type: 'array' }, edges: { type: 'array' }, updatedAt: { type: 'number' } }, required: ['id', 'name', 'nodes', 'edges', 'updatedAt'], indexes: ['updatedAt'] }; // Database type export type MyDatabaseCollections = { chats: RxCollection; workflows: RxCollection; }; export type MyDatabase = RxDatabase; let dbPromise: Promise | null = null; export const getDatabase = async (): Promise => { if (!dbPromise) { dbPromise = createRxDatabase({ name: 'codex_db', storage: getRxStorageDexie(), ignoreDuplicate: true }).then(async (db) => { await db.addCollections({ chats: { schema: chatSchema }, workflows: { schema: workflowSchema } }); return db; }); } return dbPromise; };