@geekmidas/audit 0.0.8 → 0.2.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 (64) hide show
  1. package/README.md +397 -0
  2. package/dist/{Auditor-D3me-qKX.d.mts → Auditor-_Dn2dp8d.d.mts} +46 -1
  3. package/dist/Auditor-_Dn2dp8d.d.mts.map +1 -0
  4. package/dist/{Auditor-QYUMGJCH.d.cts → Auditor-sW7YAJIA.d.cts} +46 -1
  5. package/dist/Auditor-sW7YAJIA.d.cts.map +1 -0
  6. package/dist/Auditor.d.cts +1 -1
  7. package/dist/Auditor.d.mts +1 -1
  8. package/dist/DefaultAuditor-BAVnNmRh.mjs.map +1 -1
  9. package/dist/{DefaultAuditor-BTuMMiWh.d.cts → DefaultAuditor-BSYMwojG.d.cts} +3 -2
  10. package/dist/DefaultAuditor-BSYMwojG.d.cts.map +1 -0
  11. package/dist/{DefaultAuditor-C1FWrJg6.d.mts → DefaultAuditor-CYE-uAry.d.mts} +3 -2
  12. package/dist/DefaultAuditor-CYE-uAry.d.mts.map +1 -0
  13. package/dist/DefaultAuditor-JbZ_BQfh.cjs.map +1 -1
  14. package/dist/DefaultAuditor.d.cts +2 -2
  15. package/dist/DefaultAuditor.d.mts +2 -2
  16. package/dist/cache-2VI80Vao.d.mts +96 -0
  17. package/dist/cache-2VI80Vao.d.mts.map +1 -0
  18. package/dist/cache-BbIl31RL.mjs +167 -0
  19. package/dist/cache-BbIl31RL.mjs.map +1 -0
  20. package/dist/cache-CDHqXqcl.d.cts +96 -0
  21. package/dist/cache-CDHqXqcl.d.cts.map +1 -0
  22. package/dist/cache-l7jAptBl.cjs +173 -0
  23. package/dist/cache-l7jAptBl.cjs.map +1 -0
  24. package/dist/cache.cjs +3 -0
  25. package/dist/cache.d.cts +3 -0
  26. package/dist/cache.d.mts +3 -0
  27. package/dist/cache.mjs +3 -0
  28. package/dist/index.d.cts +2 -2
  29. package/dist/index.d.mts +2 -2
  30. package/dist/kysely.cjs +24 -0
  31. package/dist/kysely.cjs.map +1 -1
  32. package/dist/kysely.d.cts +11 -1
  33. package/dist/kysely.d.cts.map +1 -0
  34. package/dist/kysely.d.mts +11 -1
  35. package/dist/kysely.d.mts.map +1 -0
  36. package/dist/kysely.mjs +24 -0
  37. package/dist/kysely.mjs.map +1 -1
  38. package/dist/memory.cjs +49 -0
  39. package/dist/memory.cjs.map +1 -0
  40. package/dist/memory.d.cts +44 -0
  41. package/dist/memory.d.cts.map +1 -0
  42. package/dist/memory.d.mts +44 -0
  43. package/dist/memory.d.mts.map +1 -0
  44. package/dist/memory.mjs +48 -0
  45. package/dist/memory.mjs.map +1 -0
  46. package/dist/storage.d.cts +1 -1
  47. package/dist/storage.d.mts +1 -1
  48. package/dist/types.d.cts +1 -1
  49. package/dist/types.d.mts +1 -1
  50. package/package.json +33 -5
  51. package/src/Auditor.ts +121 -121
  52. package/src/DefaultAuditor.ts +91 -91
  53. package/src/__tests__/CacheAuditStorage.spec.ts +382 -0
  54. package/src/__tests__/DefaultAuditor.spec.ts +520 -462
  55. package/src/__tests__/InMemoryAuditStorage.spec.ts +317 -0
  56. package/src/__tests__/KyselyAuditStorage.integration.spec.ts +500 -496
  57. package/src/__tests__/KyselyAuditStorage.spec.ts +433 -433
  58. package/src/cache.ts +263 -0
  59. package/src/index.ts +14 -15
  60. package/src/kysely.ts +292 -259
  61. package/src/memory.ts +50 -0
  62. package/src/storage.ts +132 -85
  63. package/src/types.ts +73 -74
  64. package/tsconfig.json +9 -0
