@geekmidas/audit 10.0.0-alpha.2 → 10.0.0-alpha.21

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 (77) hide show
  1. package/dist/{Auditor-CW2NrfHS.d.mts → Auditor-BBXXCD0v.d.cts} +2 -7
  2. package/dist/Auditor-BBXXCD0v.d.cts.map +1 -0
  3. package/dist/{Auditor-DpBHXIJM.d.cts → Auditor-BBXXCD0v.d.mts} +2 -7
  4. package/dist/Auditor-BBXXCD0v.d.mts.map +1 -0
  5. package/dist/Auditor.d.cts +1 -1
  6. package/dist/Auditor.d.mts +1 -1
  7. package/dist/Auditor.mjs +1 -0
  8. package/dist/DefaultAuditor.cjs +95 -2
  9. package/dist/DefaultAuditor.cjs.map +1 -0
  10. package/dist/DefaultAuditor.d.cts +55 -3
  11. package/dist/DefaultAuditor.d.cts.map +1 -0
  12. package/dist/DefaultAuditor.d.mts +55 -3
  13. package/dist/DefaultAuditor.d.mts.map +1 -0
  14. package/dist/DefaultAuditor.mjs +94 -2
  15. package/dist/DefaultAuditor.mjs.map +1 -0
  16. package/dist/cache.cjs +166 -2
  17. package/dist/cache.cjs.map +1 -0
  18. package/dist/cache.d.cts +92 -3
  19. package/dist/cache.d.cts.map +1 -0
  20. package/dist/cache.d.mts +92 -3
  21. package/dist/cache.d.mts.map +1 -0
  22. package/dist/cache.mjs +165 -2
  23. package/dist/cache.mjs.map +1 -0
  24. package/dist/index.cjs +3 -3
  25. package/dist/index.d.cts +3 -3
  26. package/dist/index.d.mts +3 -3
  27. package/dist/index.mjs +2 -3
  28. package/dist/knex.cjs +9 -9
  29. package/dist/knex.cjs.map +1 -1
  30. package/dist/knex.d.cts +9 -11
  31. package/dist/knex.d.cts.map +1 -1
  32. package/dist/knex.d.mts +9 -11
  33. package/dist/knex.d.mts.map +1 -1
  34. package/dist/knex.mjs +7 -7
  35. package/dist/knex.mjs.map +1 -1
  36. package/dist/kysely.cjs +9 -9
  37. package/dist/kysely.cjs.map +1 -1
  38. package/dist/kysely.d.cts +9 -11
  39. package/dist/kysely.d.cts.map +1 -1
  40. package/dist/kysely.d.mts +9 -11
  41. package/dist/kysely.d.mts.map +1 -1
  42. package/dist/kysely.mjs +7 -7
  43. package/dist/kysely.mjs.map +1 -1
  44. package/dist/memory.cjs +6 -7
  45. package/dist/memory.cjs.map +1 -1
  46. package/dist/memory.d.cts +3 -7
  47. package/dist/memory.d.cts.map +1 -1
  48. package/dist/memory.d.mts +3 -7
  49. package/dist/memory.d.mts.map +1 -1
  50. package/dist/memory.mjs +3 -4
  51. package/dist/memory.mjs.map +1 -1
  52. package/dist/storage.d.cts +1 -1
  53. package/dist/storage.d.mts +1 -1
  54. package/dist/storage.mjs +1 -0
  55. package/dist/types.d.cts +1 -1
  56. package/dist/types.d.mts +1 -1
  57. package/dist/types.mjs +1 -0
  58. package/package.json +13 -13
  59. package/dist/Auditor-CW2NrfHS.d.mts.map +0 -1
  60. package/dist/Auditor-DpBHXIJM.d.cts.map +0 -1
  61. package/dist/DefaultAuditor-BAVnNmRh.mjs +0 -96
  62. package/dist/DefaultAuditor-BAVnNmRh.mjs.map +0 -1
  63. package/dist/DefaultAuditor-DlJ1ENfx.d.mts +0 -59
  64. package/dist/DefaultAuditor-DlJ1ENfx.d.mts.map +0 -1
  65. package/dist/DefaultAuditor-GRFI86N_.d.cts +0 -59
  66. package/dist/DefaultAuditor-GRFI86N_.d.cts.map +0 -1
  67. package/dist/DefaultAuditor-JbZ_BQfh.cjs +0 -102
  68. package/dist/DefaultAuditor-JbZ_BQfh.cjs.map +0 -1
  69. package/dist/cache-BbIl31RL.mjs +0 -167
  70. package/dist/cache-BbIl31RL.mjs.map +0 -1
  71. package/dist/cache-Bih6HxY6.d.cts +0 -96
  72. package/dist/cache-Bih6HxY6.d.cts.map +0 -1
  73. package/dist/cache-l7jAptBl.cjs +0 -173
  74. package/dist/cache-l7jAptBl.cjs.map +0 -1
  75. package/dist/cache-wET57t6d.d.mts +0 -96
  76. package/dist/cache-wET57t6d.d.mts.map +0 -1
  77. package/dist/chunk-CUT6urMc.cjs +0 -30
