stabilize-orm 1.3.8 → 2.1.0

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.
Files changed (75) hide show
  1. package/README.md +1097 -546
  2. package/dist/auto-migrate.d.ts +34 -0
  3. package/dist/auto-migrate.d.ts.map +1 -0
  4. package/dist/auto-migrate.js +3003 -0
  5. package/dist/auto-migrate.js.map +163 -0
  6. package/dist/cache.d.ts +90 -0
  7. package/dist/cache.d.ts.map +1 -0
  8. package/dist/cache.js +166 -0
  9. package/dist/cache.js.map +64 -0
  10. package/dist/client.d.ts +73 -0
  11. package/dist/client.d.ts.map +1 -0
  12. package/dist/client.js +2997 -0
  13. package/dist/client.js.map +162 -0
  14. package/dist/hooks.d.ts +31 -0
  15. package/dist/hooks.d.ts.map +1 -0
  16. package/dist/hooks.js +4 -0
  17. package/dist/hooks.js.map +11 -0
  18. package/dist/index.d.ts +101 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +3183 -0
  21. package/dist/index.js.map +222 -0
  22. package/dist/logger.d.ts +40 -0
  23. package/dist/logger.d.ts.map +1 -0
  24. package/dist/logger.js +8 -0
  25. package/dist/logger.js.map +11 -0
  26. package/dist/migrations.d.ts +31 -0
  27. package/dist/migrations.d.ts.map +1 -0
  28. package/dist/migrations.js +3009 -0
  29. package/dist/migrations.js.map +164 -0
  30. package/{model.ts → dist/model.d.ts} +124 -189
  31. package/dist/model.d.ts.map +1 -0
  32. package/dist/model.js +4 -0
  33. package/dist/model.js.map +10 -0
  34. package/dist/query-builder.d.ts +91 -0
  35. package/dist/query-builder.d.ts.map +1 -0
  36. package/dist/query-builder.js +14 -0
  37. package/dist/query-builder.js.map +12 -0
  38. package/dist/repository.d.ts +165 -0
  39. package/dist/repository.d.ts.map +1 -0
  40. package/dist/repository.js +176 -0
  41. package/dist/repository.js.map +69 -0
  42. package/dist/tsconfig.tsbuildinfo +1 -0
  43. package/dist/types.d.ts +110 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/types.js +4 -0
  46. package/dist/types.js.map +10 -0
  47. package/dist/utils/encryption.d.ts +13 -0
  48. package/dist/utils/encryption.d.ts.map +1 -0
  49. package/dist/utils/encryption.js +4 -0
  50. package/dist/utils/encryption.js.map +10 -0
  51. package/package.json +104 -25
  52. package/.eslintrc.json +0 -10
  53. package/.github/ISSUE_TEMPLATE/PULL_REQUEST_TEMPLATE.md +0 -23
  54. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -25
  55. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -17
  56. package/.github/workflows/ci-cd.yml +0 -22
  57. package/CHANGELOG.md +0 -75
  58. package/CODE_OF_CONDUCT.md +0 -87
  59. package/CONTRIBUTING.md +0 -48
  60. package/FUNDING.md +0 -14
  61. package/SECURITY.md +0 -35
  62. package/SUPPORT.md +0 -18
  63. package/bun.lock +0 -667
  64. package/cache.ts +0 -181
  65. package/client.ts +0 -249
  66. package/docker-compose.yml +0 -22
  67. package/hooks.ts +0 -76
  68. package/index.ts +0 -158
  69. package/logger.ts +0 -127
  70. package/migrations.ts +0 -318
  71. package/query-builder.ts +0 -209
  72. package/repository.ts +0 -1096
  73. package/tests/migrations.test.ts +0 -141
  74. package/tsconfig.json +0 -32
  75. package/types.ts +0 -106
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @file hooks.ts
3
+ * @description Provides lifecycle hooks for Stabilize ORM models, integrated with the programmatic API.
4
+ * @author ElectronSz
5
+ */
6
+ export type HookType = "beforeCreate" | "afterCreate" | "beforeUpdate" | "afterUpdate" | "beforeSave" | "afterSave" | "beforeDelete" | "afterDelete";
7
+ export type HookCallback = (entity: any) => Promise<void> | void;
8
+ export interface Hook {
9
+ type: HookType;
10
+ callback: HookCallback;
11
+ }
12
+ declare module "./model" {
13
+ interface ModelConfig {
14
+ hooks?: Partial<Record<HookType, HookCallback | HookCallback[]>>;
15
+ }
16
+ }
17
+ /**
18
+ * Registers hooks for a model in the MetadataStorage.
19
+ * @param model The model class.
20
+ * @param hooks A record of hook types to their callbacks.
21
+ */
22
+ export declare function registerHooks(model: Function, hooks: Record<HookType, HookCallback | HookCallback[]>): void;
23
+ /**
24
+ * Retrieves hooks for a given entity and hook type.
25
+ * Combines hooks from MetadataStorage and class methods.
26
+ * @param entity The entity instance.
27
+ * @param type The hook type (e.g., 'beforeCreate').
28
+ * @returns An array of Hook objects to execute.
29
+ */
30
+ export declare function getHooks(entity: any, type: HookType): Hook[];
31
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../hooks.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,MAAM,MAAM,QAAQ,GAChB,cAAc,GACd,aAAa,GACb,cAAc,GACd,aAAa,GACb,YAAY,GACZ,WAAW,GACX,cAAc,GACd,aAAa,CAAC;AAElB,MAAM,MAAM,YAAY,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAEjE,MAAM,WAAW,IAAI;IACnB,IAAI,EAAE,QAAQ,CAAC;IACf,QAAQ,EAAE,YAAY,CAAC;CACxB;AAGD,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAU,WAAW;QACnB,KAAK,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,YAAY,GAAG,YAAY,EAAE,CAAC,CAAC,CAAC;KAClE;CACF;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,QAAQ,EACf,KAAK,EAAE,MAAM,CAAC,QAAQ,EAAE,YAAY,GAAG,YAAY,EAAE,CAAC,QAQvD;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,QAAQ,GAAG,IAAI,EAAE,CA8B5D"}
package/dist/hooks.js ADDED
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ var I=Object.create;var{getPrototypeOf:J,defineProperty:E,getOwnPropertyNames:K}=Object;var L=Object.prototype.hasOwnProperty;var O=(q,w,x)=>{x=q!=null?I(J(q)):{};let z=w||!q||!q.__esModule?E(x,"default",{value:q,enumerable:!0}):x;for(let A of K(q))if(!L.call(z,A))E(z,A,{get:()=>q[A],enumerable:!0});return z};var P=(q,w)=>()=>(w||q((w={exports:{}}).exports,w),w.exports);var Q=import.meta.require;class D{static models=new Map;static setModelMetadata(q,w){this.models.set(q,w)}static getModelMetadata(q){return this.models.get(q)}static getTableName(q){return this.getModelMetadata(q)?.tableName||""}static getColumns(q){return this.getModelMetadata(q)?.columns||{}}static getValidators(q){let w=this.getModelMetadata(q)?.columns||{},x={};for(let[z,A]of Object.entries(w)){let B=[];if(A.required)B.push("required");if(A.unique)B.push("unique");x[z]=B}return x}static getRelations(q){let w=this.getModelMetadata(q)?.relations||[],x={};for(let z of w)x[z.property]=z;return x}static getSoftDeleteField(q){let w=this.getModelMetadata(q)?.columns||{};for(let[x,z]of Object.entries(w))if(z.softDelete)return x;return null}static isVersioned(q){return!!this.getModelMetadata(q)?.versioned}static getScopes(q){return this.getModelMetadata(q)?.scopes||{}}static getModelByTableName(q){for(let[w,x]of this.models)if(x.tableName===q)return w;return}static getTimestamps(q){return this.getModelMetadata(q)?.timestamps||{}}}function U(q){class w{constructor(x){Object.assign(this,x)}}return D.setModelMetadata(w,{tableName:q.tableName,versioned:q.versioned||!1,softDelete:q.softDelete||!1,columns:q.columns,relations:q.relations||[],scopes:q.scopes||{},timestamps:q.timestamps||{}}),w}function X(q,w){let x=D.getModelMetadata(q)||{tableName:"",columns:{}};x.hooks={...x.hooks,...w},D.setModelMetadata(q,x)}function Y(q,w){let x=[];if(!q)return x;let z=Object.getPrototypeOf(q);if(!z)return x;let A=z.constructor,B=D.getModelMetadata(A);if(B?.hooks?.[w]){let F=Array.isArray(B.hooks[w])?B.hooks[w]:[B.hooks[w]];x.push(...F.map((H)=>({type:w,callback:()=>H(q)})))}if(typeof q[w]==="function")x.push({type:w,callback:()=>q[w]()});return x}export{X as registerHooks,Y as getHooks};
3
+
4
+ //# debugId=5124B63376B5B21364756E2164756E21
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["..\\model.ts", "..\\hooks.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * @file model.ts\n * @description Provides a programmatic API for defining models and a metadata storage system.\n * @author ElectronSz\n */\n\nimport type { QueryBuilder } from \"./query-builder\";\nimport { DataTypes, RelationType, type DefaultExpression } from \"./types\";\n\n// Interface for column configuration\nexport interface ColumnConfig {\n name?: string;\n type: DataTypes;\n length?: number;\n precision?: number;\n scale?: number;\n required?: boolean;\n unique?: boolean;\n defaultValue?: any;\n defaultExpression?: DefaultExpression;\n index?: string;\n softDelete?: boolean;\n minLength?: number;\n maxLength?: number;\n pattern?: RegExp;\n customValidator?: (val: any) => boolean | string;\n encrypted?: boolean;\n optimisticLock?: boolean;\n}\n\n// Interface for relationship configuration\nexport interface RelationConfig {\n type: RelationType;\n target: () => any; // Reference to another model\n property: string; // Property name in the model\n foreignKey?: string;\n inverseKey?: string;\n joinTable?: string;\n}\n\nexport interface TimestampsConfig {\n createdAt?: string;\n updatedAt?: string;\n}\n\n// Interface for model configuration\nexport interface ModelConfig {\n tableName: string;\n versioned?: boolean;\n softDelete?: boolean;\n columns: Record<string, ColumnConfig>;\n relations?: RelationConfig[];\n scopes?: Record<\n string,\n (qb: QueryBuilder<any>, ...args: any[]) => QueryBuilder<any>\n >; // Custom query scopes\n timestamps?: TimestampsConfig; // Auto-managed timestamp columns\n}\n\n/**\n * Metadata storage for models.\n * Stores and retrieves model configuration such as columns, relations, scopes, etc.\n */\nexport class MetadataStorage {\n private static models: Map<Function, ModelConfig> = new Map();\n\n /**\n * Associates model metadata with a class constructor.\n * @param model - The class constructor for the model.\n * @param config - The model configuration object.\n */\n static setModelMetadata(model: Function, config: ModelConfig) {\n this.models.set(model, config);\n }\n\n /**\n * Retrieves the model configuration for a given model class.\n * @param model - The class constructor for the model.\n * @returns The model configuration or undefined if not found.\n */\n static getModelMetadata(model: Function): ModelConfig | undefined {\n return this.models.get(model);\n }\n\n /**\n * Gets the table name for a given model class.\n * @param model - The class constructor for the model.\n * @returns The table name or an empty string if not found.\n */\n static getTableName(model: Function): string {\n return this.getModelMetadata(model)?.tableName || \"\";\n }\n\n /**\n * Gets the column configuration for a given model class.\n * @param model - The class constructor for the model.\n * @returns Record of column names to their configuration.\n */\n static getColumns(model: Function): Record<string, ColumnConfig> {\n return this.getModelMetadata(model)?.columns || {};\n }\n\n /**\n * Collects validation rules for each column of a given model.\n * @param model - The class constructor for the model.\n * @returns An object mapping column names to an array of validation rule names.\n */\n static getValidators(model: Function): Record<string, string[]> {\n const columns = this.getModelMetadata(model)?.columns || {};\n const validators: Record<string, string[]> = {};\n for (const [key, col] of Object.entries(columns)) {\n const rules: string[] = [];\n if (col.required) rules.push(\"required\");\n if (col.unique) rules.push(\"unique\");\n validators[key] = rules;\n }\n return validators;\n }\n\n /**\n * Gets the relationship configuration for a given model class.\n * @param model - The class constructor for the model.\n * @returns Record of property names to their relation configuration.\n */\n static getRelations(model: Function): Record<string, RelationConfig> {\n const relations = this.getModelMetadata(model)?.relations || [];\n const result: Record<string, RelationConfig> = {};\n for (const rel of relations) {\n result[rel.property] = rel;\n }\n return result;\n }\n\n /**\n * Finds the soft delete field, if any, for a given model class.\n * @param model - The class constructor for the model.\n * @returns The key of the soft delete field, or null if not found.\n */\n static getSoftDeleteField(model: Function): string | null {\n const columns = this.getModelMetadata(model)?.columns || {};\n for (const [key, col] of Object.entries(columns)) {\n if (col.softDelete) return key;\n }\n return null;\n }\n\n /**\n * Checks if the model is versioned.\n * @param model - The class constructor for the model.\n * @returns True if versioned, false otherwise.\n */\n static isVersioned(model: Function): boolean {\n return !!this.getModelMetadata(model)?.versioned;\n }\n\n /**\n * Gets custom query scopes for a given model class.\n * @param model - The class constructor for the model.\n * @returns Record of scope names to scope functions.\n */\n static getScopes(\n model: Function,\n ): Record<\n string,\n (qb: QueryBuilder<any>, ...args: any[]) => QueryBuilder<any>\n > {\n return this.getModelMetadata(model)?.scopes || {};\n }\n\n /**\n * Finds the model constructor by table name.\n * @param tableName - The table name to search for.\n * @returns The model constructor or undefined if not found.\n */\n static getModelByTableName(tableName: string): Function | undefined {\n for (const [model, config] of this.models) {\n if (config.tableName === tableName) {\n return model;\n }\n }\n return undefined;\n }\n\n static getTimestamps(model: Function): TimestampsConfig {\n return this.getModelMetadata(model)?.timestamps || {};\n }\n}\n\n/**\n * Programmatically defines a model and stores its metadata.\n * @param config - The model configuration object.\n * @returns The dynamically created model class.\n */\nexport function defineModel(config: ModelConfig) {\n class Model {\n /**\n * Constructs a model instance from plain data.\n * @param data - The plain object to assign properties from.\n */\n constructor(data: any) {\n Object.assign(this, data);\n }\n }\n\n // Store metadata\n MetadataStorage.setModelMetadata(Model, {\n tableName: config.tableName,\n versioned: config.versioned || false,\n softDelete: config.softDelete || false,\n columns: config.columns,\n relations: config.relations || [],\n scopes: config.scopes || {},\n timestamps: config.timestamps || {},\n });\n\n return Model;\n}\n",
6
+ "/**\n * @file hooks.ts\n * @description Provides lifecycle hooks for Stabilize ORM models, integrated with the programmatic API.\n * @author ElectronSz\n */\n\nimport { MetadataStorage } from \"./model\";\n\nexport type HookType =\n | \"beforeCreate\"\n | \"afterCreate\"\n | \"beforeUpdate\"\n | \"afterUpdate\"\n | \"beforeSave\"\n | \"afterSave\"\n | \"beforeDelete\"\n | \"afterDelete\";\n\nexport type HookCallback = (entity: any) => Promise<void> | void;\n\nexport interface Hook {\n type: HookType;\n callback: HookCallback;\n}\n\n// Extend ModelConfig to include hooks\ndeclare module \"./model\" {\n interface ModelConfig {\n hooks?: Partial<Record<HookType, HookCallback | HookCallback[]>>;\n }\n}\n\n/**\n * Registers hooks for a model in the MetadataStorage.\n * @param model The model class.\n * @param hooks A record of hook types to their callbacks.\n */\nexport function registerHooks(\n model: Function,\n hooks: Record<HookType, HookCallback | HookCallback[]>,\n) {\n const config = MetadataStorage.getModelMetadata(model) || {\n tableName: \"\",\n columns: {},\n };\n config.hooks = { ...config.hooks, ...hooks };\n MetadataStorage.setModelMetadata(model, config);\n}\n\n/**\n * Retrieves hooks for a given entity and hook type.\n * Combines hooks from MetadataStorage and class methods.\n * @param entity The entity instance.\n * @param type The hook type (e.g., 'beforeCreate').\n * @returns An array of Hook objects to execute.\n */\nexport function getHooks(entity: any, type: HookType): Hook[] {\n const hooks: Hook[] = [];\n if (!entity) return hooks;\n const proto = Object.getPrototypeOf(entity);\n if (!proto) return hooks;\n const model = proto.constructor;\n\n // Get hooks from MetadataStorage\n const config = MetadataStorage.getModelMetadata(model);\n if (config?.hooks?.[type]) {\n const callbacks = Array.isArray(config.hooks[type])\n ? config.hooks[type]\n : [config.hooks[type]];\n hooks.push(\n ...callbacks.map((callback) => ({\n type,\n callback: () => callback(entity),\n })),\n );\n }\n\n // Get hooks from class methods\n if (typeof entity[type] === \"function\") {\n hooks.push({\n type,\n callback: () => entity[type](),\n });\n }\n\n return hooks;\n}\n"
7
+ ],
8
+ "mappings": ";+YA+DO,MAAM,CAAgB,OACZ,QAAqC,IAAI,UAOjD,iBAAgB,CAAC,EAAiB,EAAqB,CAC5D,KAAK,OAAO,IAAI,EAAO,CAAM,QAQxB,iBAAgB,CAAC,EAA0C,CAChE,OAAO,KAAK,OAAO,IAAI,CAAK,QAQvB,aAAY,CAAC,EAAyB,CAC3C,OAAO,KAAK,iBAAiB,CAAK,GAAG,WAAa,SAQ7C,WAAU,CAAC,EAA+C,CAC/D,OAAO,KAAK,iBAAiB,CAAK,GAAG,SAAW,CAAC,QAQ5C,cAAa,CAAC,EAA2C,CAC9D,IAAM,EAAU,KAAK,iBAAiB,CAAK,GAAG,SAAW,CAAC,EACpD,EAAuC,CAAC,EAC9C,QAAY,EAAK,KAAQ,OAAO,QAAQ,CAAO,EAAG,CAChD,IAAM,EAAkB,CAAC,EACzB,GAAI,EAAI,SAAU,EAAM,KAAK,UAAU,EAC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CAAM,EAC3C,EAAgB,iBAAiB,EAAO,CAAM,EAUzC,SAAS,CAAQ,CAAC,EAAa,EAAwB,CAC5D,IAAM,EAAgB,CAAC,EACvB,GAAI,CAAC,EAAQ,OAAO,EACpB,IAAM,EAAQ,OAAO,eAAe,CAAM,EAC1C,GAAI,CAAC,EAAO,OAAO,EACnB,IAAM,EAAQ,EAAM,YAGd,EAAS,EAAgB,iBAAiB,CAAK,EACrD,GAAI,GAAQ,QAAQ,GAAO,CACzB,IAAM,EAAY,MAAM,QAAQ,EAAO,MAAM,EAAK,EAC9C,EAAO,MAAM,GACb,CAAC,EAAO,MAAM,EAAK,EACvB,EAAM,KACJ,GAAG,EAAU,IAAI,CAAC,KAAc,CAC9B,OACA,SAAU,IAAM,EAAS,CAAM,CACjC,EAAE,CACJ,EAIF,GAAI,OAAO,EAAO,KAAU,WAC1B,EAAM,KAAK,CACT,OACA,SAAU,IAAM,EAAO,GAAM,CAC/B,CAAC,EAGH,OAAO",
9
+ "debugId": "5124B63376B5B21364756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @file stabilize.ts
3
+ * @description The main entry point for the Stabilize ORM, tying together the client, cache, and repositories.
4
+ * @author ElectronSz
5
+ */
6
+ import { Cache } from "./cache";
7
+ import { DBClient } from "./client";
8
+ import { type Logger, StabilizeLogger } from "./logger";
9
+ import { QueryBuilder } from "./query-builder";
10
+ import { Repository } from "./repository";
11
+ import { runMigrations, generateMigration, type Migration, mapDataTypeToSql } from "./migrations";
12
+ import { autoMigrate, defineSeed, runSeeds, resetDatabase, type SeedDefinition } from "./auto-migrate";
13
+ import { type DBConfig, type CacheConfig, type LoggerConfig, DBType, DataTypes, StabilizeError, type PoolMetrics, type QueryHint, RelationType, type CacheStats, LogLevel, type DefaultExpression, sqlDefault, type TransactionIsolationLevel, type QueryLogEntry, type StabilizeEvent, type StabilizeEventHandler, StabilizeEmitter, generateUUID } from "./types";
14
+ import { defineModel, MetadataStorage } from "./model";
15
+ import type { Hook } from "./hooks";
16
+ export declare class Stabilize {
17
+ client: DBClient;
18
+ private cache;
19
+ private logger;
20
+ events: StabilizeEmitter;
21
+ constructor(config: DBConfig, cacheConfig?: CacheConfig, loggerConfig?: LoggerConfig, existingClient?: DBClient);
22
+ /**
23
+ * Gets a repository for a given model, used to perform CRUD operations.
24
+ * @param model The model class, defined using `defineModel`.
25
+ * @returns A new `Repository` instance for the specified model.
26
+ * @example
27
+ * ```
28
+ * const stabilize = new Stabilize(dbConfig);
29
+ * const userRepository = stabilize.getRepository(User);
30
+ *
31
+ * const user = await userRepository.findOne(1);
32
+ * console.log(user);
33
+ * ```
34
+ */
35
+ getRepository<T>(model: new (...args: any[]) => T): Repository<T>;
36
+ /**
37
+ * Executes a callback within a database transaction, ensuring all operations are atomic.
38
+ * The callback receives a transactional `DBClient` instance that must be passed to
39
+ * repository methods to ensure they are part of the same transaction.
40
+ *
41
+ * @param callback The async function to execute. It receives a `txClient` as its only argument.
42
+ * @returns The result of the callback function.
43
+ * @example
44
+ * ```
45
+ * const userRepo = stabilize.getRepository(User);
46
+ * const profileRepo = stabilize.getRepository(Profile);
47
+ *
48
+ * try {
49
+ * await stabilize.transaction(async (txClient) => {
50
+ * const newUser = await userRepo.create({ name: 'Ciniso Dlamini' }, {}, txClient);
51
+ * await profileRepo.create({ userId: newUser.id, bio: 'A new bio' }, {}, txClient);
52
+ * });
53
+ * console.log('User and profile created successfully.');
54
+ * } catch (error) {
55
+ * console.error('Transaction failed, everything was rolled back.', error);
56
+ * }
57
+ * ```
58
+ */
59
+ transaction<T>(callback: (txClient: DBClient) => Promise<T>): Promise<T>;
60
+ /**
61
+ * Retrieves statistics from the cache, if it is enabled.
62
+ * @returns A promise that resolves to an object containing cache hits, misses, and total keys.
63
+ * @example
64
+ * ```
65
+ * const stats = await stabilize.getCacheStats();
66
+ * console.log(`Cache Hits: ${stats.hits}, Misses: ${stats.misses}`);
67
+ * ```
68
+ */
69
+ getCacheStats(): Promise<CacheStats>;
70
+ /**
71
+ * Closes the database connection and disconnects the cache client for a graceful shutdown.
72
+ * @example
73
+ * ```
74
+ * await stabilize.close();
75
+ * console.log('Connections closed.');
76
+ * ```
77
+ */
78
+ close(): Promise<void>;
79
+ healthCheck(): Promise<{
80
+ status: string;
81
+ database: string;
82
+ latencyMs: number;
83
+ cacheStatus: string;
84
+ }>;
85
+ rawQuery<T = any>(query: string, params?: any[]): Promise<T[]>;
86
+ rawExec(query: string, params?: any[]): Promise<{
87
+ affectedRows: number;
88
+ }>;
89
+ migrate(config: DBConfig, migrations: Migration[]): Promise<void>;
90
+ autoMigrate(models: any | any[]): Promise<void>;
91
+ seed(seeds?: any[]): Promise<void>;
92
+ reset(models: any | any[]): Promise<void>;
93
+ poolStats(): Promise<{
94
+ active: number;
95
+ idle: number;
96
+ total: number;
97
+ }>;
98
+ }
99
+ export { Repository, DBClient, QueryBuilder, Cache, StabilizeLogger, DBType, DataTypes, LogLevel, RelationType, MetadataStorage, mapDataTypeToSql, StabilizeError, runMigrations, generateMigration, defineModel, autoMigrate, sqlDefault, defineSeed, runSeeds, resetDatabase, StabilizeEmitter, generateUUID, };
100
+ export type { Migration, DBConfig, CacheConfig, LoggerConfig, QueryHint, PoolMetrics, CacheStats, Logger, Hook, DefaultExpression, SeedDefinition, TransactionIsolationLevel, QueryLogEntry, StabilizeEvent, StabilizeEventHandler, };
101
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EAAE,KAAK,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,c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