@dqcai/sqlite 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- const R=(...h)=>h.map(e=>typeof e=="object"?JSON.stringify(e,null,2):String(e)).join(" ");class M{constructor(e){this.transports=new Map,this.transportFactory=null,this.config=e,this.sessionId=e.sessionId||this.generateSessionId()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getSessionId(){return this.sessionId}renewSession(){return this.sessionId=this.generateSessionId(),this.sessionId}setTransportFactory(e){this.transportFactory=e}addTransport(e){this.transports.set(e.name,e)}removeTransport(e){return this.transports.delete(e)}getTransport(e){return this.transports.get(e)}listTransports(){return Array.from(this.transports.keys())}setModuleConfig(e,t){this.config.modules[e]=t}getModuleConfig(e){return this.config.modules[e]}setGlobalEnabled(e){this.config.enabled=e}isGlobalEnabled(){return this.config.enabled}setDefaultLevel(e){this.config.defaultLevel=e}getConfig(){return JSON.parse(JSON.stringify(this.config))}setMetadata(e){this.config.metadata=Object.assign(Object.assign({},this.config.metadata),e)}shouldLog(e,t){if(!this.config.enabled)return!1;const a=this.config.modules[e];return a?a.enabled&&a.levels.includes(t):this.isLevelEnabled(t,this.config.defaultLevel)}isLevelEnabled(e,t){const a=["trace","debug","info","warn","error"],s=a.indexOf(e),r=a.indexOf(t);return s===-1||r===-1?!1:s>=r}getTransportsForModule(e){const t=this.config.modules[e];return((t==null?void 0:t.transports)||["console"]).map(a=>this.transports.get(a)).filter(a=>a!==void 0)}async sendToTransports(e,t){if(t.length===0)return;const a=t.map(async s=>{try{await s.log(e)}catch(r){console.error(`[UniversalLogger] Transport ${s.name} failed:`,r)}});await Promise.allSettled(a)}async log(e,t,a,s){if(!this.shouldLog(e,t))return;const r={timestamp:new Date().toISOString(),level:t,module:e,message:a,data:s,metadata:this.config.metadata,sessionId:this.sessionId},i=this.getTransportsForModule(e);await this.sendToTransports(r,i)}async trace(e,...t){const a=R(...t);await this.log(e,"trace",a)}async debug(e,...t){const a=R(...t);await this.log(e,"debug",a)}async info(e,...t){const a=R(...t);await this.log(e,"info",a)}async warn(e,...t){const a=R(...t);await this.log(e,"warn",a)}async error(e,...t){const a=R(...t);await this.log(e,"error",a)}async flush(){const e=Array.from(this.transports.values()).filter(t=>typeof t.flush=="function").map(t=>t.flush());await Promise.allSettled(e)}async cleanup(){const e=Array.from(this.transports.values()).filter(t=>typeof t.cleanup=="function").map(t=>t.cleanup());await Promise.allSettled(e)}createModuleLogger(e){return new L(e,this)}}class L{constructor(e,t){this.module=e,this.logger=t}async flush(){await this.logger.flush()}async trace(...e){const t=R(...e);await this.logger.trace(this.module,t)}async debug(...e){const t=R(...e);await this.logger.debug(this.module,t)}async info(...e){const t=R(...e);await this.logger.info(this.module,t)}async warn(...e){const t=R(...e);await this.logger.warn(this.module,t)}async error(...e){const t=R(...e);await this.logger.error(this.module,t)}getModuleName(){return this.module}}class ${constructor(e={}){this.name="console",this.config=Object.assign({colorize:!0,timestamp:!0,prefix:""},e)}log(e){const t=[];this.config.timestamp&&t.push(`[${e.timestamp}]`),this.config.prefix&&t.push(`[${this.config.prefix}]`),t.push(`[${e.module}]`,`[${e.level.toUpperCase()}]`,e.message);const a=t.join(" "),s=e.data?[e.data]:[];this.config.colorize?this.logWithColor(e.level,a,s):this.logWithoutColor(e.level,a,s)}logWithColor(e,t,a){const s={trace:"#999999",debug:"#0066cc",info:"#00cc66",warn:"#ff9900",error:"#cc0000"}[e];console.log(`%c${t}`,`color: ${s}`,...a)}logWithoutColor(e,t,a){switch(e){case"error":console.error(t,...a);break;case"warn":console.warn(t,...a);break;case"info":console.info(t,...a);break;default:console.log(t,...a)}}}class T{constructor(){this.config={enabled:!0,defaultLevel:"info",modules:{}}}setEnabled(e){return this.config.enabled=e,this}setDefaultLevel(e){return this.config.defaultLevel=e,this}setSessionId(e){return this.config.sessionId=e,this}setMetadata(e){return this.config.metadata=e,this}addModule(e,t=!0,a=["info","warn","error"],s=["console"]){return this.config.modules[e]={enabled:t,levels:a,transports:s},this}build(){return JSON.parse(JSON.stringify(this.config))}}class k{static createDevelopmentConfig(){return new T().setEnabled(!0).setDefaultLevel("debug").addModule("DatabaseManager",!0,["debug","info","warn","error"],["console"]).addModule("ApiClient",!0,["info","warn","error"],["console"]).addModule("Cache",!0,["debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule("DatabaseManager",!0,["error"],["console"]).addModule("ApiClient",!0,["warn","error"],["console"]).addModule("Cache",!1,[],[]).build()}static createCustomConfig(e=!1){return e?k.createDevelopmentConfig():k.createProductionConfig()}}const _=h=>{const e=h||k.createDevelopmentConfig(),t=new M(e);return t.addTransport(new $),t};var b;(function(h){h.DATABASE_MANAGER="DatabaseManager",h.DATABASE_FACTORY="DatabaseFactory",h.UNIVERSAL_DAO="UniversalDAO",h.BASE_SERVICE="BaseService",h.SERVICE_MANAGER="ServiceManager",h.QUERY_BUILDER="QueryBuilder",h.BASE_ADAPTER="BaseAdapter",h.UNIVERSAL_SQLITE="UniversalSQLite",h.TRANSACTION="Transaction",h.CONNECTION="Connection"})(b||(b={}));class u{static createDefaultConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule(b.UNIVERSAL_SQLITE,!0,["warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["warn","error"],["console"]).build()}static initialize(e){const t=e||u.createDefaultConfig();return u.currentConfig=t,t.enabled&&console.debug("SQLiteLoggerConfig.initialize()",JSON.stringify(t,null,2)),u.instance=_(t),u.instance}static getInstance(){return u.currentConfig&&u.currentConfig.enabled&&(u.currentConfig.defaultLevel==="trace"||u.currentConfig.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.getInstance()",JSON.stringify(u.currentConfig,null,2)),u.instance?u.instance:u.initialize()}static updateConfiguration(e){e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(e,null,2)),u.currentConfig=e,u.instance=_(e),e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug"||e.defaultLevel==="info")&&console.log("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(u.instance,null,2))}static setEnabled(e){u.currentConfig&&(u.currentConfig.enabled=e,u.updateConfiguration(u.currentConfig))}static enableModule(e,t,a){u.currentConfig&&u.currentConfig.modules&&(u.currentConfig.modules[e]={enabled:!0,levels:t||["debug","info","warn","error"],appenders:a||["console"]},u.updateConfiguration(u.currentConfig))}static disableModule(e){u.currentConfig&&u.currentConfig.modules&&(u.currentConfig.modules[e]={enabled:!1},u.updateConfiguration(u.currentConfig))}static createDebugConfig(){return new T().setEnabled(!0).setDefaultLevel("trace").addModule(b.UNIVERSAL_SQLITE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["trace","debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule(b.UNIVERSAL_SQLITE,!0,["error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["error"],["console"]).addModule(b.BASE_SERVICE,!0,["error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["error"],["console"]).addModule(b.QUERY_BUILDER,!0,["error"],["console"]).addModule(b.BASE_ADAPTER,!0,["warn","error"],["console"]).build()}static reset(){return u.initialize()}}u.instance=null,u.currentConfig=null;const z=u.getInstance(),w=h=>{const e=u.getInstance();return{trace:(t,...a)=>e.trace(h,t,...a),debug:(t,...a)=>e.debug(h,t,...a),info:(t,...a)=>e.info(h,t,...a),warn:(t,...a)=>e.warn(h,t,...a),error:(t,...a)=>e.error(h,t,...a)}};class F{constructor(e,t,a){var s,r;this.adapter=e,this.dbPath=t,this.options=a,this.connection=null,this.isConnected=!1,this.inTransaction=!1,this.typeMappingConfig=null,this.createIfNotExists=!1,this.forceRecreate=!1,this.logger=w(b.UNIVERSAL_DAO),this.createIfNotExists=(s=a==null?void 0:a.createIfNotExists)!==null&&s!==void 0?s:!1,this.forceRecreate=(r=a==null?void 0:a.forceRecreate)!==null&&r!==void 0?r:!1,this.logger.trace("UniversalDAO constructor initialized",{dbPath:this.dbPath,createIfNotExists:this.createIfNotExists,forceRecreate:this.forceRecreate})}async connect(){if(this.logger.trace("Attempting to connect to database",{dbPath:this.dbPath}),this.isConnected){this.logger.debug("Already connected to database, skipping connection");return}try{this.connection=await this.adapter.connect(this.dbPath),this.isConnected=!0,this.logger.info("Successfully connected to database",{dbPath:this.dbPath})}catch(e){throw this.logger.error("Failed to connect to database",{dbPath:this.dbPath,error:e instanceof Error?e.message:String(e)}),e}}async disconnect(){if(this.logger.trace("Attempting to disconnect from database"),this.connection&&this.isConnected)try{await this.connection.close(),this.connection=null,this.isConnected=!1,this.logger.info("Successfully disconnected from database")}catch(e){throw this.logger.error("Error during database disconnection",{error:e instanceof Error?e.message:String(e)}),e}else this.logger.debug("Database was not connected, nothing to disconnect")}async close(){this.logger.trace("Closing database connection"),await this.disconnect()}setTypeMappingConfig(e){this.logger.trace("Setting type mapping configuration",{config:e}),this.typeMappingConfig=e,this.logger.debug("Type mapping configuration updated")}convertToSQLiteType(e){if(this.logger.trace("Converting generic type to SQLite type",{genericType:e}),!this.typeMappingConfig||!this.typeMappingConfig.sqlite){const a=this.getDefaultSQLiteType(e);return this.logger.debug("Using default type mapping",{genericType:e,sqliteType:a}),a}const t=this.typeMappingConfig.sqlite[e.toLowerCase()]||"TEXT";return this.logger.debug("Using custom type mapping",{genericType:e,sqliteType:t}),t}getDefaultSQLiteType(e){return{string:"TEXT",varchar:"TEXT",char:"TEXT",email:"TEXT",url:"TEXT",uuid:"TEXT",integer:"INTEGER",bigint:"INTEGER",smallint:"INTEGER",tinyint:"INTEGER",decimal:"REAL",numeric:"REAL",float:"REAL",double:"REAL",boolean:"INTEGER",timestamp:"TEXT",datetime:"TEXT",date:"TEXT",time:"TEXT",json:"TEXT",array:"TEXT",blob:"BLOB",binary:"BLOB"}[e.toLowerCase()]||"TEXT"}processColumnDefinition(e){this.logger.trace("Processing column definition",{columnName:e.name,originalType:e.type});const t=Object.assign({},e);t.type=this.convertToSQLiteType(e.type);const a=[];if(e.constraints){this.logger.trace("Processing column constraints",{columnName:e.name,constraints:e.constraints});const s=e.constraints.toUpperCase().split(" ");s.includes("PRIMARY")&&(a.push("PRIMARY KEY"),t.primary_key=!0),(s.includes("AUTO_INCREMENT")||s.includes("AUTOINCREMENT"))&&(t.primary_key&&a.push("AUTOINCREMENT"),t.auto_increment=!0),s.includes("NOT")&&s.includes("NULL")&&(a.push("NOT NULL"),t.nullable=!1),s.includes("UNIQUE")&&(t.primary_key||a.push("UNIQUE"),t.unique=!0);const r=s.indexOf("DEFAULT");if(r!==-1&&s.length>r+1){const i=s[r+1];a.push(`DEFAULT ${i}`),t.default=i}}return t.option_key=a.join(" ").trim(),this.logger.debug("Column definition processed",{columnName:e.name,finalType:t.type,options:t.option_key}),t}async initializeFromSchema(e){var t,a;this.logger.info("Initializing database schema",{schemaVersion:e.version,tableCount:Object.keys(e.schemas).length}),this.ensureConnected();let s=!1;try{const r=await this.execute("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1");s=r.rows.length>0,s&&this.logger.debug("Existing schema detected",{currentVersion:(t=r.rows[0])===null||t===void 0?void 0:t.version})}catch(r){this.logger.debug("No existing schema found or schema info table missing"),s=!1}if(s&&!this.createIfNotExists&&!this.forceRecreate){this.logger.info("Schema exists and no recreation options set, using existing schema"),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);return}s&&this.forceRecreate&&(this.logger.warn("Force recreate option enabled, dropping all existing tables"),await this.dropAllTables()),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);try{this.logger.debug("Enabling foreign key constraints"),await this.execute("PRAGMA foreign_keys = ON")}catch(r){this.logger.warn("Failed to enable foreign key constraints",{error:r instanceof Error?r.message:String(r)})}await this.beginTransaction();try{this.logger.info("Creating tables from schema");for(const[r,i]of Object.entries(e.schemas)){this.logger.debug("Creating table",{tableName:r,columnCount:i.cols.length});const o={name:r,cols:i.cols.map(l=>this.processColumnDefinition(l)),description:i.description,indexes:i.indexes,foreign_keys:i.foreign_keys};await this.createTableWithForeignKeys(o)}this.logger.info("Creating indexes for tables");for(const[r,i]of Object.entries(e.schemas))!((a=i.indexes)===null||a===void 0)&&a.length&&(this.logger.debug("Creating indexes for table",{tableName:r,indexCount:i.indexes.length}),await this.createIndexesForTable(r,i.indexes));await this.setSchemaVersion(e.version),await this.commitTransaction(),this.logger.info("Schema initialization completed successfully",{version:e.version})}catch(r){throw this.logger.error("Schema initialization failed, rolling back transaction",{error:r instanceof Error?r.message:String(r)}),await this.rollbackTransaction(),r}}async dropAllTables(){this.logger.info("Dropping all existing tables");const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");this.logger.debug("Found tables to drop",{tableCount:e.rows.length}),await this.beginTransaction();try{for(const t of e.rows)this.logger.trace("Dropping table",{tableName:t.name}),await this.execute(`DROP TABLE IF EXISTS ${t.name}`);await this.commitTransaction(),this.logger.info("All tables dropped successfully")}catch(t){throw this.logger.error("Failed to drop tables, rolling back",{error:t instanceof Error?t.message:String(t)}),await this.rollbackTransaction(),t}}async createTableWithForeignKeys(e){this.logger.trace("Creating table with foreign keys",{tableName:e.name});const t=e.cols.map(i=>`${i.name} ${i.type} ${i.option_key||""}`.trim()),a=[];if(e.foreign_keys){this.logger.debug("Processing foreign keys",{tableName:e.name,fkCount:e.foreign_keys.length});for(const i of e.foreign_keys){let o=`FOREIGN KEY (${i.column}) REFERENCES ${i.references.table}(${i.references.column})`;i.on_delete&&(o+=` ON DELETE ${i.on_delete}`),i.on_update&&(o+=` ON UPDATE ${i.on_update}`),a.push(o)}}const s=[...t,...a],r=`CREATE TABLE IF NOT EXISTS ${e.name} (${s.join(", ")})`;try{await this.execute(r),this.logger.debug("Table created successfully",{tableName:e.name})}catch(i){throw this.logger.error("Failed to create table",{tableName:e.name,sql:r,error:i instanceof Error?i.message:String(i)}),i}}async createIndexesForTable(e,t){this.logger.trace("Creating indexes for table",{tableName:e,indexCount:t.length});for(const a of t){const s=a.columns.join(", "),r=a.unique||!1,i=`CREATE ${r?"UNIQUE":""} INDEX IF NOT EXISTS ${a.name} ON ${e} (${s})`;try{await this.execute(i),this.logger.debug("Index created successfully",{indexName:a.name,tableName:e,columns:a.columns,unique:r})}catch(o){throw this.logger.error("Failed to create index",{indexName:a.name,tableName:e,sql:i,error:o instanceof Error?o.message:String(o)}),o}}}async beginTransaction(){if(this.logger.trace("Beginning transaction"),this.inTransaction){const e=new Error("Transaction already in progress");throw this.logger.error("Cannot begin transaction",{error:e.message}),e}try{await this.execute("BEGIN TRANSACTION"),this.inTransaction=!0,this.logger.debug("Transaction started successfully")}catch(e){throw this.logger.error("Failed to begin transaction",{error:e instanceof Error?e.message:String(e)}),e}}async commitTransaction(){if(this.logger.trace("Committing transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot commit transaction",{error:e.message}),e}try{await this.execute("COMMIT"),this.inTransaction=!1,this.logger.debug("Transaction committed successfully")}catch(e){throw this.logger.error("Failed to commit transaction",{error:e instanceof Error?e.message:String(e)}),e}}async rollbackTransaction(){if(this.logger.trace("Rolling back transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot rollback transaction",{error:e.message}),e}try{await this.execute("ROLLBACK"),this.inTransaction=!1,this.logger.debug("Transaction rolled back successfully")}catch(e){throw this.logger.error("Failed to rollback transaction",{error:e instanceof Error?e.message:String(e)}),e}}async getSchemaVersion(){this.logger.trace("Getting schema version");try{const e=(await this.getRst("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).version||"0";return this.logger.debug("Schema version retrieved",{version:e}),e}catch(e){return this.logger.debug("No schema version found, returning default",{defaultVersion:"0"}),"0"}}async setSchemaVersion(e){this.logger.trace("Setting schema version",{version:e});try{await this.execute(`CREATE TABLE IF NOT EXISTS _schema_info (
1
+ const R=(...h)=>h.map(e=>typeof e=="object"?JSON.stringify(e,null,2):String(e)).join(" ");class M{constructor(e){this.transports=new Map,this.transportFactory=null,this.config=e,this.sessionId=e.sessionId||this.generateSessionId()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getSessionId(){return this.sessionId}renewSession(){return this.sessionId=this.generateSessionId(),this.sessionId}setTransportFactory(e){this.transportFactory=e}addTransport(e){this.transports.set(e.name,e)}removeTransport(e){return this.transports.delete(e)}getTransport(e){return this.transports.get(e)}listTransports(){return Array.from(this.transports.keys())}setModuleConfig(e,t){this.config.modules[e]=t}getModuleConfig(e){return this.config.modules[e]}setGlobalEnabled(e){this.config.enabled=e}isGlobalEnabled(){return this.config.enabled}setDefaultLevel(e){this.config.defaultLevel=e}getConfig(){return JSON.parse(JSON.stringify(this.config))}setMetadata(e){this.config.metadata=Object.assign(Object.assign({},this.config.metadata),e)}shouldLog(e,t){if(!this.config.enabled)return!1;const a=this.config.modules[e];return a?a.enabled&&a.levels.includes(t):this.isLevelEnabled(t,this.config.defaultLevel)}isLevelEnabled(e,t){const a=["trace","debug","info","warn","error"],s=a.indexOf(e),r=a.indexOf(t);return s===-1||r===-1?!1:s>=r}getTransportsForModule(e){const t=this.config.modules[e];return((t==null?void 0:t.transports)||["console"]).map(a=>this.transports.get(a)).filter(a=>a!==void 0)}async sendToTransports(e,t){if(t.length===0)return;const a=t.map(async s=>{try{await s.log(e)}catch(r){console.error(`[UniversalLogger] Transport ${s.name} failed:`,r)}});await Promise.allSettled(a)}async log(e,t,a,s){if(!this.shouldLog(e,t))return;const r={timestamp:new Date().toISOString(),level:t,module:e,message:a,data:s,metadata:this.config.metadata,sessionId:this.sessionId},i=this.getTransportsForModule(e);await this.sendToTransports(r,i)}async trace(e,...t){const a=R(...t);await this.log(e,"trace",a)}async debug(e,...t){const a=R(...t);await this.log(e,"debug",a)}async info(e,...t){const a=R(...t);await this.log(e,"info",a)}async warn(e,...t){const a=R(...t);await this.log(e,"warn",a)}async error(e,...t){const a=R(...t);await this.log(e,"error",a)}async flush(){const e=Array.from(this.transports.values()).filter(t=>typeof t.flush=="function").map(t=>t.flush());await Promise.allSettled(e)}async cleanup(){const e=Array.from(this.transports.values()).filter(t=>typeof t.cleanup=="function").map(t=>t.cleanup());await Promise.allSettled(e)}createModuleLogger(e){return new L(e,this)}}class L{constructor(e,t){this.module=e,this.logger=t}async flush(){await this.logger.flush()}async trace(...e){const t=R(...e);await this.logger.trace(this.module,t)}async debug(...e){const t=R(...e);await this.logger.debug(this.module,t)}async info(...e){const t=R(...e);await this.logger.info(this.module,t)}async warn(...e){const t=R(...e);await this.logger.warn(this.module,t)}async error(...e){const t=R(...e);await this.logger.error(this.module,t)}getModuleName(){return this.module}}class ${constructor(e={}){this.name="console",this.config=Object.assign({colorize:!0,timestamp:!0,prefix:""},e)}log(e){const t=[];this.config.timestamp&&t.push(`[${e.timestamp}]`),this.config.prefix&&t.push(`[${this.config.prefix}]`),t.push(`[${e.module}]`,`[${e.level.toUpperCase()}]`,e.message);const a=t.join(" "),s=e.data?[e.data]:[];this.config.colorize?this.logWithColor(e.level,a,s):this.logWithoutColor(e.level,a,s)}logWithColor(e,t,a){const s={trace:"#999999",debug:"#0066cc",info:"#00cc66",warn:"#ff9900",error:"#cc0000"}[e];console.log(`%c${t}`,`color: ${s}`,...a)}logWithoutColor(e,t,a){switch(e){case"error":console.error(t,...a);break;case"warn":console.warn(t,...a);break;case"info":console.info(t,...a);break;default:console.log(t,...a)}}}class T{constructor(){this.config={enabled:!0,defaultLevel:"info",modules:{}}}setEnabled(e){return this.config.enabled=e,this}setDefaultLevel(e){return this.config.defaultLevel=e,this}setSessionId(e){return this.config.sessionId=e,this}setMetadata(e){return this.config.metadata=e,this}addModule(e,t=!0,a=["info","warn","error"],s=["console"]){return this.config.modules[e]={enabled:t,levels:a,transports:s},this}build(){return JSON.parse(JSON.stringify(this.config))}}class k{static createDevelopmentConfig(){return new T().setEnabled(!0).setDefaultLevel("debug").addModule("DatabaseManager",!0,["debug","info","warn","error"],["console"]).addModule("ApiClient",!0,["info","warn","error"],["console"]).addModule("Cache",!0,["debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule("DatabaseManager",!0,["error"],["console"]).addModule("ApiClient",!0,["warn","error"],["console"]).addModule("Cache",!1,[],[]).build()}static createCustomConfig(e=!1){return e?k.createDevelopmentConfig():k.createProductionConfig()}}const _=h=>{const e=h||k.createDevelopmentConfig(),t=new M(e);return t.addTransport(new $),t};var b;(function(h){h.DATABASE_MANAGER="DatabaseManager",h.DATABASE_FACTORY="DatabaseFactory",h.UNIVERSAL_DAO="UniversalDAO",h.BASE_SERVICE="BaseService",h.SERVICE_MANAGER="ServiceManager",h.QUERY_BUILDER="QueryBuilder",h.BASE_ADAPTER="BaseAdapter",h.UNIVERSAL_SQLITE="UniversalSQLite",h.TRANSACTION="Transaction",h.CONNECTION="Connection"})(b||(b={}));class z{constructor(e){this.moduleName=e}trace(e,...t){d.getInstance().trace(this.moduleName,e,...t)}debug(e,...t){d.getInstance().debug(this.moduleName,e,...t)}info(e,...t){d.getInstance().info(this.moduleName,e,...t)}warn(e,...t){d.getInstance().warn(this.moduleName,e,...t)}error(e,...t){d.getInstance().error(this.moduleName,e,...t)}}class d{static createDefaultConfig(){return new T().setEnabled(!0).setDefaultLevel("warn").addModule(b.UNIVERSAL_SQLITE,!0,["warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["warn","error"],["console"]).build()}static initialize(e){const t=e||d.createDefaultConfig();return d.currentConfig=t,t.enabled&&(t.defaultLevel==="trace"||t.defaultLevel==="debug")&&console.debug(`SQLiteLoggerConfig.initialize() with ${e?"CUSTOM":"default"} config`),d.instance=_(t),d.instance}static getInstance(){return d.instance?d.instance:d.initialize()}static updateConfiguration(e){e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug")&&console.debug("SQLiteLoggerConfig.updateConfiguration()",JSON.stringify(e,null,2)),d.currentConfig=e,d.instance=_(e),e&&e.enabled&&(e.defaultLevel==="trace"||e.defaultLevel==="debug"||e.defaultLevel==="info")&&console.log("SQLiteLoggerConfig.updateConfiguration() - Configuration updated. Proxy loggers will use new settings automatically.",`Active proxies: ${Array.from(d.proxyInstances.keys())}`)}static setEnabled(e){d.currentConfig&&(d.currentConfig.enabled=e,d.updateConfiguration(d.currentConfig))}static enableModule(e,t,a){d.currentConfig&&d.currentConfig.modules&&(d.currentConfig.modules[e]={enabled:!0,levels:t||["debug","info","warn","error"],appenders:a||["console"]},d.updateConfiguration(d.currentConfig))}static disableModule(e){d.currentConfig&&d.currentConfig.modules&&(d.currentConfig.modules[e]={enabled:!1},d.updateConfiguration(d.currentConfig))}static createDebugConfig(){return new T().setEnabled(!0).setDefaultLevel("trace").addModule(b.UNIVERSAL_SQLITE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_SERVICE,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.QUERY_BUILDER,!0,["trace","debug","info","warn","error"],["console"]).addModule(b.BASE_ADAPTER,!0,["trace","debug","info","warn","error"],["console"]).build()}static createProductionConfig(){return new T().setEnabled(!0).setDefaultLevel("error").addModule(b.UNIVERSAL_SQLITE,!0,["error"],["console"]).addModule(b.DATABASE_MANAGER,!0,["error"],["console"]).addModule(b.DATABASE_FACTORY,!0,["error"],["console"]).addModule(b.UNIVERSAL_DAO,!0,["error"],["console"]).addModule(b.BASE_SERVICE,!0,["error"],["console"]).addModule(b.SERVICE_MANAGER,!0,["error"],["console"]).addModule(b.QUERY_BUILDER,!0,["error"],["console"]).addModule(b.BASE_ADAPTER,!0,["error"],["console"]).build()}static reset(){return d.initialize()}static getActiveProxyModules(){return Array.from(d.proxyInstances.keys())}static getCurrentConfig(){return d.currentConfig?Object.assign({},d.currentConfig):null}}d.instance=null,d.currentConfig=null,d.proxyInstances=new Map;const j=d.getInstance(),w=h=>{if(d.proxyInstances.has(h))return d.proxyInstances.get(h);const e=new z(h);return d.proxyInstances.set(h,e),e};class x{constructor(e,t,a){var s,r;this.adapter=e,this.dbPath=t,this.options=a,this.connection=null,this.isConnected=!1,this.inTransaction=!1,this.typeMappingConfig=null,this.createIfNotExists=!1,this.forceRecreate=!1,this.logger=w(b.UNIVERSAL_DAO),this.createIfNotExists=(s=a==null?void 0:a.createIfNotExists)!==null&&s!==void 0?s:!1,this.forceRecreate=(r=a==null?void 0:a.forceRecreate)!==null&&r!==void 0?r:!1,this.logger.trace("UniversalDAO constructor initialized",{dbPath:this.dbPath,createIfNotExists:this.createIfNotExists,forceRecreate:this.forceRecreate})}async connect(){if(this.logger.trace("Attempting to connect to database",{dbPath:this.dbPath}),this.isConnected){this.logger.debug("Already connected to database, skipping connection");return}try{this.connection=await this.adapter.connect(this.dbPath),this.isConnected=!0,this.logger.info("Successfully connected to database",{dbPath:this.dbPath})}catch(e){throw this.logger.error("Failed to connect to database",{dbPath:this.dbPath,error:e instanceof Error?e.message:String(e)}),e}}async disconnect(){if(this.logger.trace("Attempting to disconnect from database"),this.connection&&this.isConnected)try{await this.connection.close(),this.connection=null,this.isConnected=!1,this.logger.info("Successfully disconnected from database")}catch(e){throw this.logger.error("Error during database disconnection",{error:e instanceof Error?e.message:String(e)}),e}else this.logger.debug("Database was not connected, nothing to disconnect")}async close(){this.logger.trace("Closing database connection"),await this.disconnect()}setTypeMappingConfig(e){this.logger.trace("Setting type mapping configuration",{config:e}),this.typeMappingConfig=e,this.logger.debug("Type mapping configuration updated")}convertToSQLiteType(e){if(this.logger.trace("Converting generic type to SQLite type",{genericType:e}),!this.typeMappingConfig||!this.typeMappingConfig.sqlite){const a=this.getDefaultSQLiteType(e);return this.logger.debug("Using default type mapping",{genericType:e,sqliteType:a}),a}const t=this.typeMappingConfig.sqlite[e.toLowerCase()]||"TEXT";return this.logger.debug("Using custom type mapping",{genericType:e,sqliteType:t}),t}getDefaultSQLiteType(e){return{string:"TEXT",varchar:"TEXT",char:"TEXT",email:"TEXT",url:"TEXT",uuid:"TEXT",integer:"INTEGER",bigint:"INTEGER",smallint:"INTEGER",tinyint:"INTEGER",decimal:"REAL",numeric:"REAL",float:"REAL",double:"REAL",boolean:"INTEGER",timestamp:"TEXT",datetime:"TEXT",date:"TEXT",time:"TEXT",json:"TEXT",array:"TEXT",blob:"BLOB",binary:"BLOB"}[e.toLowerCase()]||"TEXT"}processColumnDefinition(e){this.logger.trace("Processing column definition",{columnName:e.name,originalType:e.type});const t=Object.assign({},e);t.type=this.convertToSQLiteType(e.type);const a=[];if(e.constraints){this.logger.trace("Processing column constraints",{columnName:e.name,constraints:e.constraints});const s=e.constraints.toUpperCase().split(" ");s.includes("PRIMARY")&&(a.push("PRIMARY KEY"),t.primary_key=!0),(s.includes("AUTO_INCREMENT")||s.includes("AUTOINCREMENT"))&&(t.primary_key&&a.push("AUTOINCREMENT"),t.auto_increment=!0),s.includes("NOT")&&s.includes("NULL")&&(a.push("NOT NULL"),t.nullable=!1),s.includes("UNIQUE")&&(t.primary_key||a.push("UNIQUE"),t.unique=!0);const r=s.indexOf("DEFAULT");if(r!==-1&&s.length>r+1){const i=s[r+1];a.push(`DEFAULT ${i}`),t.default=i}}return t.option_key=a.join(" ").trim(),this.logger.debug("Column definition processed",{columnName:e.name,finalType:t.type,options:t.option_key}),t}async initializeFromSchema(e){var t,a;this.logger.info("Initializing database schema",{schemaVersion:e.version,tableCount:Object.keys(e.schemas).length}),this.ensureConnected();let s=!1;try{const r=await this.execute("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1");s=r.rows.length>0,s&&this.logger.debug("Existing schema detected",{currentVersion:(t=r.rows[0])===null||t===void 0?void 0:t.version})}catch(r){this.logger.debug("No existing schema found or schema info table missing"),s=!1}if(s&&!this.createIfNotExists&&!this.forceRecreate){this.logger.info("Schema exists and no recreation options set, using existing schema"),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);return}s&&this.forceRecreate&&(this.logger.warn("Force recreate option enabled, dropping all existing tables"),await this.dropAllTables()),e.type_mapping&&this.setTypeMappingConfig(e.type_mapping);try{this.logger.debug("Enabling foreign key constraints"),await this.execute("PRAGMA foreign_keys = ON")}catch(r){this.logger.warn("Failed to enable foreign key constraints",{error:r instanceof Error?r.message:String(r)})}await this.beginTransaction();try{this.logger.info("Creating tables from schema");for(const[r,i]of Object.entries(e.schemas)){this.logger.debug("Creating table",{tableName:r,columnCount:i.cols.length});const o={name:r,cols:i.cols.map(l=>this.processColumnDefinition(l)),description:i.description,indexes:i.indexes,foreign_keys:i.foreign_keys};await this.createTableWithForeignKeys(o)}this.logger.info("Creating indexes for tables");for(const[r,i]of Object.entries(e.schemas))!((a=i.indexes)===null||a===void 0)&&a.length&&(this.logger.debug("Creating indexes for table",{tableName:r,indexCount:i.indexes.length}),await this.createIndexesForTable(r,i.indexes));await this.setSchemaVersion(e.version),await this.commitTransaction(),this.logger.info("Schema initialization completed successfully",{version:e.version})}catch(r){throw this.logger.error("Schema initialization failed, rolling back transaction",{error:r instanceof Error?r.message:String(r)}),await this.rollbackTransaction(),r}}async dropAllTables(){this.logger.info("Dropping all existing tables");const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");this.logger.debug("Found tables to drop",{tableCount:e.rows.length}),await this.beginTransaction();try{for(const t of e.rows)this.logger.trace("Dropping table",{tableName:t.name}),await this.execute(`DROP TABLE IF EXISTS ${t.name}`);await this.commitTransaction(),this.logger.info("All tables dropped successfully")}catch(t){throw this.logger.error("Failed to drop tables, rolling back",{error:t instanceof Error?t.message:String(t)}),await this.rollbackTransaction(),t}}async createTableWithForeignKeys(e){this.logger.trace("Creating table with foreign keys",{tableName:e.name});const t=e.cols.map(i=>`${i.name} ${i.type} ${i.option_key||""}`.trim()),a=[];if(e.foreign_keys){this.logger.debug("Processing foreign keys",{tableName:e.name,fkCount:e.foreign_keys.length});for(const i of e.foreign_keys){let o=`FOREIGN KEY (${i.column}) REFERENCES ${i.references.table}(${i.references.column})`;i.on_delete&&(o+=` ON DELETE ${i.on_delete}`),i.on_update&&(o+=` ON UPDATE ${i.on_update}`),a.push(o)}}const s=[...t,...a],r=`CREATE TABLE IF NOT EXISTS ${e.name} (${s.join(", ")})`;try{await this.execute(r),this.logger.debug("Table created successfully",{tableName:e.name})}catch(i){throw this.logger.error("Failed to create table",{tableName:e.name,sql:r,error:i instanceof Error?i.message:String(i)}),i}}async createIndexesForTable(e,t){this.logger.trace("Creating indexes for table",{tableName:e,indexCount:t.length});for(const a of t){const s=a.columns.join(", "),r=a.unique||!1,i=`CREATE ${r?"UNIQUE":""} INDEX IF NOT EXISTS ${a.name} ON ${e} (${s})`;try{await this.execute(i),this.logger.debug("Index created successfully",{indexName:a.name,tableName:e,columns:a.columns,unique:r})}catch(o){throw this.logger.error("Failed to create index",{indexName:a.name,tableName:e,sql:i,error:o instanceof Error?o.message:String(o)}),o}}}async beginTransaction(){if(this.logger.trace("Beginning transaction"),this.inTransaction){const e=new Error("Transaction already in progress");throw this.logger.error("Cannot begin transaction",{error:e.message}),e}try{await this.execute("BEGIN TRANSACTION"),this.inTransaction=!0,this.logger.debug("Transaction started successfully")}catch(e){throw this.logger.error("Failed to begin transaction",{error:e instanceof Error?e.message:String(e)}),e}}async commitTransaction(){if(this.logger.trace("Committing transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot commit transaction",{error:e.message}),e}try{await this.execute("COMMIT"),this.inTransaction=!1,this.logger.debug("Transaction committed successfully")}catch(e){throw this.logger.error("Failed to commit transaction",{error:e instanceof Error?e.message:String(e)}),e}}async rollbackTransaction(){if(this.logger.trace("Rolling back transaction"),!this.inTransaction){const e=new Error("No transaction in progress");throw this.logger.error("Cannot rollback transaction",{error:e.message}),e}try{await this.execute("ROLLBACK"),this.inTransaction=!1,this.logger.debug("Transaction rolled back successfully")}catch(e){throw this.logger.error("Failed to rollback transaction",{error:e instanceof Error?e.message:String(e)}),e}}async getSchemaVersion(){this.logger.trace("Getting schema version");try{const e=(await this.getRst("SELECT version FROM _schema_info ORDER BY applied_at DESC LIMIT 1")).version||"0";return this.logger.debug("Schema version retrieved",{version:e}),e}catch(e){return this.logger.debug("No schema version found, returning default",{defaultVersion:"0"}),"0"}}async setSchemaVersion(e){this.logger.trace("Setting schema version",{version:e});try{await this.execute(`CREATE TABLE IF NOT EXISTS _schema_info (
2
2
  version TEXT NOT NULL,
3
3
  applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
4
- )`),await this.execute("INSERT INTO _schema_info (version) VALUES (?)",[e]),this.logger.info("Schema version set successfully",{version:e})}catch(t){throw this.logger.error("Failed to set schema version",{version:e,error:t instanceof Error?t.message:String(t)}),t}}async insert(e){this.logger.trace("Performing insert operation",{tableName:e.name});const t=e.cols.filter(o=>o.value!==void 0&&o.value!==null);if(t.length===0){const o=new Error("No valid columns to insert");throw this.logger.error("Insert operation failed",{tableName:e.name,error:o.message}),o}const a=t.map(o=>o.name).join(", "),s=t.map(()=>"?").join(", "),r=t.map(o=>typeof o.value=="object"?JSON.stringify(o.value):o.value),i=`INSERT INTO ${e.name} (${a}) VALUES (${s})`;this.logger.debug("Executing insert query",{tableName:e.name,columnCount:t.length,sql:i});try{const o=await this.execute(i,r);return this.logger.info("Insert operation completed successfully",{tableName:e.name,rowsAffected:o.rowsAffected,lastInsertRowid:o.lastInsertRowId}),o}catch(o){throw this.logger.error("Insert operation failed",{tableName:e.name,sql:i,error:o instanceof Error?o.message:String(o)}),o}}async update(e){var t;this.logger.trace("Performing update operation",{tableName:e.name});const a=e.cols.filter(l=>{var m;return l.value!==void 0&&!(!((m=e.wheres)===null||m===void 0)&&m.some(f=>f.name===l.name))});if(a.length===0){const l=new Error("No columns to update");throw this.logger.error("Update operation failed",{tableName:e.name,error:l.message}),l}const s=a.map(l=>`${l.name} = ?`).join(", "),r=a.map(l=>typeof l.value=="object"?JSON.stringify(l.value):l.value);let i=`UPDATE ${e.name} SET ${s}`;const o=this.buildWhereClause(e.wheres);if(!o.sql){const l=new Error("WHERE clause is required for UPDATE operation");throw this.logger.error("Update operation failed",{tableName:e.name,error:l.message}),l}i+=o.sql,r.push(...o.params),this.logger.debug("Executing update query",{tableName:e.name,updateColumnCount:a.length,whereConditions:((t=e.wheres)===null||t===void 0?void 0:t.length)||0,sql:i});try{const l=await this.execute(i,r);return this.logger.info("Update operation completed successfully",{tableName:e.name,rowsAffected:l.rowsAffected}),l}catch(l){throw this.logger.error("Update operation failed",{tableName:e.name,sql:i,error:l instanceof Error?l.message:String(l)}),l}}async delete(e){var t;this.logger.trace("Performing delete operation",{tableName:e.name});let a=`DELETE FROM ${e.name}`;const s=this.buildWhereClause(e.wheres);if(!s.sql){const r=new Error("WHERE clause is required for DELETE operation");throw this.logger.error("Delete operation failed",{tableName:e.name,error:r.message}),r}a+=s.sql,this.logger.debug("Executing delete query",{tableName:e.name,whereConditions:((t=e.wheres)===null||t===void 0?void 0:t.length)||0,sql:a});try{const r=await this.execute(a,s.params);return this.logger.info("Delete operation completed successfully",{tableName:e.name,rowsAffected:r.rowsAffected}),r}catch(r){throw this.logger.error("Delete operation failed",{tableName:e.name,sql:a,error:r instanceof Error?r.message:String(r)}),r}}async select(e){this.logger.trace("Performing select single operation",{tableName:e.name});const{sql:t,params:a}=this.buildSelectQuery(e," LIMIT 1");this.logger.debug("Executing select single query",{tableName:e.name,sql:t});try{const s=await this.execute(t,a),r=s.rows[0]||{};return this.logger.debug("Select single operation completed",{tableName:e.name,hasResult:!!s.rows[0]}),r}catch(s){throw this.logger.error("Select single operation failed",{tableName:e.name,sql:t,error:s instanceof Error?s.message:String(s)}),s}}async selectAll(e){this.logger.trace("Performing select all operation",{tableName:e.name});const{sql:t,params:a}=this.buildSelectQuery(e);this.logger.debug("Executing select all query",{tableName:e.name,sql:t});try{const s=await this.execute(t,a);return this.logger.debug("Select all operation completed",{tableName:e.name,rowCount:s.rows.length}),s.rows}catch(s){throw this.logger.error("Select all operation failed",{tableName:e.name,sql:t,error:s instanceof Error?s.message:String(s)}),s}}buildSelectQuery(e,t=""){var a;let s=`SELECT ${e.cols.length>0?e.cols.map(i=>i.name).join(", "):"*"} FROM ${e.name}`;const r=this.buildWhereClause(e.wheres);if(s+=r.sql,!((a=e.orderbys)===null||a===void 0)&&a.length){const i=e.orderbys.map(o=>`${o.name} ${o.direction||"ASC"}`).join(", ");s+=` ORDER BY ${i}`}return e.limitOffset&&(e.limitOffset.limit&&(s+=` LIMIT ${e.limitOffset.limit}`),e.limitOffset.offset&&(s+=` OFFSET ${e.limitOffset.offset}`)),s+=t,{sql:s,params:r.params}}buildWhereClause(e,t="WHERE"){if(!e||e.length===0)return{sql:"",params:[]};const a=[],s=[];for(const r of e){const i=r.operator||"=";a.push(`${r.name} ${i} ?`),s.push(r.value)}return{sql:` ${t} ${a.join(" AND ")}`,params:s}}convertJsonToQueryTable(e,t,a=["id"]){var s,r;this.logger.trace("Converting JSON to QueryTable",{tableName:e,fieldCount:Object.keys(t).length,idFields:a});const i={name:e,cols:[],wheres:[]};for(const[o,l]of Object.entries(t))i.cols.push({name:o,value:l}),a.includes(o)&&l!==void 0&&((s=i.wheres)===null||s===void 0||s.push({name:o,value:l}));return this.logger.debug("JSON converted to QueryTable",{tableName:e,columnCount:i.cols.length,whereCount:((r=i.wheres)===null||r===void 0?void 0:r.length)||0}),i}async importData(e){this.logger.info("Starting data import operation",{tableName:e.tableName,totalRows:e.data.length,batchSize:e.batchSize||1e3,validateData:e.validateData,updateOnConflict:e.updateOnConflict,skipErrors:e.skipErrors});const t=Date.now(),a={totalRows:e.data.length,successRows:0,errorRows:0,errors:[],executionTime:0};if(!this.isConnected){const m=new Error("Database is not connected");throw this.logger.error("Import failed - database not connected"),m}if(!e.data||e.data.length===0)return this.logger.warn("No data provided for import, returning empty result"),a.executionTime=Date.now()-t,a;const s=await this.getTableInfo(e.tableName);if(s.length===0){const m=new Error(`Table '${e.tableName}' does not exist`);throw this.logger.error("Import failed - table does not exist",{tableName:e.tableName}),m}this.logger.debug("Table info retrieved for import",{tableName:e.tableName,columnCount:s.length});const r=new Map(s.map(m=>[m.name.toLowerCase(),m])),i=e.batchSize||1e3;let o=0;const l=!e.includeAutoIncrementPK;try{await this.beginTransaction();for(let m=0;m<e.data.length;m+=i){const f=e.data.slice(m,m+i);this.logger.debug("Processing import batch",{batchNumber:Math.floor(m/i)+1,batchSize:f.length,totalBatches:Math.ceil(e.data.length/i)});for(let y=0;y<f.length;y++){const N=m+y,I=f[y];try{const C=e.validateData?this.validateAndTransformRow(I,r,e.tableName,l):this.transformRowData(I,r,l);e.updateOnConflict&&e.conflictColumns?await this.insertOrUpdate(e.tableName,C,e.conflictColumns):await this.insertRow(e.tableName,C),a.successRows++}catch(C){a.errorRows++;const x={rowIndex:N,error:C instanceof Error?C.message:String(C),rowData:I};if(a.errors.push(x),this.logger.warn("Row import failed",{rowIndex:N,tableName:e.tableName,error:C instanceof Error?C.message:String(C)}),e.onError&&e.onError(C instanceof Error?C:new Error(String(C)),N,I),!e.skipErrors)throw this.logger.error("Import operation stopped due to error and skipErrors=false"),C}o++,e.onProgress&&o%100===0&&e.onProgress(o,e.data.length)}}await this.commitTransaction(),this.logger.info("Data import completed successfully",{tableName:e.tableName,totalRows:a.totalRows,successRows:a.successRows,errorRows:a.errorRows,executionTime:Date.now()-t})}catch(m){throw this.logger.error("Import operation failed, rolling back transaction",{tableName:e.tableName,processedCount:o,error:m instanceof Error?m.message:String(m)}),await this.rollbackTransaction(),m}return e.onProgress&&e.onProgress(o,e.data.length),a.executionTime=Date.now()-t,a}async importDataWithMapping(e,t,a,s={}){this.logger.info("Starting data import with column mapping",{tableName:e,dataRows:t.length,mappingCount:a.length});const r=t.map((i,o)=>{this.logger.trace("Transforming row with column mappings",{rowIndex:o});const l={};return a.forEach(m=>{if(i.hasOwnProperty(m.sourceColumn)){let f=i[m.sourceColumn];if(m.transform)try{f=m.transform(f)}catch(y){this.logger.warn("Column transformation failed",{rowIndex:o,sourceColumn:m.sourceColumn,targetColumn:m.targetColumn,error:y instanceof Error?y.message:String(y)})}l[m.targetColumn]=f}}),l});return this.logger.debug("Data transformation completed",{originalRowCount:t.length,transformedRowCount:r.length}),await this.importData(Object.assign({tableName:e,data:r},s))}async importFromCSV(e,t,a={}){this.logger.info("Starting CSV import",{tableName:e,csvLength:t.length,delimiter:a.delimiter||",",hasHeader:a.hasHeader!==!1});const s=a.delimiter||",",r=a.hasHeader!==!1,i=t.split(`
5
- `).filter(f=>f.trim());if(i.length===0){const f=new Error("CSV data is empty");throw this.logger.error("CSV import failed - empty data"),f}let o=[],l=0;if(r)o=i[0].split(s).map(f=>f.trim().replace(/^["']|["']$/g,"")),l=1,this.logger.debug("CSV headers extracted",{headers:o,headerCount:o.length});else{const f=i[0].split(s).length;o=Array.from({length:f},(y,N)=>`column_${N+1}`),this.logger.debug("Generated column headers for headerless CSV",{columnCount:f,headers:o})}const m=[];for(let f=l;f<i.length;f++){const y=i[f].split(s).map(I=>I.trim().replace(/^["']|["']$/g,"")),N={};o.forEach((I,C)=>{N[I]=y[C]||null}),m.push(N)}return this.logger.debug("CSV data parsed",{totalLines:i.length,dataRows:m.length,skipHeader:r}),a.columnMappings?(this.logger.debug("Using column mappings for CSV import"),await this.importDataWithMapping(e,m,a.columnMappings,a)):await this.importData(Object.assign({tableName:e,data:m},a))}validateAndTransformRow(e,t,a,s=!0){this.logger.trace("Validating and transforming row data",{tableName:a});const r={};for(const[i,o]of t.entries()){const l=o.notnull===1&&!o.dflt_value,m=o.pk===1&&o.type.toLowerCase().includes("integer");if(s&&m)continue;const f=this.findValueForColumn(e,i);if(l&&f==null){const y=new Error(`Required column '${i}' is missing or null in table '${a}'`);throw this.logger.error("Row validation failed",{tableName:a,columnName:i,error:y.message}),y}if(f!=null)try{r[i]=this.convertValueToColumnType(f,o.type)}catch(y){throw this.logger.error("Value conversion failed during validation",{tableName:a,columnName:i,value:f,columnType:o.type,error:y instanceof Error?y.message:String(y)}),y}}return r}transformRowData(e,t,a=!0){this.logger.trace("Transforming row data without validation");const s={};for(const[r,i]of Object.entries(e)){const o=r.toLowerCase(),l=t.get(o);if(!l){this.logger.trace("Column not found in table schema, skipping",{columnName:r});continue}const m=l.pk===1&&l.type.toLowerCase().includes("integer");if(!(a&&m)&&i!=null)try{s[r]=this.convertValueToColumnType(i,l.type)}catch(f){this.logger.warn("Value conversion failed during transformation",{columnName:r,value:i,columnType:l.type,error:f instanceof Error?f.message:String(f)})}}return s}findValueForColumn(e,t){if(e.hasOwnProperty(t))return e[t];const a=t.toLowerCase();for(const[s,r]of Object.entries(e))if(s.toLowerCase()===a)return r}convertValueToColumnType(e,t){if(e==null)return null;const a=t.toLowerCase();try{if(a.includes("integer")||a.includes("int")){if(typeof e=="boolean")return e?1:0;const s=parseInt(String(e));return isNaN(s)?null:s}if(a.includes("real")||a.includes("float")||a.includes("decimal")){const s=parseFloat(String(e));return isNaN(s)?null:s}if(a.includes("boolean")){if(typeof e=="boolean")return e?1:0;if(typeof e=="string"){const s=e.toLowerCase();return s==="true"||s==="1"||s==="yes"?1:0}return e?1:0}if(a.includes("json")){if(typeof e=="object")return JSON.stringify(e);if(typeof e=="string")try{return JSON.parse(e),e}catch(s){throw new Error(`Invalid JSON format for column type '${t}'`)}return JSON.stringify(e)}if(a.includes("timestamp")||a.includes("datetime")){if(e instanceof Date)return e.toISOString();if(typeof e=="string"||typeof e=="number"){const s=new Date(e);return isNaN(s.getTime())?e:s.toISOString()}return String(e)}return String(e)}catch(s){throw new Error(`Cannot convert value '${e}' to column type '${t}'`)}}async insertRow(e,t){const a=Object.keys(t),s=Object.values(t),r=a.map(()=>"?").join(", "),i=`INSERT INTO ${e} (${a.join(", ")}) VALUES (${r})`;try{await this.execute(i,s)}catch(o){throw this.logger.trace("Insert row failed",{tableName:e,columns:a,error:o instanceof Error?o.message:String(o)}),o}}async insertOrUpdate(e,t,a){this.logger.trace("Attempting insert or update",{tableName:e,conflictColumns:a});try{await this.insertRow(e,t)}catch(s){if(this.isConflictError(s))this.logger.debug("Insert conflict detected, attempting update",{tableName:e}),await this.updateRowByColumns(e,t,a);else throw s}}async updateRowByColumns(e,t,a){const s=Object.keys(t).filter(N=>!a.includes(N)),r=a;if(s.length===0){this.logger.debug("No columns to update, skipping update operation",{tableName:e});return}const i=s.map(N=>`${N} = ?`).join(", "),o=r.map(N=>`${N} = ?`).join(" AND "),l=s.map(N=>t[N]),m=r.map(N=>t[N]),f=[...l,...m],y=`UPDATE ${e} SET ${i} WHERE ${o}`;try{await this.execute(y,f),this.logger.trace("Update by columns completed",{tableName:e,updateColumns:s,whereColumns:r})}catch(N){throw this.logger.error("Update by columns failed",{tableName:e,sql:y,error:N instanceof Error?N.message:String(N)}),N}}isConflictError(e){return e.code==="SQLITE_CONSTRAINT_UNIQUE"||e.code==="SQLITE_CONSTRAINT_PRIMARYKEY"||e.message&&e.message.includes("UNIQUE constraint failed")}async getDatabaseInfo(){this.logger.trace("Getting database information");try{const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table'"),t=await this.getSchemaVersion(),a={name:this.dbPath,tables:e.rows.map(s=>s.name),isConnected:this.isConnected,version:t};return this.logger.debug("Database information retrieved",{tableCount:a.tables.length,isConnected:a.isConnected,version:a.version}),a}catch(e){throw this.logger.error("Failed to get database information",{error:e instanceof Error?e.message:String(e)}),e}}async getTableInfo(e){this.logger.trace("Getting table information",{tableName:e});try{const t=await this.execute(`PRAGMA table_info(${e})`);return this.logger.debug("Table information retrieved",{tableName:e,columnCount:t.rows.length}),t.rows}catch(t){throw this.logger.error("Failed to get table information",{tableName:e,error:t instanceof Error?t.message:String(t)}),t}}async dropTable(e){this.logger.info("Dropping table",{tableName:e});const t=`DROP TABLE IF EXISTS ${e}`;try{await this.execute(t),this.logger.info("Table dropped successfully",{tableName:e})}catch(a){throw this.logger.error("Failed to drop table",{tableName:e,error:a instanceof Error?a.message:String(a)}),a}}isConnectionOpen(){const e=this.isConnected&&!!this.connection;return this.logger.trace("Connection status checked",{isOpen:e}),e}async ensureConnected(){this.isConnectionOpen()||(this.logger.debug("Connection not open, attempting to connect"),await this.connect())}async execute(e,t=[]){var a;this.logger.trace("Executing SQL query",{sql:e.substring(0,100)+(e.length>100?"...":""),paramCount:t.length}),this.ensureConnected();try{const s=await this.connection.execute(e,t);return this.logger.trace("SQL query executed successfully",{rowsAffected:s.rowsAffected,rowsReturned:((a=s.rows)===null||a===void 0?void 0:a.length)||0}),s}catch(s){throw this.logger.error("SQL query execution failed",{sql:e.substring(0,200)+(e.length>200?"...":""),paramCount:t.length,error:s instanceof Error?s.message:String(s)}),s}}async getRst(e,t=[]){return(await this.execute(e,t)).rows[0]||{}}async getRsts(e,t=[]){return(await this.execute(e,t)).rows}}const d=w(b.DATABASE_FACTORY);class v{static registerAdapter(e){d.info(`Registering SQLite adapter: ${e.constructor.name}`,{adapterName:e.constructor.name,totalAdapters:this.adapters.length+1}),this.adapters.push(e),d.debug(`Successfully registered adapter. Total adapters: ${this.adapters.length}`)}static getEnvironmentInfo(){d.trace("Detecting runtime environment");let e;return typeof navigator!="undefined"&&navigator.product==="ReactNative"?e="React Native":typeof globalThis.Bun!="undefined"?e="Bun":typeof globalThis.Deno!="undefined"?e="Deno":typeof window!="undefined"?e="Browser":typeof process!="undefined"?e="Node.js":e="Unknown",d.debug(`Detected runtime environment: ${e}`),e}static detectBestAdapter(){d.trace("Detecting best available SQLite adapter",{totalAdapters:this.adapters.length,environment:this.getEnvironmentInfo()});for(const e of this.adapters){if(d.trace(`Testing adapter: ${e.constructor.name}`),e.isSupported())return d.info(`Selected adapter: ${e.constructor.name}`,{adapterName:e.constructor.name,environment:this.getEnvironmentInfo()}),e;d.debug(`Adapter ${e.constructor.name} is not supported in current environment`)}throw d.error("No supported SQLite adapter found",{totalAdapters:this.adapters.length,environment:this.getEnvironmentInfo()}),new Error("No supported SQLite adapter found")}static async validateSchemaVersion(e,t){d.trace("Validating schema version compatibility",{databaseName:t.database_name,configVersion:t.version});try{const a=await e.getDatabaseInfo();if(d.debug("Retrieved database info",{databaseVersion:a.version,configVersion:t.version}),a.version!==t.version){const s=`Schema version mismatch: database (${a.version}) vs config (${t.version})`;throw d.error("Schema version mismatch",{databaseName:t.database_name,databaseVersion:a.version,configVersion:t.version}),new Error(s)}d.debug("Schema version validation successful",{databaseName:t.database_name,version:t.version})}catch(a){throw d.error("Error during schema version validation",{databaseName:t.database_name,error:a.message}),new Error(`Error validating schema version for ${t.database_name}: ${a.message}`)}}static validateSchema(e){if(d.trace("Validating database schema configuration"),!e)throw d.error("Schema validation failed: null or undefined schema"),new Error("Schema configuration is null or undefined.");if(typeof e.database_name!="string"||e.database_name.trim()==="")throw d.error("Schema validation failed: invalid database_name",{databaseName:e.database_name,type:typeof e.database_name}),new Error("Invalid or missing 'database_name' in schema. This is required to name the database file.");if(typeof e.schemas!="object"||e.schemas===null||Object.keys(e.schemas).length===0)throw d.error("Schema validation failed: invalid schemas object",{databaseName:e.database_name,schemasType:typeof e.schemas,schemasCount:e.schemas?Object.keys(e.schemas).length:0}),new Error("Invalid or missing 'schemas' object in schema. At least one table definition is required.");return d.debug("Schema validation successful",{databaseName:e.database_name,tablesCount:Object.keys(e.schemas).length,version:e.version}),!0}static createDAO(e,t){var a,s,r,i;d.info("Creating new UniversalDAO instance",{dbPath:e,hasCustomAdapter:!!(t!=null&&t.adapter),createIfNotExists:(a=t==null?void 0:t.createIfNotExists)!==null&&a!==void 0?a:!1,forceRecreate:(s=t==null?void 0:t.forceRecreate)!==null&&s!==void 0?s:!1});let o;t!=null&&t.adapter?(d.debug("Using provided custom adapter",{adapterName:t.adapter.constructor.name}),o=t.adapter):(d.debug("Detecting best adapter automatically"),o=this.detectBestAdapter());const l=new F(o,e,{createIfNotExists:(r=t==null?void 0:t.createIfNotExists)!==null&&r!==void 0?r:!1,forceRecreate:(i=t==null?void 0:t.forceRecreate)!==null&&i!==void 0?i:!1});return d.debug("UniversalDAO instance created successfully",{dbPath:e,adapterName:o.constructor.name}),l}static async openExisting(e,t={}){d.info("Opening existing database",{dbName:e,options:t});const a=e.endsWith(".db")?e:`${e}.db`;d.debug("Resolved database filename",{originalName:e,resolvedName:a});const s=this.createDAO(a,t);try{return d.debug("Connecting to database",{dbFileName:a}),await s.connect(),d.debug("Running integrity check",{dbFileName:a}),await s.execute("PRAGMA integrity_check"),d.info("Database opened successfully",{dbFileName:a}),s}catch(r){d.error("Error opening database",{dbFileName:a,error:r.message});try{await s.close()}catch(i){d.warn("Error closing DAO after failed open",{dbFileName:a,closeError:i.message})}throw new Error(`Error opening database '${a}': ${r.message}`)}}static async createOrOpenInternal(e,t=!1,a=!1){d.info("Creating or opening database internally",{isForceInit:t,isForceDelete:a,hasConfig:!!e.config,hasConfigAsset:!!e.configAsset});let s;if(d.trace("Loading database schema"),e.config)d.debug("Using provided config object"),s=e.config;else if(e.configAsset)d.debug("Using provided config asset"),s=e.configAsset;else throw d.error("No database schema configuration provided"),new Error("Either 'config', 'configAsset', or 'configPath' must be provided to the factory.");d.trace("Validating schema configuration"),this.validateSchema(s);const r=s.database_name.endsWith(".db")?s.database_name:`${s.database_name}.db`;d.debug("Database filename resolved",{originalName:s.database_name,resolvedName:r}),d.debug("Creating DAO instance",{dbFileName:r,hasCustomAdapter:!!e.adapter,createIfNotExists:t,forceRecreate:a});const i=this.createDAO(r,{adapter:e.adapter,createIfNotExists:t,forceRecreate:a});try{d.debug("Connecting to database",{dbFileName:r}),await i.connect(),d.debug("Initializing database schema",{dbFileName:r}),await i.initializeFromSchema(s),d.debug("Validating schema version compatibility");try{await this.validateSchemaVersion(i,s)}catch(o){throw d.error("Schema version validation failed",{dbFileName:r,error:o.message}),await i.close(),new Error(`Schema mismatch in existing database. Use forceRecreate=true to recreate with updated schema. Error: ${o.message}`)}return d.info("Database created/opened successfully",{dbFileName:r,databaseName:s.database_name,version:s.version}),i}catch(o){if(d.error("Error during database creation/opening",{dbFileName:r,error:o.message}),i.isConnectionOpen())try{await i.close()}catch(l){d.warn("Error closing DAO after failed operation",{dbFileName:r,closeError:l.message})}throw o}}static async create(e){var t,a;return d.warn("Creating database with force recreate - this will delete existing database",{databaseName:((t=e.config)===null||t===void 0?void 0:t.database_name)||((a=e.configAsset)===null||a===void 0?void 0:a.database_name)}),this.createOrOpenInternal(e,!0,!0)}static async createOrOpen(e,t=!1){var a,s;return d.info("Smart create or open database",{databaseName:((a=e.config)===null||a===void 0?void 0:a.database_name)||((s=e.configAsset)===null||s===void 0?void 0:s.database_name),isForceInit:t}),this.createOrOpenInternal(e,t)}static async createFromAsset(e,t={}){d.info("Creating database from asset",{databaseName:e.database_name,version:e.version});try{return await this.create(Object.assign(Object.assign({},t),{configAsset:e}))}catch(a){throw d.error("Error creating database from asset",{databaseName:e.database_name,error:a.message}),new Error(`Error creating database from asset: ${a.message}`)}}static async createFromConfig(e,t={}){d.info("Creating database from config",{databaseName:e.database_name,version:e.version});try{return await this.create(Object.assign(Object.assign({},t),{config:e}))}catch(a){throw d.error("Error creating database from config",{databaseName:e.database_name,error:a.message}),new Error(`Error creating database from config: ${a.message}`)}}}v.adapters=[];const n=w(b.DATABASE_MANAGER);class p{static getMaxConnections(){return n.trace("Getting max connections",{maxConnections:this.maxConnections}),this.maxConnections}static setMaxConnections(e){if(n.debug("Setting max connections",{newMaxConnections:e,currentMax:this.maxConnections}),e<=0)throw n.error("Invalid max connections value",{maxConnections:e}),new Error("Maximum connections must be a positive number");const t=Object.keys(this.connections).length;if(t>e)throw n.error("Cannot set max connections - would exceed current active connections",{requestedMax:e,currentActiveConnections:t,activeConnectionKeys:Object.keys(this.connections)}),new Error(`Cannot set maximum connections to ${e}. Current active connections (${t}) exceed the new limit. Please close some connections first.`);this.maxConnections=e,n.info("Max connections updated successfully",{newMaxConnections:e,currentActiveConnections:t})}static setSchemaManager(e){n.debug("Setting schema manager",{hadPreviousManager:this.schemaManager!==null}),this.schemaManager=e,n.info("Schema manager set successfully")}static registerSchema(e,t){n.debug("Registering schema",{key:e,schemaName:t.database_name}),this.schemaConfigurations[e]=t,n.info("Schema registered successfully",{key:e,schemaName:t.database_name})}static registerSchemas(e){const t=Object.keys(e);n.debug("Registering multiple schemas",{count:t.length,keys:t}),Object.entries(e).forEach(([a,s])=>{this.registerSchema(a,s)}),n.info("Multiple schemas registered successfully",{count:t.length})}static getSchema(e){if(n.trace("Getting schema",{key:e}),this.schemaConfigurations[e])return n.trace("Schema found in internal configurations",{key:e}),this.schemaConfigurations[e];if(this.schemaManager){n.trace("Checking external schema manager",{key:e});const t=this.schemaManager.getSchema(e);if(t)return n.trace("Schema found in external manager",{key:e}),t}n.warn("Schema not found",{key:e})}static getAvailableSchemas(){var e;const t=Object.keys(this.schemaConfigurations),a=((e=this.schemaManager)===null||e===void 0?void 0:e.getAllSchemaKeys())||[],s=[...new Set([...t,...a])];return n.trace("Getting available schemas",{internalCount:t.length,externalCount:a.length,totalUnique:s.length}),s}static registerRole(e){n.debug("Registering role",{roleName:e.roleName,requiredDatabases:e.requiredDatabases,optionalDatabases:e.optionalDatabases,priority:e.priority}),this.roleRegistry[e.roleName]=e,n.info("Role registered successfully",{roleName:e.roleName})}static registerRoles(e){n.debug("Registering multiple roles",{count:e.length}),e.forEach(t=>this.registerRole(t)),n.info("Multiple roles registered successfully",{count:e.length})}static getRegisteredRoles(){return n.trace("Getting registered roles",{count:Object.keys(this.roleRegistry).length}),Object.assign({},this.roleRegistry)}static getRoleDatabases(e){n.trace("Getting role databases",{roleName:e});const t=this.roleRegistry[e];if(!t)throw n.error("Role not found in registry",{roleName:e,availableRoles:Object.keys(this.roleRegistry)}),new Error(`Role '${e}' is not registered.`);const a=[...t.requiredDatabases,...t.optionalDatabases||[]];return n.trace("Role databases retrieved",{roleName:e,databases:a}),a}static getCurrentUserDatabases(){n.trace("Getting current user databases",{currentUserRoles:this.currentUserRoles});const e=new Set;e.add("core");for(const a of this.currentUserRoles){const s=this.roleRegistry[a];s?(s.requiredDatabases.forEach(r=>e.add(r)),s.optionalDatabases&&s.optionalDatabases.forEach(r=>e.add(r))):n.warn("Role config not found for current user role",{roleName:a})}const t=Array.from(e);return n.debug("Current user databases calculated",{userRoles:this.currentUserRoles,databases:t}),t}static async initializeCoreConnection(){if(n.debug("Initializing core database connection"),this.connections.core){n.debug("Core connection already exists");return}try{const e=this.getSchema("core");if(!e)throw n.error("Core database schema not found"),new Error("Core database schema not found.");n.debug("Creating core database connection",{schemaName:e.database_name});const t=await v.createOrOpen({config:e},!1);await t.execute("PRAGMA integrity_check"),this.connections.core=t,n.info("Core database connection initialized successfully")}catch(e){throw n.error("Error initializing core database",{error:e.message}),new Error(`Error initializing core database: ${e.message}`)}}static async setCurrentUserRoles(e,t){n.debug("Setting current user roles",{userRoles:e,primaryRole:t});for(const s of e)if(!this.roleRegistry[s])throw n.error("Role not registered",{roleName:s,availableRoles:Object.keys(this.roleRegistry)}),new Error(`Role '${s}' is not registered. Please register it first.`);const a=[...this.currentUserRoles];this.currentUserRoles=e,this.currentRole=t||e[0]||null,n.info("User roles updated",{previousRoles:a,newRoles:e,primaryRole:this.currentRole});try{await this.initializeUserRoleConnections(),await this.cleanupUnusedConnections(a),n.info("User role connections initialized successfully")}catch(s){throw n.error("Failed to initialize user role connections",{error:s.message}),s}}static getCurrentUserRoles(){return n.trace("Getting current user roles",{roles:this.currentUserRoles}),[...this.currentUserRoles]}static getCurrentRole(){return n.trace("Getting current primary role",{role:this.currentRole}),this.currentRole}static async initializeUserRoleConnections(){const e=this.getCurrentUserDatabases();n.debug("Initializing user role connections",{requiredDatabases:e});const t=[],a=e.map(async s=>{if(this.connections[s]){n.trace("Database already connected",{dbKey:s});return}try{n.debug("Initializing database connection",{dbKey:s});const r=this.getSchema(s);if(!r)throw new Error(`Database key '${s}' not found in schema configurations.`);const i=await v.createOrOpen({config:r},!1);await i.execute("PRAGMA integrity_check"),this.connections[s]=i,n.info("Database connection initialized",{dbKey:s,schemaName:r.database_name})}catch(r){const i=r instanceof Error?r:new Error(String(r));n.error("Failed to initialize database connection",{dbKey:s,error:i.message}),this.currentUserRoles.some(o=>{const l=this.roleRegistry[o];return l&&l.requiredDatabases.includes(s)})?t.push({key:s,error:i}):n.warn("Optional database initialization failed",{dbKey:s,error:i.message})}});if(await Promise.all(a),t.length>0){const s=t.map(r=>` - ${r.key}: ${r.error.message}`).join(`
4
+ )`),await this.execute("INSERT INTO _schema_info (version) VALUES (?)",[e]),this.logger.info("Schema version set successfully",{version:e})}catch(t){throw this.logger.error("Failed to set schema version",{version:e,error:t instanceof Error?t.message:String(t)}),t}}async insert(e){this.logger.trace("Performing insert operation",{tableName:e.name});const t=e.cols.filter(o=>o.value!==void 0&&o.value!==null);if(t.length===0){const o=new Error("No valid columns to insert");throw this.logger.error("Insert operation failed",{tableName:e.name,error:o.message}),o}const a=t.map(o=>o.name).join(", "),s=t.map(()=>"?").join(", "),r=t.map(o=>typeof o.value=="object"?JSON.stringify(o.value):o.value),i=`INSERT INTO ${e.name} (${a}) VALUES (${s})`;this.logger.debug("Executing insert query",{tableName:e.name,columnCount:t.length,sql:i});try{const o=await this.execute(i,r);return this.logger.info("Insert operation completed successfully",{tableName:e.name,rowsAffected:o.rowsAffected,lastInsertRowid:o.lastInsertRowId}),o}catch(o){throw this.logger.error("Insert operation failed",{tableName:e.name,sql:i,error:o instanceof Error?o.message:String(o)}),o}}async update(e){var t;this.logger.trace("Performing update operation",{tableName:e.name});const a=e.cols.filter(l=>{var m;return l.value!==void 0&&!(!((m=e.wheres)===null||m===void 0)&&m.some(f=>f.name===l.name))});if(a.length===0){const l=new Error("No columns to update");throw this.logger.error("Update operation failed",{tableName:e.name,error:l.message}),l}const s=a.map(l=>`${l.name} = ?`).join(", "),r=a.map(l=>typeof l.value=="object"?JSON.stringify(l.value):l.value);let i=`UPDATE ${e.name} SET ${s}`;const o=this.buildWhereClause(e.wheres);if(!o.sql){const l=new Error("WHERE clause is required for UPDATE operation");throw this.logger.error("Update operation failed",{tableName:e.name,error:l.message}),l}i+=o.sql,r.push(...o.params),this.logger.debug("Executing update query",{tableName:e.name,updateColumnCount:a.length,whereConditions:((t=e.wheres)===null||t===void 0?void 0:t.length)||0,sql:i});try{const l=await this.execute(i,r);return this.logger.info("Update operation completed successfully",{tableName:e.name,rowsAffected:l.rowsAffected}),l}catch(l){throw this.logger.error("Update operation failed",{tableName:e.name,sql:i,error:l instanceof Error?l.message:String(l)}),l}}async delete(e){var t;this.logger.trace("Performing delete operation",{tableName:e.name});let a=`DELETE FROM ${e.name}`;const s=this.buildWhereClause(e.wheres);if(!s.sql){const r=new Error("WHERE clause is required for DELETE operation");throw this.logger.error("Delete operation failed",{tableName:e.name,error:r.message}),r}a+=s.sql,this.logger.debug("Executing delete query",{tableName:e.name,whereConditions:((t=e.wheres)===null||t===void 0?void 0:t.length)||0,sql:a});try{const r=await this.execute(a,s.params);return this.logger.info("Delete operation completed successfully",{tableName:e.name,rowsAffected:r.rowsAffected}),r}catch(r){throw this.logger.error("Delete operation failed",{tableName:e.name,sql:a,error:r instanceof Error?r.message:String(r)}),r}}async select(e){this.logger.trace("Performing select single operation",{tableName:e.name});const{sql:t,params:a}=this.buildSelectQuery(e," LIMIT 1");this.logger.debug("Executing select single query",{tableName:e.name,sql:t});try{const s=await this.execute(t,a),r=s.rows[0]||{};return this.logger.debug("Select single operation completed",{tableName:e.name,hasResult:!!s.rows[0]}),r}catch(s){throw this.logger.error("Select single operation failed",{tableName:e.name,sql:t,error:s instanceof Error?s.message:String(s)}),s}}async selectAll(e){this.logger.trace("Performing select all operation",{tableName:e.name});const{sql:t,params:a}=this.buildSelectQuery(e);this.logger.debug("Executing select all query",{tableName:e.name,sql:t});try{const s=await this.execute(t,a);return this.logger.debug("Select all operation completed",{tableName:e.name,rowCount:s.rows.length}),s.rows}catch(s){throw this.logger.error("Select all operation failed",{tableName:e.name,sql:t,error:s instanceof Error?s.message:String(s)}),s}}buildSelectQuery(e,t=""){var a;let s=`SELECT ${e.cols.length>0?e.cols.map(i=>i.name).join(", "):"*"} FROM ${e.name}`;const r=this.buildWhereClause(e.wheres);if(s+=r.sql,!((a=e.orderbys)===null||a===void 0)&&a.length){const i=e.orderbys.map(o=>`${o.name} ${o.direction||"ASC"}`).join(", ");s+=` ORDER BY ${i}`}return e.limitOffset&&(e.limitOffset.limit&&(s+=` LIMIT ${e.limitOffset.limit}`),e.limitOffset.offset&&(s+=` OFFSET ${e.limitOffset.offset}`)),s+=t,{sql:s,params:r.params}}buildWhereClause(e,t="WHERE"){if(!e||e.length===0)return{sql:"",params:[]};const a=[],s=[];for(const r of e){const i=r.operator||"=";a.push(`${r.name} ${i} ?`),s.push(r.value)}return{sql:` ${t} ${a.join(" AND ")}`,params:s}}convertJsonToQueryTable(e,t,a=["id"]){var s,r;this.logger.trace("Converting JSON to QueryTable",{tableName:e,fieldCount:Object.keys(t).length,idFields:a});const i={name:e,cols:[],wheres:[]};for(const[o,l]of Object.entries(t))i.cols.push({name:o,value:l}),a.includes(o)&&l!==void 0&&((s=i.wheres)===null||s===void 0||s.push({name:o,value:l}));return this.logger.debug("JSON converted to QueryTable",{tableName:e,columnCount:i.cols.length,whereCount:((r=i.wheres)===null||r===void 0?void 0:r.length)||0}),i}async importData(e){this.logger.info("Starting data import operation",{tableName:e.tableName,totalRows:e.data.length,batchSize:e.batchSize||1e3,validateData:e.validateData,updateOnConflict:e.updateOnConflict,skipErrors:e.skipErrors});const t=Date.now(),a={totalRows:e.data.length,successRows:0,errorRows:0,errors:[],executionTime:0};if(!this.isConnected){const m=new Error("Database is not connected");throw this.logger.error("Import failed - database not connected"),m}if(!e.data||e.data.length===0)return this.logger.warn("No data provided for import, returning empty result"),a.executionTime=Date.now()-t,a;const s=await this.getTableInfo(e.tableName);if(s.length===0){const m=new Error(`Table '${e.tableName}' does not exist`);throw this.logger.error("Import failed - table does not exist",{tableName:e.tableName}),m}this.logger.debug("Table info retrieved for import",{tableName:e.tableName,columnCount:s.length});const r=new Map(s.map(m=>[m.name.toLowerCase(),m])),i=e.batchSize||1e3;let o=0;const l=!e.includeAutoIncrementPK;try{await this.beginTransaction();for(let m=0;m<e.data.length;m+=i){const f=e.data.slice(m,m+i);this.logger.debug("Processing import batch",{batchNumber:Math.floor(m/i)+1,batchSize:f.length,totalBatches:Math.ceil(e.data.length/i)});for(let y=0;y<f.length;y++){const N=m+y,A=f[y];try{const C=e.validateData?this.validateAndTransformRow(A,r,e.tableName,l):this.transformRowData(A,r,l);e.updateOnConflict&&e.conflictColumns?await this.insertOrUpdate(e.tableName,C,e.conflictColumns):await this.insertRow(e.tableName,C),a.successRows++}catch(C){a.errorRows++;const F={rowIndex:N,error:C instanceof Error?C.message:String(C),rowData:A};if(a.errors.push(F),this.logger.warn("Row import failed",{rowIndex:N,tableName:e.tableName,error:C instanceof Error?C.message:String(C)}),e.onError&&e.onError(C instanceof Error?C:new Error(String(C)),N,A),!e.skipErrors)throw this.logger.error("Import operation stopped due to error and skipErrors=false"),C}o++,e.onProgress&&o%100===0&&e.onProgress(o,e.data.length)}}await this.commitTransaction(),this.logger.info("Data import completed successfully",{tableName:e.tableName,totalRows:a.totalRows,successRows:a.successRows,errorRows:a.errorRows,executionTime:Date.now()-t})}catch(m){throw this.logger.error("Import operation failed, rolling back transaction",{tableName:e.tableName,processedCount:o,error:m instanceof Error?m.message:String(m)}),await this.rollbackTransaction(),m}return e.onProgress&&e.onProgress(o,e.data.length),a.executionTime=Date.now()-t,a}async importDataWithMapping(e,t,a,s={}){this.logger.info("Starting data import with column mapping",{tableName:e,dataRows:t.length,mappingCount:a.length});const r=t.map((i,o)=>{this.logger.trace("Transforming row with column mappings",{rowIndex:o});const l={};return a.forEach(m=>{if(i.hasOwnProperty(m.sourceColumn)){let f=i[m.sourceColumn];if(m.transform)try{f=m.transform(f)}catch(y){this.logger.warn("Column transformation failed",{rowIndex:o,sourceColumn:m.sourceColumn,targetColumn:m.targetColumn,error:y instanceof Error?y.message:String(y)})}l[m.targetColumn]=f}}),l});return this.logger.debug("Data transformation completed",{originalRowCount:t.length,transformedRowCount:r.length}),await this.importData(Object.assign({tableName:e,data:r},s))}async importFromCSV(e,t,a={}){this.logger.info("Starting CSV import",{tableName:e,csvLength:t.length,delimiter:a.delimiter||",",hasHeader:a.hasHeader!==!1});const s=a.delimiter||",",r=a.hasHeader!==!1,i=t.split(`
5
+ `).filter(f=>f.trim());if(i.length===0){const f=new Error("CSV data is empty");throw this.logger.error("CSV import failed - empty data"),f}let o=[],l=0;if(r)o=i[0].split(s).map(f=>f.trim().replace(/^["']|["']$/g,"")),l=1,this.logger.debug("CSV headers extracted",{headers:o,headerCount:o.length});else{const f=i[0].split(s).length;o=Array.from({length:f},(y,N)=>`column_${N+1}`),this.logger.debug("Generated column headers for headerless CSV",{columnCount:f,headers:o})}const m=[];for(let f=l;f<i.length;f++){const y=i[f].split(s).map(A=>A.trim().replace(/^["']|["']$/g,"")),N={};o.forEach((A,C)=>{N[A]=y[C]||null}),m.push(N)}return this.logger.debug("CSV data parsed",{totalLines:i.length,dataRows:m.length,skipHeader:r}),a.columnMappings?(this.logger.debug("Using column mappings for CSV import"),await this.importDataWithMapping(e,m,a.columnMappings,a)):await this.importData(Object.assign({tableName:e,data:m},a))}validateAndTransformRow(e,t,a,s=!0){this.logger.trace("Validating and transforming row data",{tableName:a});const r={};for(const[i,o]of t.entries()){const l=o.notnull===1&&!o.dflt_value,m=o.pk===1&&o.type.toLowerCase().includes("integer");if(s&&m)continue;const f=this.findValueForColumn(e,i);if(l&&f==null){const y=new Error(`Required column '${i}' is missing or null in table '${a}'`);throw this.logger.error("Row validation failed",{tableName:a,columnName:i,error:y.message}),y}if(f!=null)try{r[i]=this.convertValueToColumnType(f,o.type)}catch(y){throw this.logger.error("Value conversion failed during validation",{tableName:a,columnName:i,value:f,columnType:o.type,error:y instanceof Error?y.message:String(y)}),y}}return r}transformRowData(e,t,a=!0){this.logger.trace("Transforming row data without validation");const s={};for(const[r,i]of Object.entries(e)){const o=r.toLowerCase(),l=t.get(o);if(!l){this.logger.trace("Column not found in table schema, skipping",{columnName:r});continue}const m=l.pk===1&&l.type.toLowerCase().includes("integer");if(!(a&&m)&&i!=null)try{s[r]=this.convertValueToColumnType(i,l.type)}catch(f){this.logger.warn("Value conversion failed during transformation",{columnName:r,value:i,columnType:l.type,error:f instanceof Error?f.message:String(f)})}}return s}findValueForColumn(e,t){if(e.hasOwnProperty(t))return e[t];const a=t.toLowerCase();for(const[s,r]of Object.entries(e))if(s.toLowerCase()===a)return r}convertValueToColumnType(e,t){if(e==null)return null;const a=t.toLowerCase();try{if(a.includes("integer")||a.includes("int")){if(typeof e=="boolean")return e?1:0;const s=parseInt(String(e));return isNaN(s)?null:s}if(a.includes("real")||a.includes("float")||a.includes("decimal")){const s=parseFloat(String(e));return isNaN(s)?null:s}if(a.includes("boolean")){if(typeof e=="boolean")return e?1:0;if(typeof e=="string"){const s=e.toLowerCase();return s==="true"||s==="1"||s==="yes"?1:0}return e?1:0}if(a.includes("json")){if(typeof e=="object")return JSON.stringify(e);if(typeof e=="string")try{return JSON.parse(e),e}catch(s){throw new Error(`Invalid JSON format for column type '${t}'`)}return JSON.stringify(e)}if(a.includes("timestamp")||a.includes("datetime")){if(e instanceof Date)return e.toISOString();if(typeof e=="string"||typeof e=="number"){const s=new Date(e);return isNaN(s.getTime())?e:s.toISOString()}return String(e)}return String(e)}catch(s){throw new Error(`Cannot convert value '${e}' to column type '${t}'`)}}async insertRow(e,t){const a=Object.keys(t),s=Object.values(t),r=a.map(()=>"?").join(", "),i=`INSERT INTO ${e} (${a.join(", ")}) VALUES (${r})`;try{await this.execute(i,s)}catch(o){throw this.logger.trace("Insert row failed",{tableName:e,columns:a,error:o instanceof Error?o.message:String(o)}),o}}async insertOrUpdate(e,t,a){this.logger.trace("Attempting insert or update",{tableName:e,conflictColumns:a});try{await this.insertRow(e,t)}catch(s){if(this.isConflictError(s))this.logger.debug("Insert conflict detected, attempting update",{tableName:e}),await this.updateRowByColumns(e,t,a);else throw s}}async updateRowByColumns(e,t,a){const s=Object.keys(t).filter(N=>!a.includes(N)),r=a;if(s.length===0){this.logger.debug("No columns to update, skipping update operation",{tableName:e});return}const i=s.map(N=>`${N} = ?`).join(", "),o=r.map(N=>`${N} = ?`).join(" AND "),l=s.map(N=>t[N]),m=r.map(N=>t[N]),f=[...l,...m],y=`UPDATE ${e} SET ${i} WHERE ${o}`;try{await this.execute(y,f),this.logger.trace("Update by columns completed",{tableName:e,updateColumns:s,whereColumns:r})}catch(N){throw this.logger.error("Update by columns failed",{tableName:e,sql:y,error:N instanceof Error?N.message:String(N)}),N}}isConflictError(e){return e.code==="SQLITE_CONSTRAINT_UNIQUE"||e.code==="SQLITE_CONSTRAINT_PRIMARYKEY"||e.message&&e.message.includes("UNIQUE constraint failed")}async getDatabaseInfo(){this.logger.trace("Getting database information");try{const e=await this.execute("SELECT name FROM sqlite_master WHERE type='table'"),t=await this.getSchemaVersion(),a={name:this.dbPath,tables:e.rows.map(s=>s.name),isConnected:this.isConnected,version:t};return this.logger.debug("Database information retrieved",{tableCount:a.tables.length,isConnected:a.isConnected,version:a.version}),a}catch(e){throw this.logger.error("Failed to get database information",{error:e instanceof Error?e.message:String(e)}),e}}async getTableInfo(e){this.logger.trace("Getting table information",{tableName:e});try{const t=await this.execute(`PRAGMA table_info(${e})`);return this.logger.debug("Table information retrieved",{tableName:e,columnCount:t.rows.length}),t.rows}catch(t){throw this.logger.error("Failed to get table information",{tableName:e,error:t instanceof Error?t.message:String(t)}),t}}async dropTable(e){this.logger.info("Dropping table",{tableName:e});const t=`DROP TABLE IF EXISTS ${e}`;try{await this.execute(t),this.logger.info("Table dropped successfully",{tableName:e})}catch(a){throw this.logger.error("Failed to drop table",{tableName:e,error:a instanceof Error?a.message:String(a)}),a}}isConnectionOpen(){const e=this.isConnected&&!!this.connection;return this.logger.trace("Connection status checked",{isOpen:e}),e}async ensureConnected(){this.isConnectionOpen()||(this.logger.debug("Connection not open, attempting to connect"),await this.connect())}async execute(e,t=[]){var a;this.logger.trace("Executing SQL query",{sql:e.substring(0,100)+(e.length>100?"...":""),paramCount:t.length}),this.ensureConnected();try{const s=await this.connection.execute(e,t);return this.logger.trace("SQL query executed successfully",{rowsAffected:s.rowsAffected,rowsReturned:((a=s.rows)===null||a===void 0?void 0:a.length)||0}),s}catch(s){throw this.logger.error("SQL query execution failed",{sql:e.substring(0,200)+(e.length>200?"...":""),paramCount:t.length,error:s instanceof Error?s.message:String(s)}),s}}async getRst(e,t=[]){return(await this.execute(e,t)).rows[0]||{}}async getRsts(e,t=[]){return(await this.execute(e,t)).rows}}const g=w(b.DATABASE_FACTORY);class v{static registerAdapter(e){g.info(`Registering SQLite adapter: ${e.constructor.name}`,{adapterName:e.constructor.name,totalAdapters:this.adapters.length+1}),this.adapters.push(e),g.debug(`Successfully registered adapter. Total adapters: ${this.adapters.length}`)}static getEnvironmentInfo(){g.trace("Detecting runtime environment");let e;return typeof navigator!="undefined"&&navigator.product==="ReactNative"?e="React Native":typeof globalThis.Bun!="undefined"?e="Bun":typeof globalThis.Deno!="undefined"?e="Deno":typeof window!="undefined"?e="Browser":typeof process!="undefined"?e="Node.js":e="Unknown",g.debug(`Detected runtime environment: ${e}`),e}static detectBestAdapter(){g.trace("Detecting best available SQLite adapter",{totalAdapters:this.adapters.length,environment:this.getEnvironmentInfo()});for(const e of this.adapters){if(g.trace(`Testing adapter: ${e.constructor.name}`),e.isSupported())return g.info(`Selected adapter: ${e.constructor.name}`,{adapterName:e.constructor.name,environment:this.getEnvironmentInfo()}),e;g.debug(`Adapter ${e.constructor.name} is not supported in current environment`)}throw g.error("No supported SQLite adapter found",{totalAdapters:this.adapters.length,environment:this.getEnvironmentInfo()}),new Error("No supported SQLite adapter found")}static async validateSchemaVersion(e,t){g.trace("Validating schema version compatibility",{databaseName:t.database_name,configVersion:t.version});try{const a=await e.getDatabaseInfo();if(g.debug("Retrieved database info",{databaseVersion:a.version,configVersion:t.version}),a.version!==t.version){const s=`Schema version mismatch: database (${a.version}) vs config (${t.version})`;throw g.error("Schema version mismatch",{databaseName:t.database_name,databaseVersion:a.version,configVersion:t.version}),new Error(s)}g.debug("Schema version validation successful",{databaseName:t.database_name,version:t.version})}catch(a){throw g.error("Error during schema version validation",{databaseName:t.database_name,error:a.message}),new Error(`Error validating schema version for ${t.database_name}: ${a.message}`)}}static validateSchema(e){if(g.trace("Validating database schema configuration"),!e)throw g.error("Schema validation failed: null or undefined schema"),new Error("Schema configuration is null or undefined.");if(typeof e.database_name!="string"||e.database_name.trim()==="")throw g.error("Schema validation failed: invalid database_name",{databaseName:e.database_name,type:typeof e.database_name}),new Error("Invalid or missing 'database_name' in schema. This is required to name the database file.");if(typeof e.schemas!="object"||e.schemas===null||Object.keys(e.schemas).length===0)throw g.error("Schema validation failed: invalid schemas object",{databaseName:e.database_name,schemasType:typeof e.schemas,schemasCount:e.schemas?Object.keys(e.schemas).length:0}),new Error("Invalid or missing 'schemas' object in schema. At least one table definition is required.");return g.debug("Schema validation successful",{databaseName:e.database_name,tablesCount:Object.keys(e.schemas).length,version:e.version}),!0}static createDAO(e,t){var a,s,r,i;g.info("Creating new UniversalDAO instance",{dbPath:e,hasCustomAdapter:!!(t!=null&&t.adapter),createIfNotExists:(a=t==null?void 0:t.createIfNotExists)!==null&&a!==void 0?a:!1,forceRecreate:(s=t==null?void 0:t.forceRecreate)!==null&&s!==void 0?s:!1});let o;t!=null&&t.adapter?(g.debug("Using provided custom adapter",{adapterName:t.adapter.constructor.name}),o=t.adapter):(g.debug("Detecting best adapter automatically"),o=this.detectBestAdapter());const l=new x(o,e,{createIfNotExists:(r=t==null?void 0:t.createIfNotExists)!==null&&r!==void 0?r:!1,forceRecreate:(i=t==null?void 0:t.forceRecreate)!==null&&i!==void 0?i:!1});return g.debug("UniversalDAO instance created successfully",{dbPath:e,adapterName:o.constructor.name}),l}static async openExisting(e,t={}){g.info("Opening existing database",{dbName:e,options:t});const a=e.endsWith(".db")?e:`${e}.db`;g.debug("Resolved database filename",{originalName:e,resolvedName:a});const s=this.createDAO(a,t);try{return g.debug("Connecting to database",{dbFileName:a}),await s.connect(),g.debug("Running integrity check",{dbFileName:a}),await s.execute("PRAGMA integrity_check"),g.info("Database opened successfully",{dbFileName:a}),s}catch(r){g.error("Error opening database",{dbFileName:a,error:r.message});try{await s.close()}catch(i){g.warn("Error closing DAO after failed open",{dbFileName:a,closeError:i.message})}throw new Error(`Error opening database '${a}': ${r.message}`)}}static async createOrOpenInternal(e,t=!1,a=!1){g.info("Creating or opening database internally",{isForceInit:t,isForceDelete:a,hasConfig:!!e.config,hasConfigAsset:!!e.configAsset});let s;if(g.trace("Loading database schema"),e.config)g.debug("Using provided config object"),s=e.config;else if(e.configAsset)g.debug("Using provided config asset"),s=e.configAsset;else throw g.error("No database schema configuration provided"),new Error("Either 'config', 'configAsset', or 'configPath' must be provided to the factory.");g.trace("Validating schema configuration"),this.validateSchema(s);const r=s.database_name.endsWith(".db")?s.database_name:`${s.database_name}.db`;g.debug("Database filename resolved",{originalName:s.database_name,resolvedName:r}),g.debug("Creating DAO instance",{dbFileName:r,hasCustomAdapter:!!e.adapter,createIfNotExists:t,forceRecreate:a});const i=this.createDAO(r,{adapter:e.adapter,createIfNotExists:t,forceRecreate:a});try{g.debug("Connecting to database",{dbFileName:r}),await i.connect(),g.debug("Initializing database schema",{dbFileName:r}),await i.initializeFromSchema(s),g.debug("Validating schema version compatibility");try{await this.validateSchemaVersion(i,s)}catch(o){throw g.error("Schema version validation failed",{dbFileName:r,error:o.message}),await i.close(),new Error(`Schema mismatch in existing database. Use forceRecreate=true to recreate with updated schema. Error: ${o.message}`)}return g.info("Database created/opened successfully",{dbFileName:r,databaseName:s.database_name,version:s.version}),i}catch(o){if(g.error("Error during database creation/opening",{dbFileName:r,error:o.message}),i.isConnectionOpen())try{await i.close()}catch(l){g.warn("Error closing DAO after failed operation",{dbFileName:r,closeError:l.message})}throw o}}static async create(e){var t,a;return g.warn("Creating database with force recreate - this will delete existing database",{databaseName:((t=e.config)===null||t===void 0?void 0:t.database_name)||((a=e.configAsset)===null||a===void 0?void 0:a.database_name)}),this.createOrOpenInternal(e,!0,!0)}static async createOrOpen(e,t=!1){var a,s;return g.info("Smart create or open database",{databaseName:((a=e.config)===null||a===void 0?void 0:a.database_name)||((s=e.configAsset)===null||s===void 0?void 0:s.database_name),isForceInit:t}),this.createOrOpenInternal(e,t)}static async createFromAsset(e,t={}){g.info("Creating database from asset",{databaseName:e.database_name,version:e.version});try{return await this.create(Object.assign(Object.assign({},t),{configAsset:e}))}catch(a){throw g.error("Error creating database from asset",{databaseName:e.database_name,error:a.message}),new Error(`Error creating database from asset: ${a.message}`)}}static async createFromConfig(e,t={}){g.info("Creating database from config",{databaseName:e.database_name,version:e.version});try{return await this.create(Object.assign(Object.assign({},t),{config:e}))}catch(a){throw g.error("Error creating database from config",{databaseName:e.database_name,error:a.message}),new Error(`Error creating database from config: ${a.message}`)}}}v.adapters=[];const n=w(b.DATABASE_MANAGER);class p{static getMaxConnections(){return n.trace("Getting max connections",{maxConnections:this.maxConnections}),this.maxConnections}static setMaxConnections(e){if(n.debug("Setting max connections",{newMaxConnections:e,currentMax:this.maxConnections}),e<=0)throw n.error("Invalid max connections value",{maxConnections:e}),new Error("Maximum connections must be a positive number");const t=Object.keys(this.connections).length;if(t>e)throw n.error("Cannot set max connections - would exceed current active connections",{requestedMax:e,currentActiveConnections:t,activeConnectionKeys:Object.keys(this.connections)}),new Error(`Cannot set maximum connections to ${e}. Current active connections (${t}) exceed the new limit. Please close some connections first.`);this.maxConnections=e,n.info("Max connections updated successfully",{newMaxConnections:e,currentActiveConnections:t})}static setSchemaManager(e){n.debug("Setting schema manager",{hadPreviousManager:this.schemaManager!==null}),this.schemaManager=e,n.info("Schema manager set successfully")}static registerSchema(e,t){n.debug("Registering schema",{key:e,schemaName:t.database_name}),this.schemaConfigurations[e]=t,n.info("Schema registered successfully",{key:e,schemaName:t.database_name})}static registerSchemas(e){const t=Object.keys(e);n.debug("Registering multiple schemas",{count:t.length,keys:t}),Object.entries(e).forEach(([a,s])=>{this.registerSchema(a,s)}),n.info("Multiple schemas registered successfully",{count:t.length})}static getSchema(e){if(n.trace("Getting schema",{key:e}),this.schemaConfigurations[e])return n.trace("Schema found in internal configurations",{key:e}),this.schemaConfigurations[e];if(this.schemaManager){n.trace("Checking external schema manager",{key:e});const t=this.schemaManager.getSchema(e);if(t)return n.trace("Schema found in external manager",{key:e}),t}n.warn("Schema not found",{key:e})}static getAvailableSchemas(){var e;const t=Object.keys(this.schemaConfigurations),a=((e=this.schemaManager)===null||e===void 0?void 0:e.getAllSchemaKeys())||[],s=[...new Set([...t,...a])];return n.trace("Getting available schemas",{internalCount:t.length,externalCount:a.length,totalUnique:s.length}),s}static registerRole(e){n.debug("Registering role",{roleName:e.roleName,requiredDatabases:e.requiredDatabases,optionalDatabases:e.optionalDatabases,priority:e.priority}),this.roleRegistry[e.roleName]=e,n.info("Role registered successfully",{roleName:e.roleName})}static registerRoles(e){n.debug("Registering multiple roles",{count:e.length}),e.forEach(t=>this.registerRole(t)),n.info("Multiple roles registered successfully",{count:e.length})}static getRegisteredRoles(){return n.trace("Getting registered roles",{count:Object.keys(this.roleRegistry).length}),Object.assign({},this.roleRegistry)}static getRoleDatabases(e){n.trace("Getting role databases",{roleName:e});const t=this.roleRegistry[e];if(!t)throw n.error("Role not found in registry",{roleName:e,availableRoles:Object.keys(this.roleRegistry)}),new Error(`Role '${e}' is not registered.`);const a=[...t.requiredDatabases,...t.optionalDatabases||[]];return n.trace("Role databases retrieved",{roleName:e,databases:a}),a}static getCurrentUserDatabases(){n.trace("Getting current user databases",{currentUserRoles:this.currentUserRoles});const e=new Set;e.add("core");for(const a of this.currentUserRoles){const s=this.roleRegistry[a];s?(s.requiredDatabases.forEach(r=>e.add(r)),s.optionalDatabases&&s.optionalDatabases.forEach(r=>e.add(r))):n.warn("Role config not found for current user role",{roleName:a})}const t=Array.from(e);return n.debug("Current user databases calculated",{userRoles:this.currentUserRoles,databases:t}),t}static async initializeCoreConnection(){if(n.debug("Initializing core database connection"),this.connections.core){n.debug("Core connection already exists");return}try{const e=this.getSchema("core");if(!e)throw n.error("Core database schema not found"),new Error("Core database schema not found.");n.debug("Creating core database connection",{schemaName:e.database_name});const t=await v.createOrOpen({config:e},!1);await t.execute("PRAGMA integrity_check"),this.connections.core=t,n.info("Core database connection initialized successfully")}catch(e){throw n.error("Error initializing core database",{error:e.message}),new Error(`Error initializing core database: ${e.message}`)}}static async setCurrentUserRoles(e,t){n.debug("Setting current user roles",{userRoles:e,primaryRole:t});for(const s of e)if(!this.roleRegistry[s])throw n.error("Role not registered",{roleName:s,availableRoles:Object.keys(this.roleRegistry)}),new Error(`Role '${s}' is not registered. Please register it first.`);const a=[...this.currentUserRoles];this.currentUserRoles=e,this.currentRole=t||e[0]||null,n.info("User roles updated",{previousRoles:a,newRoles:e,primaryRole:this.currentRole});try{await this.initializeUserRoleConnections(),await this.cleanupUnusedConnections(a),n.info("User role connections initialized successfully")}catch(s){throw n.error("Failed to initialize user role connections",{error:s.message}),s}}static getCurrentUserRoles(){return n.trace("Getting current user roles",{roles:this.currentUserRoles}),[...this.currentUserRoles]}static getCurrentRole(){return n.trace("Getting current primary role",{role:this.currentRole}),this.currentRole}static async initializeUserRoleConnections(){const e=this.getCurrentUserDatabases();n.debug("Initializing user role connections",{requiredDatabases:e});const t=[],a=e.map(async s=>{if(this.connections[s]){n.trace("Database already connected",{dbKey:s});return}try{n.debug("Initializing database connection",{dbKey:s});const r=this.getSchema(s);if(!r)throw new Error(`Database key '${s}' not found in schema configurations.`);const i=await v.createOrOpen({config:r},!1);await i.execute("PRAGMA integrity_check"),this.connections[s]=i,n.info("Database connection initialized",{dbKey:s,schemaName:r.database_name})}catch(r){const i=r instanceof Error?r:new Error(String(r));n.error("Failed to initialize database connection",{dbKey:s,error:i.message}),this.currentUserRoles.some(o=>{const l=this.roleRegistry[o];return l&&l.requiredDatabases.includes(s)})?t.push({key:s,error:i}):n.warn("Optional database initialization failed",{dbKey:s,error:i.message})}});if(await Promise.all(a),t.length>0){const s=t.map(r=>` - ${r.key}: ${r.error.message}`).join(`
6
6
  `);throw n.error("Failed to initialize required databases",{failedDatabases:t.map(r=>r.key),errorSummary:s}),new Error(`Failed to initialize required databases for user roles:
7
7
  ${s}`)}}static async cleanupUnusedConnections(e){n.debug("Cleaning up unused connections",{previousRoles:e});const t=new Set;t.add("core");for(const r of e){const i=this.roleRegistry[r];i&&(i.requiredDatabases.forEach(o=>t.add(o)),i.optionalDatabases&&i.optionalDatabases.forEach(o=>t.add(o)))}const a=new Set(this.getCurrentUserDatabases()),s=Array.from(t).filter(r=>!a.has(r));if(n.debug("Databases to cleanup",{databasesToClose:s,previousDatabaseCount:t.size,currentDatabaseCount:a.size}),s.length>0){for(const r of s)if(this.connections[r])try{n.debug("Closing unused database connection",{dbKey:r}),await this.connections[r].close(),delete this.connections[r],n.info("Database connection closed",{dbKey:r})}catch(i){n.error("Error closing database connection during cleanup",{dbKey:r,error:i.message})}n.info("Cleanup completed",{closedConnections:s})}else n.debug("No connections to cleanup")}static hasAccessToDatabase(e){const t=this.getSchema(e)!==void 0;return n.trace("Checking database access",{dbKey:e,hasAccess:t}),t}static get(e){if(n.trace("Getting database connection",{key:e}),!this.hasAccessToDatabase(e))throw n.error("Access denied to database",{key:e}),new Error(`Access denied: Database '${e}' is not accessible.`);const t=this.connections[e];if(!t)throw n.error("Database not connected",{key:e,availableConnections:Object.keys(this.connections)}),new Error(`Database '${e}' is not connected. Please ensure it's initialized.`);return n.trace("Database connection retrieved successfully",{key:e}),t}static onDatabaseReconnect(e,t){n.debug("Registering database reconnect listener",{schemaName:e}),this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),n.trace("Database reconnect listener registered",{schemaName:e,listenerCount:this.eventListeners.get(e).length})}static offDatabaseReconnect(e,t){n.debug("Removing database reconnect listener",{schemaName:e});const a=this.eventListeners.get(e);if(a){const s=a.indexOf(t);s>-1?(a.splice(s,1),n.trace("Database reconnect listener removed",{schemaName:e,remainingListeners:a.length})):n.warn("Database reconnect listener not found for removal",{schemaName:e})}else n.warn("No listeners found for schema",{schemaName:e})}static notifyDatabaseReconnect(e,t){const a=this.eventListeners.get(e);a?(n.debug("Notifying database reconnect listeners",{schemaName:e,listenerCount:a.length}),a.forEach((s,r)=>{try{s(t),n.trace("Database reconnect listener notified",{schemaName:e,listenerIndex:r})}catch(i){n.error("Error in database reconnect listener",{schemaName:e,listenerIndex:r,error:i.message})}})):n.trace("No listeners to notify for database reconnection",{schemaName:e})}static async closeAllConnections(){if(this.isClosingConnections){n.debug("Already closing connections, skipping");return}n.info("Closing all database connections",{connectionCount:Object.keys(this.connections).length}),this.isClosingConnections=!0;try{const e=Object.keys(this.connections);e.forEach(a=>this.activeDatabases.add(a)),n.debug("Saving active database list for potential reconnection",{activeDatabases:e});const t=Object.entries(this.connections).map(async([a,s])=>{try{n.debug("Closing database connection",{dbKey:a}),await s.close(),n.trace("Database connection closed",{dbKey:a})}catch(r){n.error("Error closing database connection",{dbKey:a,error:r.message})}});await Promise.all(t),this.connections={},n.info("All database connections closed successfully")}finally{this.isClosingConnections=!1}}static async reopenConnections(){n.info("Reopening database connections");try{await this.initializeCoreConnection(),this.currentUserRoles.length>0&&await this.initializeUserRoleConnections();const e=Array.from(this.activeDatabases);if(n.debug("Reinitializing previously active databases",{activeDatabases:e}),e.length>0)for(const t of e)if(this.connections[t])this.connections[t]&&(n.trace("Database already connected, notifying listeners",{dbKey:t}),this.notifyDatabaseReconnect(t,this.connections[t]));else{const a=this.getSchema(t);if(a)try{n.debug("Reopening database connection",{dbKey:t});const s=await v.createOrOpen({config:a},!1);await s.connect(),this.connections[t]=s,this.notifyDatabaseReconnect(t,s),n.info("Database connection reopened",{dbKey:t})}catch(s){n.error("Failed to reopen database connection",{dbKey:t,error:s.message})}else n.warn("Schema not found for previously active database",{dbKey:t})}n.info("Database connections reopened successfully")}catch(e){throw n.error("Failed to reopen database connections",{error:e.message}),e}}static async ensureDatabaseConnection(e){if(n.debug("Ensuring database connection",{key:e}),this.activeDatabases.add(e),!this.hasAccessToDatabase(e))throw n.error("Access denied when ensuring database connection",{key:e}),new Error(`Access denied: Database '${e}' is not accessible.`);if(this.connections[e])try{if(this.connections[e].isConnectionOpen())return n.trace("Database connection already active",{key:e}),this.connections[e];n.warn("Database connection inactive, cleaning up",{key:e});try{await this.connections[e].close().catch(()=>{})}catch(t){n.debug("Error during connection cleanup",{key:e,error:t.message})}delete this.connections[e]}catch(t){n.error("Error checking connection status",{key:e,error:t.message}),delete this.connections[e]}return n.debug("Creating new database connection",{key:e}),await this.getLazyLoading(e)}static getConnections(){return n.trace("Getting all connections",{count:Object.keys(this.connections).length}),Object.assign({},this.connections)}static async openAllExisting(e){n.info("Opening all existing databases",{databaseKeys:e});const t=[];for(const a of e)try{n.debug("Opening database",{key:a});const s=this.getSchema(a);if(!s)throw new Error(`Invalid database key: ${a}. Schema not found.`);const r=await v.createOrOpen({config:s},!1);await r.execute("PRAGMA integrity_check"),this.connections[a]=r,n.info("Database opened successfully",{key:a,schemaName:s.database_name})}catch(s){const r=s instanceof Error?s:new Error(String(s));n.error("Failed to open database",{key:a,error:r.message}),t.push({key:a,error:r})}if(t.length>0){const a=t.map(s=>` - ${s.key}: ${s.error.message}`).join(`
8
8
  `);throw n.error("Failed to open one or more databases",{failedDatabases:t.map(s=>s.key),errorSummary:a}),new Error(`Failed to open one or more databases:
@@ -10,5 +10,5 @@ ${a}`)}return this.isInitialized=!0,n.info("All databases opened successfully",{
10
10
  `);throw n.error("Failed to initialize one or more databases",{failedDatabases:r.map(l=>l.key),errorSummary:o}),new Error(`Failed to initialize one or more databases:
11
11
  ${o}`)}return Object.keys(this.connections).length>0&&(this.isInitialized=!0,n.info("Lazy schema initialization completed",{initializedCount:e.length-r.length})),!0}static async initializeAll(){if(this.isInitialized){n.debug("Database manager already initialized");return}const e=this.getAvailableSchemas();n.info("Initializing all available databases",{schemaCount:e.length,schemas:e});const t=[],a=e.map(async s=>{try{n.debug("Initializing schema",{key:s});const r=this.getSchema(s),i=await v.createOrOpen({config:r},!1);this.connections[s]=i,n.info("Schema initialized successfully",{key:s,schemaName:r.database_name})}catch(r){const i=r instanceof Error?r:new Error(String(r));n.error("Failed to initialize schema",{key:s,error:i.message}),t.push({key:s,error:i})}});if(await Promise.all(a),t.length>0){this.isInitialized=!1;const s=t.map(r=>` - ${r.key}: ${r.error.message}`).join(`
12
12
  `);throw n.error("Failed to initialize one or more databases",{failedDatabases:t.map(r=>r.key),errorSummary:s}),new Error(`Failed to initialize one or more databases:
13
- ${s}`)}this.isInitialized=!0,n.info("All databases initialized successfully",{totalSchemas:e.length})}static async getLazyLoading(e){if(n.debug("Getting database with lazy loading",{key:e}),this.activeDatabases.add(e),!this.hasAccessToDatabase(e))throw n.error("Access denied for lazy loading",{key:e}),new Error(`Access denied: Database '${e}' is not accessible.`);if(!this.connections[e]){const t=this.getSchema(e);if(!t)throw n.error("Schema not found for lazy loading",{key:e}),new Error(`Invalid database key: ${e}. Schema not found.`);if(Object.keys(this.connections).length>=this.maxConnections)throw n.error("Maximum connections reached",{currentConnections:Object.keys(this.connections).length,maxConnections:this.maxConnections}),new Error("Maximum number of database connections reached");n.debug("Creating new connection for lazy loading",{key:e,schemaName:t.database_name});const a=await v.createOrOpen({config:t},!1);await a.connect(),this.connections[e]=a,n.info("Database connection created via lazy loading",{key:e})}return this.isInitialized=!0,this.connections[e]}static async executeCrossSchemaTransaction(e,t){n.debug("Executing cross-schema transaction",{schemas:e});for(const s of e)if(!this.hasAccessToDatabase(s))throw n.error("Access denied for cross-schema transaction",{key:s,schemas:e}),new Error(`Access denied: Database '${s}' is not accessible.`);const a=e.reduce((s,r)=>(s[r]=this.get(r),s),{});n.debug("Starting cross-schema transaction",{schemas:e});try{await Promise.all(Object.values(a).map(s=>s.beginTransaction())),n.trace("All transactions started successfully"),await t(a),n.trace("Transaction callback completed successfully"),await Promise.all(Object.values(a).map(s=>s.commitTransaction())),n.info("Cross-schema transaction completed successfully",{schemas:e})}catch(s){throw n.error("Cross-schema transaction failed, rolling back",{schemas:e,error:s.message}),await Promise.all(Object.values(a).map(r=>r.rollbackTransaction())),n.debug("Cross-schema transaction rolled back"),s}}static async importDataToTable(e,t,a,s={}){if(n.debug("Importing data to table",{databaseKey:e,tableName:t,recordCount:a.length,options:s}),!this.hasAccessToDatabase(e))throw n.error("Access denied for data import",{databaseKey:e,tableName:t}),new Error(`Access denied: Database '${e}' is not accessible.`);const r=this.get(e);try{const i=await r.importData(Object.assign({tableName:t,data:a},s));return n.info("Data import completed successfully",{databaseKey:e,tableName:t,importedRows:i.successRows,skippedRows:i.errorRows}),i}catch(i){throw n.error("Data import failed",{databaseKey:e,tableName:t,error:i.message}),i}}static async importDataWithMapping(e,t,a,s,r={}){if(n.debug("Importing data with column mapping",{databaseKey:e,tableName:t,recordCount:a.length,mappingCount:s.length,options:r}),!this.hasAccessToDatabase(e))throw n.error("Access denied for data import with mapping",{databaseKey:e,tableName:t}),new Error(`Access denied: Database '${e}' is not accessible.`);const i=this.get(e);try{const o=await i.importDataWithMapping(t,a,s,r);return n.info("Data import with mapping completed successfully",{databaseKey:e,tableName:t,importedRows:o.successRows,skippedRows:o.errorRows}),o}catch(o){throw n.error("Data import with mapping failed",{databaseKey:e,tableName:t,error:o.message}),o}}static async bulkImport(e){const t=Date.now();n.info("Starting bulk import",{configCount:e.length,configs:e.map(s=>({databaseKey:s.databaseKey,tableName:s.tableName,recordCount:s.data.length}))});const a={totalDatabases:e.length,successDatabases:0,results:{},errors:{},executionTime:0};for(const s of e){const r=`${s.databaseKey}.${s.tableName}`;n.debug("Processing bulk import config",{configKey:r});try{if(!this.hasAccessToDatabase(s.databaseKey))throw new Error(`Access denied: Database '${s.databaseKey}' is not accessible.`);const i=this.get(s.databaseKey);let o;s.columnMappings?(n.trace("Using column mappings for import",{configKey:r}),o=await i.importDataWithMapping(s.tableName,s.data,s.columnMappings,s.options)):(n.trace("Using direct import",{configKey:r}),o=await i.importData(Object.assign({tableName:s.tableName,data:s.data},s.options))),a.results[r]=o,a.successDatabases++,n.info("Bulk import config completed successfully",{configKey:r,importedRows:o.successRows,skippedRows:o.errorRows})}catch(i){const o=i instanceof Error?i:new Error(String(i));n.error("Bulk import config failed",{configKey:r,error:o.message}),a.errors[r]=o}}return a.executionTime=Date.now()-t,n.info("Bulk import completed",{totalConfigs:a.totalDatabases,successfulConfigs:a.successDatabases,failedConfigs:Object.keys(a.errors).length,executionTimeMs:a.executionTime}),a}static async importFromCSV(e,t,a,s={}){if(n.debug("Importing from CSV",{databaseKey:e,tableName:t,csvSize:a.length,options:s}),!this.hasAccessToDatabase(e))throw n.error("Access denied for CSV import",{databaseKey:e,tableName:t}),new Error(`Access denied: Database '${e}' is not accessible.`);const r=this.get(e);try{const i=await r.importFromCSV(t,a,s);return n.info("CSV import completed successfully",{databaseKey:e,tableName:t,importedRows:i.successRows,skippedRows:i.errorRows}),i}catch(i){throw n.error("CSV import failed",{databaseKey:e,tableName:t,error:i.message}),i}}static getConnectionCount(){const e=Object.keys(this.connections).length;return n.trace("Getting connection count",{count:e}),e}static listConnections(){const e=Object.keys(this.connections);return n.trace("Listing connections",{connections:e}),e}static async closeConnection(e){n.debug("Closing specific connection",{dbKey:e});const t=this.connections[e];if(t)try{await t.disconnect(),delete this.connections[e],n.info("Database connection closed successfully",{dbKey:e})}catch(a){throw n.error("Error closing database connection",{dbKey:e,error:a.message}),a}else n.warn("Attempted to close non-existent connection",{dbKey:e})}static async closeAll(){n.info("Closing all connections and resetting state"),await this.closeAllConnections(),this.currentUserRoles=[],this.currentRole=null,this.isInitialized=!1,this.activeDatabases.clear(),this.eventListeners.clear(),this.isClosingConnections=!1,n.info("All connections closed and state reset successfully")}static async logout(){n.info("Logging out user",{currentUserRoles:this.currentUserRoles});const e=Object.keys(this.connections).filter(t=>t!=="core");n.debug("Closing role-specific connections",{connectionsToClose:e});for(const t of e)try{await this.connections[t].close(),delete this.connections[t],n.debug("Role-specific connection closed",{dbKey:t})}catch(a){n.error("Error closing connection during logout",{dbKey:t,error:a.message})}this.currentUserRoles=[],this.currentRole=null,n.info("User logout completed successfully",{closedConnections:e.length})}}p.maxConnections=10,p.connections={},p.isInitialized=!1,p.roleRegistry={},p.currentRole=null,p.currentUserRoles=[],p.activeDatabases=new Set,p.isClosingConnections=!1,p.schemaConfigurations={},p.schemaManager=null,p.eventListeners=new Map;const c=w(b.BASE_SERVICE);class D{constructor(e,t){this.dao=null,this.isOpened=!1,this.isInitialized=!1,this.errorHandlers=new Map,this.eventListeners=new Map,this.primaryKeyFields=["id"],this.cache=new Map,this.schemaName=e,this.tableName=t||e,c.debug("Creating BaseService instance",{schemaName:this.schemaName,tableName:this.tableName,primaryKeyFields:this.primaryKeyFields}),this.reconnectHandler=a=>{c.info("Database reconnected for service",{schemaName:this.schemaName,tableName:this.tableName}),this.dao=a,this._emit("daoReconnected",{schemaName:this.schemaName})},p.onDatabaseReconnect(e,this.reconnectHandler),this.bindMethods(),c.trace("BaseService instance created successfully",{schemaName:this.schemaName,tableName:this.tableName})}bindMethods(){c.trace("Binding service methods",{schemaName:this.schemaName,tableName:this.tableName}),Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach(e=>{typeof this[e]=="function"&&e!=="constructor"&&(this[e]=this[e].bind(this))})}setPrimaryKeyFields(e){return c.debug("Setting primary key fields",{schemaName:this.schemaName,tableName:this.tableName,previousFields:this.primaryKeyFields,newFields:e}),this.primaryKeyFields=e,this}async init(){c.info("Initializing BaseService",{schemaName:this.schemaName,tableName:this.tableName,isInitialized:this.isInitialized});try{if(this.isInitialized)return c.debug("Service already initialized, skipping",{schemaName:this.schemaName}),this;if(c.debug("Getting DAO from DatabaseManager",{schemaName:this.schemaName}),this.dao=await p.getLazyLoading(this.schemaName),!this.dao){const e=`Failed to initialize DAO for schema: ${this.schemaName}`;throw c.error(e,{schemaName:this.schemaName}),new Error(e)}return this.dao.isConnectionOpen()||(c.debug("DAO connection not open, connecting",{schemaName:this.schemaName}),await this.dao.connect()),this.isOpened=!0,this.isInitialized=!0,c.info("BaseService initialized successfully",{schemaName:this.schemaName,tableName:this.tableName,isOpened:this.isOpened,isInitialized:this.isInitialized}),this._emit("initialized",{schemaName:this.schemaName}),this}catch(e){throw c.error("Error initializing BaseService",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),this._handleError("INIT_ERROR",e),e}}async create(e){c.debug("Creating new record",{schemaName:this.schemaName,tableName:this.tableName,hasData:!!e,dataKeys:e?Object.keys(e):[]}),await this._ensureInitialized(),await this.ensureValidConnection();try{this._validateData(e),c.trace("Building data table for insert",{schemaName:this.schemaName,tableName:this.tableName});const t=this.buildDataTable(e),a=await this.dao.insert(t);if(a.rowsAffected===0){const i="Insert operation failed - no rows affected";throw c.error(i,{schemaName:this.schemaName,tableName:this.tableName,result:a}),new Error(i)}c.debug("Insert operation successful",{schemaName:this.schemaName,tableName:this.tableName,rowsAffected:a.rowsAffected,lastInsertRowId:a.lastInsertRowId});let s=null;const r=e[this.primaryKeyFields[0]];try{r!=null?(c.trace("Retrieving created record by primary key",{schemaName:this.schemaName,tableName:this.tableName,primaryKeyField:this.primaryKeyFields[0],primaryKeyValue:r}),s=await this.findById(r)):a.lastInsertRowId&&(c.trace("Retrieving created record by last insert ID",{schemaName:this.schemaName,tableName:this.tableName,lastInsertRowId:a.lastInsertRowId}),s=await this.findById(a.lastInsertRowId))}catch(i){c.warn("Could not retrieve created record",{schemaName:this.schemaName,tableName:this.tableName,findError:i.message})}return s||(c.debug("Using original data as created record",{schemaName:this.schemaName,tableName:this.tableName}),s=e),c.info("Record created successfully",{schemaName:this.schemaName,tableName:this.tableName,recordRetrieved:!!s}),this._emit("dataCreated",{operation:"create",data:s}),s}catch(t){throw c.error("Error creating record",{schemaName:this.schemaName,tableName:this.tableName,error:t.message}),this._handleError("CREATE_ERROR",t),t}}async update(e,t){c.debug("Updating record",{schemaName:this.schemaName,tableName:this.tableName,id:e,hasData:!!t,dataKeys:t?Object.keys(t):[]}),await this._ensureInitialized();try{if(!e){const i="ID is required for update";throw c.error(i,{schemaName:this.schemaName,tableName:this.tableName}),new Error(i)}this._validateData(t);const a=Object.assign(Object.assign({},t),{[this.primaryKeyFields[0]]:e});c.trace("Building update query table",{schemaName:this.schemaName,tableName:this.tableName,id:e});const s=this.buildDataTable(a);await this.dao.update(s),c.debug("Update operation completed",{schemaName:this.schemaName,tableName:this.tableName,id:e});const r=await this.findById(e);return c.info("Record updated successfully",{schemaName:this.schemaName,tableName:this.tableName,id:e,recordFound:!!r}),this._emit("dataUpdated",{operation:"update",id:e,data:r}),r}catch(a){throw c.error("Error updating record",{schemaName:this.schemaName,tableName:this.tableName,id:e,error:a.message}),this._handleError("UPDATE_ERROR",a),a}}async delete(e){c.debug("Deleting record",{schemaName:this.schemaName,tableName:this.tableName,id:e}),await this._ensureInitialized();try{if(!e){const r="ID is required for delete";throw c.error(r,{schemaName:this.schemaName,tableName:this.tableName}),new Error(r)}const t={name:this.tableName,cols:[],wheres:[{name:this.primaryKeyFields[0],value:e}]};c.trace("Executing delete operation",{schemaName:this.schemaName,tableName:this.tableName,id:e,primaryKeyField:this.primaryKeyFields[0]});const a=await this.dao.delete(t),s=a.rowsAffected>0;return s?(c.info("Record deleted successfully",{schemaName:this.schemaName,tableName:this.tableName,id:e,rowsAffected:a.rowsAffected}),this._emit("dataDeleted",{operation:"delete",id:e})):c.warn("Delete operation completed but no rows affected",{schemaName:this.schemaName,tableName:this.tableName,id:e}),s}catch(t){throw c.error("Error deleting record",{schemaName:this.schemaName,tableName:this.tableName,id:e,error:t.message}),this._handleError("DELETE_ERROR",t),t}}async findById(e){c.debug("Finding record by ID",{schemaName:this.schemaName,tableName:this.tableName,id:e}),await this._ensureInitialized();try{if(!e){const i="ID is required";throw c.error(i,{schemaName:this.schemaName,tableName:this.tableName}),new Error(i)}const t={[this.primaryKeyFields[0]]:e};c.trace("Building select query",{schemaName:this.schemaName,tableName:this.tableName,conditions:t});const a=this.buildSelectTable(t),s=await this.dao.select(a),r=Object.keys(s).length>0?s:null;return c.debug("Find by ID completed",{schemaName:this.schemaName,tableName:this.tableName,id:e,recordFound:!!r}),this._emit("dataFetched",{operation:"findById",id:e}),r}catch(t){throw c.error("Error finding record by ID",{schemaName:this.schemaName,tableName:this.tableName,id:e,error:t.message}),this._handleError("FIND_BY_ID_ERROR",t),t}}async findFirst(e={}){c.debug("Finding first record",{schemaName:this.schemaName,tableName:this.tableName,conditionsCount:Object.keys(e).length,conditions:e}),await this._ensureInitialized();try{c.trace("Building select query for findFirst",{schemaName:this.schemaName,tableName:this.tableName});const t=this.buildSelectTable(e),a=await this.dao.select(t),s=Object.keys(a).length>0?a:null;return c.debug("Find first completed",{schemaName:this.schemaName,tableName:this.tableName,recordFound:!!s}),this._emit("dataFetched",{operation:"findFirst"}),s}catch(t){throw c.error("Error finding first record",{schemaName:this.schemaName,tableName:this.tableName,conditions:e,error:t.message}),this._handleError("FIND_FIRST_ERROR",t),t}}async findAll(e={},t={}){c.debug("Finding all records",{schemaName:this.schemaName,tableName:this.tableName,conditionsCount:Object.keys(e).length,hasLimit:!!t.limit,hasOffset:!!t.offset,hasOrderBy:!!(t.orderBy&&t.orderBy.length>0),limit:t.limit,offset:t.offset}),await this._ensureInitialized();try{const a=[...this.buildWhereFromObject(e),...t.where||[]];c.trace("Building query for findAll",{schemaName:this.schemaName,tableName:this.tableName,totalWheres:a.length,hasColumns:!!(t.columns&&t.columns.length>0)});const s={name:this.tableName,cols:t.columns?t.columns.map(i=>({name:i})):[],wheres:a,orderbys:t.orderBy,limitOffset:{limit:t.limit,offset:t.offset}},r=await this.dao.selectAll(s);return c.info("Find all completed",{schemaName:this.schemaName,tableName:this.tableName,recordsFound:r.length,conditionsCount:Object.keys(e).length}),this._emit("dataFetched",{operation:"findAll",count:r.length}),r}catch(a){throw c.error("Error finding all records",{schemaName:this.schemaName,tableName:this.tableName,conditions:e,options:t,error:a.message}),this._handleError("FIND_ALL_ERROR",a),a}}async count(e){c.debug("Counting records",{schemaName:this.schemaName,tableName:this.tableName,hasWhere:!!e,whereType:e?Array.isArray(e)?"array":"object":"none"}),await this._ensureInitialized();try{let t=[];Array.isArray(e)?(t=e,c.trace("Using array where conditions",{schemaName:this.schemaName,whereCount:t.length})):e&&typeof e=="object"&&(t=this.buildWhereFromObject(e),c.trace("Built where conditions from object",{schemaName:this.schemaName,whereCount:t.length}));const a={name:this.tableName,cols:[{name:"COUNT(*) as count"}],wheres:t},s=(await this.dao.select(a)).count||0;return c.debug("Count completed",{schemaName:this.schemaName,tableName:this.tableName,count:s}),s}catch(t){throw c.error("Error counting records",{schemaName:this.schemaName,tableName:this.tableName,where:e,error:t.message}),this._handleError("COUNT_ERROR",t),t}}async exists(e){c.debug("Checking if record exists",{schemaName:this.schemaName,tableName:this.tableName,id:e});const t=await this.findById(e)!==null;return c.debug("Existence check completed",{schemaName:this.schemaName,tableName:this.tableName,id:e,exists:t}),t}async truncate(){c.warn("Truncating table - this will delete all data",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized();try{c.debug("Executing truncate operations",{schemaName:this.schemaName,tableName:this.tableName}),await this.dao.execute(`DELETE FROM ${this.tableName}`),await this.dao.execute(`DELETE FROM sqlite_sequence WHERE name='${this.tableName}'`),c.info("Table truncated successfully",{schemaName:this.schemaName,tableName:this.tableName}),this._emit("tableTruncated",{tableName:this.tableName})}catch(e){throw c.error("Error truncating table",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),this._handleError("TRUNCATE_ERROR",e),e}}async bulkInsert(e){c.info("Starting bulk insert",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length}),await this._ensureInitialized();try{if(!Array.isArray(e)||e.length===0){const a="Items must be a non-empty array";throw c.error(a,{schemaName:this.schemaName,tableName:this.tableName,itemsType:typeof e,itemsLength:Array.isArray(e)?e.length:"N/A"}),new Error(a)}c.debug("Executing bulk insert operation",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length});const t=await this.dao.importData({tableName:this.tableName,data:e,batchSize:1e3,skipErrors:!1,validateData:!0});return c.info("Bulk insert completed",{schemaName:this.schemaName,tableName:this.tableName,totalRows:t.totalRows,successRows:t.successRows,errorRows:t.errorRows}),this._emit("dataBulkCreated",{operation:"bulkInsert",count:t.successRows}),t}catch(t){throw c.error("Error during bulk insert",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length,error:t.message}),this._handleError("BULK_INSERT_ERROR",t),t}}async bulkCreate(e){c.info("Starting bulk create with transaction",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length}),await this._ensureInitialized();try{if(!Array.isArray(e)||e.length===0){const a="Data must be a non-empty array";throw c.error(a,{schemaName:this.schemaName,tableName:this.tableName,dataType:typeof e,dataLength:Array.isArray(e)?e.length:"N/A"}),new Error(a)}const t=[];return c.debug("Executing bulk create in transaction",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length}),await this.executeTransaction(async()=>{for(let a=0;a<e.length;a++){const s=e[a];a%100===0&&c.trace("Bulk create progress",{schemaName:this.schemaName,tableName:this.tableName,processed:a,total:e.length}),this._validateData(s);const r=this.buildDataTable(s);await this.dao.insert(r),t.push(s)}}),c.info("Bulk create completed successfully",{schemaName:this.schemaName,tableName:this.tableName,recordsCreated:t.length}),this._emit("dataBulkCreated",{operation:"bulkCreate",count:t.length}),t}catch(t){throw c.error("Error during bulk create",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length,error:t.message}),this._handleError("BULK_CREATE_ERROR",t),t}}async executeTransaction(e){c.debug("Starting transaction",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized();try{c.trace("Beginning database transaction",{schemaName:this.schemaName}),await this.dao.beginTransaction();const t=await e();return c.trace("Committing transaction",{schemaName:this.schemaName}),await this.dao.commitTransaction(),c.info("Transaction completed successfully",{schemaName:this.schemaName,tableName:this.tableName}),this._emit("transactionCompleted",{operation:"transaction"}),t}catch(t){c.error("Transaction failed, rolling back",{schemaName:this.schemaName,tableName:this.tableName,error:t.message});try{await this.dao.rollbackTransaction(),c.debug("Transaction rollback successful",{schemaName:this.schemaName})}catch(a){c.error("Error during transaction rollback",{schemaName:this.schemaName,rollbackError:a.message}),this._handleError("ROLLBACK_ERROR",a)}throw this._handleError("TRANSACTION_ERROR",t),t}}async importFromCSV(e,t={}){c.info("Starting CSV import",{schemaName:this.schemaName,tableName:this.tableName,csvDataLength:e.length,delimiter:t.delimiter,hasHeader:t.hasHeader,hasMappings:!!(t.columnMappings&&t.columnMappings.length>0)}),await this._ensureInitialized();try{const a=await this.dao.importFromCSV(this.tableName,e,t);return c.info("CSV import completed",{schemaName:this.schemaName,tableName:this.tableName,totalRows:a.totalRows,successRows:a.successRows,errorRows:a.errorRows}),this._emit("dataImported",{operation:"importFromCSV",result:a}),a}catch(a){throw c.error("Error during CSV import",{schemaName:this.schemaName,tableName:this.tableName,csvDataLength:e.length,error:a.message}),this._handleError("IMPORT_CSV_ERROR",a),a}}async importDataWithMapping(e,t,a={}){c.info("Starting import with column mapping",{schemaName:this.schemaName,tableName:this.tableName,dataCount:e.length,mappingsCount:t.length}),await this._ensureInitialized();try{const s=await this.dao.importDataWithMapping(this.tableName,e,t,a);return c.info("Import with mapping completed",{schemaName:this.schemaName,tableName:this.tableName,totalRows:s.totalRows,successRows:s.successRows,errorRows:s.errorRows}),this._emit("dataImported",{operation:"importWithMapping",result:s}),s}catch(s){throw c.error("Error during import with mapping",{schemaName:this.schemaName,tableName:this.tableName,dataCount:e.length,mappingsCount:t.length,error:s.message}),this._handleError("IMPORT_MAPPING_ERROR",s),s}}buildSelectTable(e={},t={}){c.trace("Building select table query",{schemaName:this.schemaName,tableName:this.tableName,conditionsCount:Object.keys(e).length,hasOptions:Object.keys(t).length>0});const a={name:this.tableName,cols:[],wheres:[],orderbys:t.orderBy||[],limitOffset:{}};return t.columns&&t.columns.length>0&&(a.cols=t.columns.map(s=>({name:s}))),e&&Object.keys(e).length>0&&(a.wheres=Object.entries(e).map(([s,r])=>({name:s,value:r,operator:"="}))),t.limit!==void 0&&(a.limitOffset.limit=t.limit),t.offset!==void 0&&(a.limitOffset.offset=t.offset),a}buildDataTable(e){return c.trace("Building data table for query",{schemaName:this.schemaName,tableName:this.tableName,dataKeys:Object.keys(e)}),this.dao.convertJsonToQueryTable(this.tableName,e,this.primaryKeyFields)}buildWhereFromObject(e){const t=Object.entries(e).filter(([a,s])=>s!==void 0).map(([a,s])=>({name:a,value:s}));return c.trace("Built where clauses from object",{schemaName:this.schemaName,originalKeys:Object.keys(e).length,filteredWheres:t.length}),t}on(e,t){return c.trace("Adding event listener",{schemaName:this.schemaName,tableName:this.tableName,event:e}),this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}off(e,t){c.trace("Removing event listener",{schemaName:this.schemaName,tableName:this.tableName,event:e});const a=this.eventListeners.get(e);if(a){const s=a.indexOf(t);s>-1&&a.splice(s,1)}return this}_emit(e,t){c.trace("Emitting event",{schemaName:this.schemaName,tableName:this.tableName,event:e,hasData:!!t});const a=this.eventListeners.get(e);a&&a.forEach(s=>{try{s(t)}catch(r){c.error("Error in event handler",{schemaName:this.schemaName,tableName:this.tableName,event:e,error:r.message})}})}setErrorHandler(e,t){return c.debug("Setting error handler",{schemaName:this.schemaName,tableName:this.tableName,errorType:e}),this.errorHandlers.set(e,t),this}_handleError(e,t){c.error("Handling service error",{schemaName:this.schemaName,tableName:this.tableName,errorType:e,error:t.message});const a=this.errorHandlers.get(e);if(a)try{a(t)}catch(s){c.error("Error in error handler",{schemaName:this.schemaName,tableName:this.tableName,errorType:e,handlerError:s.message})}this._emit("error",{errorType:e,error:t})}_validateData(e){if(!e||typeof e!="object"){const t="Data must be a valid object";throw c.error("Data validation failed",{schemaName:this.schemaName,tableName:this.tableName,dataType:typeof e,isNull:e===null}),new Error(t)}}async _ensureInitialized(){this.isInitialized||(c.debug("Service not initialized, initializing now",{schemaName:this.schemaName,tableName:this.tableName}),await this.init())}async ensureValidConnection(){var e;c.trace("Ensuring valid database connection",{schemaName:this.schemaName,tableName:this.tableName});try{!((e=this.dao)===null||e===void 0)&&e.isConnectionOpen()||(c.debug("Connection not valid, getting new connection",{schemaName:this.schemaName}),this.dao=await p.ensureDatabaseConnection(this.schemaName))}catch(t){c.warn("Error checking connection, getting new connection",{schemaName:this.schemaName,error:t.message}),this.dao=await p.ensureDatabaseConnection(this.schemaName)}}async getDatabaseInfo(){return c.trace("Getting database info",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized(),await this.dao.getDatabaseInfo()}async getTableInfo(){return c.trace("Getting table info",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized(),await this.dao.getTableInfo(this.tableName)}getStatus(){const e={schemaName:this.schemaName,tableName:this.tableName,isOpened:this.isOpened,isInitialized:this.isInitialized,hasDao:!!this.dao};return c.trace("Getting service status",e),e}async healthCheck(){c.debug("Performing health check",{schemaName:this.schemaName,tableName:this.tableName});try{await this._ensureInitialized();const e=await this.count(),t={healthy:!0,schemaName:this.schemaName,recordCount:e,timestamp:new Date().toISOString()};return c.info("Health check passed",{schemaName:this.schemaName,tableName:this.tableName,recordCount:e}),t}catch(e){const t={healthy:!1,schemaName:this.schemaName,error:e.message,timestamp:new Date().toISOString()};return c.error("Health check failed",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),t}}async close(){c.info("Closing BaseService",{schemaName:this.schemaName,tableName:this.tableName,isOpened:this.isOpened,isInitialized:this.isInitialized});try{return this.dao&&(await this.dao.close(),c.debug("DAO closed successfully",{schemaName:this.schemaName})),this.isOpened=!1,this.isInitialized=!1,this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear(),c.info("BaseService closed successfully",{schemaName:this.schemaName,tableName:this.tableName}),this._emit("closed",{schemaName:this.schemaName}),!0}catch(e){throw c.error("Error closing BaseService",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),this._handleError("CLOSE_ERROR",e),e}}destroy(){c.debug("Destroying BaseService",{schemaName:this.schemaName,tableName:this.tableName}),p.offDatabaseReconnect(this.schemaName,this.reconnectHandler),this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear(),c.trace("BaseService destroyed",{schemaName:this.schemaName,tableName:this.tableName})}async getAll(e={},t={}){return c.trace("Using getAll alias",{schemaName:this.schemaName,tableName:this.tableName}),this.findAll(e,t)}async getById(e){return c.trace("Using getById alias",{schemaName:this.schemaName,tableName:this.tableName,id:e}),this.findById(e)}async getFirst(e={}){return c.trace("Using getFirst alias",{schemaName:this.schemaName,tableName:this.tableName}),this.findFirst(e)}}class A{constructor(e){this.tableName="",this.selectFields=["*"],this.joinClauses=[],this.whereConditions=[],this.groupByFields=[],this.havingConditions=[],this.orderByFields=[],this.limitValue=null,this.offsetValue=null,this.params=[],this.unionQueries=[],this.subQueries=[],this.cteQueries=new Map,this.dao=null,this.dao=e||null}static table(e,t){const a=new A(t);return a.tableName=e,a}static from(e,t){return A.table(e,t)}select(e){return this.selectFields=Array.isArray(e)?e:[e],this}selectRaw(e){return this.selectFields=[e],this}selectDistinct(e){const t=Array.isArray(e)?e.join(", "):e;return this.selectFields=[`DISTINCT ${t}`],this}join(e,t,a="INNER"){return this.joinClauses.push({type:a,table:e,condition:t}),this}innerJoin(e,t){return this.join(e,t,"INNER")}leftJoin(e,t){return this.join(e,t,"LEFT")}rightJoin(e,t){return this.join(e,t,"RIGHT")}fullOuterJoin(e,t){return this.join(e,t,"FULL OUTER")}where(e,t,a){if(typeof e=="object")return Object.entries(e).forEach(([i,o])=>{this.whereConditions.push({field:i,operator:"=",value:o})}),this;let s="=",r=t;return arguments.length===3&&(s=t,r=a),this.whereConditions.push({field:e,operator:s,value:r}),this}whereEquals(e,t){return this.where(e,"=",t)}whereNot(e,t){return this.where(e,"!=",t)}whereLike(e,t){return this.where(e,"LIKE",t)}whereNotLike(e,t){return this.where(e,"NOT LIKE",t)}whereIn(e,t){return this.whereConditions.push({field:e,operator:"IN",value:t}),this}whereNotIn(e,t){return this.whereConditions.push({field:e,operator:"NOT IN",value:t}),this}whereBetween(e,t,a){return this.whereConditions.push({field:e,operator:"BETWEEN",value:[t,a]}),this}whereNotBetween(e,t,a){return this.whereConditions.push({field:e,operator:"NOT BETWEEN",value:[t,a]}),this}whereNull(e){return this.whereConditions.push({field:e,operator:"IS NULL",value:null}),this}whereNotNull(e){return this.whereConditions.push({field:e,operator:"IS NOT NULL",value:null}),this}whereExists(e){return this.whereConditions.push({field:"",operator:"EXISTS",value:e}),this}whereNotExists(e){return this.whereConditions.push({field:"",operator:"NOT EXISTS",value:e}),this}orWhere(e,t,a){return this.where(e,t,a)}groupBy(e){return this.groupByFields=Array.isArray(e)?e:[e],this}having(e,t,a){let s="=",r=t;return arguments.length===3&&(s=t,r=a),this.havingConditions.push({field:e,operator:s,value:r}),this}havingCount(e,t,a){return this.having(`COUNT(${e})`,t,a)}orderBy(e,t="ASC"){return this.orderByFields.push(`${e} ${t}`),this}orderByDesc(e){return this.orderBy(e,"DESC")}orderByRaw(e){return this.orderByFields.push(e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderBy(e,"ASC")}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}firstRow(){return this.limit(1)}paginate(e,t){return this.limitValue=t,this.offsetValue=(e-1)*t,this}union(e){return this.unionQueries.push(e),this}unionAll(e){return this.union(e)}with(e,t){return this.cteQueries.set(e,t),this}whereSubQuery(e,t,a){return this.subQueries.push({query:a,alias:""}),this.whereConditions.push({field:e,operator:t,value:a}),this}count(e="*"){return this.selectFields=[`COUNT(${e}) as count`],this}sum(e){return this.selectFields=[`SUM(${e}) as sum`],this}avg(e){return this.selectFields=[`AVG(${e}) as avg`],this}max(e){return this.selectFields=[`MAX(${e}) as max`],this}min(e){return this.selectFields=[`MIN(${e}) as min`],this}toSQL(){let e="";const t=[];if(this.cteQueries.size>0){const a=[];this.cteQueries.forEach((s,r)=>{const{sql:i,params:o}=s.toSQL();a.push(`${r} AS (${i})`),t.push(...o)}),e+=`WITH ${a.join(", ")} `}if(e+=`SELECT ${this.selectFields.join(", ")} FROM ${this.tableName}`,this.joinClauses.length>0&&this.joinClauses.forEach(a=>{e+=` ${a.type} JOIN ${a.table} ON ${a.condition}`}),this.whereConditions.length>0){const a=[];this.whereConditions.forEach(s=>{const{clause:r,conditionParams:i}=this.buildCondition(s);a.push(r),t.push(...i)}),e+=` WHERE ${a.join(" AND ")}`}if(this.groupByFields.length>0&&(e+=` GROUP BY ${this.groupByFields.join(", ")}`),this.havingConditions.length>0){const a=[];this.havingConditions.forEach(s=>{const{clause:r,conditionParams:i}=this.buildCondition(s);a.push(r),t.push(...i)}),e+=` HAVING ${a.join(" AND ")}`}return this.orderByFields.length>0&&(e+=` ORDER BY ${this.orderByFields.join(", ")}`),this.limitValue!==null&&(e+=` LIMIT ${this.limitValue}`),this.offsetValue!==null&&(e+=` OFFSET ${this.offsetValue}`),this.unionQueries.length>0&&this.unionQueries.forEach(a=>{const{sql:s,params:r}=a.toSQL();e+=` UNION ${s}`,t.push(...r)}),{sql:e,params:t}}buildCondition(e){const{field:t,operator:a,value:s}=e,r=[];switch(a.toUpperCase()){case"IN":case"NOT IN":const i=s.map(()=>"?").join(", ");return r.push(...s),{clause:`${t} ${a} (${i})`,conditionParams:r};case"BETWEEN":case"NOT BETWEEN":return r.push(s[0],s[1]),{clause:`${t} ${a} ? AND ?`,conditionParams:r};case"IS NULL":case"IS NOT NULL":return{clause:`${t} ${a}`,conditionParams:[]};case"EXISTS":case"NOT EXISTS":const{sql:o,params:l}=s.toSQL();return r.push(...l),{clause:`${a} (${o})`,conditionParams:r};default:if(s instanceof A){const{sql:m,params:f}=s.toSQL();return r.push(...f),{clause:`${t} ${a} (${m})`,conditionParams:r}}return r.push(s),{clause:`${t} ${a} ?`,conditionParams:r}}}async get(){if(!this.dao)throw new Error("DAO instance required for query execution");const{sql:e,params:t}=this.toSQL();return(await this.dao.execute(e,t)).rows}async first(){this.limit(1);const e=await this.get();return e.length>0?e[0]:null}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async exists(){return this.select("1").limit(1),(await this.get()).length>0}async countResult(){this.count();const e=await this.first();return e?e.count:0}static insert(e,t){const a=Object.keys(t),s=Object.values(t),r=s.map(()=>"?").join(", ");return{sql:`INSERT INTO ${e} (${a.join(", ")}) VALUES (${r})`,params:s}}static insertMany(e,t){if(t.length===0)throw new Error("Data array cannot be empty");const a=Object.keys(t[0]),s=a.map(()=>"?").join(", "),r=t.map(()=>`(${s})`).join(", "),i=t.flatMap(o=>Object.values(o));return{sql:`INSERT INTO ${e} (${a.join(", ")}) VALUES ${r}`,params:i}}static update(e,t,a,s=[]){const r=Object.keys(t).map(o=>`${o} = ?`).join(", "),i=[...Object.values(t),...s];return{sql:`UPDATE ${e} SET ${r} WHERE ${a}`,params:i}}static delete(e,t,a=[]){return{sql:`DELETE FROM ${e} WHERE ${t}`,params:a}}static upsert(e,t,a){const s=Object.keys(t),r=Object.values(t),i=r.map(()=>"?").join(", "),o=s.filter(f=>!a.includes(f)),l=o.length>0?o.map(f=>`${f} = excluded.${f}`).join(", "):"";let m=`INSERT INTO ${e} (${s.join(", ")}) VALUES (${i})`;return o.length>0?m+=` ON CONFLICT(${a.join(", ")}) DO UPDATE SET ${l}`:m+=` ON CONFLICT(${a.join(", ")}) DO NOTHING`,{sql:m,params:r}}clone(){if(!this.dao)throw new Error("DAO instance required for cloning QueryBuilder");const e=new A(this.dao);return e.tableName=this.tableName,e.selectFields=[...this.selectFields],e.joinClauses=[...this.joinClauses],e.whereConditions=[...this.whereConditions],e.groupByFields=[...this.groupByFields],e.havingConditions=[...this.havingConditions],e.orderByFields=[...this.orderByFields],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e.unionQueries=[...this.unionQueries],e.subQueries=[...this.subQueries],e.cteQueries=new Map(this.cteQueries),e}toRawSQL(){const{sql:e,params:t}=this.toSQL();let a=e;return t.forEach(s=>{typeof s=="string"?a=a.replace("?",`'${s.replace(/'/g,"''")}'`):s==null?a=a.replace("?","NULL"):a=a.replace("?",String(s))}),a}explain(){return this.selectFields=["EXPLAIN QUERY PLAN "+this.selectFields.join(", ")],this}}const g=w(b.SERVICE_MANAGER);class O extends D{}class S{constructor(){this.services=new Map,this.serviceConfigs=new Map,this.serviceMetadata=new Map,this.eventHandlers=new Map,this.isShuttingDown=!1,this.cleanupInterval=null,g.info("ServiceManager instance created"),this.bindMethods(),this.startPeriodicCleanup()}static getInstance(){return S.instance?g.trace("Returning existing ServiceManager singleton instance"):(g.debug("Creating new ServiceManager singleton instance"),S.instance=new S),S.instance}static resetInstance(){g.warn("Resetting ServiceManager singleton instance"),S.instance?(S.instance.destroy(),S.instance=null,g.info("ServiceManager singleton instance reset successfully")):g.debug("No ServiceManager instance to reset")}bindMethods(){g.trace("Binding ServiceManager methods");const e=Object.getOwnPropertyNames(Object.getPrototypeOf(this));e.forEach(t=>{typeof this[t]=="function"&&t!=="constructor"&&(this[t]=this[t].bind(this))}),g.trace("ServiceManager methods bound successfully",{methodCount:e.length})}createServiceKey(e,t){const a=`${e}:${t}`;return g.trace("Created service key",{schemaName:e,tableName:t,key:a}),a}validateServiceConfig(e){var t,a;if(g.trace("Validating service config",{schemaName:e.schemaName,tableName:e.tableName}),!(!((t=e.schemaName)===null||t===void 0)&&t.trim()))throw g.error("Invalid service config: schema name missing",{config:e}),new Error("Schema name is required and cannot be empty");if(!(!((a=e.tableName)===null||a===void 0)&&a.trim()))throw g.error("Invalid service config: table name missing",{config:e}),new Error("Table name is required and cannot be empty");g.trace("Service config validation passed",{schemaName:e.schemaName,tableName:e.tableName})}registerService(e){g.debug("Registering service",{schemaName:e.schemaName,tableName:e.tableName,primaryKeyFields:e.primaryKeyFields,hasCustomServiceClass:!!e.serviceClass}),this.validateServiceConfig(e);const t=this.createServiceKey(e.schemaName,e.tableName),a={schemaName:e.schemaName.trim(),tableName:e.tableName.trim(),primaryKeyFields:e.primaryKeyFields||["id"],serviceClass:e.serviceClass||O},s=this.serviceConfigs.has(t);return this.serviceConfigs.set(t,a),s?g.info("Service configuration updated",{serviceKey:t}):g.info("Service registered successfully",{serviceKey:t}),this}registerServices(e){return g.debug("Registering multiple services",{count:e.length}),e.forEach((t,a)=>{try{this.registerService(t)}catch(s){throw g.error("Failed to register service in batch",{index:a,config:t,error:s.message}),s}}),g.info("Multiple services registered successfully",{count:e.length}),this}async createServiceInstance(e){var t;g.debug("Creating service instance",{schemaName:e.schemaName,tableName:e.tableName,serviceClassName:((t=e.serviceClass)===null||t===void 0?void 0:t.name)||"DefaultService"});const a=e.serviceClass||O,s=new a(e.schemaName,e.tableName);return e.primaryKeyFields&&(g.trace("Setting primary key fields",{schemaName:e.schemaName,tableName:e.tableName,primaryKeyFields:e.primaryKeyFields}),s.setPrimaryKeyFields(e.primaryKeyFields)),g.info("Service instance created successfully",{schemaName:e.schemaName,tableName:e.tableName}),s}async getService(e,t){if(this.isShuttingDown)throw g.error("ServiceManager is shutting down, cannot get service",{schemaName:e,tableName:t}),new Error("ServiceManager is shutting down");const a=this.createServiceKey(e,t);g.debug("Getting service",{serviceKey:a});const s=this.serviceMetadata.get(a);if(s&&(s.lastAccessed=new Date().toISOString(),g.trace("Updated service access time",{serviceKey:a})),this.services.has(a))return g.trace("Returning existing service",{serviceKey:a}),this.services.get(a);let r=this.serviceConfigs.get(a);r||(g.debug("Creating default config for unregistered service",{serviceKey:a}),r={schemaName:e,tableName:t,primaryKeyFields:["id"],serviceClass:O},this.serviceConfigs.set(a,r));try{const i=await this.createServiceInstance(r);return this.services.set(a,i),this.serviceMetadata.set(a,{createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString()}),this.emit("SERVICE_CREATED",{serviceKey:a,schemaName:e,tableName:t}),g.info("Service created and cached successfully",{serviceKey:a}),i}catch(i){throw g.error("Failed to create service",{serviceKey:a,error:i.message}),this.emit("SERVICE_ERROR",{serviceKey:a,schemaName:e,tableName:t,error:i}),i}}getExistingService(e,t){const a=this.createServiceKey(e,t);g.trace("Getting existing service",{serviceKey:a});const s=this.services.get(a)||null;return s?g.trace("Existing service found",{serviceKey:a}):g.trace("Existing service not found",{serviceKey:a}),s}async initializeService(e,t){const a=this.createServiceKey(e,t);g.debug("Initializing service",{serviceKey:a});try{const s=await this.getService(e,t);return await s.init(),g.info("Service initialized successfully",{serviceKey:a}),s}catch(s){throw g.error("Failed to initialize service",{serviceKey:a,error:s.message}),s}}async destroyService(e,t){const a=this.createServiceKey(e,t);g.debug("Destroying service",{serviceKey:a});const s=this.services.get(a);if(!s)return g.warn("Service not found for destruction",{serviceKey:a}),!1;try{return await s.close(),s.destroy(),this.services.delete(a),this.serviceMetadata.delete(a),this.emit("SERVICE_DESTROYED",{serviceKey:a,schemaName:e,tableName:t}),g.info("Service destroyed successfully",{serviceKey:a}),!0}catch(r){return g.error("Failed to destroy service",{serviceKey:a,error:r.message}),this.emit("SERVICE_ERROR",{serviceKey:a,schemaName:e,tableName:t,error:r}),!1}}getServicesBySchema(e){g.trace("Getting services by schema",{schemaName:e});const t=[];for(const[a,s]of this.services){const[r]=a.split(":");r===e&&t.push(s)}return g.debug("Found services for schema",{schemaName:e,count:t.length}),t}getServiceKeysBySchema(e){g.trace("Getting service keys by schema",{schemaName:e});const t=[];for(const a of this.services.keys()){const[s]=a.split(":");s===e&&t.push(a)}return g.debug("Found service keys for schema",{schemaName:e,keys:t}),t}async destroyServicesBySchema(e){const t=this.getServiceKeysBySchema(e);if(g.debug("Destroying services by schema",{schemaName:e,serviceKeys:t}),t.length===0){g.debug("No services found to destroy for schema",{schemaName:e});return}const a=t.map(async r=>{const[,i]=r.split(":");try{const o=await this.destroyService(e,i);return g.trace("Service destroy result",{serviceKey:r,result:o}),o}catch(o){return g.error("Error destroying service in schema cleanup",{serviceKey:r,error:o.message}),!1}}),s=(await Promise.all(a)).filter(Boolean).length;g.info("Schema services destruction completed",{schemaName:e,totalServices:t.length,successfulDestroys:s})}getAllServiceInfo(){g.trace("Getting all service info");const e=[];for(const[t,a]of this.serviceConfigs){const s=this.services.get(t),r=this.serviceMetadata.get(t);e.push({key:t,schemaName:a.schemaName,tableName:a.tableName,status:s?s.getStatus():{schemaName:a.schemaName,tableName:a.tableName,isOpened:!1,isInitialized:!1,hasDao:!1},isRegistered:!0,createdAt:(r==null?void 0:r.createdAt)||"N/A",lastAccessed:r==null?void 0:r.lastAccessed})}for(const[t,a]of this.services)if(!this.serviceConfigs.has(t)){const[s,r]=t.split(":"),i=this.serviceMetadata.get(t);e.push({key:t,schemaName:s,tableName:r,status:a.getStatus(),isRegistered:!1,createdAt:(i==null?void 0:i.createdAt)||"N/A",lastAccessed:i==null?void 0:i.lastAccessed})}return e}async healthCheck(){const e=Array.from(this.services.entries()).map(async([r,i])=>{try{const o=await i.healthCheck();return Object.assign(Object.assign({},o),{serviceKey:r})}catch(o){const[l,m]=r.split(":");return{healthy:!1,schemaName:l,error:o.message,timestamp:new Date().toISOString(),serviceKey:r}}}),t=await Promise.all(e),a=t.filter(r=>r.healthy).length,s={totalServices:t.length,healthyServices:a,unhealthyServices:t.length-a,services:t,timestamp:new Date().toISOString(),overallHealth:a===t.length};return this.emit("HEALTH_CHECK_COMPLETED",{serviceKey:"*",schemaName:"*",tableName:"*",data:s}),s}async executeSchemaTransaction(e,t){g.trace(`Executing schema transaction for schema ${e}`);const a=this.getServicesBySchema(e);if(a.length===0)throw g.error("No services found for schema",{schemaName:e}),new Error(`No services found for schema: ${e}`);for(const s of a)await s.init();return await a[0].executeTransaction(async()=>await t(a))}startPeriodicCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupUnusedServices()},300*1e3)}async cleanupUnusedServices(e=1800*1e3){if(this.isShuttingDown)return;const t=Date.now(),a=[];for(const[s,r]of this.serviceMetadata){if(!r.lastAccessed)continue;const i=new Date(r.lastAccessed).getTime();t-i>e&&a.push(s)}for(const s of a){const[r,i]=s.split(":");await this.destroyService(r,i)}}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),this}off(e,t){const a=this.eventHandlers.get(e);if(a){const s=a.indexOf(t);s>-1&&a.splice(s,1)}return this}emit(e,t){const a=Object.assign(Object.assign({},t),{type:e,timestamp:new Date().toISOString()}),s=this.eventHandlers.get(e);s&&s.forEach(i=>{try{i(a)}catch(o){console.error(`ServiceManager: Error in ${e} event handler:`,o)}});const r=this.eventHandlers.get("*");r&&r.forEach(i=>{try{i(a)}catch(o){console.error("ServiceManager: Error in global event handler:",o)}})}hasService(e,t){const a=this.createServiceKey(e,t);return this.services.has(a)}isRegistered(e,t){const a=this.createServiceKey(e,t);return this.serviceConfigs.has(a)}getServiceCount(){return this.services.size}getRegisteredCount(){return this.serviceConfigs.size}getSchemas(){const e=new Set;for(const t of this.services.keys()){const[a]=t.split(":");e.add(a)}return Array.from(e)}async destroy(){this.isShuttingDown=!0,this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);const e=Array.from(this.services.entries()).map(async([t,a])=>{try{await a.close(),a.destroy()}catch(s){console.error(`Error destroying service ${t}:`,s)}});await Promise.all(e),this.services.clear(),this.serviceConfigs.clear(),this.serviceMetadata.clear(),this.eventHandlers.clear(),this.isShuttingDown=!1}}S.instance=null,S.getInstance();class j{sanitizeSQL(e){return e.trim()}bindParameters(e,t){if(!t||t.length===0)return e;let a=0;return e.replace(/\?/g,()=>{if(a<t.length){const s=t[a++];return typeof s=="string"?`'${s.replace(/'/g,"''")}'`:s==null?"NULL":String(s)}return"?"})}}class E{constructor(){if(this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners=new Map,this.logger=w(b.UNIVERSAL_SQLITE),E.instance)throw new Error("UniversalSQLite is a singleton. Use UniversalSQLite.getInstance() instead.");this.logger.debug("UniversalSQLite instance created")}static getInstance(){return E.instance||(E.instance=new E),E.instance}static resetInstance(){E.instance&&(w(b.UNIVERSAL_SQLITE).debug("Resetting UniversalSQLite instance"),E.instance.closeAll().catch(()=>{})),E.instance=null}static configureLogger(e){u.updateConfiguration(e)}static enableDebugLogging(){const e=u.createDebugConfig();u.updateConfiguration(e)}static setProductionLogging(){const e=u.createProductionConfig();u.updateConfiguration(e)}static enableLogging(){u.setEnabled(!0)}static disableLogging(){u.setEnabled(!1)}static enableModuleLogging(e,t,a){u.enableModule(e,t,a)}static disableModuleLogging(e){u.disableModule(e)}async initialize(e,t={}){return this.logger.debug("Starting initialization",{schemas:Object.keys(e),options:t}),this.isInitialized?(this.logger.debug("Already initialized, returning existing promise"),this.initializationPromise||Promise.resolve()):this.initializationPromise?(this.logger.debug("Initialization in progress, waiting..."),this.initializationPromise):(this.initializationPromise=this._performInitialization(e,t),this.initializationPromise)}async _performInitialization(e,t){try{this.logger.info("Performing initialization",{schemaCount:Object.keys(e).length}),t.loggerConfig&&(this.logger.debug("Configuring custom logger"),u.updateConfiguration(t.loggerConfig)),t.registerAdapters&&(this.logger.debug("Registering adapters",{count:t.registerAdapters.length}),t.registerAdapters.forEach(a=>{v.registerAdapter(a)})),t.globalErrorHandler&&(this.logger.debug("Registering global error handler"),this.on("error",t.globalErrorHandler)),this.logger.debug("Registering schemas with DatabaseManager"),p.registerSchemas(e),e.core&&t.autoConnectCore!==!1&&(this.logger.debug("Initializing core connection"),await p.initializeCoreConnection()),t.defaultRoles&&t.defaultRoles.length>0&&(this.logger.debug("Setting default roles",{roles:t.defaultRoles}),await p.setCurrentUserRoles(t.defaultRoles)),this.isInitialized=!0,this.logger.info("Initialization completed successfully"),this._emit("initialized",{schemas:Object.keys(e)})}catch(a){throw this.isInitialized=!1,this.initializationPromise=null,this.logger.error("Initialization failed",a),this._emit("error",a,"initialization"),a}}async initializeFromSchema(e,t={}){this.logger.debug("Initializing from single schema",{schemaName:e.database_name});const a={[e.database_name]:e};return this.initialize(a,Object.assign(Object.assign({},t),{autoConnectCore:t.autoConnect!==!1}))}async connect(e){this.logger.debug("Connecting to schema",{schemaName:e}),this.ensureInitialized(),this.currentSchema=e;try{const t=await p.getLazyLoading(e);return this.logger.info("Successfully connected to schema",{schemaName:e}),this._emit("connected",{schemaName:e}),t}catch(t){throw this.logger.error("Failed to connect to schema",{schemaName:e,error:t}),this._emit("error",t,"connection"),t}}getDAO(e){this.ensureInitialized();const t=e||this.currentSchema;if(!t){const a=new Error("No schema specified. Use connect() first or provide schemaName parameter.");throw this.logger.error("getDAO failed: No schema specified"),a}try{return this.logger.trace("Getting DAO for schema",{schema:t}),p.get(t)}catch(a){throw this.logger.error("Failed to get DAO",{schema:t,error:a}),this._emit("error",a,"getDAO"),a}}getCurrentDAO(){if(!this.currentSchema){const e=new Error("No current connection. Call connect() first.");throw this.logger.error("getCurrentDAO failed: No current connection"),e}return this.getDAO(this.currentSchema)}async ensureDatabaseConnection(e){this.logger.debug("Ensuring database connection",{schemaName:e}),this.ensureInitialized();try{const t=await p.ensureDatabaseConnection(e);return this.logger.debug("Database connection ensured",{schemaName:e}),t}catch(t){throw this.logger.error("Failed to ensure database connection",{schemaName:e,error:t}),this._emit("error",t,"ensureConnection"),t}}createService(e,t){const a=t||this.currentSchema;if(!a){const r=new Error("No schema specified. Use connect() first or provide schemaName parameter.");throw this.logger.error("createService failed: No schema specified",{tableName:e}),r}this.logger.debug("Creating service",{tableName:e,schema:a});const s=class extends D{constructor(){if(!a)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");super(a,e)}};return new s}createServices(e,t){this.logger.debug("Creating multiple services",{tableNames:e,schemaName:t});const a={};return e.forEach(s=>{a[s]=this.createService(s,t)}),this.logger.debug("Created services",{count:e.length}),a}query(e,t){this.logger.trace("Creating query builder",{tableName:e,schemaName:t});const a=this.getDAO(t);return e?A.table(e,a):new A(a)}table(e,t){return this.query(e,t)}async execute(e,t,a){this.logger.debug("Executing SQL",{sql:e.substring(0,100)+"...",paramsCount:t==null?void 0:t.length});try{const s=await this.getDAO(a).execute(e,t);return this.logger.debug("SQL executed successfully",{rowsAffected:s.rowsAffected,lastInsertRowId:s.lastInsertRowId}),this._emit("queryExecuted",{sql:e,params:t,rowCount:s.rowsAffected}),s}catch(s){throw this.logger.error("SQL execution failed",{sql:e.substring(0,100)+"...",error:s}),this._emit("error",s,"execute"),s}}async getRst(e,t,a){return this.logger.trace("Getting first row",{sql:e.substring(0,100)+"..."}),await this.getDAO(a).getRst(e,t)}async getRsts(e,t,a){return this.logger.trace("Getting all rows",{sql:e.substring(0,100)+"..."}),await this.getDAO(a).getRsts(e,t)}async initializeSchema(e,t=!1){this.logger.info("Initializing schema",{schemaName:e.database_name,forceRecreate:t});try{await(await v.createOrOpen({config:e},t)).initializeFromSchema(e),this.logger.info("Schema initialized successfully",{schemaName:e.database_name}),this._emit("schemaInitialized",{schemaName:e.database_name})}catch(a){throw this.logger.error("Schema initialization failed",{schemaName:e.database_name,error:a}),this._emit("error",a,"schemaInitialization"),a}}async getSchemaVersion(e){return this.logger.debug("Getting schema version",{schemaName:e}),await this.getDAO(e).getSchemaVersion()}async getDatabaseInfo(e){return this.logger.debug("Getting database info",{schemaName:e}),await this.getDAO(e).getDatabaseInfo()}async getTableInfo(e,t){return this.logger.debug("Getting table info",{tableName:e,schemaName:t}),await this.getDAO(t).getTableInfo(e)}async importData(e,t,a,s){this.logger.info("Starting data import",{schemaName:e,tableName:t,recordCount:a.length});try{const r=await p.importDataToTable(e,t,a,s);return this.logger.info("Data import completed",{schemaName:e,tableName:t,successRows:r.successRows,failedRows:r.errorRows,errors:r.errors.length}),this._emit("dataImported",{schemaName:e,tableName:t,recordCount:r.successRows}),r}catch(r){throw this.logger.error("Data import failed",{schemaName:e,tableName:t,error:r}),this._emit("error",r,"dataImport"),r}}async importDataWithMapping(e,t,a,s,r){this.logger.info("Starting data import with mapping",{schemaName:e,tableName:t,recordCount:a.length,mappingCount:s.length});try{const i=await p.importDataWithMapping(e,t,a,s,r);return this.logger.info("Data import with mapping completed",{schemaName:e,tableName:t,successRows:i.successRows,failedRows:i.errorRows}),this._emit("dataImported",{schemaName:e,tableName:t,recordCount:i.successRows}),i}catch(i){throw this.logger.error("Data import with mapping failed",{schemaName:e,tableName:t,error:i}),this._emit("error",i,"dataImportWithMapping"),i}}async importFromCSV(e,t,a,s){this.logger.info("Starting CSV import",{schemaName:e,tableName:t,csvLength:a.length,delimiter:s==null?void 0:s.delimiter,hasHeader:s==null?void 0:s.hasHeader});try{const r=await p.importFromCSV(e,t,a,s);return this.logger.info("CSV import completed",{schemaName:e,tableName:t,successRows:r.successRows,failedRows:r.errorRows}),this._emit("csvImported",{schemaName:e,tableName:t,recordCount:r.successRows}),r}catch(r){throw this.logger.error("CSV import failed",{schemaName:e,tableName:t,error:r}),this._emit("error",r,"csvImport"),r}}async setUserRoles(e,t){this.logger.info("Setting user roles",{roles:e,primaryRole:t}),this.ensureInitialized();try{await p.setCurrentUserRoles(e,t),this.logger.info("User roles set successfully",{roles:e,primaryRole:t}),this._emit("userRolesSet",{roles:e,primaryRole:t})}catch(a){throw this.logger.error("Failed to set user roles",{roles:e,primaryRole:t,error:a}),this._emit("error",a,"setUserRoles"),a}}getCurrentUserRoles(){const e=p.getCurrentUserRoles();return this.logger.trace("Getting current user roles",{roles:e}),e}getCurrentRole(){const e=p.getCurrentRole();return this.logger.trace("Getting current role",{role:e}),e}hasAccessToDatabase(e){const t=p.hasAccessToDatabase(e);return this.logger.trace("Checking database access",{dbKey:e,hasAccess:t}),t}async executeTransaction(e,t){this.logger.info("Starting cross-schema transaction",{schemas:e});try{await p.executeCrossSchemaTransaction(e,t),this.logger.info("Cross-schema transaction completed successfully",{schemas:e}),this._emit("transactionCompleted",{schemas:e})}catch(a){throw this.logger.error("Cross-schema transaction failed",{schemas:e,error:a}),this._emit("error",a,"transaction"),a}}async executeTransactionOnCurrent(e){this.logger.debug("Starting transaction on current connection");const t=this.getCurrentDAO();try{await t.beginTransaction(),this.logger.trace("Transaction begun");const a=await e(t);return await t.commitTransaction(),this.logger.debug("Transaction committed successfully"),a}catch(a){throw this.logger.warn("Transaction failed, rolling back",{error:a}),await t.rollbackTransaction(),a}}getEnvironment(){const e=v.getEnvironmentInfo();return this.logger.trace("Getting environment info",{env:e}),e}getConnectionStatus(){const e={isInitialized:this.isInitialized,currentSchema:this.currentSchema,activeConnections:p.listConnections(),connectionCount:p.getConnectionCount(),userRoles:this.getCurrentUserRoles(),primaryRole:this.getCurrentRole()};return this.logger.trace("Getting connection status",e),e}getAvailableSchemas(){const e=p.getAvailableSchemas();return this.logger.trace("Getting available schemas",{schemas:e}),e}async healthCheck(){this.logger.debug("Starting health check for all connections");const e=p.getConnections(),t={};for(const[a,s]of Object.entries(e))try{await s.execute("SELECT 1"),t[a]={healthy:!0},this.logger.trace("Health check passed",{schemaName:a})}catch(r){t[a]={healthy:!1,error:r.message},this.logger.warn("Health check failed",{schemaName:a,error:r})}return this.logger.debug("Health check completed",{totalConnections:Object.keys(t).length,healthyConnections:Object.values(t).filter(a=>a.healthy).length}),t}on(e,t){return this.logger.trace("Adding event listener",{event:e}),this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}off(e,t){this.logger.trace("Removing event listener",{event:e});const a=this.eventListeners.get(e);if(a){const s=a.indexOf(t);s>-1&&a.splice(s,1)}return this}_emit(e,...t){this.logger.trace("Emitting event",{event:e,argsCount:t.length});const a=this.eventListeners.get(e);a&&a.forEach(s=>{try{s(...t)}catch(r){this.logger.error("Error in event handler",{event:e,error:r})}})}async closeConnection(e){this.logger.info("Closing connection",{schemaName:e});try{await p.closeConnection(e),this.currentSchema===e&&(this.currentSchema=null,this.logger.debug("Current schema reset due to connection close")),this.logger.info("Connection closed successfully",{schemaName:e}),this._emit("connectionClosed",{schemaName:e})}catch(t){throw this.logger.error("Failed to close connection",{schemaName:e,error:t}),this._emit("error",t,"closeConnection"),t}}async closeAll(){this.logger.info("Closing all connections");try{await p.closeAll(),this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners.clear(),this.logger.info("All connections closed successfully"),this._emit("allConnectionsClosed")}catch(e){throw this.logger.error("Failed to close all connections",{error:e}),this._emit("error",e,"closeAll"),e}}async logout(){this.logger.info("User logout initiated");try{await p.logout(),this.currentSchema=null,this.logger.info("User logout completed successfully"),this._emit("userLoggedOut")}catch(e){throw this.logger.error("User logout failed",{error:e}),this._emit("error",e,"logout"),e}}static registerAdapter(e){w(b.UNIVERSAL_SQLITE).debug("Registering adapter",{adapterName:e.name,adapterVersion:e.version}),v.registerAdapter(e)}static registerRole(e){w(b.UNIVERSAL_SQLITE).debug("Registering role",{roleConfig:e}),p.registerRole(e)}static registerRoles(e){w(b.UNIVERSAL_SQLITE).debug("Registering multiple roles",{roleCount:e.length}),p.registerRoles(e)}ensureInitialized(){if(!this.isInitialized){const e=new Error("UniversalSQLite not initialized. Call initialize() first.");throw this.logger.error("Operation attempted on uninitialized instance"),e}}}E.instance=null;const U=(h,e)=>(w(b.DATABASE_FACTORY).debug("Creating UniversalDAO",{dbPath:h,options:e}),v.createDAO(h,e)),B=async(h,e)=>(w(b.DATABASE_FACTORY).debug("Creating database from schema",{schemaName:h.database_name}),await v.createFromConfig(h,e)),K=async(h,e)=>(w(b.DATABASE_FACTORY).debug("Opening existing database",{dbName:h}),await v.openExisting(h,e)),P=h=>(w(b.QUERY_BUILDER).trace("Creating query builder"),new A(h)),V=(h,e)=>(w(b.BASE_SERVICE).debug("Creating base service",{schemaName:h,tableName:e}),new class extends D{constructor(){super(h,e)}}),q=async h=>{const e=w(b.UNIVERSAL_SQLITE);e.info("Setting up UniversalSQLite",{schemaCount:Object.keys(h.schemas).length,autoConnect:h.autoConnect,enableDebugLogging:h.enableDebugLogging});const t=E.getInstance();return h.enableDebugLogging&&E.enableDebugLogging(),await t.initialize(h.schemas,{registerAdapters:h.adapters,defaultRoles:h.defaultRoles,loggerConfig:h.loggerConfig}),h.autoConnect&&await t.connect(h.autoConnect),e.info("UniversalSQLite setup completed"),t},G=async(h,e)=>{const t=w(b.UNIVERSAL_SQLITE);t.info("Creating single database",{schemaName:h.database_name,enableDebugLogging:e==null?void 0:e.enableDebugLogging});const a=E.getInstance();e!=null&&e.enableDebugLogging&&E.enableDebugLogging(),await a.initializeFromSchema(h,{registerAdapters:e!=null&&e.adapter?[e.adapter]:void 0,autoConnect:e==null?void 0:e.autoConnect,loggerConfig:e==null?void 0:e.loggerConfig});const s=(e==null?void 0:e.autoConnect)!==!1?await a.connect(h.database_name):a.getDAO(h.database_name);return t.info("Single database creation completed"),{sqlite:a,dao:s}},H=E.getInstance();export{j as BaseAdapter,D as BaseService,v as DatabaseFactory,p as DatabaseManager,O as DefaultService,A as QueryBuilder,u as SQLiteLoggerConfig,b as SQLiteModules,S as ServiceManager,F as UniversalDAO,E as UniversalSQLite,V as createBaseService,B as createDatabaseFromSchema,w as createModuleLogger,P as createQueryBuilder,G as createSingleDatabase,U as createUniversalDAO,H as default,K as openExistingDatabase,q as setupUniversalSQLite,z as sqliteLogger};
13
+ ${s}`)}this.isInitialized=!0,n.info("All databases initialized successfully",{totalSchemas:e.length})}static async getLazyLoading(e){if(n.debug("Getting database with lazy loading",{key:e}),this.activeDatabases.add(e),!this.hasAccessToDatabase(e))throw n.error("Access denied for lazy loading",{key:e}),new Error(`Access denied: Database '${e}' is not accessible.`);if(!this.connections[e]){const t=this.getSchema(e);if(!t)throw n.error("Schema not found for lazy loading",{key:e}),new Error(`Invalid database key: ${e}. Schema not found.`);if(Object.keys(this.connections).length>=this.maxConnections)throw n.error("Maximum connections reached",{currentConnections:Object.keys(this.connections).length,maxConnections:this.maxConnections}),new Error("Maximum number of database connections reached");n.debug("Creating new connection for lazy loading",{key:e,schemaName:t.database_name});const a=await v.createOrOpen({config:t},!1);await a.connect(),this.connections[e]=a,n.info("Database connection created via lazy loading",{key:e})}return this.isInitialized=!0,this.connections[e]}static async executeCrossSchemaTransaction(e,t){n.debug("Executing cross-schema transaction",{schemas:e});for(const s of e)if(!this.hasAccessToDatabase(s))throw n.error("Access denied for cross-schema transaction",{key:s,schemas:e}),new Error(`Access denied: Database '${s}' is not accessible.`);const a=e.reduce((s,r)=>(s[r]=this.get(r),s),{});n.debug("Starting cross-schema transaction",{schemas:e});try{await Promise.all(Object.values(a).map(s=>s.beginTransaction())),n.trace("All transactions started successfully"),await t(a),n.trace("Transaction callback completed successfully"),await Promise.all(Object.values(a).map(s=>s.commitTransaction())),n.info("Cross-schema transaction completed successfully",{schemas:e})}catch(s){throw n.error("Cross-schema transaction failed, rolling back",{schemas:e,error:s.message}),await Promise.all(Object.values(a).map(r=>r.rollbackTransaction())),n.debug("Cross-schema transaction rolled back"),s}}static async importDataToTable(e,t,a,s={}){if(n.debug("Importing data to table",{databaseKey:e,tableName:t,recordCount:a.length,options:s}),!this.hasAccessToDatabase(e))throw n.error("Access denied for data import",{databaseKey:e,tableName:t}),new Error(`Access denied: Database '${e}' is not accessible.`);const r=this.get(e);try{const i=await r.importData(Object.assign({tableName:t,data:a},s));return n.info("Data import completed successfully",{databaseKey:e,tableName:t,importedRows:i.successRows,skippedRows:i.errorRows}),i}catch(i){throw n.error("Data import failed",{databaseKey:e,tableName:t,error:i.message}),i}}static async importDataWithMapping(e,t,a,s,r={}){if(n.debug("Importing data with column mapping",{databaseKey:e,tableName:t,recordCount:a.length,mappingCount:s.length,options:r}),!this.hasAccessToDatabase(e))throw n.error("Access denied for data import with mapping",{databaseKey:e,tableName:t}),new Error(`Access denied: Database '${e}' is not accessible.`);const i=this.get(e);try{const o=await i.importDataWithMapping(t,a,s,r);return n.info("Data import with mapping completed successfully",{databaseKey:e,tableName:t,importedRows:o.successRows,skippedRows:o.errorRows}),o}catch(o){throw n.error("Data import with mapping failed",{databaseKey:e,tableName:t,error:o.message}),o}}static async bulkImport(e){const t=Date.now();n.info("Starting bulk import",{configCount:e.length,configs:e.map(s=>({databaseKey:s.databaseKey,tableName:s.tableName,recordCount:s.data.length}))});const a={totalDatabases:e.length,successDatabases:0,results:{},errors:{},executionTime:0};for(const s of e){const r=`${s.databaseKey}.${s.tableName}`;n.debug("Processing bulk import config",{configKey:r});try{if(!this.hasAccessToDatabase(s.databaseKey))throw new Error(`Access denied: Database '${s.databaseKey}' is not accessible.`);const i=this.get(s.databaseKey);let o;s.columnMappings?(n.trace("Using column mappings for import",{configKey:r}),o=await i.importDataWithMapping(s.tableName,s.data,s.columnMappings,s.options)):(n.trace("Using direct import",{configKey:r}),o=await i.importData(Object.assign({tableName:s.tableName,data:s.data},s.options))),a.results[r]=o,a.successDatabases++,n.info("Bulk import config completed successfully",{configKey:r,importedRows:o.successRows,skippedRows:o.errorRows})}catch(i){const o=i instanceof Error?i:new Error(String(i));n.error("Bulk import config failed",{configKey:r,error:o.message}),a.errors[r]=o}}return a.executionTime=Date.now()-t,n.info("Bulk import completed",{totalConfigs:a.totalDatabases,successfulConfigs:a.successDatabases,failedConfigs:Object.keys(a.errors).length,executionTimeMs:a.executionTime}),a}static async importFromCSV(e,t,a,s={}){if(n.debug("Importing from CSV",{databaseKey:e,tableName:t,csvSize:a.length,options:s}),!this.hasAccessToDatabase(e))throw n.error("Access denied for CSV import",{databaseKey:e,tableName:t}),new Error(`Access denied: Database '${e}' is not accessible.`);const r=this.get(e);try{const i=await r.importFromCSV(t,a,s);return n.info("CSV import completed successfully",{databaseKey:e,tableName:t,importedRows:i.successRows,skippedRows:i.errorRows}),i}catch(i){throw n.error("CSV import failed",{databaseKey:e,tableName:t,error:i.message}),i}}static getConnectionCount(){const e=Object.keys(this.connections).length;return n.trace("Getting connection count",{count:e}),e}static listConnections(){const e=Object.keys(this.connections);return n.trace("Listing connections",{connections:e}),e}static async closeConnection(e){n.debug("Closing specific connection",{dbKey:e});const t=this.connections[e];if(t)try{await t.disconnect(),delete this.connections[e],n.info("Database connection closed successfully",{dbKey:e})}catch(a){throw n.error("Error closing database connection",{dbKey:e,error:a.message}),a}else n.warn("Attempted to close non-existent connection",{dbKey:e})}static async closeAll(){n.info("Closing all connections and resetting state"),await this.closeAllConnections(),this.currentUserRoles=[],this.currentRole=null,this.isInitialized=!1,this.activeDatabases.clear(),this.eventListeners.clear(),this.isClosingConnections=!1,n.info("All connections closed and state reset successfully")}static async logout(){n.info("Logging out user",{currentUserRoles:this.currentUserRoles});const e=Object.keys(this.connections).filter(t=>t!=="core");n.debug("Closing role-specific connections",{connectionsToClose:e});for(const t of e)try{await this.connections[t].close(),delete this.connections[t],n.debug("Role-specific connection closed",{dbKey:t})}catch(a){n.error("Error closing connection during logout",{dbKey:t,error:a.message})}this.currentUserRoles=[],this.currentRole=null,n.info("User logout completed successfully",{closedConnections:e.length})}}p.maxConnections=10,p.connections={},p.isInitialized=!1,p.roleRegistry={},p.currentRole=null,p.currentUserRoles=[],p.activeDatabases=new Set,p.isClosingConnections=!1,p.schemaConfigurations={},p.schemaManager=null,p.eventListeners=new Map;const c=w(b.BASE_SERVICE);class D{constructor(e,t){this.dao=null,this.isOpened=!1,this.isInitialized=!1,this.errorHandlers=new Map,this.eventListeners=new Map,this.primaryKeyFields=["id"],this.cache=new Map,this.schemaName=e,this.tableName=t||e,c.debug("Creating BaseService instance",{schemaName:this.schemaName,tableName:this.tableName,primaryKeyFields:this.primaryKeyFields}),this.reconnectHandler=a=>{c.info("Database reconnected for service",{schemaName:this.schemaName,tableName:this.tableName}),this.dao=a,this._emit("daoReconnected",{schemaName:this.schemaName})},p.onDatabaseReconnect(e,this.reconnectHandler),this.bindMethods(),c.trace("BaseService instance created successfully",{schemaName:this.schemaName,tableName:this.tableName})}bindMethods(){c.trace("Binding service methods",{schemaName:this.schemaName,tableName:this.tableName}),Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach(e=>{typeof this[e]=="function"&&e!=="constructor"&&(this[e]=this[e].bind(this))})}setPrimaryKeyFields(e){return c.debug("Setting primary key fields",{schemaName:this.schemaName,tableName:this.tableName,previousFields:this.primaryKeyFields,newFields:e}),this.primaryKeyFields=e,this}async init(){c.info("Initializing BaseService",{schemaName:this.schemaName,tableName:this.tableName,isInitialized:this.isInitialized});try{if(this.isInitialized)return c.debug("Service already initialized, skipping",{schemaName:this.schemaName}),this;if(c.debug("Getting DAO from DatabaseManager",{schemaName:this.schemaName}),this.dao=await p.getLazyLoading(this.schemaName),!this.dao){const e=`Failed to initialize DAO for schema: ${this.schemaName}`;throw c.error(e,{schemaName:this.schemaName}),new Error(e)}return this.dao.isConnectionOpen()||(c.debug("DAO connection not open, connecting",{schemaName:this.schemaName}),await this.dao.connect()),this.isOpened=!0,this.isInitialized=!0,c.info("BaseService initialized successfully",{schemaName:this.schemaName,tableName:this.tableName,isOpened:this.isOpened,isInitialized:this.isInitialized}),this._emit("initialized",{schemaName:this.schemaName}),this}catch(e){throw c.error("Error initializing BaseService",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),this._handleError("INIT_ERROR",e),e}}async create(e){c.debug("Creating new record",{schemaName:this.schemaName,tableName:this.tableName,hasData:!!e,dataKeys:e?Object.keys(e):[]}),await this._ensureInitialized(),await this.ensureValidConnection();try{this._validateData(e),c.trace("Building data table for insert",{schemaName:this.schemaName,tableName:this.tableName});const t=this.buildDataTable(e),a=await this.dao.insert(t);if(a.rowsAffected===0){const i="Insert operation failed - no rows affected";throw c.error(i,{schemaName:this.schemaName,tableName:this.tableName,result:a}),new Error(i)}c.debug("Insert operation successful",{schemaName:this.schemaName,tableName:this.tableName,rowsAffected:a.rowsAffected,lastInsertRowId:a.lastInsertRowId});let s=null;const r=e[this.primaryKeyFields[0]];try{r!=null?(c.trace("Retrieving created record by primary key",{schemaName:this.schemaName,tableName:this.tableName,primaryKeyField:this.primaryKeyFields[0],primaryKeyValue:r}),s=await this.findById(r)):a.lastInsertRowId&&(c.trace("Retrieving created record by last insert ID",{schemaName:this.schemaName,tableName:this.tableName,lastInsertRowId:a.lastInsertRowId}),s=await this.findById(a.lastInsertRowId))}catch(i){c.warn("Could not retrieve created record",{schemaName:this.schemaName,tableName:this.tableName,findError:i.message})}return s||(c.debug("Using original data as created record",{schemaName:this.schemaName,tableName:this.tableName}),s=e),c.info("Record created successfully",{schemaName:this.schemaName,tableName:this.tableName,recordRetrieved:!!s}),this._emit("dataCreated",{operation:"create",data:s}),s}catch(t){throw c.error("Error creating record",{schemaName:this.schemaName,tableName:this.tableName,error:t.message}),this._handleError("CREATE_ERROR",t),t}}async update(e,t){c.debug("Updating record",{schemaName:this.schemaName,tableName:this.tableName,id:e,hasData:!!t,dataKeys:t?Object.keys(t):[]}),await this._ensureInitialized();try{if(!e){const i="ID is required for update";throw c.error(i,{schemaName:this.schemaName,tableName:this.tableName}),new Error(i)}this._validateData(t);const a=Object.assign(Object.assign({},t),{[this.primaryKeyFields[0]]:e});c.trace("Building update query table",{schemaName:this.schemaName,tableName:this.tableName,id:e});const s=this.buildDataTable(a);await this.dao.update(s),c.debug("Update operation completed",{schemaName:this.schemaName,tableName:this.tableName,id:e});const r=await this.findById(e);return c.info("Record updated successfully",{schemaName:this.schemaName,tableName:this.tableName,id:e,recordFound:!!r}),this._emit("dataUpdated",{operation:"update",id:e,data:r}),r}catch(a){throw c.error("Error updating record",{schemaName:this.schemaName,tableName:this.tableName,id:e,error:a.message}),this._handleError("UPDATE_ERROR",a),a}}async delete(e){c.debug("Deleting record",{schemaName:this.schemaName,tableName:this.tableName,id:e}),await this._ensureInitialized();try{if(!e){const r="ID is required for delete";throw c.error(r,{schemaName:this.schemaName,tableName:this.tableName}),new Error(r)}const t={name:this.tableName,cols:[],wheres:[{name:this.primaryKeyFields[0],value:e}]};c.trace("Executing delete operation",{schemaName:this.schemaName,tableName:this.tableName,id:e,primaryKeyField:this.primaryKeyFields[0]});const a=await this.dao.delete(t),s=a.rowsAffected>0;return s?(c.info("Record deleted successfully",{schemaName:this.schemaName,tableName:this.tableName,id:e,rowsAffected:a.rowsAffected}),this._emit("dataDeleted",{operation:"delete",id:e})):c.warn("Delete operation completed but no rows affected",{schemaName:this.schemaName,tableName:this.tableName,id:e}),s}catch(t){throw c.error("Error deleting record",{schemaName:this.schemaName,tableName:this.tableName,id:e,error:t.message}),this._handleError("DELETE_ERROR",t),t}}async findById(e){c.debug("Finding record by ID",{schemaName:this.schemaName,tableName:this.tableName,id:e}),await this._ensureInitialized();try{if(!e){const i="ID is required";throw c.error(i,{schemaName:this.schemaName,tableName:this.tableName}),new Error(i)}const t={[this.primaryKeyFields[0]]:e};c.trace("Building select query",{schemaName:this.schemaName,tableName:this.tableName,conditions:t});const a=this.buildSelectTable(t),s=await this.dao.select(a),r=Object.keys(s).length>0?s:null;return c.debug("Find by ID completed",{schemaName:this.schemaName,tableName:this.tableName,id:e,recordFound:!!r}),this._emit("dataFetched",{operation:"findById",id:e}),r}catch(t){throw c.error("Error finding record by ID",{schemaName:this.schemaName,tableName:this.tableName,id:e,error:t.message}),this._handleError("FIND_BY_ID_ERROR",t),t}}async findFirst(e={}){c.debug("Finding first record",{schemaName:this.schemaName,tableName:this.tableName,conditionsCount:Object.keys(e).length,conditions:e}),await this._ensureInitialized();try{c.trace("Building select query for findFirst",{schemaName:this.schemaName,tableName:this.tableName});const t=this.buildSelectTable(e),a=await this.dao.select(t),s=Object.keys(a).length>0?a:null;return c.debug("Find first completed",{schemaName:this.schemaName,tableName:this.tableName,recordFound:!!s}),this._emit("dataFetched",{operation:"findFirst"}),s}catch(t){throw c.error("Error finding first record",{schemaName:this.schemaName,tableName:this.tableName,conditions:e,error:t.message}),this._handleError("FIND_FIRST_ERROR",t),t}}async findAll(e={},t={}){c.debug("Finding all records",{schemaName:this.schemaName,tableName:this.tableName,conditionsCount:Object.keys(e).length,hasLimit:!!t.limit,hasOffset:!!t.offset,hasOrderBy:!!(t.orderBy&&t.orderBy.length>0),limit:t.limit,offset:t.offset}),await this._ensureInitialized();try{const a=[...this.buildWhereFromObject(e),...t.where||[]];c.trace("Building query for findAll",{schemaName:this.schemaName,tableName:this.tableName,totalWheres:a.length,hasColumns:!!(t.columns&&t.columns.length>0)});const s={name:this.tableName,cols:t.columns?t.columns.map(i=>({name:i})):[],wheres:a,orderbys:t.orderBy,limitOffset:{limit:t.limit,offset:t.offset}},r=await this.dao.selectAll(s);return c.info("Find all completed",{schemaName:this.schemaName,tableName:this.tableName,recordsFound:r.length,conditionsCount:Object.keys(e).length}),this._emit("dataFetched",{operation:"findAll",count:r.length}),r}catch(a){throw c.error("Error finding all records",{schemaName:this.schemaName,tableName:this.tableName,conditions:e,options:t,error:a.message}),this._handleError("FIND_ALL_ERROR",a),a}}async count(e){c.debug("Counting records",{schemaName:this.schemaName,tableName:this.tableName,hasWhere:!!e,whereType:e?Array.isArray(e)?"array":"object":"none"}),await this._ensureInitialized();try{let t=[];Array.isArray(e)?(t=e,c.trace("Using array where conditions",{schemaName:this.schemaName,whereCount:t.length})):e&&typeof e=="object"&&(t=this.buildWhereFromObject(e),c.trace("Built where conditions from object",{schemaName:this.schemaName,whereCount:t.length}));const a={name:this.tableName,cols:[{name:"COUNT(*) as count"}],wheres:t},s=(await this.dao.select(a)).count||0;return c.debug("Count completed",{schemaName:this.schemaName,tableName:this.tableName,count:s}),s}catch(t){throw c.error("Error counting records",{schemaName:this.schemaName,tableName:this.tableName,where:e,error:t.message}),this._handleError("COUNT_ERROR",t),t}}async exists(e){c.debug("Checking if record exists",{schemaName:this.schemaName,tableName:this.tableName,id:e});const t=await this.findById(e)!==null;return c.debug("Existence check completed",{schemaName:this.schemaName,tableName:this.tableName,id:e,exists:t}),t}async truncate(){c.warn("Truncating table - this will delete all data",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized();try{c.debug("Executing truncate operations",{schemaName:this.schemaName,tableName:this.tableName}),await this.dao.execute(`DELETE FROM ${this.tableName}`),await this.dao.execute(`DELETE FROM sqlite_sequence WHERE name='${this.tableName}'`),c.info("Table truncated successfully",{schemaName:this.schemaName,tableName:this.tableName}),this._emit("tableTruncated",{tableName:this.tableName})}catch(e){throw c.error("Error truncating table",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),this._handleError("TRUNCATE_ERROR",e),e}}async bulkInsert(e){c.info("Starting bulk insert",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length}),await this._ensureInitialized();try{if(!Array.isArray(e)||e.length===0){const a="Items must be a non-empty array";throw c.error(a,{schemaName:this.schemaName,tableName:this.tableName,itemsType:typeof e,itemsLength:Array.isArray(e)?e.length:"N/A"}),new Error(a)}c.debug("Executing bulk insert operation",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length});const t=await this.dao.importData({tableName:this.tableName,data:e,batchSize:1e3,skipErrors:!1,validateData:!0});return c.info("Bulk insert completed",{schemaName:this.schemaName,tableName:this.tableName,totalRows:t.totalRows,successRows:t.successRows,errorRows:t.errorRows}),this._emit("dataBulkCreated",{operation:"bulkInsert",count:t.successRows}),t}catch(t){throw c.error("Error during bulk insert",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length,error:t.message}),this._handleError("BULK_INSERT_ERROR",t),t}}async bulkCreate(e){c.info("Starting bulk create with transaction",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length}),await this._ensureInitialized();try{if(!Array.isArray(e)||e.length===0){const a="Data must be a non-empty array";throw c.error(a,{schemaName:this.schemaName,tableName:this.tableName,dataType:typeof e,dataLength:Array.isArray(e)?e.length:"N/A"}),new Error(a)}const t=[];return c.debug("Executing bulk create in transaction",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length}),await this.executeTransaction(async()=>{for(let a=0;a<e.length;a++){const s=e[a];a%100===0&&c.trace("Bulk create progress",{schemaName:this.schemaName,tableName:this.tableName,processed:a,total:e.length}),this._validateData(s);const r=this.buildDataTable(s);await this.dao.insert(r),t.push(s)}}),c.info("Bulk create completed successfully",{schemaName:this.schemaName,tableName:this.tableName,recordsCreated:t.length}),this._emit("dataBulkCreated",{operation:"bulkCreate",count:t.length}),t}catch(t){throw c.error("Error during bulk create",{schemaName:this.schemaName,tableName:this.tableName,itemsCount:e.length,error:t.message}),this._handleError("BULK_CREATE_ERROR",t),t}}async executeTransaction(e){c.debug("Starting transaction",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized();try{c.trace("Beginning database transaction",{schemaName:this.schemaName}),await this.dao.beginTransaction();const t=await e();return c.trace("Committing transaction",{schemaName:this.schemaName}),await this.dao.commitTransaction(),c.info("Transaction completed successfully",{schemaName:this.schemaName,tableName:this.tableName}),this._emit("transactionCompleted",{operation:"transaction"}),t}catch(t){c.error("Transaction failed, rolling back",{schemaName:this.schemaName,tableName:this.tableName,error:t.message});try{await this.dao.rollbackTransaction(),c.debug("Transaction rollback successful",{schemaName:this.schemaName})}catch(a){c.error("Error during transaction rollback",{schemaName:this.schemaName,rollbackError:a.message}),this._handleError("ROLLBACK_ERROR",a)}throw this._handleError("TRANSACTION_ERROR",t),t}}async importFromCSV(e,t={}){c.info("Starting CSV import",{schemaName:this.schemaName,tableName:this.tableName,csvDataLength:e.length,delimiter:t.delimiter,hasHeader:t.hasHeader,hasMappings:!!(t.columnMappings&&t.columnMappings.length>0)}),await this._ensureInitialized();try{const a=await this.dao.importFromCSV(this.tableName,e,t);return c.info("CSV import completed",{schemaName:this.schemaName,tableName:this.tableName,totalRows:a.totalRows,successRows:a.successRows,errorRows:a.errorRows}),this._emit("dataImported",{operation:"importFromCSV",result:a}),a}catch(a){throw c.error("Error during CSV import",{schemaName:this.schemaName,tableName:this.tableName,csvDataLength:e.length,error:a.message}),this._handleError("IMPORT_CSV_ERROR",a),a}}async importDataWithMapping(e,t,a={}){c.info("Starting import with column mapping",{schemaName:this.schemaName,tableName:this.tableName,dataCount:e.length,mappingsCount:t.length}),await this._ensureInitialized();try{const s=await this.dao.importDataWithMapping(this.tableName,e,t,a);return c.info("Import with mapping completed",{schemaName:this.schemaName,tableName:this.tableName,totalRows:s.totalRows,successRows:s.successRows,errorRows:s.errorRows}),this._emit("dataImported",{operation:"importWithMapping",result:s}),s}catch(s){throw c.error("Error during import with mapping",{schemaName:this.schemaName,tableName:this.tableName,dataCount:e.length,mappingsCount:t.length,error:s.message}),this._handleError("IMPORT_MAPPING_ERROR",s),s}}buildSelectTable(e={},t={}){c.trace("Building select table query",{schemaName:this.schemaName,tableName:this.tableName,conditionsCount:Object.keys(e).length,hasOptions:Object.keys(t).length>0});const a={name:this.tableName,cols:[],wheres:[],orderbys:t.orderBy||[],limitOffset:{}};return t.columns&&t.columns.length>0&&(a.cols=t.columns.map(s=>({name:s}))),e&&Object.keys(e).length>0&&(a.wheres=Object.entries(e).map(([s,r])=>({name:s,value:r,operator:"="}))),t.limit!==void 0&&(a.limitOffset.limit=t.limit),t.offset!==void 0&&(a.limitOffset.offset=t.offset),a}buildDataTable(e){return c.trace("Building data table for query",{schemaName:this.schemaName,tableName:this.tableName,dataKeys:Object.keys(e)}),this.dao.convertJsonToQueryTable(this.tableName,e,this.primaryKeyFields)}buildWhereFromObject(e){const t=Object.entries(e).filter(([a,s])=>s!==void 0).map(([a,s])=>({name:a,value:s}));return c.trace("Built where clauses from object",{schemaName:this.schemaName,originalKeys:Object.keys(e).length,filteredWheres:t.length}),t}on(e,t){return c.trace("Adding event listener",{schemaName:this.schemaName,tableName:this.tableName,event:e}),this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}off(e,t){c.trace("Removing event listener",{schemaName:this.schemaName,tableName:this.tableName,event:e});const a=this.eventListeners.get(e);if(a){const s=a.indexOf(t);s>-1&&a.splice(s,1)}return this}_emit(e,t){c.trace("Emitting event",{schemaName:this.schemaName,tableName:this.tableName,event:e,hasData:!!t});const a=this.eventListeners.get(e);a&&a.forEach(s=>{try{s(t)}catch(r){c.error("Error in event handler",{schemaName:this.schemaName,tableName:this.tableName,event:e,error:r.message})}})}setErrorHandler(e,t){return c.debug("Setting error handler",{schemaName:this.schemaName,tableName:this.tableName,errorType:e}),this.errorHandlers.set(e,t),this}_handleError(e,t){c.error("Handling service error",{schemaName:this.schemaName,tableName:this.tableName,errorType:e,error:t.message});const a=this.errorHandlers.get(e);if(a)try{a(t)}catch(s){c.error("Error in error handler",{schemaName:this.schemaName,tableName:this.tableName,errorType:e,handlerError:s.message})}this._emit("error",{errorType:e,error:t})}_validateData(e){if(!e||typeof e!="object"){const t="Data must be a valid object";throw c.error("Data validation failed",{schemaName:this.schemaName,tableName:this.tableName,dataType:typeof e,isNull:e===null}),new Error(t)}}async _ensureInitialized(){this.isInitialized||(c.debug("Service not initialized, initializing now",{schemaName:this.schemaName,tableName:this.tableName}),await this.init())}async ensureValidConnection(){var e;c.trace("Ensuring valid database connection",{schemaName:this.schemaName,tableName:this.tableName});try{!((e=this.dao)===null||e===void 0)&&e.isConnectionOpen()||(c.debug("Connection not valid, getting new connection",{schemaName:this.schemaName}),this.dao=await p.ensureDatabaseConnection(this.schemaName))}catch(t){c.warn("Error checking connection, getting new connection",{schemaName:this.schemaName,error:t.message}),this.dao=await p.ensureDatabaseConnection(this.schemaName)}}async getDatabaseInfo(){return c.trace("Getting database info",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized(),await this.dao.getDatabaseInfo()}async getTableInfo(){return c.trace("Getting table info",{schemaName:this.schemaName,tableName:this.tableName}),await this._ensureInitialized(),await this.dao.getTableInfo(this.tableName)}getStatus(){const e={schemaName:this.schemaName,tableName:this.tableName,isOpened:this.isOpened,isInitialized:this.isInitialized,hasDao:!!this.dao};return c.trace("Getting service status",e),e}async healthCheck(){c.debug("Performing health check",{schemaName:this.schemaName,tableName:this.tableName});try{await this._ensureInitialized();const e=await this.count(),t={healthy:!0,schemaName:this.schemaName,recordCount:e,timestamp:new Date().toISOString()};return c.info("Health check passed",{schemaName:this.schemaName,tableName:this.tableName,recordCount:e}),t}catch(e){const t={healthy:!1,schemaName:this.schemaName,error:e.message,timestamp:new Date().toISOString()};return c.error("Health check failed",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),t}}async close(){c.info("Closing BaseService",{schemaName:this.schemaName,tableName:this.tableName,isOpened:this.isOpened,isInitialized:this.isInitialized});try{return this.dao&&(await this.dao.close(),c.debug("DAO closed successfully",{schemaName:this.schemaName})),this.isOpened=!1,this.isInitialized=!1,this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear(),c.info("BaseService closed successfully",{schemaName:this.schemaName,tableName:this.tableName}),this._emit("closed",{schemaName:this.schemaName}),!0}catch(e){throw c.error("Error closing BaseService",{schemaName:this.schemaName,tableName:this.tableName,error:e.message}),this._handleError("CLOSE_ERROR",e),e}}destroy(){c.debug("Destroying BaseService",{schemaName:this.schemaName,tableName:this.tableName}),p.offDatabaseReconnect(this.schemaName,this.reconnectHandler),this.eventListeners.clear(),this.errorHandlers.clear(),this.cache.clear(),c.trace("BaseService destroyed",{schemaName:this.schemaName,tableName:this.tableName})}async getAll(e={},t={}){return c.trace("Using getAll alias",{schemaName:this.schemaName,tableName:this.tableName}),this.findAll(e,t)}async getById(e){return c.trace("Using getById alias",{schemaName:this.schemaName,tableName:this.tableName,id:e}),this.findById(e)}async getFirst(e={}){return c.trace("Using getFirst alias",{schemaName:this.schemaName,tableName:this.tableName}),this.findFirst(e)}}class I{constructor(e){this.tableName="",this.selectFields=["*"],this.joinClauses=[],this.whereConditions=[],this.groupByFields=[],this.havingConditions=[],this.orderByFields=[],this.limitValue=null,this.offsetValue=null,this.params=[],this.unionQueries=[],this.subQueries=[],this.cteQueries=new Map,this.dao=null,this.dao=e||null}static table(e,t){const a=new I(t);return a.tableName=e,a}static from(e,t){return I.table(e,t)}select(e){return this.selectFields=Array.isArray(e)?e:[e],this}selectRaw(e){return this.selectFields=[e],this}selectDistinct(e){const t=Array.isArray(e)?e.join(", "):e;return this.selectFields=[`DISTINCT ${t}`],this}join(e,t,a="INNER"){return this.joinClauses.push({type:a,table:e,condition:t}),this}innerJoin(e,t){return this.join(e,t,"INNER")}leftJoin(e,t){return this.join(e,t,"LEFT")}rightJoin(e,t){return this.join(e,t,"RIGHT")}fullOuterJoin(e,t){return this.join(e,t,"FULL OUTER")}where(e,t,a){if(typeof e=="object")return Object.entries(e).forEach(([i,o])=>{this.whereConditions.push({field:i,operator:"=",value:o})}),this;let s="=",r=t;return arguments.length===3&&(s=t,r=a),this.whereConditions.push({field:e,operator:s,value:r}),this}whereEquals(e,t){return this.where(e,"=",t)}whereNot(e,t){return this.where(e,"!=",t)}whereLike(e,t){return this.where(e,"LIKE",t)}whereNotLike(e,t){return this.where(e,"NOT LIKE",t)}whereIn(e,t){return this.whereConditions.push({field:e,operator:"IN",value:t}),this}whereNotIn(e,t){return this.whereConditions.push({field:e,operator:"NOT IN",value:t}),this}whereBetween(e,t,a){return this.whereConditions.push({field:e,operator:"BETWEEN",value:[t,a]}),this}whereNotBetween(e,t,a){return this.whereConditions.push({field:e,operator:"NOT BETWEEN",value:[t,a]}),this}whereNull(e){return this.whereConditions.push({field:e,operator:"IS NULL",value:null}),this}whereNotNull(e){return this.whereConditions.push({field:e,operator:"IS NOT NULL",value:null}),this}whereExists(e){return this.whereConditions.push({field:"",operator:"EXISTS",value:e}),this}whereNotExists(e){return this.whereConditions.push({field:"",operator:"NOT EXISTS",value:e}),this}orWhere(e,t,a){return this.where(e,t,a)}groupBy(e){return this.groupByFields=Array.isArray(e)?e:[e],this}having(e,t,a){let s="=",r=t;return arguments.length===3&&(s=t,r=a),this.havingConditions.push({field:e,operator:s,value:r}),this}havingCount(e,t,a){return this.having(`COUNT(${e})`,t,a)}orderBy(e,t="ASC"){return this.orderByFields.push(`${e} ${t}`),this}orderByDesc(e){return this.orderBy(e,"DESC")}orderByRaw(e){return this.orderByFields.push(e),this}latest(e="created_at"){return this.orderByDesc(e)}oldest(e="created_at"){return this.orderBy(e,"ASC")}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}skip(e){return this.offset(e)}take(e){return this.limit(e)}firstRow(){return this.limit(1)}paginate(e,t){return this.limitValue=t,this.offsetValue=(e-1)*t,this}union(e){return this.unionQueries.push(e),this}unionAll(e){return this.union(e)}with(e,t){return this.cteQueries.set(e,t),this}whereSubQuery(e,t,a){return this.subQueries.push({query:a,alias:""}),this.whereConditions.push({field:e,operator:t,value:a}),this}count(e="*"){return this.selectFields=[`COUNT(${e}) as count`],this}sum(e){return this.selectFields=[`SUM(${e}) as sum`],this}avg(e){return this.selectFields=[`AVG(${e}) as avg`],this}max(e){return this.selectFields=[`MAX(${e}) as max`],this}min(e){return this.selectFields=[`MIN(${e}) as min`],this}toSQL(){let e="";const t=[];if(this.cteQueries.size>0){const a=[];this.cteQueries.forEach((s,r)=>{const{sql:i,params:o}=s.toSQL();a.push(`${r} AS (${i})`),t.push(...o)}),e+=`WITH ${a.join(", ")} `}if(e+=`SELECT ${this.selectFields.join(", ")} FROM ${this.tableName}`,this.joinClauses.length>0&&this.joinClauses.forEach(a=>{e+=` ${a.type} JOIN ${a.table} ON ${a.condition}`}),this.whereConditions.length>0){const a=[];this.whereConditions.forEach(s=>{const{clause:r,conditionParams:i}=this.buildCondition(s);a.push(r),t.push(...i)}),e+=` WHERE ${a.join(" AND ")}`}if(this.groupByFields.length>0&&(e+=` GROUP BY ${this.groupByFields.join(", ")}`),this.havingConditions.length>0){const a=[];this.havingConditions.forEach(s=>{const{clause:r,conditionParams:i}=this.buildCondition(s);a.push(r),t.push(...i)}),e+=` HAVING ${a.join(" AND ")}`}return this.orderByFields.length>0&&(e+=` ORDER BY ${this.orderByFields.join(", ")}`),this.limitValue!==null&&(e+=` LIMIT ${this.limitValue}`),this.offsetValue!==null&&(e+=` OFFSET ${this.offsetValue}`),this.unionQueries.length>0&&this.unionQueries.forEach(a=>{const{sql:s,params:r}=a.toSQL();e+=` UNION ${s}`,t.push(...r)}),{sql:e,params:t}}buildCondition(e){const{field:t,operator:a,value:s}=e,r=[];switch(a.toUpperCase()){case"IN":case"NOT IN":const i=s.map(()=>"?").join(", ");return r.push(...s),{clause:`${t} ${a} (${i})`,conditionParams:r};case"BETWEEN":case"NOT BETWEEN":return r.push(s[0],s[1]),{clause:`${t} ${a} ? AND ?`,conditionParams:r};case"IS NULL":case"IS NOT NULL":return{clause:`${t} ${a}`,conditionParams:[]};case"EXISTS":case"NOT EXISTS":const{sql:o,params:l}=s.toSQL();return r.push(...l),{clause:`${a} (${o})`,conditionParams:r};default:if(s instanceof I){const{sql:m,params:f}=s.toSQL();return r.push(...f),{clause:`${t} ${a} (${m})`,conditionParams:r}}return r.push(s),{clause:`${t} ${a} ?`,conditionParams:r}}}async get(){if(!this.dao)throw new Error("DAO instance required for query execution");const{sql:e,params:t}=this.toSQL();return(await this.dao.execute(e,t)).rows}async first(){this.limit(1);const e=await this.get();return e.length>0?e[0]:null}async pluck(e){return this.select(e),(await this.get()).map(t=>t[e])}async exists(){return this.select("1").limit(1),(await this.get()).length>0}async countResult(){this.count();const e=await this.first();return e?e.count:0}static insert(e,t){const a=Object.keys(t),s=Object.values(t),r=s.map(()=>"?").join(", ");return{sql:`INSERT INTO ${e} (${a.join(", ")}) VALUES (${r})`,params:s}}static insertMany(e,t){if(t.length===0)throw new Error("Data array cannot be empty");const a=Object.keys(t[0]),s=a.map(()=>"?").join(", "),r=t.map(()=>`(${s})`).join(", "),i=t.flatMap(o=>Object.values(o));return{sql:`INSERT INTO ${e} (${a.join(", ")}) VALUES ${r}`,params:i}}static update(e,t,a,s=[]){const r=Object.keys(t).map(o=>`${o} = ?`).join(", "),i=[...Object.values(t),...s];return{sql:`UPDATE ${e} SET ${r} WHERE ${a}`,params:i}}static delete(e,t,a=[]){return{sql:`DELETE FROM ${e} WHERE ${t}`,params:a}}static upsert(e,t,a){const s=Object.keys(t),r=Object.values(t),i=r.map(()=>"?").join(", "),o=s.filter(f=>!a.includes(f)),l=o.length>0?o.map(f=>`${f} = excluded.${f}`).join(", "):"";let m=`INSERT INTO ${e} (${s.join(", ")}) VALUES (${i})`;return o.length>0?m+=` ON CONFLICT(${a.join(", ")}) DO UPDATE SET ${l}`:m+=` ON CONFLICT(${a.join(", ")}) DO NOTHING`,{sql:m,params:r}}clone(){if(!this.dao)throw new Error("DAO instance required for cloning QueryBuilder");const e=new I(this.dao);return e.tableName=this.tableName,e.selectFields=[...this.selectFields],e.joinClauses=[...this.joinClauses],e.whereConditions=[...this.whereConditions],e.groupByFields=[...this.groupByFields],e.havingConditions=[...this.havingConditions],e.orderByFields=[...this.orderByFields],e.limitValue=this.limitValue,e.offsetValue=this.offsetValue,e.unionQueries=[...this.unionQueries],e.subQueries=[...this.subQueries],e.cteQueries=new Map(this.cteQueries),e}toRawSQL(){const{sql:e,params:t}=this.toSQL();let a=e;return t.forEach(s=>{typeof s=="string"?a=a.replace("?",`'${s.replace(/'/g,"''")}'`):s==null?a=a.replace("?","NULL"):a=a.replace("?",String(s))}),a}explain(){return this.selectFields=["EXPLAIN QUERY PLAN "+this.selectFields.join(", ")],this}}const u=w(b.SERVICE_MANAGER);class O extends D{}class S{constructor(){this.services=new Map,this.serviceConfigs=new Map,this.serviceMetadata=new Map,this.eventHandlers=new Map,this.isShuttingDown=!1,this.cleanupInterval=null,u.info("ServiceManager instance created"),this.bindMethods(),this.startPeriodicCleanup()}static getInstance(){return S.instance?u.trace("Returning existing ServiceManager singleton instance"):(u.debug("Creating new ServiceManager singleton instance"),S.instance=new S),S.instance}static resetInstance(){u.warn("Resetting ServiceManager singleton instance"),S.instance?(S.instance.destroy(),S.instance=null,u.info("ServiceManager singleton instance reset successfully")):u.debug("No ServiceManager instance to reset")}bindMethods(){u.trace("Binding ServiceManager methods");const e=Object.getOwnPropertyNames(Object.getPrototypeOf(this));e.forEach(t=>{typeof this[t]=="function"&&t!=="constructor"&&(this[t]=this[t].bind(this))}),u.trace("ServiceManager methods bound successfully",{methodCount:e.length})}createServiceKey(e,t){const a=`${e}:${t}`;return u.trace("Created service key",{schemaName:e,tableName:t,key:a}),a}validateServiceConfig(e){var t,a;if(u.trace("Validating service config",{schemaName:e.schemaName,tableName:e.tableName}),!(!((t=e.schemaName)===null||t===void 0)&&t.trim()))throw u.error("Invalid service config: schema name missing",{config:e}),new Error("Schema name is required and cannot be empty");if(!(!((a=e.tableName)===null||a===void 0)&&a.trim()))throw u.error("Invalid service config: table name missing",{config:e}),new Error("Table name is required and cannot be empty");u.trace("Service config validation passed",{schemaName:e.schemaName,tableName:e.tableName})}registerService(e){u.debug("Registering service",{schemaName:e.schemaName,tableName:e.tableName,primaryKeyFields:e.primaryKeyFields,hasCustomServiceClass:!!e.serviceClass}),this.validateServiceConfig(e);const t=this.createServiceKey(e.schemaName,e.tableName),a={schemaName:e.schemaName.trim(),tableName:e.tableName.trim(),primaryKeyFields:e.primaryKeyFields||["id"],serviceClass:e.serviceClass||O},s=this.serviceConfigs.has(t);return this.serviceConfigs.set(t,a),s?u.info("Service configuration updated",{serviceKey:t}):u.info("Service registered successfully",{serviceKey:t}),this}registerServices(e){return u.debug("Registering multiple services",{count:e.length}),e.forEach((t,a)=>{try{this.registerService(t)}catch(s){throw u.error("Failed to register service in batch",{index:a,config:t,error:s.message}),s}}),u.info("Multiple services registered successfully",{count:e.length}),this}async createServiceInstance(e){var t;u.debug("Creating service instance",{schemaName:e.schemaName,tableName:e.tableName,serviceClassName:((t=e.serviceClass)===null||t===void 0?void 0:t.name)||"DefaultService"});const a=e.serviceClass||O,s=new a(e.schemaName,e.tableName);return e.primaryKeyFields&&(u.trace("Setting primary key fields",{schemaName:e.schemaName,tableName:e.tableName,primaryKeyFields:e.primaryKeyFields}),s.setPrimaryKeyFields(e.primaryKeyFields)),u.info("Service instance created successfully",{schemaName:e.schemaName,tableName:e.tableName}),s}async getService(e,t){if(this.isShuttingDown)throw u.error("ServiceManager is shutting down, cannot get service",{schemaName:e,tableName:t}),new Error("ServiceManager is shutting down");const a=this.createServiceKey(e,t);u.debug("Getting service",{serviceKey:a});const s=this.serviceMetadata.get(a);if(s&&(s.lastAccessed=new Date().toISOString(),u.trace("Updated service access time",{serviceKey:a})),this.services.has(a))return u.trace("Returning existing service",{serviceKey:a}),this.services.get(a);let r=this.serviceConfigs.get(a);r||(u.debug("Creating default config for unregistered service",{serviceKey:a}),r={schemaName:e,tableName:t,primaryKeyFields:["id"],serviceClass:O},this.serviceConfigs.set(a,r));try{const i=await this.createServiceInstance(r);return this.services.set(a,i),this.serviceMetadata.set(a,{createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString()}),this.emit("SERVICE_CREATED",{serviceKey:a,schemaName:e,tableName:t}),u.info("Service created and cached successfully",{serviceKey:a}),i}catch(i){throw u.error("Failed to create service",{serviceKey:a,error:i.message}),this.emit("SERVICE_ERROR",{serviceKey:a,schemaName:e,tableName:t,error:i}),i}}getExistingService(e,t){const a=this.createServiceKey(e,t);u.trace("Getting existing service",{serviceKey:a});const s=this.services.get(a)||null;return s?u.trace("Existing service found",{serviceKey:a}):u.trace("Existing service not found",{serviceKey:a}),s}async initializeService(e,t){const a=this.createServiceKey(e,t);u.debug("Initializing service",{serviceKey:a});try{const s=await this.getService(e,t);return await s.init(),u.info("Service initialized successfully",{serviceKey:a}),s}catch(s){throw u.error("Failed to initialize service",{serviceKey:a,error:s.message}),s}}async destroyService(e,t){const a=this.createServiceKey(e,t);u.debug("Destroying service",{serviceKey:a});const s=this.services.get(a);if(!s)return u.warn("Service not found for destruction",{serviceKey:a}),!1;try{return await s.close(),s.destroy(),this.services.delete(a),this.serviceMetadata.delete(a),this.emit("SERVICE_DESTROYED",{serviceKey:a,schemaName:e,tableName:t}),u.info("Service destroyed successfully",{serviceKey:a}),!0}catch(r){return u.error("Failed to destroy service",{serviceKey:a,error:r.message}),this.emit("SERVICE_ERROR",{serviceKey:a,schemaName:e,tableName:t,error:r}),!1}}getServicesBySchema(e){u.trace("Getting services by schema",{schemaName:e});const t=[];for(const[a,s]of this.services){const[r]=a.split(":");r===e&&t.push(s)}return u.debug("Found services for schema",{schemaName:e,count:t.length}),t}getServiceKeysBySchema(e){u.trace("Getting service keys by schema",{schemaName:e});const t=[];for(const a of this.services.keys()){const[s]=a.split(":");s===e&&t.push(a)}return u.debug("Found service keys for schema",{schemaName:e,keys:t}),t}async destroyServicesBySchema(e){const t=this.getServiceKeysBySchema(e);if(u.debug("Destroying services by schema",{schemaName:e,serviceKeys:t}),t.length===0){u.debug("No services found to destroy for schema",{schemaName:e});return}const a=t.map(async r=>{const[,i]=r.split(":");try{const o=await this.destroyService(e,i);return u.trace("Service destroy result",{serviceKey:r,result:o}),o}catch(o){return u.error("Error destroying service in schema cleanup",{serviceKey:r,error:o.message}),!1}}),s=(await Promise.all(a)).filter(Boolean).length;u.info("Schema services destruction completed",{schemaName:e,totalServices:t.length,successfulDestroys:s})}getAllServiceInfo(){u.trace("Getting all service info");const e=[];for(const[t,a]of this.serviceConfigs){const s=this.services.get(t),r=this.serviceMetadata.get(t);e.push({key:t,schemaName:a.schemaName,tableName:a.tableName,status:s?s.getStatus():{schemaName:a.schemaName,tableName:a.tableName,isOpened:!1,isInitialized:!1,hasDao:!1},isRegistered:!0,createdAt:(r==null?void 0:r.createdAt)||"N/A",lastAccessed:r==null?void 0:r.lastAccessed})}for(const[t,a]of this.services)if(!this.serviceConfigs.has(t)){const[s,r]=t.split(":"),i=this.serviceMetadata.get(t);e.push({key:t,schemaName:s,tableName:r,status:a.getStatus(),isRegistered:!1,createdAt:(i==null?void 0:i.createdAt)||"N/A",lastAccessed:i==null?void 0:i.lastAccessed})}return e}async healthCheck(){const e=Array.from(this.services.entries()).map(async([r,i])=>{try{const o=await i.healthCheck();return Object.assign(Object.assign({},o),{serviceKey:r})}catch(o){const[l,m]=r.split(":");return{healthy:!1,schemaName:l,error:o.message,timestamp:new Date().toISOString(),serviceKey:r}}}),t=await Promise.all(e),a=t.filter(r=>r.healthy).length,s={totalServices:t.length,healthyServices:a,unhealthyServices:t.length-a,services:t,timestamp:new Date().toISOString(),overallHealth:a===t.length};return this.emit("HEALTH_CHECK_COMPLETED",{serviceKey:"*",schemaName:"*",tableName:"*",data:s}),s}async executeSchemaTransaction(e,t){u.trace(`Executing schema transaction for schema ${e}`);const a=this.getServicesBySchema(e);if(a.length===0)throw u.error("No services found for schema",{schemaName:e}),new Error(`No services found for schema: ${e}`);for(const s of a)await s.init();return await a[0].executeTransaction(async()=>await t(a))}startPeriodicCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupUnusedServices()},300*1e3)}async cleanupUnusedServices(e=1800*1e3){if(this.isShuttingDown)return;const t=Date.now(),a=[];for(const[s,r]of this.serviceMetadata){if(!r.lastAccessed)continue;const i=new Date(r.lastAccessed).getTime();t-i>e&&a.push(s)}for(const s of a){const[r,i]=s.split(":");await this.destroyService(r,i)}}on(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t),this}off(e,t){const a=this.eventHandlers.get(e);if(a){const s=a.indexOf(t);s>-1&&a.splice(s,1)}return this}emit(e,t){const a=Object.assign(Object.assign({},t),{type:e,timestamp:new Date().toISOString()}),s=this.eventHandlers.get(e);s&&s.forEach(i=>{try{i(a)}catch(o){console.error(`ServiceManager: Error in ${e} event handler:`,o)}});const r=this.eventHandlers.get("*");r&&r.forEach(i=>{try{i(a)}catch(o){console.error("ServiceManager: Error in global event handler:",o)}})}hasService(e,t){const a=this.createServiceKey(e,t);return this.services.has(a)}isRegistered(e,t){const a=this.createServiceKey(e,t);return this.serviceConfigs.has(a)}getServiceCount(){return this.services.size}getRegisteredCount(){return this.serviceConfigs.size}getSchemas(){const e=new Set;for(const t of this.services.keys()){const[a]=t.split(":");e.add(a)}return Array.from(e)}async destroy(){this.isShuttingDown=!0,this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null);const e=Array.from(this.services.entries()).map(async([t,a])=>{try{await a.close(),a.destroy()}catch(s){console.error(`Error destroying service ${t}:`,s)}});await Promise.all(e),this.services.clear(),this.serviceConfigs.clear(),this.serviceMetadata.clear(),this.eventHandlers.clear(),this.isShuttingDown=!1}}S.instance=null,S.getInstance();class U{sanitizeSQL(e){return e.trim()}bindParameters(e,t){if(!t||t.length===0)return e;let a=0;return e.replace(/\?/g,()=>{if(a<t.length){const s=t[a++];return typeof s=="string"?`'${s.replace(/'/g,"''")}'`:s==null?"NULL":String(s)}return"?"})}}class E{constructor(){if(this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners=new Map,this.logger=w(b.UNIVERSAL_SQLITE),E.instance)throw new Error("UniversalSQLite is a singleton. Use UniversalSQLite.getInstance() instead.");this.logger.debug("UniversalSQLite instance created")}static getInstance(){return E.instance||(E.instance=new E),E.instance}static resetInstance(){E.instance&&(w(b.UNIVERSAL_SQLITE).debug("Resetting UniversalSQLite instance"),E.instance.closeAll().catch(()=>{})),E.instance=null}static configureLogger(e){d.updateConfiguration(e)}static enableDebugLogging(){const e=d.createDebugConfig();d.updateConfiguration(e)}static setProductionLogging(){const e=d.createProductionConfig();d.updateConfiguration(e)}static enableLogging(){d.setEnabled(!0)}static disableLogging(){d.setEnabled(!1)}static enableModuleLogging(e,t,a){d.enableModule(e,t,a)}static disableModuleLogging(e){d.disableModule(e)}async initialize(e,t={}){return this.logger.debug("Starting initialization",{schemas:Object.keys(e),options:t}),this.isInitialized?(this.logger.debug("Already initialized, returning existing promise"),this.initializationPromise||Promise.resolve()):this.initializationPromise?(this.logger.debug("Initialization in progress, waiting..."),this.initializationPromise):(this.initializationPromise=this._performInitialization(e,t),this.initializationPromise)}async _performInitialization(e,t){try{this.logger.info("Performing initialization",{schemaCount:Object.keys(e).length}),t.loggerConfig&&(this.logger.debug("Configuring custom logger"),d.updateConfiguration(t.loggerConfig)),t.registerAdapters&&(this.logger.debug("Registering adapters",{count:t.registerAdapters.length}),t.registerAdapters.forEach(a=>{v.registerAdapter(a)})),t.globalErrorHandler&&(this.logger.debug("Registering global error handler"),this.on("error",t.globalErrorHandler)),this.logger.debug("Registering schemas with DatabaseManager"),p.registerSchemas(e),e.core&&t.autoConnectCore!==!1&&(this.logger.debug("Initializing core connection"),await p.initializeCoreConnection()),t.defaultRoles&&t.defaultRoles.length>0&&(this.logger.debug("Setting default roles",{roles:t.defaultRoles}),await p.setCurrentUserRoles(t.defaultRoles)),this.isInitialized=!0,this.logger.info("Initialization completed successfully"),this._emit("initialized",{schemas:Object.keys(e)})}catch(a){throw this.isInitialized=!1,this.initializationPromise=null,this.logger.error("Initialization failed",a),this._emit("error",a,"initialization"),a}}async initializeFromSchema(e,t={}){this.logger.debug("Initializing from single schema",{schemaName:e.database_name});const a={[e.database_name]:e};return this.initialize(a,Object.assign(Object.assign({},t),{autoConnectCore:t.autoConnect!==!1}))}async connect(e){this.logger.debug("Connecting to schema",{schemaName:e}),this.ensureInitialized(),this.currentSchema=e;try{const t=await p.getLazyLoading(e);return this.logger.info("Successfully connected to schema",{schemaName:e}),this._emit("connected",{schemaName:e}),t}catch(t){throw this.logger.error("Failed to connect to schema",{schemaName:e,error:t}),this._emit("error",t,"connection"),t}}getDAO(e){this.ensureInitialized();const t=e||this.currentSchema;if(!t){const a=new Error("No schema specified. Use connect() first or provide schemaName parameter.");throw this.logger.error("getDAO failed: No schema specified"),a}try{return this.logger.trace("Getting DAO for schema",{schema:t}),p.get(t)}catch(a){throw this.logger.error("Failed to get DAO",{schema:t,error:a}),this._emit("error",a,"getDAO"),a}}getCurrentDAO(){if(!this.currentSchema){const e=new Error("No current connection. Call connect() first.");throw this.logger.error("getCurrentDAO failed: No current connection"),e}return this.getDAO(this.currentSchema)}async ensureDatabaseConnection(e){this.logger.debug("Ensuring database connection",{schemaName:e}),this.ensureInitialized();try{const t=await p.ensureDatabaseConnection(e);return this.logger.debug("Database connection ensured",{schemaName:e}),t}catch(t){throw this.logger.error("Failed to ensure database connection",{schemaName:e,error:t}),this._emit("error",t,"ensureConnection"),t}}createService(e,t){const a=t||this.currentSchema;if(!a){const r=new Error("No schema specified. Use connect() first or provide schemaName parameter.");throw this.logger.error("createService failed: No schema specified",{tableName:e}),r}this.logger.debug("Creating service",{tableName:e,schema:a});const s=class extends D{constructor(){if(!a)throw new Error("No schema specified. Use connect() first or provide schemaName parameter.");super(a,e)}};return new s}createServices(e,t){this.logger.debug("Creating multiple services",{tableNames:e,schemaName:t});const a={};return e.forEach(s=>{a[s]=this.createService(s,t)}),this.logger.debug("Created services",{count:e.length}),a}query(e,t){this.logger.trace("Creating query builder",{tableName:e,schemaName:t});const a=this.getDAO(t);return e?I.table(e,a):new I(a)}table(e,t){return this.query(e,t)}async execute(e,t,a){this.logger.debug("Executing SQL",{sql:e.substring(0,100)+"...",paramsCount:t==null?void 0:t.length});try{const s=await this.getDAO(a).execute(e,t);return this.logger.debug("SQL executed successfully",{rowsAffected:s.rowsAffected,lastInsertRowId:s.lastInsertRowId}),this._emit("queryExecuted",{sql:e,params:t,rowCount:s.rowsAffected}),s}catch(s){throw this.logger.error("SQL execution failed",{sql:e.substring(0,100)+"...",error:s}),this._emit("error",s,"execute"),s}}async getRst(e,t,a){return this.logger.trace("Getting first row",{sql:e.substring(0,100)+"..."}),await this.getDAO(a).getRst(e,t)}async getRsts(e,t,a){return this.logger.trace("Getting all rows",{sql:e.substring(0,100)+"..."}),await this.getDAO(a).getRsts(e,t)}async initializeSchema(e,t=!1){this.logger.info("Initializing schema",{schemaName:e.database_name,forceRecreate:t});try{await(await v.createOrOpen({config:e},t)).initializeFromSchema(e),this.logger.info("Schema initialized successfully",{schemaName:e.database_name}),this._emit("schemaInitialized",{schemaName:e.database_name})}catch(a){throw this.logger.error("Schema initialization failed",{schemaName:e.database_name,error:a}),this._emit("error",a,"schemaInitialization"),a}}async getSchemaVersion(e){return this.logger.debug("Getting schema version",{schemaName:e}),await this.getDAO(e).getSchemaVersion()}async getDatabaseInfo(e){return this.logger.debug("Getting database info",{schemaName:e}),await this.getDAO(e).getDatabaseInfo()}async getTableInfo(e,t){return this.logger.debug("Getting table info",{tableName:e,schemaName:t}),await this.getDAO(t).getTableInfo(e)}async importData(e,t,a,s){this.logger.info("Starting data import",{schemaName:e,tableName:t,recordCount:a.length});try{const r=await p.importDataToTable(e,t,a,s);return this.logger.info("Data import completed",{schemaName:e,tableName:t,successRows:r.successRows,failedRows:r.errorRows,errors:r.errors.length}),this._emit("dataImported",{schemaName:e,tableName:t,recordCount:r.successRows}),r}catch(r){throw this.logger.error("Data import failed",{schemaName:e,tableName:t,error:r}),this._emit("error",r,"dataImport"),r}}async importDataWithMapping(e,t,a,s,r){this.logger.info("Starting data import with mapping",{schemaName:e,tableName:t,recordCount:a.length,mappingCount:s.length});try{const i=await p.importDataWithMapping(e,t,a,s,r);return this.logger.info("Data import with mapping completed",{schemaName:e,tableName:t,successRows:i.successRows,failedRows:i.errorRows}),this._emit("dataImported",{schemaName:e,tableName:t,recordCount:i.successRows}),i}catch(i){throw this.logger.error("Data import with mapping failed",{schemaName:e,tableName:t,error:i}),this._emit("error",i,"dataImportWithMapping"),i}}async importFromCSV(e,t,a,s){this.logger.info("Starting CSV import",{schemaName:e,tableName:t,csvLength:a.length,delimiter:s==null?void 0:s.delimiter,hasHeader:s==null?void 0:s.hasHeader});try{const r=await p.importFromCSV(e,t,a,s);return this.logger.info("CSV import completed",{schemaName:e,tableName:t,successRows:r.successRows,failedRows:r.errorRows}),this._emit("csvImported",{schemaName:e,tableName:t,recordCount:r.successRows}),r}catch(r){throw this.logger.error("CSV import failed",{schemaName:e,tableName:t,error:r}),this._emit("error",r,"csvImport"),r}}async setUserRoles(e,t){this.logger.info("Setting user roles",{roles:e,primaryRole:t}),this.ensureInitialized();try{await p.setCurrentUserRoles(e,t),this.logger.info("User roles set successfully",{roles:e,primaryRole:t}),this._emit("userRolesSet",{roles:e,primaryRole:t})}catch(a){throw this.logger.error("Failed to set user roles",{roles:e,primaryRole:t,error:a}),this._emit("error",a,"setUserRoles"),a}}getCurrentUserRoles(){const e=p.getCurrentUserRoles();return this.logger.trace("Getting current user roles",{roles:e}),e}getCurrentRole(){const e=p.getCurrentRole();return this.logger.trace("Getting current role",{role:e}),e}hasAccessToDatabase(e){const t=p.hasAccessToDatabase(e);return this.logger.trace("Checking database access",{dbKey:e,hasAccess:t}),t}async executeTransaction(e,t){this.logger.info("Starting cross-schema transaction",{schemas:e});try{await p.executeCrossSchemaTransaction(e,t),this.logger.info("Cross-schema transaction completed successfully",{schemas:e}),this._emit("transactionCompleted",{schemas:e})}catch(a){throw this.logger.error("Cross-schema transaction failed",{schemas:e,error:a}),this._emit("error",a,"transaction"),a}}async executeTransactionOnCurrent(e){this.logger.debug("Starting transaction on current connection");const t=this.getCurrentDAO();try{await t.beginTransaction(),this.logger.trace("Transaction begun");const a=await e(t);return await t.commitTransaction(),this.logger.debug("Transaction committed successfully"),a}catch(a){throw this.logger.warn("Transaction failed, rolling back",{error:a}),await t.rollbackTransaction(),a}}getEnvironment(){const e=v.getEnvironmentInfo();return this.logger.trace("Getting environment info",{env:e}),e}getConnectionStatus(){const e={isInitialized:this.isInitialized,currentSchema:this.currentSchema,activeConnections:p.listConnections(),connectionCount:p.getConnectionCount(),userRoles:this.getCurrentUserRoles(),primaryRole:this.getCurrentRole()};return this.logger.trace("Getting connection status",e),e}getAvailableSchemas(){const e=p.getAvailableSchemas();return this.logger.trace("Getting available schemas",{schemas:e}),e}async healthCheck(){this.logger.debug("Starting health check for all connections");const e=p.getConnections(),t={};for(const[a,s]of Object.entries(e))try{await s.execute("SELECT 1"),t[a]={healthy:!0},this.logger.trace("Health check passed",{schemaName:a})}catch(r){t[a]={healthy:!1,error:r.message},this.logger.warn("Health check failed",{schemaName:a,error:r})}return this.logger.debug("Health check completed",{totalConnections:Object.keys(t).length,healthyConnections:Object.values(t).filter(a=>a.healthy).length}),t}on(e,t){return this.logger.trace("Adding event listener",{event:e}),this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t),this}off(e,t){this.logger.trace("Removing event listener",{event:e});const a=this.eventListeners.get(e);if(a){const s=a.indexOf(t);s>-1&&a.splice(s,1)}return this}_emit(e,...t){this.logger.trace("Emitting event",{event:e,argsCount:t.length});const a=this.eventListeners.get(e);a&&a.forEach(s=>{try{s(...t)}catch(r){this.logger.error("Error in event handler",{event:e,error:r})}})}async closeConnection(e){this.logger.info("Closing connection",{schemaName:e});try{await p.closeConnection(e),this.currentSchema===e&&(this.currentSchema=null,this.logger.debug("Current schema reset due to connection close")),this.logger.info("Connection closed successfully",{schemaName:e}),this._emit("connectionClosed",{schemaName:e})}catch(t){throw this.logger.error("Failed to close connection",{schemaName:e,error:t}),this._emit("error",t,"closeConnection"),t}}async closeAll(){this.logger.info("Closing all connections");try{await p.closeAll(),this.currentSchema=null,this.isInitialized=!1,this.initializationPromise=null,this.eventListeners.clear(),this.logger.info("All connections closed successfully"),this._emit("allConnectionsClosed")}catch(e){throw this.logger.error("Failed to close all connections",{error:e}),this._emit("error",e,"closeAll"),e}}async logout(){this.logger.info("User logout initiated");try{await p.logout(),this.currentSchema=null,this.logger.info("User logout completed successfully"),this._emit("userLoggedOut")}catch(e){throw this.logger.error("User logout failed",{error:e}),this._emit("error",e,"logout"),e}}static registerAdapter(e){w(b.UNIVERSAL_SQLITE).debug("Registering adapter",{adapterName:e.name,adapterVersion:e.version}),v.registerAdapter(e)}static registerRole(e){w(b.UNIVERSAL_SQLITE).debug("Registering role",{roleConfig:e}),p.registerRole(e)}static registerRoles(e){w(b.UNIVERSAL_SQLITE).debug("Registering multiple roles",{roleCount:e.length}),p.registerRoles(e)}ensureInitialized(){if(!this.isInitialized){const e=new Error("UniversalSQLite not initialized. Call initialize() first.");throw this.logger.error("Operation attempted on uninitialized instance"),e}}}E.instance=null;const B=(h,e)=>(w(b.DATABASE_FACTORY).debug("Creating UniversalDAO",{dbPath:h,options:e}),v.createDAO(h,e)),K=async(h,e)=>(w(b.DATABASE_FACTORY).debug("Creating database from schema",{schemaName:h.database_name}),await v.createFromConfig(h,e)),P=async(h,e)=>(w(b.DATABASE_FACTORY).debug("Opening existing database",{dbName:h}),await v.openExisting(h,e)),V=h=>(w(b.QUERY_BUILDER).trace("Creating query builder"),new I(h)),q=(h,e)=>(w(b.BASE_SERVICE).debug("Creating base service",{schemaName:h,tableName:e}),new class extends D{constructor(){super(h,e)}}),G=async h=>{const e=w(b.UNIVERSAL_SQLITE);e.info("Setting up UniversalSQLite",{schemaCount:Object.keys(h.schemas).length,autoConnect:h.autoConnect,enableDebugLogging:h.enableDebugLogging});const t=E.getInstance();return h.enableDebugLogging&&E.enableDebugLogging(),await t.initialize(h.schemas,{registerAdapters:h.adapters,defaultRoles:h.defaultRoles,loggerConfig:h.loggerConfig}),h.autoConnect&&await t.connect(h.autoConnect),e.info("UniversalSQLite setup completed"),t},H=async(h,e)=>{const t=w(b.UNIVERSAL_SQLITE);t.info("Creating single database",{schemaName:h.database_name,enableDebugLogging:e==null?void 0:e.enableDebugLogging});const a=E.getInstance();e!=null&&e.enableDebugLogging&&E.enableDebugLogging(),await a.initializeFromSchema(h,{registerAdapters:e!=null&&e.adapter?[e.adapter]:void 0,autoConnect:e==null?void 0:e.autoConnect,loggerConfig:e==null?void 0:e.loggerConfig});const s=(e==null?void 0:e.autoConnect)!==!1?await a.connect(h.database_name):a.getDAO(h.database_name);return t.info("Single database creation completed"),{sqlite:a,dao:s}},Q=E.getInstance();export{U as BaseAdapter,D as BaseService,v as DatabaseFactory,p as DatabaseManager,O as DefaultService,I as QueryBuilder,d as SQLiteLoggerConfig,b as SQLiteModules,S as ServiceManager,x as UniversalDAO,E as UniversalSQLite,q as createBaseService,K as createDatabaseFromSchema,w as createModuleLogger,V as createQueryBuilder,H as createSingleDatabase,B as createUniversalDAO,Q as default,P as openExistingDatabase,G as setupUniversalSQLite,j as sqliteLogger};
14
14
  //# sourceMappingURL=index.mjs.map