@@ -1,102 +0,0 @@
1
- const require_chunk = require('./chunk-CUT6urMc.cjs');
2
- const nanoid = require_chunk.__toESM(require("nanoid"));
3
-
4
- //#region src/DefaultAuditor.ts
5
- /**
6
- * Default implementation of the Auditor interface.
7
- * Collects audit records in memory and flushes to storage.
8
- *
9
- * @template TAuditAction - Union of all allowed audit action types
10
- * @template TTransaction - Transaction type (e.g., Kysely Transaction)
11
- *
12
- * @example
13
- * ```typescript
14
- * const auditor = new DefaultAuditor<AppAuditAction>({
15
- * actor: { id: 'user-123', type: 'user' },
16
- * storage: auditStorage,
17
- * metadata: { requestId: 'req-456', endpoint: '/users' },
18
- * });
19
- *
20
- * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });
21
- *
22
- * // Flush inside transaction
23
- * await auditor.flush(trx);
24
- * ```
25
- */
26
- var DefaultAuditor = class {
27
- actor;
28
- storage;
29
- metadata;
30
- generateId;
31
- records = [];
32
- transaction;
33
- constructor(config) {
34
- this.actor = config.actor;
35
- this.storage = config.storage;
36
- this.metadata = config.metadata;
37
- this.generateId = config.generateId ?? (() => (0, nanoid.nanoid)());
38
- }
39
- audit(type, payload, options) {
40
- const record = {
41
- id: this.generateId(),
42
- type,
43
- operation: options?.operation ?? "CUSTOM",
44
- table: options?.table,
45
- entityId: options?.entityId,
46
- oldValues: options?.oldValues,
47
- newValues: options?.newValues,
48
- payload,
49
- timestamp: /* @__PURE__ */ new Date(),
50
- actor: this.actor,
51
- metadata: this.metadata
52
- };
53
- this.records.push(record);
54
- }
55
- record(record) {
56
- const fullRecord = {
57
- ...record,
58
- id: this.generateId(),
59
- timestamp: /* @__PURE__ */ new Date(),
60
- actor: this.actor,
61
- metadata: this.metadata ? {
62
- ...this.metadata,
63
- ...record.metadata
64
- } : record.metadata
65
- };
66
- this.records.push(fullRecord);
67
- }
68
- getRecords() {
69
- return [...this.records];
70
- }
71
- async flush(trx) {
72
- if (this.records.length === 0) return;
73
- const recordsToFlush = [...this.records];
74
- this.records = [];
75
- const transactionToUse = trx ?? this.transaction;
76
- await this.storage.write(recordsToFlush, transactionToUse);
77
- }
78
- setTransaction(trx) {
79
- this.transaction = trx;
80
- }
81
- getTransaction() {
82
- return this.transaction;
83
- }
84
- clear() {
85
- this.records = [];
86
- }
87
- addMetadata(metadata) {
88
- this.metadata = this.metadata ? {
89
- ...this.metadata,
90
- ...metadata
91
- } : metadata;
92
- }
93
- };
94
-
95
- //#endregion
96
- Object.defineProperty(exports, 'DefaultAuditor', {
97
- enumerable: true,
98
- get: function () {
99
- return DefaultAuditor;
100
- }
101
- });
102
- //# sourceMappingURL=DefaultAuditor-JbZ_BQfh.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DefaultAuditor-JbZ_BQfh.cjs","names":["config: DefaultAuditorConfig","type: TType","payload: ExtractAuditPayload<TAuditAction, TType>","options?: AuditOptions","record: AuditRecord","record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>","fullRecord: AuditRecord","trx?: TTransaction","trx: TTransaction","metadata: AuditMetadata"],"sources":["../src/DefaultAuditor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type { Auditor } from './Auditor';\nimport type { AuditStorage } from './storage';\nimport type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditMetadata,\n\tAuditOptions,\n\tAuditRecord,\n\tExtractAuditPayload,\n\tExtractAuditType,\n} from './types';\n\n/**\n * Configuration for DefaultAuditor.\n */\nexport interface DefaultAuditorConfig {\n\t/** The actor performing audits (set at construction, immutable) */\n\tactor: AuditActor;\n\t/** Storage backend for persisting audits */\n\tstorage: AuditStorage;\n\t/** Optional metadata to attach to all audits */\n\tmetadata?: AuditMetadata;\n\t/** Optional custom ID generator (defaults to nanoid) */\n\tgenerateId?: () => string;\n}\n\n/**\n * Default implementation of the Auditor interface.\n * Collects audit records in memory and flushes to storage.\n *\n * @template TAuditAction - Union of all allowed audit action types\n * @template TTransaction - Transaction type (e.g., Kysely Transaction)\n *\n * @example\n * ```typescript\n * const auditor = new DefaultAuditor<AppAuditAction>({\n * actor: { id: 'user-123', type: 'user' },\n * storage: auditStorage,\n * metadata: { requestId: 'req-456', endpoint: '/users' },\n * });\n *\n * auditor.audit('user.created', { userId: '789', email: 'test@example.com' });\n *\n * // Flush inside transaction\n * await auditor.flush(trx);\n * ```\n */\nexport class DefaultAuditor<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTTransaction = unknown,\n> implements Auditor<TAuditAction, TTransaction>\n{\n\treadonly actor: AuditActor;\n\tprivate readonly storage: AuditStorage;\n\tprivate metadata?: AuditMetadata;\n\tprivate readonly generateId: () => string;\n\tprivate records: AuditRecord[] = [];\n\tprivate transaction?: TTransaction;\n\n\tconstructor(config: DefaultAuditorConfig) {\n\t\tthis.actor = config.actor;\n\t\tthis.storage = config.storage;\n\t\tthis.metadata = config.metadata;\n\t\tthis.generateId = config.generateId ?? (() => nanoid());\n\t}\n\n\taudit<TType extends ExtractAuditType<TAuditAction>>(\n\t\ttype: TType,\n\t\tpayload: ExtractAuditPayload<TAuditAction, TType>,\n\t\toptions?: AuditOptions,\n\t): void {\n\t\tconst record: AuditRecord = {\n\t\t\tid: this.generateId(),\n\t\t\ttype,\n\t\t\toperation: options?.operation ?? 'CUSTOM',\n\t\t\ttable: options?.table,\n\t\t\tentityId: options?.entityId,\n\t\t\toldValues: options?.oldValues,\n\t\t\tnewValues: options?.newValues,\n\t\t\tpayload,\n\t\t\ttimestamp: new Date(),\n\t\t\tactor: this.actor,\n\t\t\tmetadata: this.metadata,\n\t\t};\n\n\t\tthis.records.push(record);\n\t}\n\n\trecord(record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>): void {\n\t\tconst fullRecord: AuditRecord = {\n\t\t\t...record,\n\t\t\tid: this.generateId(),\n\t\t\ttimestamp: new Date(),\n\t\t\tactor: this.actor,\n\t\t\tmetadata: this.metadata\n\t\t\t\t? { ...this.metadata, ...record.metadata }\n\t\t\t\t: record.metadata,\n\t\t};\n\n\t\tthis.records.push(fullRecord);\n\t}\n\n\tgetRecords(): AuditRecord[] {\n\t\treturn [...this.records];\n\t}\n\n\tasync flush(trx?: TTransaction): Promise<void> {\n\t\tif (this.records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst recordsToFlush = [...this.records];\n\t\tthis.records = [];\n\n\t\t// Use explicitly passed transaction, or fall back to stored transaction\n\t\tconst transactionToUse = trx ?? this.transaction;\n\t\tawait this.storage.write(recordsToFlush, transactionToUse);\n\t}\n\n\tsetTransaction(trx: TTransaction): void {\n\t\tthis.transaction = trx;\n\t}\n\n\tgetTransaction(): TTransaction | undefined {\n\t\treturn this.transaction;\n\t}\n\n\tclear(): void {\n\t\tthis.records = [];\n\t}\n\n\taddMetadata(metadata: AuditMetadata): void {\n\t\tthis.metadata = this.metadata\n\t\t\t? { ...this.metadata, ...metadata }\n\t\t\t: metadata;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,iBAAb,MAOA;CACC,AAAS;CACT,AAAiB;CACjB,AAAQ;CACR,AAAiB;CACjB,AAAQ,UAAyB,CAAE;CACnC,AAAQ;CAER,YAAYA,QAA8B;AACzC,OAAK,QAAQ,OAAO;AACpB,OAAK,UAAU,OAAO;AACtB,OAAK,WAAW,OAAO;AACvB,OAAK,aAAa,OAAO,eAAe,MAAM,oBAAQ;CACtD;CAED,MACCC,MACAC,SACAC,SACO;EACP,MAAMC,SAAsB;GAC3B,IAAI,KAAK,YAAY;GACrB;GACA,WAAW,SAAS,aAAa;GACjC,OAAO,SAAS;GAChB,UAAU,SAAS;GACnB,WAAW,SAAS;GACpB,WAAW,SAAS;GACpB;GACA,2BAAW,IAAI;GACf,OAAO,KAAK;GACZ,UAAU,KAAK;EACf;AAED,OAAK,QAAQ,KAAK,OAAO;CACzB;CAED,OAAOC,QAA+D;EACrE,MAAMC,aAA0B;GAC/B,GAAG;GACH,IAAI,KAAK,YAAY;GACrB,2BAAW,IAAI;GACf,OAAO,KAAK;GACZ,UAAU,KAAK,WACZ;IAAE,GAAG,KAAK;IAAU,GAAG,OAAO;GAAU,IACxC,OAAO;EACV;AAED,OAAK,QAAQ,KAAK,WAAW;CAC7B;CAED,aAA4B;AAC3B,SAAO,CAAC,GAAG,KAAK,OAAQ;CACxB;CAED,MAAM,MAAMC,KAAmC;AAC9C,MAAI,KAAK,QAAQ,WAAW,EAC3B;EAGD,MAAM,iBAAiB,CAAC,GAAG,KAAK,OAAQ;AACxC,OAAK,UAAU,CAAE;EAGjB,MAAM,mBAAmB,OAAO,KAAK;AACrC,QAAM,KAAK,QAAQ,MAAM,gBAAgB,iBAAiB;CAC1D;CAED,eAAeC,KAAyB;AACvC,OAAK,cAAc;CACnB;CAED,iBAA2C;AAC1C,SAAO,KAAK;CACZ;CAED,QAAc;AACb,OAAK,UAAU,CAAE;CACjB;CAED,YAAYC,UAA+B;AAC1C,OAAK,WAAW,KAAK,WAClB;GAAE,GAAG,KAAK;GAAU,GAAG;EAAU,IACjC;CACH;AACD"}
@@ -1,167 +0,0 @@
1
- //#region src/cache.ts
2
- /**
3
- * Cache-based audit storage implementation.
4
- * Uses any @geekmidas/cache implementation for storage.
5
- *
6
- * Best suited for:
7
- * - Development and testing
8
- * - Temporary audit logs that don't need persistence
9
- * - Applications with existing cache infrastructure
10
- * - Distributed systems needing shared audit state (with Redis/Upstash)
11
- *
12
- * Note: Query performance may degrade with large numbers of records
13
- * since filtering happens in memory after fetching all records.
14
- *
15
- * @template TAuditAction - Optional type parameter for type-safe audit actions.
16
- *
17
- * @example
18
- * ```typescript
19
- * import { CacheAuditStorage } from '@geekmidas/audit/cache';
20
- * import { InMemoryCache } from '@geekmidas/cache/memory';
21
- * import { UpstashCache } from '@geekmidas/cache/upstash';
22
- *
23
- * // With in-memory cache (development/testing)
24
- * const storage = new CacheAuditStorage({
25
- * cache: new InMemoryCache(),
26
- * ttl: 86400, // 24 hours
27
- * });
28
- *
29
- * // With Upstash Redis (production)
30
- * const storage = new CacheAuditStorage({
31
- * cache: new UpstashCache({
32
- * url: process.env.UPSTASH_REDIS_URL,
33
- * token: process.env.UPSTASH_REDIS_TOKEN,
34
- * }),
35
- * ttl: 604800, // 7 days
36
- * });
37
- * ```
38
- */
39
- var CacheAuditStorage = class {
40
- cache;
41
- prefix;
42
- ttl;
43
- indexKey;
44
- constructor(config) {
45
- this.cache = config.cache;
46
- this.prefix = config.prefix ?? "audit";
47
- this.ttl = config.ttl;
48
- this.indexKey = `${this.prefix}:__index__`;
49
- }
50
- /**
51
- * Write audit records to cache.
52
- */
53
- async write(records) {
54
- if (records.length === 0) return;
55
- const existingIds = await this.cache.get(this.indexKey) ?? [];
56
- const newIds = [];
57
- for (const record of records) {
58
- const key = this.getRecordKey(record.id);
59
- const serialized = this.serializeRecord(record);
60
- await this.cache.set(key, serialized, this.ttl);
61
- newIds.push(record.id);
62
- }
63
- const updatedIds = [...existingIds, ...newIds];
64
- await this.cache.set(this.indexKey, updatedIds, this.ttl);
65
- }
66
- /**
67
- * Query audit records from cache.
68
- */
69
- async query(options) {
70
- const allRecords = await this.getAllRecords();
71
- let results = this.applyFilters(allRecords, options);
72
- const orderBy = options.orderBy ?? "timestamp";
73
- const orderDirection = options.orderDirection ?? "desc";
74
- results.sort((a, b) => {
75
- const aValue = orderBy === "timestamp" ? a.timestamp.getTime() : a.type;
76
- const bValue = orderBy === "timestamp" ? b.timestamp.getTime() : b.type;
77
- if (aValue < bValue) return orderDirection === "asc" ? -1 : 1;
78
- if (aValue > bValue) return orderDirection === "asc" ? 1 : -1;
79
- return 0;
80
- });
81
- if (options.offset !== void 0) results = results.slice(options.offset);
82
- if (options.limit !== void 0) results = results.slice(0, options.limit);
83
- return results;
84
- }
85
- /**
86
- * Count audit records matching filters.
87
- */
88
- async count(options) {
89
- const allRecords = await this.getAllRecords();
90
- return this.applyFilters(allRecords, options).length;
91
- }
92
- /**
93
- * Get all stored records (for testing/debugging).
94
- */
95
- async getRecords() {
96
- return this.getAllRecords();
97
- }
98
- /**
99
- * Clear all stored records.
100
- */
101
- async clear() {
102
- const ids = await this.cache.get(this.indexKey) ?? [];
103
- for (const id of ids) await this.cache.delete(this.getRecordKey(id));
104
- await this.cache.delete(this.indexKey);
105
- }
106
- getRecordKey(id) {
107
- return `${this.prefix}:${id}`;
108
- }
109
- async getAllRecords() {
110
- const ids = await this.cache.get(this.indexKey) ?? [];
111
- const records = [];
112
- const validIds = [];
113
- for (const id of ids) {
114
- const key = this.getRecordKey(id);
115
- const serialized = await this.cache.get(key);
116
- if (serialized) {
117
- records.push(this.deserializeRecord(serialized));
118
- validIds.push(id);
119
- }
120
- }
121
- if (validIds.length !== ids.length) await this.cache.set(this.indexKey, validIds, this.ttl);
122
- return records;
123
- }
124
- serializeRecord(record) {
125
- return {
126
- ...record,
127
- timestamp: record.timestamp.toISOString()
128
- };
129
- }
130
- deserializeRecord(serialized) {
131
- return {
132
- ...serialized,
133
- timestamp: new Date(serialized.timestamp)
134
- };
135
- }
136
- applyFilters(records, options) {
137
- return records.filter((record) => {
138
- if (options.type !== void 0) {
139
- if (Array.isArray(options.type)) {
140
- if (!options.type.includes(record.type)) return false;
141
- } else if (record.type !== options.type) return false;
142
- }
143
- if (options.entityId !== void 0) {
144
- const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
145
- const recordEntityId = typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId);
146
- if (recordEntityId !== entityId) return false;
147
- }
148
- if (options.table !== void 0) {
149
- if (record.table !== options.table) return false;
150
- }
151
- if (options.actorId !== void 0) {
152
- if (record.actor?.id !== options.actorId) return false;
153
- }
154
- if (options.from !== void 0) {
155
- if (record.timestamp < options.from) return false;
156
- }
157
- if (options.to !== void 0) {
158
- if (record.timestamp > options.to) return false;
159
- }
160
- return true;
161
- });
162
- }
163
- };
164
-
165
- //#endregion
166
- export { CacheAuditStorage };
167
- //# sourceMappingURL=cache-BbIl31RL.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cache-BbIl31RL.mjs","names":["config: CacheAuditStorageConfig","records: AuditRecord[]","newIds: string[]","options: AuditQueryOptions","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","id: string","validIds: string[]","record: AuditRecord","serialized: SerializedAuditRecord"],"sources":["../src/cache.ts"],"sourcesContent":["import type { Cache } from '@geekmidas/cache';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditableAction, AuditRecord } from './types';\n\n/**\n * Configuration for CacheAuditStorage.\n */\nexport interface CacheAuditStorageConfig {\n\t/** Cache instance to use for storage */\n\tcache: Cache;\n\t/**\n\t * Key prefix for audit records.\n\t * Records are stored as `${prefix}:${id}`.\n\t * @default 'audit'\n\t */\n\tprefix?: string;\n\t/**\n\t * TTL (time-to-live) in seconds for audit records.\n\t * If not set, records use the cache's default TTL.\n\t */\n\tttl?: number;\n}\n\n/**\n * Cache-based audit storage implementation.\n * Uses any @geekmidas/cache implementation for storage.\n *\n * Best suited for:\n * - Development and testing\n * - Temporary audit logs that don't need persistence\n * - Applications with existing cache infrastructure\n * - Distributed systems needing shared audit state (with Redis/Upstash)\n *\n * Note: Query performance may degrade with large numbers of records\n * since filtering happens in memory after fetching all records.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { CacheAuditStorage } from '@geekmidas/audit/cache';\n * import { InMemoryCache } from '@geekmidas/cache/memory';\n * import { UpstashCache } from '@geekmidas/cache/upstash';\n *\n * // With in-memory cache (development/testing)\n * const storage = new CacheAuditStorage({\n * cache: new InMemoryCache(),\n * ttl: 86400, // 24 hours\n * });\n *\n * // With Upstash Redis (production)\n * const storage = new CacheAuditStorage({\n * cache: new UpstashCache({\n * url: process.env.UPSTASH_REDIS_URL,\n * token: process.env.UPSTASH_REDIS_TOKEN,\n * }),\n * ttl: 604800, // 7 days\n * });\n * ```\n */\nexport class CacheAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> implements AuditStorage<TAuditAction>\n{\n\tprivate readonly cache: Cache;\n\tprivate readonly prefix: string;\n\tprivate readonly ttl?: number;\n\tprivate readonly indexKey: string;\n\n\tconstructor(config: CacheAuditStorageConfig) {\n\t\tthis.cache = config.cache;\n\t\tthis.prefix = config.prefix ?? 'audit';\n\t\tthis.ttl = config.ttl;\n\t\tthis.indexKey = `${this.prefix}:__index__`;\n\t}\n\n\t/**\n\t * Write audit records to cache.\n\t */\n\tasync write(records: AuditRecord[]): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Get existing index\n\t\tconst existingIds = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst newIds: string[] = [];\n\n\t\t// Write each record\n\t\tfor (const record of records) {\n\t\t\tconst key = this.getRecordKey(record.id);\n\t\t\t// Serialize Date to ISO string for cache storage\n\t\t\tconst serialized = this.serializeRecord(record);\n\t\t\tawait this.cache.set(key, serialized, this.ttl);\n\t\t\tnewIds.push(record.id);\n\t\t}\n\n\t\t// Update index with new IDs\n\t\tconst updatedIds = [...existingIds, ...newIds];\n\t\tawait this.cache.set(this.indexKey, updatedIds, this.ttl);\n\t}\n\n\t/**\n\t * Query audit records from cache.\n\t */\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\tlet results = this.applyFilters(allRecords, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tresults.sort((a, b) => {\n\t\t\tconst aValue = orderBy === 'timestamp' ? a.timestamp.getTime() : a.type;\n\t\t\tconst bValue = orderBy === 'timestamp' ? b.timestamp.getTime() : b.type;\n\t\t\tif (aValue < bValue) return orderDirection === 'asc' ? -1 : 1;\n\t\t\tif (aValue > bValue) return orderDirection === 'asc' ? 1 : -1;\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Pagination\n\t\tif (options.offset !== undefined) {\n\t\t\tresults = results.slice(options.offset);\n\t\t}\n\t\tif (options.limit !== undefined) {\n\t\t\tresults = results.slice(0, options.limit);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Count audit records matching filters.\n\t */\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\treturn this.applyFilters(allRecords, options).length;\n\t}\n\n\t/**\n\t * Get all stored records (for testing/debugging).\n\t */\n\tasync getRecords(): Promise<AuditRecord[]> {\n\t\treturn this.getAllRecords();\n\t}\n\n\t/**\n\t * Clear all stored records.\n\t */\n\tasync clear(): Promise<void> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\n\t\t// Delete all records\n\t\tfor (const id of ids) {\n\t\t\tawait this.cache.delete(this.getRecordKey(id));\n\t\t}\n\n\t\t// Delete index\n\t\tawait this.cache.delete(this.indexKey);\n\t}\n\n\tprivate getRecordKey(id: string): string {\n\t\treturn `${this.prefix}:${id}`;\n\t}\n\n\tprivate async getAllRecords(): Promise<AuditRecord[]> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst records: AuditRecord[] = [];\n\t\tconst validIds: string[] = [];\n\n\t\tfor (const id of ids) {\n\t\t\tconst key = this.getRecordKey(id);\n\t\t\tconst serialized = await this.cache.get<SerializedAuditRecord>(key);\n\t\t\tif (serialized) {\n\t\t\t\trecords.push(this.deserializeRecord(serialized));\n\t\t\t\tvalidIds.push(id);\n\t\t\t}\n\t\t}\n\n\t\t// Clean up index if some records expired\n\t\tif (validIds.length !== ids.length) {\n\t\t\tawait this.cache.set(this.indexKey, validIds, this.ttl);\n\t\t}\n\n\t\treturn records;\n\t}\n\n\tprivate serializeRecord(record: AuditRecord): SerializedAuditRecord {\n\t\treturn {\n\t\t\t...record,\n\t\t\ttimestamp: record.timestamp.toISOString(),\n\t\t};\n\t}\n\n\tprivate deserializeRecord(serialized: SerializedAuditRecord): AuditRecord {\n\t\treturn {\n\t\t\t...serialized,\n\t\t\ttimestamp: new Date(serialized.timestamp),\n\t\t};\n\t}\n\n\tprivate applyFilters(\n\t\trecords: AuditRecord[],\n\t\toptions: AuditQueryOptions,\n\t): AuditRecord[] {\n\t\treturn records.filter((record) => {\n\t\t\t// Type filter\n\t\t\tif (options.type !== undefined) {\n\t\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\t\tif (!options.type.includes(record.type)) return false;\n\t\t\t\t} else {\n\t\t\t\t\tif (record.type !== options.type) return false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Entity ID filter\n\t\t\tif (options.entityId !== undefined) {\n\t\t\t\tconst entityId =\n\t\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t\t? options.entityId\n\t\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\t\tconst recordEntityId =\n\t\t\t\t\ttypeof 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\t\tif (recordEntityId !== entityId) return false;\n\t\t\t}\n\n\t\t\t// Table filter\n\t\t\tif (options.table !== undefined) {\n\t\t\t\tif (record.table !== options.table) return false;\n\t\t\t}\n\n\t\t\t// Actor ID filter\n\t\t\tif (options.actorId !== undefined) {\n\t\t\t\tif (record.actor?.id !== options.actorId) return false;\n\t\t\t}\n\n\t\t\t// Date range filters\n\t\t\tif (options.from !== undefined) {\n\t\t\t\tif (record.timestamp < options.from) return false;\n\t\t\t}\n\t\t\tif (options.to !== undefined) {\n\t\t\t\tif (record.timestamp > options.to) return false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\t}\n}\n\n/**\n * Serialized version of AuditRecord for cache storage.\n * Dates are stored as ISO strings.\n */\ntype SerializedAuditRecord = Omit<AuditRecord,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AG;GACH,WAAW,IAAI,KAAK,WAAW;EAC/B;CACD;CAED,AAAQ,aACPP,SACAE,SACgB;AAChB,SAAO,QAAQ,OAAO,CAAC,WAAW;AAEjC,OAAI,QAAQ,iBACX;QAAI,MAAM,QAAQ,QAAQ,KAAK,EAC9B;UAAK,QAAQ,KAAK,SAAS,OAAO,KAAK,CAAE,QAAO;IAAM,WAElD,OAAO,SAAS,QAAQ,KAAM,QAAO;GACzC;AAIF,OAAI,QAAQ,qBAAwB;IACnC,MAAM,kBACE,QAAQ,aAAa,WACzB,QAAQ,WACR,KAAK,UAAU,QAAQ,SAAS;IACpC,MAAM,wBACE,OAAO,aAAa,WACxB,OAAO,WACP,KAAK,UAAU,OAAO,SAAS;AACnC,QAAI,mBAAmB,SAAU,QAAO;GACxC;AAGD,OAAI,QAAQ,kBACX;QAAI,OAAO,UAAU,QAAQ,MAAO,QAAO;GAAM;AAIlD,OAAI,QAAQ,oBACX;QAAI,OAAO,OAAO,OAAO,QAAQ,QAAS,QAAO;GAAM;AAIxD,OAAI,QAAQ,iBACX;QAAI,OAAO,YAAY,QAAQ,KAAM,QAAO;GAAM;AAEnD,OAAI,QAAQ,eACX;QAAI,OAAO,YAAY,QAAQ,GAAI,QAAO;GAAM;AAGjD,UAAO;EACP,EAAC;CACF;AACD"}
@@ -1,96 +0,0 @@
1
- import { AuditQueryOptions, AuditRecord, AuditStorage, AuditableAction } from "./Auditor-DpBHXIJM.cjs";
2
- import { Cache } from "@geekmidas/cache";
3
-
4
- //#region src/cache.d.ts
5
-
6
- /**
7
- * Configuration for CacheAuditStorage.
8
- */
9
- interface CacheAuditStorageConfig {
10
- /** Cache instance to use for storage */
11
- cache: Cache;
12
- /**
13
- * Key prefix for audit records.
14
- * Records are stored as `${prefix}:${id}`.
15
- * @default 'audit'
16
- */
17
- prefix?: string;
18
- /**
19
- * TTL (time-to-live) in seconds for audit records.
20
- * If not set, records use the cache's default TTL.
21
- */
22
- ttl?: number;
23
- }
24
- /**
25
- * Cache-based audit storage implementation.
26
- * Uses any @geekmidas/cache implementation for storage.
27
- *
28
- * Best suited for:
29
- * - Development and testing
30
- * - Temporary audit logs that don't need persistence
31
- * - Applications with existing cache infrastructure
32
- * - Distributed systems needing shared audit state (with Redis/Upstash)
33
- *
34
- * Note: Query performance may degrade with large numbers of records
35
- * since filtering happens in memory after fetching all records.
36
- *
37
- * @template TAuditAction - Optional type parameter for type-safe audit actions.
38
- *
39
- * @example
40
- * ```typescript
41
- * import { CacheAuditStorage } from '@geekmidas/audit/cache';
42
- * import { InMemoryCache } from '@geekmidas/cache/memory';
43
- * import { UpstashCache } from '@geekmidas/cache/upstash';
44
- *
45
- * // With in-memory cache (development/testing)
46
- * const storage = new CacheAuditStorage({
47
- * cache: new InMemoryCache(),
48
- * ttl: 86400, // 24 hours
49
- * });
50
- *
51
- * // With Upstash Redis (production)
52
- * const storage = new CacheAuditStorage({
53
- * cache: new UpstashCache({
54
- * url: process.env.UPSTASH_REDIS_URL,
55
- * token: process.env.UPSTASH_REDIS_TOKEN,
56
- * }),
57
- * ttl: 604800, // 7 days
58
- * });
59
- * ```
60
- */
61
- declare class CacheAuditStorage<TAuditAction extends AuditableAction<string, unknown> = AuditableAction<string, unknown>> implements AuditStorage<TAuditAction> {
62
- private readonly cache;
63
- private readonly prefix;
64
- private readonly ttl?;
65
- private readonly indexKey;
66
- constructor(config: CacheAuditStorageConfig);
67
- /**
68
- * Write audit records to cache.
69
- */
70
- write(records: AuditRecord[]): Promise<void>;
71
- /**
72
- * Query audit records from cache.
73
- */
74
- query(options: AuditQueryOptions): Promise<AuditRecord[]>;
75
- /**
76
- * Count audit records matching filters.
77
- */
78
- count(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;
79
- /**
80
- * Get all stored records (for testing/debugging).
81
- */
82
- getRecords(): Promise<AuditRecord[]>;
83
- /**
84
- * Clear all stored records.
85
- */
86
- clear(): Promise<void>;
87
- private getRecordKey;
88
- private getAllRecords;
89
- private serializeRecord;
90
- private deserializeRecord;
91
- private applyFilters;
92
- }
93
- //# sourceMappingURL=cache.d.ts.map
94
- //#endregion
95
- export { CacheAuditStorage, CacheAuditStorageConfig };
96
- //# sourceMappingURL=cache-Bih6HxY6.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cache-Bih6HxY6.d.cts","names":[],"sources":["../src/cache.ts"],"sourcesContent":[],"mappings":";;;;;;AAOA;AAqDA;AAA8B,UArDb,uBAAA,CAqDa;EAAA;EACO,KAAoB,EApDjD,KAoDiD;EAAe;;;;;EA+CjC,MAAW,CAAA,EAAA,MAAA;EAAW;;;;EA+BlD,GAQkB,CAAA,EAAA,MAAA;;;;AAlFJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cALZ,uCACS,mCAAmC,6CAI5C,aAAa;;;;;sBAOL;;;;iBAUC,gBAAgB;;;;iBA0BhB,oBAAoB,QAAQ;;;;iBA8BvC,KAAK,yCACZ;;;;gBAQiB,QAAQ;;;;WAOb"}
@@ -1,173 +0,0 @@
1
-
2
- //#region src/cache.ts
3
- /**
4
- * Cache-based audit storage implementation.
5
- * Uses any @geekmidas/cache implementation for storage.
6
- *
7
- * Best suited for:
8
- * - Development and testing
9
- * - Temporary audit logs that don't need persistence
10
- * - Applications with existing cache infrastructure
11
- * - Distributed systems needing shared audit state (with Redis/Upstash)
12
- *
13
- * Note: Query performance may degrade with large numbers of records
14
- * since filtering happens in memory after fetching all records.
15
- *
16
- * @template TAuditAction - Optional type parameter for type-safe audit actions.
17
- *
18
- * @example
19
- * ```typescript
20
- * import { CacheAuditStorage } from '@geekmidas/audit/cache';
21
- * import { InMemoryCache } from '@geekmidas/cache/memory';
22
- * import { UpstashCache } from '@geekmidas/cache/upstash';
23
- *
24
- * // With in-memory cache (development/testing)
25
- * const storage = new CacheAuditStorage({
26
- * cache: new InMemoryCache(),
27
- * ttl: 86400, // 24 hours
28
- * });
29
- *
30
- * // With Upstash Redis (production)
31
- * const storage = new CacheAuditStorage({
32
- * cache: new UpstashCache({
33
- * url: process.env.UPSTASH_REDIS_URL,
34
- * token: process.env.UPSTASH_REDIS_TOKEN,
35
- * }),
36
- * ttl: 604800, // 7 days
37
- * });
38
- * ```
39
- */
40
- var CacheAuditStorage = class {
41
- cache;
42
- prefix;
43
- ttl;
44
- indexKey;
45
- constructor(config) {
46
- this.cache = config.cache;
47
- this.prefix = config.prefix ?? "audit";
48
- this.ttl = config.ttl;
49
- this.indexKey = `${this.prefix}:__index__`;
50
- }
51
- /**
52
- * Write audit records to cache.
53
- */
54
- async write(records) {
55
- if (records.length === 0) return;
56
- const existingIds = await this.cache.get(this.indexKey) ?? [];
57
- const newIds = [];
58
- for (const record of records) {
59
- const key = this.getRecordKey(record.id);
60
- const serialized = this.serializeRecord(record);
61
- await this.cache.set(key, serialized, this.ttl);
62
- newIds.push(record.id);
63
- }
64
- const updatedIds = [...existingIds, ...newIds];
65
- await this.cache.set(this.indexKey, updatedIds, this.ttl);
66
- }
67
- /**
68
- * Query audit records from cache.
69
- */
70
- async query(options) {
71
- const allRecords = await this.getAllRecords();
72
- let results = this.applyFilters(allRecords, options);
73
- const orderBy = options.orderBy ?? "timestamp";
74
- const orderDirection = options.orderDirection ?? "desc";
75
- results.sort((a, b) => {
76
- const aValue = orderBy === "timestamp" ? a.timestamp.getTime() : a.type;
77
- const bValue = orderBy === "timestamp" ? b.timestamp.getTime() : b.type;
78
- if (aValue < bValue) return orderDirection === "asc" ? -1 : 1;
79
- if (aValue > bValue) return orderDirection === "asc" ? 1 : -1;
80
- return 0;
81
- });
82
- if (options.offset !== void 0) results = results.slice(options.offset);
83
- if (options.limit !== void 0) results = results.slice(0, options.limit);
84
- return results;
85
- }
86
- /**
87
- * Count audit records matching filters.
88
- */
89
- async count(options) {
90
- const allRecords = await this.getAllRecords();
91
- return this.applyFilters(allRecords, options).length;
92
- }
93
- /**
94
- * Get all stored records (for testing/debugging).
95
- */
96
- async getRecords() {
97
- return this.getAllRecords();
98
- }
99
- /**
100
- * Clear all stored records.
101
- */
102
- async clear() {
103
- const ids = await this.cache.get(this.indexKey) ?? [];
104
- for (const id of ids) await this.cache.delete(this.getRecordKey(id));
105
- await this.cache.delete(this.indexKey);
106
- }
107
- getRecordKey(id) {
108
- return `${this.prefix}:${id}`;
109
- }
110
- async getAllRecords() {
111
- const ids = await this.cache.get(this.indexKey) ?? [];
112
- const records = [];
113
- const validIds = [];
114
- for (const id of ids) {
115
- const key = this.getRecordKey(id);
116
- const serialized = await this.cache.get(key);
117
- if (serialized) {
118
- records.push(this.deserializeRecord(serialized));
119
- validIds.push(id);
120
- }
121
- }
122
- if (validIds.length !== ids.length) await this.cache.set(this.indexKey, validIds, this.ttl);
123
- return records;
124
- }
125
- serializeRecord(record) {
126
- return {
127
- ...record,
128
- timestamp: record.timestamp.toISOString()
129
- };
130
- }
131
- deserializeRecord(serialized) {
132
- return {
133
- ...serialized,
134
- timestamp: new Date(serialized.timestamp)
135
- };
136
- }
137
- applyFilters(records, options) {
138
- return records.filter((record) => {
139
- if (options.type !== void 0) {
140
- if (Array.isArray(options.type)) {
141
- if (!options.type.includes(record.type)) return false;
142
- } else if (record.type !== options.type) return false;
143
- }
144
- if (options.entityId !== void 0) {
145
- const entityId = typeof options.entityId === "string" ? options.entityId : JSON.stringify(options.entityId);
146
- const recordEntityId = typeof record.entityId === "string" ? record.entityId : JSON.stringify(record.entityId);
147
- if (recordEntityId !== entityId) return false;
148
- }
149
- if (options.table !== void 0) {
150
- if (record.table !== options.table) return false;
151
- }
152
- if (options.actorId !== void 0) {
153
- if (record.actor?.id !== options.actorId) return false;
154
- }
155
- if (options.from !== void 0) {
156
- if (record.timestamp < options.from) return false;
157
- }
158
- if (options.to !== void 0) {
159
- if (record.timestamp > options.to) return false;
160
- }
161
- return true;
162
- });
163
- }
164
- };
165
-
166
- //#endregion
167
- Object.defineProperty(exports, 'CacheAuditStorage', {
168
- enumerable: true,
169
- get: function () {
170
- return CacheAuditStorage;
171
- }
172
- });
173
- //# sourceMappingURL=cache-l7jAptBl.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cache-l7jAptBl.cjs","names":["config: CacheAuditStorageConfig","records: AuditRecord[]","newIds: string[]","options: AuditQueryOptions","options: Omit<AuditQueryOptions, 'limit' | 'offset'>","id: string","validIds: string[]","record: AuditRecord","serialized: SerializedAuditRecord"],"sources":["../src/cache.ts"],"sourcesContent":["import type { Cache } from '@geekmidas/cache';\nimport type { AuditQueryOptions, AuditStorage } from './storage';\nimport type { AuditableAction, AuditRecord } from './types';\n\n/**\n * Configuration for CacheAuditStorage.\n */\nexport interface CacheAuditStorageConfig {\n\t/** Cache instance to use for storage */\n\tcache: Cache;\n\t/**\n\t * Key prefix for audit records.\n\t * Records are stored as `${prefix}:${id}`.\n\t * @default 'audit'\n\t */\n\tprefix?: string;\n\t/**\n\t * TTL (time-to-live) in seconds for audit records.\n\t * If not set, records use the cache's default TTL.\n\t */\n\tttl?: number;\n}\n\n/**\n * Cache-based audit storage implementation.\n * Uses any @geekmidas/cache implementation for storage.\n *\n * Best suited for:\n * - Development and testing\n * - Temporary audit logs that don't need persistence\n * - Applications with existing cache infrastructure\n * - Distributed systems needing shared audit state (with Redis/Upstash)\n *\n * Note: Query performance may degrade with large numbers of records\n * since filtering happens in memory after fetching all records.\n *\n * @template TAuditAction - Optional type parameter for type-safe audit actions.\n *\n * @example\n * ```typescript\n * import { CacheAuditStorage } from '@geekmidas/audit/cache';\n * import { InMemoryCache } from '@geekmidas/cache/memory';\n * import { UpstashCache } from '@geekmidas/cache/upstash';\n *\n * // With in-memory cache (development/testing)\n * const storage = new CacheAuditStorage({\n * cache: new InMemoryCache(),\n * ttl: 86400, // 24 hours\n * });\n *\n * // With Upstash Redis (production)\n * const storage = new CacheAuditStorage({\n * cache: new UpstashCache({\n * url: process.env.UPSTASH_REDIS_URL,\n * token: process.env.UPSTASH_REDIS_TOKEN,\n * }),\n * ttl: 604800, // 7 days\n * });\n * ```\n */\nexport class CacheAuditStorage<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> implements AuditStorage<TAuditAction>\n{\n\tprivate readonly cache: Cache;\n\tprivate readonly prefix: string;\n\tprivate readonly ttl?: number;\n\tprivate readonly indexKey: string;\n\n\tconstructor(config: CacheAuditStorageConfig) {\n\t\tthis.cache = config.cache;\n\t\tthis.prefix = config.prefix ?? 'audit';\n\t\tthis.ttl = config.ttl;\n\t\tthis.indexKey = `${this.prefix}:__index__`;\n\t}\n\n\t/**\n\t * Write audit records to cache.\n\t */\n\tasync write(records: AuditRecord[]): Promise<void> {\n\t\tif (records.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Get existing index\n\t\tconst existingIds = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst newIds: string[] = [];\n\n\t\t// Write each record\n\t\tfor (const record of records) {\n\t\t\tconst key = this.getRecordKey(record.id);\n\t\t\t// Serialize Date to ISO string for cache storage\n\t\t\tconst serialized = this.serializeRecord(record);\n\t\t\tawait this.cache.set(key, serialized, this.ttl);\n\t\t\tnewIds.push(record.id);\n\t\t}\n\n\t\t// Update index with new IDs\n\t\tconst updatedIds = [...existingIds, ...newIds];\n\t\tawait this.cache.set(this.indexKey, updatedIds, this.ttl);\n\t}\n\n\t/**\n\t * Query audit records from cache.\n\t */\n\tasync query(options: AuditQueryOptions): Promise<AuditRecord[]> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\tlet results = this.applyFilters(allRecords, options);\n\n\t\t// Ordering\n\t\tconst orderBy = options.orderBy ?? 'timestamp';\n\t\tconst orderDirection = options.orderDirection ?? 'desc';\n\t\tresults.sort((a, b) => {\n\t\t\tconst aValue = orderBy === 'timestamp' ? a.timestamp.getTime() : a.type;\n\t\t\tconst bValue = orderBy === 'timestamp' ? b.timestamp.getTime() : b.type;\n\t\t\tif (aValue < bValue) return orderDirection === 'asc' ? -1 : 1;\n\t\t\tif (aValue > bValue) return orderDirection === 'asc' ? 1 : -1;\n\t\t\treturn 0;\n\t\t});\n\n\t\t// Pagination\n\t\tif (options.offset !== undefined) {\n\t\t\tresults = results.slice(options.offset);\n\t\t}\n\t\tif (options.limit !== undefined) {\n\t\t\tresults = results.slice(0, options.limit);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Count audit records matching filters.\n\t */\n\tasync count(\n\t\toptions: Omit<AuditQueryOptions, 'limit' | 'offset'>,\n\t): Promise<number> {\n\t\tconst allRecords = await this.getAllRecords();\n\t\treturn this.applyFilters(allRecords, options).length;\n\t}\n\n\t/**\n\t * Get all stored records (for testing/debugging).\n\t */\n\tasync getRecords(): Promise<AuditRecord[]> {\n\t\treturn this.getAllRecords();\n\t}\n\n\t/**\n\t * Clear all stored records.\n\t */\n\tasync clear(): Promise<void> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\n\t\t// Delete all records\n\t\tfor (const id of ids) {\n\t\t\tawait this.cache.delete(this.getRecordKey(id));\n\t\t}\n\n\t\t// Delete index\n\t\tawait this.cache.delete(this.indexKey);\n\t}\n\n\tprivate getRecordKey(id: string): string {\n\t\treturn `${this.prefix}:${id}`;\n\t}\n\n\tprivate async getAllRecords(): Promise<AuditRecord[]> {\n\t\tconst ids = (await this.cache.get<string[]>(this.indexKey)) ?? [];\n\t\tconst records: AuditRecord[] = [];\n\t\tconst validIds: string[] = [];\n\n\t\tfor (const id of ids) {\n\t\t\tconst key = this.getRecordKey(id);\n\t\t\tconst serialized = await this.cache.get<SerializedAuditRecord>(key);\n\t\t\tif (serialized) {\n\t\t\t\trecords.push(this.deserializeRecord(serialized));\n\t\t\t\tvalidIds.push(id);\n\t\t\t}\n\t\t}\n\n\t\t// Clean up index if some records expired\n\t\tif (validIds.length !== ids.length) {\n\t\t\tawait this.cache.set(this.indexKey, validIds, this.ttl);\n\t\t}\n\n\t\treturn records;\n\t}\n\n\tprivate serializeRecord(record: AuditRecord): SerializedAuditRecord {\n\t\treturn {\n\t\t\t...record,\n\t\t\ttimestamp: record.timestamp.toISOString(),\n\t\t};\n\t}\n\n\tprivate deserializeRecord(serialized: SerializedAuditRecord): AuditRecord {\n\t\treturn {\n\t\t\t...serialized,\n\t\t\ttimestamp: new Date(serialized.timestamp),\n\t\t};\n\t}\n\n\tprivate applyFilters(\n\t\trecords: AuditRecord[],\n\t\toptions: AuditQueryOptions,\n\t): AuditRecord[] {\n\t\treturn records.filter((record) => {\n\t\t\t// Type filter\n\t\t\tif (options.type !== undefined) {\n\t\t\t\tif (Array.isArray(options.type)) {\n\t\t\t\t\tif (!options.type.includes(record.type)) return false;\n\t\t\t\t} else {\n\t\t\t\t\tif (record.type !== options.type) return false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Entity ID filter\n\t\t\tif (options.entityId !== undefined) {\n\t\t\t\tconst entityId =\n\t\t\t\t\ttypeof options.entityId === 'string'\n\t\t\t\t\t\t? options.entityId\n\t\t\t\t\t\t: JSON.stringify(options.entityId);\n\t\t\t\tconst recordEntityId =\n\t\t\t\t\ttypeof 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\t\tif (recordEntityId !== entityId) return false;\n\t\t\t}\n\n\t\t\t// Table filter\n\t\t\tif (options.table !== undefined) {\n\t\t\t\tif (record.table !== options.table) return false;\n\t\t\t}\n\n\t\t\t// Actor ID filter\n\t\t\tif (options.actorId !== undefined) {\n\t\t\t\tif (record.actor?.id !== options.actorId) return false;\n\t\t\t}\n\n\t\t\t// Date range filters\n\t\t\tif (options.from !== undefined) {\n\t\t\t\tif (record.timestamp < options.from) return false;\n\t\t\t}\n\t\t\tif (options.to !== undefined) {\n\t\t\t\tif (record.timestamp > options.to) return false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\t}\n}\n\n/**\n * Serialized version of AuditRecord for cache storage.\n * Dates are stored as ISO strings.\n */\ntype SerializedAuditRecord = Omit<AuditRecord, 'timestamp'> & {\n\ttimestamp: string;\n};\n"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