@@ -1 +1 @@
1
- {"version":3,"file":"kysely.cjs","names":["db: DatabaseConnection<DB>","auditor: TransactionAwareAuditor<Transaction<DB>>","cb: (trx: Transaction<DB>) => Promise<T>","settings?: TransactionSettings","trx: Transaction<DB>","config: KyselyAuditStorageConfig<DB>","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","eb: any","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * Column names use snake_case to match standard PostgreSQL conventions.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: unknown | null;\n newValues: unknown | null;\n payload: unknown | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: unknown | null;\n metadata: unknown | null;\n}\n\n/**\n * Insertable version of AuditLogTable where id is optional.\n * Use this when your database auto-generates IDs or when using autoId option.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * // For insertions where id is auto-generated\n * type NewAuditLog = InsertableAuditLogTable;\n * ```\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n id?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n /**\n * Service name of the database service.\n * When set, endpoint adaptors will automatically use the audit transaction as `db`\n * in the handler context if the endpoint's database service has the same name.\n */\n databaseServiceName?: string;\n /**\n * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n * When true, the ID field is omitted from inserts if not provided.\n * When false (default), IDs are generated using nanoid if not provided.\n * @default false\n */\n autoId?: boolean;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n private readonly autoId: boolean;\n readonly databaseServiceName?: string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n this.databaseServiceName = config.databaseServiceName;\n this.autoId = config.autoId ?? false;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any).insertInto(this.tableName).values(rows).execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n // If autoId is true, let database generate ID (ignore record.id)\n // If autoId is false (default), use record.id or generate with nanoid\n const id = this.autoId ? undefined : record.id || nanoid();\n\n return {\n ...(id && { id }),\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues: record.oldValues ?? null,\n newValues: record.newValues ?? null,\n payload: record.payload ?? null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined ? this.getActorData(record.actor) : null,\n metadata: record.metadata ?? null,\n } as AuditLogTable;\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n oldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n newValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: unknown): Record<string, unknown> {\n if (typeof value === 'object' && value !== null) {\n return value as Record<string, unknown>;\n }\n if (typeof value === 'string') {\n return JSON.parse(value);\n }\n return {};\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(entityId: string): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;\n } catch {\n return entityId;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,eAAsB,yBACpBA,IACAC,SACAC,IACAC,UACY;CACZ,MAAM,UAAU,OAAOC,QAAqC;AAE1D,UAAQ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s","names":["db: DatabaseConnection<DB>","auditor: TransactionAwareAuditor<Transaction<DB>>","cb: (trx: Transaction<DB>) => Promise<T>","settings?: TransactionSettings","trx: Transaction<DB>","config: KyselyAuditStorageConfig<DB>","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","eb: any","callback: () => Promise<T>","db?: DatabaseConnection<DB>","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n\tControlledTransaction,\n\tIsolationLevel,\n\tKysely,\n\tTransaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n\t/** Register the transaction with the auditor for use during flush */\n\tsetTransaction(trx: TTransaction): void;\n\t/** Flush all pending audits, optionally within a transaction */\n\tflush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n\tisolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n\t| ControlledTransaction<T>\n\t| Kysely<T>\n\t| Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n\tdb: DatabaseConnection<DB>,\n\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\tcb: (trx: Transaction<DB>) => Promise<T>,\n\tsettings?: TransactionSettings,\n): Promise<T> {\n\tconst execute = async (trx: Transaction<DB>): Promise<T> => {\n\t\t// Register transaction with auditor\n\t\tauditor.setTransaction(trx);\n\n\t\t// Execute the callback\n\t\tconst result = await cb(trx);\n\n\t\t// Flush audits BEFORE transaction commits\n\t\t// If this fails, the transaction will roll back\n\t\tawait auditor.flush(trx);\n\n\t\treturn result;\n\t};\n\n\t// If already in a transaction, just run with it\n\tif (db.isTransaction) {\n\t\treturn execute(db as Transaction<DB>);\n\t}\n\n\tconst builder = db.transaction();\n\n\tif (settings?.isolationLevel) {\n\t\treturn builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n\t}\n\n\treturn builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * Column names use snake_case to match standard PostgreSQL conventions.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n\tid: string;\n\ttype: string;\n\toperation: string;\n\ttable: string | null;\n\tentityId: string | null;\n\toldValues: unknown | null;\n\tnewValues: unknown | null;\n\tpayload: unknown | null;\n\ttimestamp: Date;\n\tactorId: string | null;\n\tactorType: string | null;\n\tactorData: unknown | null;\n\tmetadata: unknown | null;\n}\n\n/**\n * Insertable version of AuditLogTable where id is optional.\n * Use this when your database auto-generates IDs or when using autoId option.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * // For insertions where id is auto-generated\n * type NewAuditLog = InsertableAuditLogTable;\n * ```\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n\tid?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n\t/** Kysely database instance */\n\tdb: Kysely<DB>;\n\t/** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n\ttableName: keyof DB & string;\n\t/**\n\t * Service name of the database service.\n\t * When set, endpoint adaptors will automatically use the audit transaction as `db`\n\t * in the handler context if the endpoint's database service has the same name.\n\t */\n\tdatabaseServiceName?: string;\n\t/**\n\t * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n\t * When true, the ID field is omitted from inserts if not provided.\n\t * When false (default), IDs are generated using nanoid if not provided.\n\t * @default false\n\t */\n\tautoId?: boolean;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n\tprivate readonly db: Kysely<DB>;\n\tprivate readonly tableName: keyof DB & string;\n\tprivate readonly autoId: boolean;\n\treadonly databaseServiceName?: string;\n\n\tconstructor(config: KyselyAuditStorageConfig<DB>) {\n\t\tthis.db = config.db;\n\t\tthis.tableName = config.tableName;\n\t\tthis.databaseServiceName = config.databaseServiceName;\n\t\tthis.autoId = config.autoId ?? false;\n\t}\n\n\tasync write(records: AuditRecord[], trx?: unknown): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst db = (trx as Transaction<DB>) ?? this.db;\n\t\tconst rows = records.map((record) => this.toRow(record));\n\n\t\tawait (db as any).insertInto(this.tableName).values(rows).execute();\n\t}\n\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tlet query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tquery = query.orderBy(\n\t\t\torderBy === 'timestamp' ? 'timestamp' : 'type',\n\t\t\torderDirection,\n\t\t);\n\n\t\t// Pagination\n\t\tif (options.limit !== undefined) {\n\t\t\tquery = query.limit(options.limit);\n\t\t}\n\t\tif (options.offset !== undefined) {\n\t\t\tquery = query.offset(options.offset);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row: AuditLogTable) => this.fromRow(row));\n\t}\n\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tlet query = (this.db as any)\n\t\t\t.selectFrom(this.tableName)\n\t\t\t.select((eb: any) => eb.fn.count('id').as('count'));\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Get the Kysely database instance for transactional operations.\n\t * Used by endpoint adaptors to automatically wrap handlers in transactions.\n\t */\n\tgetDatabase(): Kysely<DB> {\n\t\treturn this.db;\n\t}\n\n\t/**\n\t * Execute a callback within a Kysely transaction with automatic audit handling.\n\t * The auditor is registered with the transaction and audits are flushed\n\t * before the transaction commits.\n\t *\n\t * If the provided db connection is already a transaction, it will be reused\n\t * instead of creating a nested transaction.\n\t */\n\tasync withTransaction<T>(\n\t\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\t\tcallback: () => Promise<T>,\n\t\tdb?: DatabaseConnection<DB>,\n\t): Promise<T> {\n\t\tconst connection = db ?? this.db;\n\n\t\t// If already in a transaction, reuse it\n\t\tif (connection.isTransaction) {\n\t\t\tconst trx = connection as Transaction<DB>;\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t}\n\n\t\t// Create new transaction\n\t\treturn connection.transaction().execute(async (trx) => {\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tprivate applyFilters(query: any, options: AuditQueryOptions): any {\n\t\t// Type filter\n\t\tif (options.type !== undefined) {\n\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\tquery = query.where('type', 'in', options.type);\n\t\t\t} else {\n\t\t\t\tquery = query.where('type', '=', options.type);\n\t\t\t}\n\t\t}\n\n\t\t// Entity ID filter\n\t\tif (options.entityId !== undefined) {\n\t\t\tconst entityId =\n\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t? options.entityId\n\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\tquery = query.where('entityId', '=', entityId);\n\t\t}\n\n\t\t// Table filter\n\t\tif (options.table !== undefined) {\n\t\t\tquery = query.where('table', '=', options.table);\n\t\t}\n\n\t\t// Actor ID filter\n\t\tif (options.actorId !== undefined) {\n\t\t\tquery = query.where('actorId', '=', options.actorId);\n\t\t}\n\n\t\t// Date range filters\n\t\tif (options.from !== undefined) {\n\t\t\tquery = query.where('timestamp', '>=', options.from);\n\t\t}\n\t\tif (options.to !== undefined) {\n\t\t\tquery = query.where('timestamp', '<=', options.to);\n\t\t}\n\n\t\treturn query;\n\t}\n\n\tprivate toRow(record: AuditRecord): AuditLogTable {\n\t\t// If autoId is true, let database generate ID (ignore record.id)\n\t\t// If autoId is false (default), use record.id or generate with nanoid\n\t\tconst id = this.autoId ? undefined : record.id || nanoid();\n\n\t\treturn {\n\t\t\t...(id && { id }),\n\t\t\ttype: record.type,\n\t\t\toperation: record.operation,\n\t\t\ttable: record.table ?? null,\n\t\t\tentityId:\n\t\t\t\trecord.entityId === undefined\n\t\t\t\t\t? null\n\t\t\t\t\t: typeof record.entityId === 'string'\n\t\t\t\t\t\t? record.entityId\n\t\t\t\t\t\t: JSON.stringify(record.entityId),\n\t\t\toldValues: record.oldValues ?? null,\n\t\t\tnewValues: record.newValues ?? null,\n\t\t\tpayload: record.payload ?? null,\n\t\t\ttimestamp: record.timestamp,\n\t\t\tactorId: record.actor?.id ?? null,\n\t\t\tactorType: record.actor?.type ?? null,\n\t\t\tactorData:\n\t\t\t\trecord.actor !== undefined ? this.getActorData(record.actor) : null,\n\t\t\tmetadata: record.metadata ?? null,\n\t\t} as AuditLogTable;\n\t}\n\n\tprivate fromRow(row: AuditLogTable): AuditRecord {\n\t\tconst actor =\n\t\t\trow.actorId !== null || row.actorType !== null\n\t\t\t\t? {\n\t\t\t\t\t\tid: row.actorId ?? undefined,\n\t\t\t\t\t\ttype: row.actorType ?? undefined,\n\t\t\t\t\t\t...(row.actorData ? this.parseJson(row.actorData) : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\ttype: row.type,\n\t\t\toperation: row.operation as AuditRecord['operation'],\n\t\t\ttable: row.table ?? undefined,\n\t\t\tentityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n\t\t\toldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n\t\t\tnewValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n\t\t\tpayload: row.payload ? this.parseJson(row.payload) : undefined,\n\t\t\ttimestamp: row.timestamp,\n\t\t\tactor,\n\t\t\tmetadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n\t */\n\tprivate parseJson(value: unknown): Record<string, unknown> {\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\treturn value as Record<string, unknown>;\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn JSON.parse(value);\n\t\t}\n\t\treturn {};\n\t}\n\n\tprivate getActorData(\n\t\tactor: NonNullable<AuditRecord['actor']>,\n\t): Record<string, unknown> {\n\t\tconst { id, type, ...rest } = actor;\n\t\treturn rest;\n\t}\n\n\tprivate parseEntityId(entityId: string): string | Record<string, unknown> {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(entityId);\n\t\t\tif (typeof parsed === 'object' && parsed !== null) {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn entityId;\n\t\t} catch {\n\t\t\treturn entityId;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,eAAsB,yBACrBA,IACAC,SACAC,IACAC,UACa;CACb,MAAM,UAAU,OAAOC,QAAqC;AAE3D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACP;AAGD,KAAI,GAAG,cACN,QAAO,QAAQ,GAAsB;CAGtC,MAAM,UAAU,GAAG,aAAa;AAEhC,KAAI,UAAU,eACb,QAAO,QAAQ,kBAAkB,SAAS,eAAe,CAAC,QAAQ,QAAQ;AAG3E,QAAO,QAAQ,QAAQ,QAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;;;A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;AAER,UAAO;EACP,QAAO;AACP,UAAO;EACP;CACD;AACD"}
package/dist/kysely.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { AuditQueryOptions, AuditRecord, AuditStorage } from "./Auditor-QYUMGJCH.cjs";
1
+ import { AuditQueryOptions, AuditRecord, AuditStorage } from "./Auditor-sW7YAJIA.cjs";
2
2
  import { ControlledTransaction, IsolationLevel, Kysely, Transaction } from "kysely";
3
3
 
4
4
  //#region src/kysely.d.ts
@@ -183,6 +183,15 @@ declare class KyselyAuditStorage<DB> implements AuditStorage {
183
183
  * Used by endpoint adaptors to automatically wrap handlers in transactions.
184
184
  */
185
185
  getDatabase(): Kysely<DB>;
186
+ /**
187
+ * Execute a callback within a Kysely transaction with automatic audit handling.
188
+ * The auditor is registered with the transaction and audits are flushed
189
+ * before the transaction commits.
190
+ *
191
+ * If the provided db connection is already a transaction, it will be reused
192
+ * instead of creating a nested transaction.
193
+ */
194
+ withTransaction<T>(auditor: TransactionAwareAuditor<Transaction<DB>>, callback: () => Promise<T>, db?: DatabaseConnection<DB>): Promise<T>;
186
195
  private applyFilters;
187
196
  private toRow;
188
197
  private fromRow;
@@ -193,6 +202,7 @@ declare class KyselyAuditStorage<DB> implements AuditStorage {
193
202
  private getActorData;
194
203
  private parseEntityId;
195
204
  }
205
+ //# sourceMappingURL=kysely.d.ts.map
196
206
  //#endregion
197
207
  export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
198
208
  //# sourceMappingURL=kysely.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kysely.d.cts","names":[],"sources":["../src/kysely.ts"],"sourcesContent":[],"mappings":";;;;;;AA+BA;;;;;AAImC;AAGnC;AAIA;;;;;;;;AAGc;AA6Cd;;;;AAE8C,UA7D7B,uBA6D6B,CAAA,eAAA,OAAA,CAAA,CAAA;EAAE;EAAH,cAAnC,CAAA,GAAA,EA3DW,YA2DX,CAAA,EAAA,IAAA;EAAuB;EACR,KAAd,CAAA,GAAA,CAAA,EA1DE,YA0DF,CAAA,EA1DiB,OA0DjB,CAAA,IAAA,CAAA;;AAAoB,UAvDd,mBAAA,CAuDc;EAAO,cAC1B,CAAA,EAvDM,cAuDN;;AACT,KArDS,kBAqDT,CAAA,CAAA,CAAA,GApDA,qBAoDA,CApDsB,CAoDtB,CAAA,GAnDA,MAmDA,CAnDO,CAmDP,CAAA,GAlDA,WAkDA,CAlDY,CAkDZ,CAAA;AAAO;AA2CV;AA8BA;;;;AAA0C;AAO1C;;;;;AAIoB;AAuCpB;;;;;;;;;;;;;;;;;;;;;;;;AAA2D;;;;;;iBAhIrC,oCACjB,mBAAmB,cACd,wBAAwB,YAAY,gBACnC,YAAY,QAAQ,QAAQ,eAC3B,sBACT,QAAQ;;;;;;;;;;;;;;;UA2CM,aAAA;;;;;;;;;aASL;;;;;;;;;;;;;;;;;;;;KAqBA,uBAAA,GAA0B,KAAK;;;;;;UAO1B;;MAEZ,OAAO;;mBAEM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAuCL,kCAAkC;;;;;sBAM1B,yBAAyB;iBAOxB,+BAA+B;iBAW/B,oBAAoB,QAAQ;iBA0BvC,KAAK,yCACZ;;;;;iBAeY,OAAO;;;;;;;;;8BAaZ,wBAAwB,YAAY,sBAC7B,QAAQ,SACnB,mBAAmB,MACtB,QAAQ"}
package/dist/kysely.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { AuditQueryOptions, AuditRecord, AuditStorage } from "./Auditor-D3me-qKX.mjs";
1
+ import { AuditQueryOptions, AuditRecord, AuditStorage } from "./Auditor-_Dn2dp8d.mjs";
2
2
  import { ControlledTransaction, IsolationLevel, Kysely, Transaction } from "kysely";
3
3
 
4
4
  //#region src/kysely.d.ts
@@ -183,6 +183,15 @@ declare class KyselyAuditStorage<DB> implements AuditStorage {
183
183
  * Used by endpoint adaptors to automatically wrap handlers in transactions.
184
184
  */
185
185
  getDatabase(): Kysely<DB>;
186
+ /**
187
+ * Execute a callback within a Kysely transaction with automatic audit handling.
188
+ * The auditor is registered with the transaction and audits are flushed
189
+ * before the transaction commits.
190
+ *
191
+ * If the provided db connection is already a transaction, it will be reused
192
+ * instead of creating a nested transaction.
193
+ */
194
+ withTransaction<T>(auditor: TransactionAwareAuditor<Transaction<DB>>, callback: () => Promise<T>, db?: DatabaseConnection<DB>): Promise<T>;
186
195
  private applyFilters;
187
196
  private toRow;
188
197
  private fromRow;
@@ -193,6 +202,7 @@ declare class KyselyAuditStorage<DB> implements AuditStorage {
193
202
  private getActorData;
194
203
  private parseEntityId;
195
204
  }
205
+ //# sourceMappingURL=kysely.d.ts.map
196
206
  //#endregion
197
207
  export { AuditLogTable, DatabaseConnection, InsertableAuditLogTable, KyselyAuditStorage, KyselyAuditStorageConfig, TransactionAwareAuditor, TransactionSettings, withAuditableTransaction };
198
208
  //# sourceMappingURL=kysely.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kysely.d.mts","names":[],"sources":["../src/kysely.ts"],"sourcesContent":[],"mappings":";;;;;;AA+BA;;;;;AAImC;AAGnC;AAIA;;;;;;;;AAGc;AA6Cd;;;;AAE8C,UA7D7B,uBA6D6B,CAAA,eAAA,OAAA,CAAA,CAAA;EAAE;EAAH,cAAnC,CAAA,GAAA,EA3DW,YA2DX,CAAA,EAAA,IAAA;EAAuB;EACR,KAAd,CAAA,GAAA,CAAA,EA1DE,YA0DF,CAAA,EA1DiB,OA0DjB,CAAA,IAAA,CAAA;;AAAoB,UAvDd,mBAAA,CAuDc;EAAO,cAC1B,CAAA,EAvDM,cAuDN;;AACT,KArDS,kBAqDT,CAAA,CAAA,CAAA,GApDA,qBAoDA,CApDsB,CAoDtB,CAAA,GAnDA,MAmDA,CAnDO,CAmDP,CAAA,GAlDA,WAkDA,CAlDY,CAkDZ,CAAA;AAAO;AA2CV;AA8BA;;;;AAA0C;AAO1C;;;;;AAIoB;AAuCpB;;;;;;;;;;;;;;;;;;;;;;;;AAA2D;;;;;;iBAhIrC,oCACjB,mBAAmB,cACd,wBAAwB,YAAY,gBACnC,YAAY,QAAQ,QAAQ,eAC3B,sBACT,QAAQ;;;;;;;;;;;;;;;UA2CM,aAAA;;;;;;;;;aASL;;;;;;;;;;;;;;;;;;;;KAqBA,uBAAA,GAA0B,KAAK;;;;;;UAO1B;;MAEZ,OAAO;;mBAEM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAuCL,kCAAkC;;;;;sBAM1B,yBAAyB;iBAOxB,+BAA+B;iBAW/B,oBAAoB,QAAQ;iBA0BvC,KAAK,yCACZ;;;;;iBAeY,OAAO;;;;;;;;;8BAaZ,wBAAwB,YAAY,sBAC7B,QAAQ,SACnB,mBAAmB,MACtB,QAAQ"}
package/dist/kysely.mjs CHANGED
@@ -120,6 +120,30 @@ var KyselyAuditStorage = class {
120
120
  getDatabase() {
121
121
  return this.db;
122
122
  }
123
+ /**
124
+ * Execute a callback within a Kysely transaction with automatic audit handling.
125
+ * The auditor is registered with the transaction and audits are flushed
126
+ * before the transaction commits.
127
+ *
128
+ * If the provided db connection is already a transaction, it will be reused
129
+ * instead of creating a nested transaction.
130
+ */
131
+ async withTransaction(auditor, callback, db) {
132
+ const connection = db ?? this.db;
133
+ if (connection.isTransaction) {
134
+ const trx = connection;
135
+ auditor.setTransaction(trx);
136
+ const result = await callback();
137
+ await auditor.flush(trx);
138
+ return result;
139
+ }
140
+ return connection.transaction().execute(async (trx) => {
141
+ auditor.setTransaction(trx);
142
+ const result = await callback();
143
+ await auditor.flush(trx);
144
+ return result;
145
+ });
146
+ }
123
147
  applyFilters(query, options) {
124
148
  if (options.type !== void 0) if (Array.isArray(options.type)) query = query.where("type", "in", options.type);
125
149
  else query = query.where("type", "=", options.type);
@@ -1 +1 @@
1
- {"version":3,"file":"kysely.mjs","names":["db: DatabaseConnection<DB>","auditor: TransactionAwareAuditor<Transaction<DB>>","cb: (trx: Transaction<DB>) => Promise<T>","settings?: TransactionSettings","trx: Transaction<DB>","config: KyselyAuditStorageConfig<DB>","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","eb: any","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n ControlledTransaction,\n IsolationLevel,\n Kysely,\n Transaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n /** Register the transaction with the auditor for use during flush */\n setTransaction(trx: TTransaction): void;\n /** Flush all pending audits, optionally within a transaction */\n flush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n isolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n | ControlledTransaction<T>\n | Kysely<T>\n | Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n db: DatabaseConnection<DB>,\n auditor: TransactionAwareAuditor<Transaction<DB>>,\n cb: (trx: Transaction<DB>) => Promise<T>,\n settings?: TransactionSettings,\n): Promise<T> {\n const execute = async (trx: Transaction<DB>): Promise<T> => {\n // Register transaction with auditor\n auditor.setTransaction(trx);\n\n // Execute the callback\n const result = await cb(trx);\n\n // Flush audits BEFORE transaction commits\n // If this fails, the transaction will roll back\n await auditor.flush(trx);\n\n return result;\n };\n\n // If already in a transaction, just run with it\n if (db.isTransaction) {\n return execute(db as Transaction<DB>);\n }\n\n const builder = db.transaction();\n\n if (settings?.isolationLevel) {\n return builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n }\n\n return builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * Column names use snake_case to match standard PostgreSQL conventions.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n id: string;\n type: string;\n operation: string;\n table: string | null;\n entityId: string | null;\n oldValues: unknown | null;\n newValues: unknown | null;\n payload: unknown | null;\n timestamp: Date;\n actorId: string | null;\n actorType: string | null;\n actorData: unknown | null;\n metadata: unknown | null;\n}\n\n/**\n * Insertable version of AuditLogTable where id is optional.\n * Use this when your database auto-generates IDs or when using autoId option.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * // For insertions where id is auto-generated\n * type NewAuditLog = InsertableAuditLogTable;\n * ```\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n id?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n /** Kysely database instance */\n db: Kysely<DB>;\n /** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n tableName: keyof DB & string;\n /**\n * Service name of the database service.\n * When set, endpoint adaptors will automatically use the audit transaction as `db`\n * in the handler context if the endpoint's database service has the same name.\n */\n databaseServiceName?: string;\n /**\n * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n * When true, the ID field is omitted from inserts if not provided.\n * When false (default), IDs are generated using nanoid if not provided.\n * @default false\n */\n autoId?: boolean;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n private readonly db: Kysely<DB>;\n private readonly tableName: keyof DB & string;\n private readonly autoId: boolean;\n readonly databaseServiceName?: string;\n\n constructor(config: KyselyAuditStorageConfig<DB>) {\n this.db = config.db;\n this.tableName = config.tableName;\n this.databaseServiceName = config.databaseServiceName;\n this.autoId = config.autoId ?? false;\n }\n\n async write(records: AuditRecord[], trx?: unknown): Promise<void> {\n if (records.length === 0) {\n return;\n }\n\n const db = (trx as Transaction<DB>) ?? this.db;\n const rows = records.map((record) => this.toRow(record));\n\n await (db as any).insertInto(this.tableName).values(rows).execute();\n }\n\n async query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n let query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n query = this.applyFilters(query, options);\n\n // Ordering\n const orderBy = options.orderBy ?? 'timestamp';\n const orderDirection = options.orderDirection ?? 'desc';\n query = query.orderBy(\n orderBy === 'timestamp' ? 'timestamp' : 'type',\n orderDirection,\n );\n\n // Pagination\n if (options.limit !== undefined) {\n query = query.limit(options.limit);\n }\n if (options.offset !== undefined) {\n query = query.offset(options.offset);\n }\n\n const rows = await query.execute();\n return rows.map((row: AuditLogTable) => this.fromRow(row));\n }\n\n async count(\n options: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n ): Promise<number> {\n let query = (this.db as any)\n .selectFrom(this.tableName)\n .select((eb: any) => eb.fn.count('id').as('count'));\n\n query = this.applyFilters(query, options);\n\n const result = await query.executeTakeFirst();\n return Number(result?.count ?? 0);\n }\n\n /**\n * Get the Kysely database instance for transactional operations.\n * Used by endpoint adaptors to automatically wrap handlers in transactions.\n */\n getDatabase(): Kysely<DB> {\n return this.db;\n }\n\n private applyFilters(query: any, options: AuditQueryOptions): any {\n // Type filter\n if (options.type !== undefined) {\n if (Array.isArray(options.type)) {\n query = query.where('type', 'in', options.type);\n } else {\n query = query.where('type', '=', options.type);\n }\n }\n\n // Entity ID filter\n if (options.entityId !== undefined) {\n const entityId =\n typeof options.entityId === 'string'\n ? options.entityId\n : JSON.stringify(options.entityId);\n query = query.where('entityId', '=', entityId);\n }\n\n // Table filter\n if (options.table !== undefined) {\n query = query.where('table', '=', options.table);\n }\n\n // Actor ID filter\n if (options.actorId !== undefined) {\n query = query.where('actorId', '=', options.actorId);\n }\n\n // Date range filters\n if (options.from !== undefined) {\n query = query.where('timestamp', '>=', options.from);\n }\n if (options.to !== undefined) {\n query = query.where('timestamp', '<=', options.to);\n }\n\n return query;\n }\n\n private toRow(record: AuditRecord): AuditLogTable {\n // If autoId is true, let database generate ID (ignore record.id)\n // If autoId is false (default), use record.id or generate with nanoid\n const id = this.autoId ? undefined : record.id || nanoid();\n\n return {\n ...(id && { id }),\n type: record.type,\n operation: record.operation,\n table: record.table ?? null,\n entityId:\n record.entityId === undefined\n ? null\n : typeof record.entityId === 'string'\n ? record.entityId\n : JSON.stringify(record.entityId),\n oldValues: record.oldValues ?? null,\n newValues: record.newValues ?? null,\n payload: record.payload ?? null,\n timestamp: record.timestamp,\n actorId: record.actor?.id ?? null,\n actorType: record.actor?.type ?? null,\n actorData:\n record.actor !== undefined ? this.getActorData(record.actor) : null,\n metadata: record.metadata ?? null,\n } as AuditLogTable;\n }\n\n private fromRow(row: AuditLogTable): AuditRecord {\n const actor =\n row.actorId !== null || row.actorType !== null\n ? {\n id: row.actorId ?? undefined,\n type: row.actorType ?? undefined,\n ...(row.actorData ? this.parseJson(row.actorData) : {}),\n }\n : undefined;\n\n return {\n id: row.id,\n type: row.type,\n operation: row.operation as AuditRecord['operation'],\n table: row.table ?? undefined,\n entityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n oldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n newValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n payload: row.payload ? this.parseJson(row.payload) : undefined,\n timestamp: row.timestamp,\n actor,\n metadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n };\n }\n\n /**\n * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n */\n private parseJson(value: unknown): Record<string, unknown> {\n if (typeof value === 'object' && value !== null) {\n return value as Record<string, unknown>;\n }\n if (typeof value === 'string') {\n return JSON.parse(value);\n }\n return {};\n }\n\n private getActorData(\n actor: NonNullable<AuditRecord['actor']>,\n ): Record<string, unknown> {\n const { id, type, ...rest } = actor;\n return rest;\n }\n\n private parseEntityId(entityId: string): string | Record<string, unknown> {\n try {\n const parsed = JSON.parse(entityId);\n if (typeof parsed === 'object' && parsed !== null) {\n return parsed;\n }\n return entityId;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Q,cAAcC,UAAoD;AACxE,MAAI;GACF,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC3C,QAAO;AAET,UAAO;EACR,QAAO;AACN,UAAO;EACR;CACF;AACF"}
1
+ {"version":3,"file":"kysely.mjs","names":["db: DatabaseConnection<DB>","auditor: TransactionAwareAuditor<Transaction<DB>>","cb: (trx: Transaction<DB>) => Promise<T>","settings?: TransactionSettings","trx: Transaction<DB>","config: KyselyAuditStorageConfig<DB>","records: AuditRecord[]","trx?: unknown","options: AuditQueryOptions","row: AuditLogTable","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","eb: any","callback: () => Promise<T>","db?: DatabaseConnection<DB>","query: any","record: AuditRecord","value: unknown","actor: NonNullable<AuditRecord['actor']>","entityId: string"],"sources":["../src/kysely.ts"],"sourcesContent":["import type {\n\tControlledTransaction,\n\tIsolationLevel,\n\tKysely,\n\tTransaction,\n} from 'kysely';\nimport { nanoid } from 'nanoid';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditRecord } from './types';\n\n/**\n * Minimal interface for transaction-aware audit flushing.\n * Use this when you need to flush audits within a database transaction.\n *\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n * import type { TransactionAwareAuditor } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * db,\n * auditor as TransactionAwareAuditor<Transaction<DB>>,\n * async (trx) => {\n * // Your transactional operations\n * return result;\n * },\n * );\n * ```\n */\nexport interface TransactionAwareAuditor<TTransaction = unknown> {\n\t/** Register the transaction with the auditor for use during flush */\n\tsetTransaction(trx: TTransaction): void;\n\t/** Flush all pending audits, optionally within a transaction */\n\tflush(trx?: TTransaction): Promise<void>;\n}\n\nexport interface TransactionSettings {\n\tisolationLevel?: IsolationLevel;\n}\n\nexport type DatabaseConnection<T> =\n\t| ControlledTransaction<T>\n\t| Kysely<T>\n\t| Transaction<T>;\n\n/**\n * Execute a callback within a database transaction with automatic audit handling.\n *\n * This wrapper ensures that:\n * 1. The transaction is automatically registered with the auditor\n * 2. Manual audits (via `auditor.audit()`) are flushed BEFORE the transaction commits\n * 3. If audit flush fails, the entire transaction rolls back\n * 4. If the callback fails, audits are NOT written (atomic consistency)\n *\n * **Note:** Declarative audits (defined via `.audit([...])` on the endpoint builder)\n * are processed AFTER the handler returns, so they run outside this transaction.\n * If you need all audits to be atomic with your database operations, use manual\n * audits via `auditor.audit()` inside this wrapper.\n *\n * @param db - Database connection (Kysely, Transaction, or ControlledTransaction)\n * @param auditor - Auditor instance that will receive the transaction\n * @param cb - Callback to execute within the transaction\n * @param settings - Optional transaction settings (isolation level)\n * @returns The result of the callback\n *\n * @example\n * ```typescript\n * import { withAuditableTransaction } from '@geekmidas/audit/kysely';\n *\n * const result = await withAuditableTransaction(\n * services.database,\n * auditor,\n * async (trx) => {\n * const user = await trx\n * .insertInto('users')\n * .values(data)\n * .returningAll()\n * .executeTakeFirstOrThrow();\n *\n * // Manual audits are atomic with the transaction\n * auditor.audit('user.created', { userId: user.id, email: user.email });\n *\n * return user;\n * },\n * );\n * // Audits are automatically flushed inside the transaction before commit\n * ```\n */\nexport async function withAuditableTransaction<DB, T>(\n\tdb: DatabaseConnection<DB>,\n\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\tcb: (trx: Transaction<DB>) => Promise<T>,\n\tsettings?: TransactionSettings,\n): Promise<T> {\n\tconst execute = async (trx: Transaction<DB>): Promise<T> => {\n\t\t// Register transaction with auditor\n\t\tauditor.setTransaction(trx);\n\n\t\t// Execute the callback\n\t\tconst result = await cb(trx);\n\n\t\t// Flush audits BEFORE transaction commits\n\t\t// If this fails, the transaction will roll back\n\t\tawait auditor.flush(trx);\n\n\t\treturn result;\n\t};\n\n\t// If already in a transaction, just run with it\n\tif (db.isTransaction) {\n\t\treturn execute(db as Transaction<DB>);\n\t}\n\n\tconst builder = db.transaction();\n\n\tif (settings?.isolationLevel) {\n\t\treturn builder.setIsolationLevel(settings.isolationLevel).execute(execute);\n\t}\n\n\treturn builder.execute(execute);\n}\n\n/**\n * Database table interface for audit records.\n * Use this to define your audit_logs table in your Kysely database schema.\n *\n * Column names use snake_case to match standard PostgreSQL conventions.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * // ... other tables\n * }\n * ```\n */\nexport interface AuditLogTable {\n\tid: string;\n\ttype: string;\n\toperation: string;\n\ttable: string | null;\n\tentityId: string | null;\n\toldValues: unknown | null;\n\tnewValues: unknown | null;\n\tpayload: unknown | null;\n\ttimestamp: Date;\n\tactorId: string | null;\n\tactorType: string | null;\n\tactorData: unknown | null;\n\tmetadata: unknown | null;\n}\n\n/**\n * Insertable version of AuditLogTable where id is optional.\n * Use this when your database auto-generates IDs or when using autoId option.\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * // For insertions where id is auto-generated\n * type NewAuditLog = InsertableAuditLogTable;\n * ```\n */\nexport type InsertableAuditLogTable = Omit<AuditLogTable, 'id'> & {\n\tid?: string;\n};\n\n/**\n * Configuration for KyselyAuditStorage.\n */\nexport interface KyselyAuditStorageConfig<DB> {\n\t/** Kysely database instance */\n\tdb: Kysely<DB>;\n\t/** Table name for audit logs (must be a key in DB that extends AuditLogTable) */\n\ttableName: keyof DB & string;\n\t/**\n\t * Service name of the database service.\n\t * When set, endpoint adaptors will automatically use the audit transaction as `db`\n\t * in the handler context if the endpoint's database service has the same name.\n\t */\n\tdatabaseServiceName?: string;\n\t/**\n\t * Let the database auto-generate IDs (e.g., via DEFAULT gen_random_uuid()).\n\t * When true, the ID field is omitted from inserts if not provided.\n\t * When false (default), IDs are generated using nanoid if not provided.\n\t * @default false\n\t */\n\tautoId?: boolean;\n}\n\n/**\n * Kysely-based audit storage implementation.\n * Stores audit records in a database table using Kysely.\n *\n * @template DB - Your Kysely database schema\n *\n * @example\n * ```typescript\n * interface Database {\n * audit_logs: AuditLogTable;\n * }\n *\n * const storage = new KyselyAuditStorage({\n * db: kyselyDb,\n * tableName: 'audit_logs',\n * });\n *\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n * ```\n */\nexport class KyselyAuditStorage<DB> implements AuditStorage {\n\tprivate readonly db: Kysely<DB>;\n\tprivate readonly tableName: keyof DB & string;\n\tprivate readonly autoId: boolean;\n\treadonly databaseServiceName?: string;\n\n\tconstructor(config: KyselyAuditStorageConfig<DB>) {\n\t\tthis.db = config.db;\n\t\tthis.tableName = config.tableName;\n\t\tthis.databaseServiceName = config.databaseServiceName;\n\t\tthis.autoId = config.autoId ?? false;\n\t}\n\n\tasync write(records: AuditRecord[], trx?: unknown): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst db = (trx as Transaction<DB>) ?? this.db;\n\t\tconst rows = records.map((record) => this.toRow(record));\n\n\t\tawait (db as any).insertInto(this.tableName).values(rows).execute();\n\t}\n\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tlet query = (this.db as any).selectFrom(this.tableName).selectAll();\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tquery = query.orderBy(\n\t\t\torderBy === 'timestamp' ? 'timestamp' : 'type',\n\t\t\torderDirection,\n\t\t);\n\n\t\t// Pagination\n\t\tif (options.limit !== undefined) {\n\t\t\tquery = query.limit(options.limit);\n\t\t}\n\t\tif (options.offset !== undefined) {\n\t\t\tquery = query.offset(options.offset);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row: AuditLogTable) => this.fromRow(row));\n\t}\n\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tlet query = (this.db as any)\n\t\t\t.selectFrom(this.tableName)\n\t\t\t.select((eb: any) => eb.fn.count('id').as('count'));\n\n\t\tquery = this.applyFilters(query, options);\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Get the Kysely database instance for transactional operations.\n\t * Used by endpoint adaptors to automatically wrap handlers in transactions.\n\t */\n\tgetDatabase(): Kysely<DB> {\n\t\treturn this.db;\n\t}\n\n\t/**\n\t * Execute a callback within a Kysely transaction with automatic audit handling.\n\t * The auditor is registered with the transaction and audits are flushed\n\t * before the transaction commits.\n\t *\n\t * If the provided db connection is already a transaction, it will be reused\n\t * instead of creating a nested transaction.\n\t */\n\tasync withTransaction<T>(\n\t\tauditor: TransactionAwareAuditor<Transaction<DB>>,\n\t\tcallback: () => Promise<T>,\n\t\tdb?: DatabaseConnection<DB>,\n\t): Promise<T> {\n\t\tconst connection = db ?? this.db;\n\n\t\t// If already in a transaction, reuse it\n\t\tif (connection.isTransaction) {\n\t\t\tconst trx = connection as Transaction<DB>;\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t}\n\n\t\t// Create new transaction\n\t\treturn connection.transaction().execute(async (trx) => {\n\t\t\tauditor.setTransaction(trx);\n\t\t\tconst result = await callback();\n\t\t\tawait auditor.flush(trx);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tprivate applyFilters(query: any, options: AuditQueryOptions): any {\n\t\t// Type filter\n\t\tif (options.type !== undefined) {\n\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\tquery = query.where('type', 'in', options.type);\n\t\t\t} else {\n\t\t\t\tquery = query.where('type', '=', options.type);\n\t\t\t}\n\t\t}\n\n\t\t// Entity ID filter\n\t\tif (options.entityId !== undefined) {\n\t\t\tconst entityId =\n\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t? options.entityId\n\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\tquery = query.where('entityId', '=', entityId);\n\t\t}\n\n\t\t// Table filter\n\t\tif (options.table !== undefined) {\n\t\t\tquery = query.where('table', '=', options.table);\n\t\t}\n\n\t\t// Actor ID filter\n\t\tif (options.actorId !== undefined) {\n\t\t\tquery = query.where('actorId', '=', options.actorId);\n\t\t}\n\n\t\t// Date range filters\n\t\tif (options.from !== undefined) {\n\t\t\tquery = query.where('timestamp', '>=', options.from);\n\t\t}\n\t\tif (options.to !== undefined) {\n\t\t\tquery = query.where('timestamp', '<=', options.to);\n\t\t}\n\n\t\treturn query;\n\t}\n\n\tprivate toRow(record: AuditRecord): AuditLogTable {\n\t\t// If autoId is true, let database generate ID (ignore record.id)\n\t\t// If autoId is false (default), use record.id or generate with nanoid\n\t\tconst id = this.autoId ? undefined : record.id || nanoid();\n\n\t\treturn {\n\t\t\t...(id && { id }),\n\t\t\ttype: record.type,\n\t\t\toperation: record.operation,\n\t\t\ttable: record.table ?? null,\n\t\t\tentityId:\n\t\t\t\trecord.entityId === undefined\n\t\t\t\t\t? null\n\t\t\t\t\t: typeof record.entityId === 'string'\n\t\t\t\t\t\t? record.entityId\n\t\t\t\t\t\t: JSON.stringify(record.entityId),\n\t\t\toldValues: record.oldValues ?? null,\n\t\t\tnewValues: record.newValues ?? null,\n\t\t\tpayload: record.payload ?? null,\n\t\t\ttimestamp: record.timestamp,\n\t\t\tactorId: record.actor?.id ?? null,\n\t\t\tactorType: record.actor?.type ?? null,\n\t\t\tactorData:\n\t\t\t\trecord.actor !== undefined ? this.getActorData(record.actor) : null,\n\t\t\tmetadata: record.metadata ?? null,\n\t\t} as AuditLogTable;\n\t}\n\n\tprivate fromRow(row: AuditLogTable): AuditRecord {\n\t\tconst actor =\n\t\t\trow.actorId !== null || row.actorType !== null\n\t\t\t\t? {\n\t\t\t\t\t\tid: row.actorId ?? undefined,\n\t\t\t\t\t\ttype: row.actorType ?? undefined,\n\t\t\t\t\t\t...(row.actorData ? this.parseJson(row.actorData) : {}),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\ttype: row.type,\n\t\t\toperation: row.operation as AuditRecord['operation'],\n\t\t\ttable: row.table ?? undefined,\n\t\t\tentityId: row.entityId ? this.parseEntityId(row.entityId) : undefined,\n\t\t\toldValues: row.oldValues ? this.parseJson(row.oldValues) : undefined,\n\t\t\tnewValues: row.newValues ? this.parseJson(row.newValues) : undefined,\n\t\t\tpayload: row.payload ? this.parseJson(row.payload) : undefined,\n\t\t\ttimestamp: row.timestamp,\n\t\t\tactor,\n\t\t\tmetadata: row.metadata ? this.parseJson(row.metadata) : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Parse a JSON value that may already be parsed (e.g., from jsonb columns).\n\t */\n\tprivate parseJson(value: unknown): Record<string, unknown> {\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\treturn value as Record<string, unknown>;\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn JSON.parse(value);\n\t\t}\n\t\treturn {};\n\t}\n\n\tprivate getActorData(\n\t\tactor: NonNullable<AuditRecord['actor']>,\n\t): Record<string, unknown> {\n\t\tconst { id, type, ...rest } = actor;\n\t\treturn rest;\n\t}\n\n\tprivate parseEntityId(entityId: string): string | Record<string, unknown> {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(entityId);\n\t\t\tif (typeof parsed === 'object' && parsed !== null) {\n\t\t\t\treturn parsed;\n\t\t\t}\n\t\t\treturn entityId;\n\t\t} catch {\n\t\t\treturn entityId;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,eAAsB,yBACrBA,IACAC,SACAC,IACAC,UACa;CACb,MAAM,UAAU,OAAOC,QAAqC;AAE3D,UAAQ,eAAe,IAAI;EAG3B,MAAM,SAAS,MAAM,GAAG,IAAI;AAI5B,QAAM,QAAQ,MAAM,IAAI;AAExB,SAAO;CACP;AAGD,KAAI,GAAG,cACN,QAAO,QAAQ,GAAsB;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1B,MAAM,EAAE,IAAI,KAAM,GAAG,MAAM,GAAG;AAC9B,SAAO;CACP;CAED,AAAQ,cAAcC,UAAoD;AACzE,MAAI;GACH,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,cAAW,WAAW,YAAY,WAAW,KAC5C,QAAO;AAER,UAAO;EACP,QAAO;AACP,UAAO;EACP;CACD;AACD"}
@@ -0,0 +1,49 @@
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const require_cache = require('./cache-l7jAptBl.cjs');
3
+ const __geekmidas_cache_memory = require_chunk.__toESM(require("@geekmidas/cache/memory"));
4
+
5
+ //#region src/memory.ts
6
+ /**
7
+ * In-memory audit storage implementation.
8
+ * Convenience wrapper around CacheAuditStorage with InMemoryCache.
9
+ *
10
+ * Useful for testing, development, and applications that don't need persistent audit logs.
11
+ *
12
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';
17
+ * import { DefaultAuditor } from '@geekmidas/audit';
18
+ *
19
+ * const storage = new InMemoryAuditStorage();
20
+ * const auditor = new DefaultAuditor({
21
+ * actor: { id: 'user-123', type: 'user' },
22
+ * storage,
23
+ * });
24
+ *
25
+ * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });
26
+ * await auditor.flush();
27
+ *
28
+ * // Query stored records
29
+ * const records = await storage.query({ type: 'user.created' });
30
+ *
31
+ * // Get all records (for testing)
32
+ * const all = await storage.getRecords();
33
+ *
34
+ * // Clear for next test
35
+ * await storage.clear();
36
+ * ```
37
+ */
38
+ var InMemoryAuditStorage = class extends require_cache.CacheAuditStorage {
39
+ constructor() {
40
+ super({
41
+ cache: new __geekmidas_cache_memory.InMemoryCache(),
42
+ ttl: 86400 * 365
43
+ });
44
+ }
45
+ };
46
+
47
+ //#endregion
48
+ exports.InMemoryAuditStorage = InMemoryAuditStorage;
49
+ //# sourceMappingURL=memory.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.cjs","names":["CacheAuditStorage","InMemoryCache"],"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryCache } from '@geekmidas/cache/memory';\nimport { CacheAuditStorage } from './cache';\nimport type { AuditableAction } from './types';\n\n/**\n * In-memory audit storage implementation.\n * Convenience wrapper around CacheAuditStorage with InMemoryCache.\n *\n * Useful for testing, development, and applications that don't need persistent audit logs.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';\n * import { DefaultAuditor } from '@geekmidas/audit';\n *\n * const storage = new InMemoryAuditStorage();\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n * await auditor.flush();\n *\n * // Query stored records\n * const records = await storage.query({ type: 'user.created' });\n *\n * // Get all records (for testing)\n * const all = await storage.getRecords();\n *\n * // Clear for next test\n * await storage.clear();\n * ```\n */\nexport class InMemoryAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> extends CacheAuditStorage<TAuditAction> {\n\tconstructor() {\n\t\tsuper({\n\t\t\tcache: new InMemoryCache(),\n\t\t\t// Use a long TTL since in-memory cache expires items\n\t\t\tttl: 86400 * 365, // 1 year\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,uBAAb,cAKUA,gCAAgC;CACzC,cAAc;AACb,QAAM;GACL,OAAO,IAAIC;GAEX,KAAK,QAAQ;EACb,EAAC;CACF;AACD"}
@@ -0,0 +1,44 @@
1
+ import { AuditableAction } from "./Auditor-sW7YAJIA.cjs";
2
+ import { CacheAuditStorage } from "./cache-CDHqXqcl.cjs";
3
+
4
+ //#region src/memory.d.ts
5
+
6
+ /**
7
+ * In-memory audit storage implementation.
8
+ * Convenience wrapper around CacheAuditStorage with InMemoryCache.
9
+ *
10
+ * Useful for testing, development, and applications that don't need persistent audit logs.
11
+ *
12
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';
17
+ * import { DefaultAuditor } from '@geekmidas/audit';
18
+ *
19
+ * const storage = new InMemoryAuditStorage();
20
+ * const auditor = new DefaultAuditor({
21
+ * actor: { id: 'user-123', type: 'user' },
22
+ * storage,
23
+ * });
24
+ *
25
+ * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });
26
+ * await auditor.flush();
27
+ *
28
+ * // Query stored records
29
+ * const records = await storage.query({ type: 'user.created' });
30
+ *
31
+ * // Get all records (for testing)
32
+ * const all = await storage.getRecords();
33
+ *
34
+ * // Clear for next test
35
+ * await storage.clear();
36
+ * ```
37
+ */
38
+ declare class InMemoryAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> extends CacheAuditStorage<TAuditAction> {
39
+ constructor();
40
+ }
41
+ //# sourceMappingURL=memory.d.ts.map
42
+ //#endregion
43
+ export { InMemoryAuditStorage };
44
+ //# sourceMappingURL=memory.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.cts","names":[],"sources":["../src/memory.ts"],"sourcesContent":[],"mappings":";;;;;;;AAoCA;;;;;;AAK2B;;;;;;;;;;;;;;;;;;;;;;;;cALd,0CACS,mCAAmC,0CAI/C,kBAAkB"}
@@ -0,0 +1,44 @@
1
+ import { AuditableAction } from "./Auditor-_Dn2dp8d.mjs";
2
+ import { CacheAuditStorage } from "./cache-2VI80Vao.mjs";
3
+
4
+ //#region src/memory.d.ts
5
+
6
+ /**
7
+ * In-memory audit storage implementation.
8
+ * Convenience wrapper around CacheAuditStorage with InMemoryCache.
9
+ *
10
+ * Useful for testing, development, and applications that don't need persistent audit logs.
11
+ *
12
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';
17
+ * import { DefaultAuditor } from '@geekmidas/audit';
18
+ *
19
+ * const storage = new InMemoryAuditStorage();
20
+ * const auditor = new DefaultAuditor({
21
+ * actor: { id: 'user-123', type: 'user' },
22
+ * storage,
23
+ * });
24
+ *
25
+ * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });
26
+ * await auditor.flush();
27
+ *
28
+ * // Query stored records
29
+ * const records = await storage.query({ type: 'user.created' });
30
+ *
31
+ * // Get all records (for testing)
32
+ * const all = await storage.getRecords();
33
+ *
34
+ * // Clear for next test
35
+ * await storage.clear();
36
+ * ```
37
+ */
38
+ declare class InMemoryAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> extends CacheAuditStorage<TAuditAction> {
39
+ constructor();
40
+ }
41
+ //# sourceMappingURL=memory.d.ts.map
42
+ //#endregion
43
+ export { InMemoryAuditStorage };
44
+ //# sourceMappingURL=memory.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.mts","names":[],"sources":["../src/memory.ts"],"sourcesContent":[],"mappings":";;;;;;;AAoCA;;;;;;AAK2B;;;;;;;;;;;;;;;;;;;;;;;;cALd,0CACS,mCAAmC,0CAI/C,kBAAkB"}
@@ -0,0 +1,48 @@
1
+ import { CacheAuditStorage } from "./cache-BbIl31RL.mjs";
2
+ import { InMemoryCache } from "@geekmidas/cache/memory";
3
+
4
+ //#region src/memory.ts
5
+ /**
6
+ * In-memory audit storage implementation.
7
+ * Convenience wrapper around CacheAuditStorage with InMemoryCache.
8
+ *
9
+ * Useful for testing, development, and applications that don't need persistent audit logs.
10
+ *
11
+ * @template TAuditAction - Optional type parameter for type-safe audit actions.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';
16
+ * import { DefaultAuditor } from '@geekmidas/audit';
17
+ *
18
+ * const storage = new InMemoryAuditStorage();
19
+ * const auditor = new DefaultAuditor({
20
+ * actor: { id: 'user-123', type: 'user' },
21
+ * storage,
22
+ * });
23
+ *
24
+ * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });
25
+ * await auditor.flush();
26
+ *
27
+ * // Query stored records
28
+ * const records = await storage.query({ type: 'user.created' });
29
+ *
30
+ * // Get all records (for testing)
31
+ * const all = await storage.getRecords();
32
+ *
33
+ * // Clear for next test
34
+ * await storage.clear();
35
+ * ```
36
+ */
37
+ var InMemoryAuditStorage = class extends CacheAuditStorage {
38
+ constructor() {
39
+ super({
40
+ cache: new InMemoryCache(),
41
+ ttl: 86400 * 365
42
+ });
43
+ }
44
+ };
45
+
46
+ //#endregion
47
+ export { InMemoryAuditStorage };
48
+ //# sourceMappingURL=memory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.mjs","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import { InMemoryCache } from '@geekmidas/cache/memory';\nimport { CacheAuditStorage } from './cache';\nimport type { AuditableAction } from './types';\n\n/**\n * In-memory audit storage implementation.\n * Convenience wrapper around CacheAuditStorage with InMemoryCache.\n *\n * Useful for testing, development, and applications that don't need persistent audit logs.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { InMemoryAuditStorage } from '@geekmidas/audit/memory';\n * import { DefaultAuditor } from '@geekmidas/audit';\n *\n * const storage = new InMemoryAuditStorage();\n * const auditor = new DefaultAuditor({\n * actor: { id: 'user-123', type: 'user' },\n * storage,\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n * await auditor.flush();\n *\n * // Query stored records\n * const records = await storage.query({ type: 'user.created' });\n *\n * // Get all records (for testing)\n * const all = await storage.getRecords();\n *\n * // Clear for next test\n * await storage.clear();\n * ```\n */\nexport class InMemoryAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> extends CacheAuditStorage<TAuditAction> {\n\tconstructor() {\n\t\tsuper({\n\t\t\tcache: new InMemoryCache(),\n\t\t\t// Use a long TTL since in-memory cache expires items\n\t\t\tttl: 86400 * 365, // 1 year\n\t\t});\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,uBAAb,cAKU,kBAAgC;CACzC,cAAc;AACb,QAAM;GACL,OAAO,IAAI;GAEX,KAAK,QAAQ;EACb,EAAC;CACF;AACD"}
@@ -1,2 +1,2 @@
1
- import { AuditQueryOptions, AuditStorage } from "./Auditor-QYUMGJCH.cjs";
1
+ import { AuditQueryOptions, AuditStorage } from "./Auditor-sW7YAJIA.cjs";
2
2
  export { AuditQueryOptions, AuditStorage };
@@ -1,2 +1,2 @@
1
- import { AuditQueryOptions, AuditStorage } from "./Auditor-D3me-qKX.mjs";
1
+ import { AuditQueryOptions, AuditStorage } from "./Auditor-_Dn2dp8d.mjs";
2
2
  export { AuditQueryOptions, AuditStorage };
package/dist/types.d.cts CHANGED
@@ -1,2 +1,2 @@
1
- import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-QYUMGJCH.cjs";
1
+ import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-sW7YAJIA.cjs";
2
2
  export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit };
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-D3me-qKX.mjs";
1
+ import { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit } from "./Auditor-_Dn2dp8d.mjs";
2
2
  export { AuditActor, AuditMetadata, AuditOperation, AuditOptions, AuditRecord, AuditableAction, ExtractAuditPayload, ExtractAuditType, ExtractAuditorAction, ExtractStorageAuditAction, MappedAudit };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/audit",
3
- "version": "0.0.8",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -12,23 +12,51 @@
12
12
  "types": "./dist/kysely.d.ts",
13
13
  "import": "./dist/kysely.mjs",
14
14
  "require": "./dist/kysely.cjs"
15
+ },
16
+ "./memory": {
17
+ "types": "./dist/memory.d.ts",
18
+ "import": "./dist/memory.mjs",
19
+ "require": "./dist/memory.cjs"
20
+ },
21
+ "./cache": {
22
+ "types": "./dist/cache.d.ts",
23
+ "import": "./dist/cache.mjs",
24
+ "require": "./dist/cache.cjs"
15
25
  }
16
26
  },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "https://github.com/geekmidas/toolbox"
30
+ },
17
31
  "publishConfig": {
18
32
  "registry": "https://registry.npmjs.org/",
19
33
  "access": "public"
20
34
  },
21
35
  "dependencies": {
22
36
  "@standard-schema/spec": "~1.0.0",
23
- "nanoid": "~5.1.5",
24
- "@geekmidas/schema": "0.0.2"
37
+ "nanoid": "~5.1.5"
25
38
  },
26
39
  "peerDependencies": {
27
- "kysely": "^0.28.0"
40
+ "kysely": "^0.28.0",
41
+ "@geekmidas/cache": "^0.2.0",
42
+ "@geekmidas/schema": "^0.1.0"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "@geekmidas/cache": {
46
+ "optional": true
47
+ },
48
+ "@geekmidas/schema": {
49
+ "optional": true
50
+ },
51
+ "kysely": {
52
+ "optional": true
53
+ }
28
54
  },
29
55
  "devDependencies": {
30
56
  "kysely": "~0.28.2",
31
57
  "pg": "~8.16.0",
32
- "@types/pg": "~8.15.6"
58
+ "@types/pg": "~8.15.6",
59
+ "@geekmidas/cache": "^0.2.0",
60
+ "@geekmidas/schema": "^0.1.0"
33
61
  }
34
62
  }