@zero-server/sdk 0.9.1 → 0.9.3

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 (128) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +460 -443
  3. package/index.js +414 -412
  4. package/lib/app.js +1172 -1172
  5. package/lib/auth/authorize.js +399 -399
  6. package/lib/auth/enrollment.js +367 -367
  7. package/lib/auth/index.js +57 -57
  8. package/lib/auth/jwt.js +731 -731
  9. package/lib/auth/oauth.js +362 -362
  10. package/lib/auth/session.js +588 -588
  11. package/lib/auth/trustedDevice.js +409 -409
  12. package/lib/auth/twoFactor.js +1150 -1150
  13. package/lib/auth/webauthn.js +946 -946
  14. package/lib/body/index.js +14 -14
  15. package/lib/body/json.js +109 -109
  16. package/lib/body/multipart.js +440 -440
  17. package/lib/body/raw.js +71 -71
  18. package/lib/body/rawBuffer.js +160 -160
  19. package/lib/body/sendError.js +25 -25
  20. package/lib/body/text.js +75 -75
  21. package/lib/body/typeMatch.js +41 -41
  22. package/lib/body/urlencoded.js +235 -235
  23. package/lib/cli.js +845 -845
  24. package/lib/cluster.js +666 -666
  25. package/lib/debug.js +372 -372
  26. package/lib/env/index.js +465 -465
  27. package/lib/errors.js +683 -683
  28. package/lib/fetch/index.js +256 -256
  29. package/lib/grpc/balancer.js +378 -378
  30. package/lib/grpc/call.js +708 -708
  31. package/lib/grpc/client.js +764 -764
  32. package/lib/grpc/codec.js +1221 -1221
  33. package/lib/grpc/credentials.js +398 -398
  34. package/lib/grpc/frame.js +262 -262
  35. package/lib/grpc/health.js +287 -287
  36. package/lib/grpc/index.js +121 -121
  37. package/lib/grpc/metadata.js +461 -461
  38. package/lib/grpc/proto.js +821 -821
  39. package/lib/grpc/reflection.js +590 -590
  40. package/lib/grpc/server.js +445 -445
  41. package/lib/grpc/status.js +118 -118
  42. package/lib/grpc/watch.js +173 -173
  43. package/lib/http/index.js +10 -10
  44. package/lib/http/request.js +727 -727
  45. package/lib/http/response.js +799 -799
  46. package/lib/lifecycle.js +557 -557
  47. package/lib/middleware/compress.js +230 -230
  48. package/lib/middleware/cookieParser.js +237 -237
  49. package/lib/middleware/cors.js +93 -93
  50. package/lib/middleware/csrf.js +137 -137
  51. package/lib/middleware/errorHandler.js +101 -101
  52. package/lib/middleware/helmet.js +175 -175
  53. package/lib/middleware/index.js +19 -17
  54. package/lib/middleware/logger.js +74 -74
  55. package/lib/middleware/rateLimit.js +88 -88
  56. package/lib/middleware/requestId.js +53 -53
  57. package/lib/middleware/static.js +326 -326
  58. package/lib/middleware/timeout.js +71 -71
  59. package/lib/middleware/validator.js +255 -255
  60. package/lib/observe/health.js +326 -326
  61. package/lib/observe/index.js +50 -50
  62. package/lib/observe/logger.js +359 -359
  63. package/lib/observe/metrics.js +805 -805
  64. package/lib/observe/tracing.js +592 -592
  65. package/lib/orm/adapters/json.js +290 -290
  66. package/lib/orm/adapters/memory.js +764 -764
  67. package/lib/orm/adapters/mongo.js +764 -764
  68. package/lib/orm/adapters/mysql.js +933 -933
  69. package/lib/orm/adapters/postgres.js +1144 -1144
  70. package/lib/orm/adapters/redis.js +1534 -1534
  71. package/lib/orm/adapters/sql-base.js +212 -212
  72. package/lib/orm/adapters/sqlite.js +858 -858
  73. package/lib/orm/audit.js +649 -649
  74. package/lib/orm/cache.js +394 -394
  75. package/lib/orm/geo.js +387 -387
  76. package/lib/orm/index.js +784 -784
  77. package/lib/orm/migrate.js +432 -432
  78. package/lib/orm/model.js +1706 -1706
  79. package/lib/orm/plugin.js +375 -375
  80. package/lib/orm/procedures.js +836 -836
  81. package/lib/orm/profiler.js +233 -233
  82. package/lib/orm/query.js +1772 -1772
  83. package/lib/orm/replicas.js +241 -241
  84. package/lib/orm/schema.js +307 -307
  85. package/lib/orm/search.js +380 -380
  86. package/lib/orm/seed/data/commerce.js +136 -136
  87. package/lib/orm/seed/data/internet.js +111 -111
  88. package/lib/orm/seed/data/locations.js +204 -204
  89. package/lib/orm/seed/data/names.js +338 -338
  90. package/lib/orm/seed/data/person.js +128 -128
  91. package/lib/orm/seed/data/phone.js +211 -211
  92. package/lib/orm/seed/data/words.js +134 -134
  93. package/lib/orm/seed/factory.js +178 -178
  94. package/lib/orm/seed/fake.js +1186 -1186
  95. package/lib/orm/seed/index.js +18 -18
  96. package/lib/orm/seed/rng.js +70 -70
  97. package/lib/orm/seed/seeder.js +124 -124
  98. package/lib/orm/seed/unique.js +68 -68
  99. package/lib/orm/snapshot.js +366 -366
  100. package/lib/orm/tenancy.js +605 -605
  101. package/lib/orm/views.js +350 -350
  102. package/lib/router/index.js +436 -436
  103. package/lib/sse/index.js +8 -8
  104. package/lib/sse/stream.js +349 -349
  105. package/lib/ws/connection.js +451 -451
  106. package/lib/ws/handshake.js +125 -125
  107. package/lib/ws/index.js +14 -14
  108. package/lib/ws/room.js +223 -223
  109. package/package.json +73 -73
  110. package/types/app.d.ts +223 -223
  111. package/types/auth.d.ts +520 -520
  112. package/types/body.d.ts +14 -0
  113. package/types/cli.d.ts +2 -0
  114. package/types/cluster.d.ts +75 -75
  115. package/types/env.d.ts +80 -80
  116. package/types/errors.d.ts +316 -316
  117. package/types/fetch.d.ts +43 -43
  118. package/types/grpc.d.ts +432 -432
  119. package/types/index.d.ts +384 -384
  120. package/types/lifecycle.d.ts +60 -60
  121. package/types/middleware.d.ts +320 -320
  122. package/types/observe.d.ts +304 -304
  123. package/types/orm.d.ts +1887 -1887
  124. package/types/request.d.ts +109 -109
  125. package/types/response.d.ts +157 -157
  126. package/types/router.d.ts +78 -78
  127. package/types/sse.d.ts +78 -78
  128. package/types/websocket.d.ts +126 -126
package/lib/orm/audit.js CHANGED
@@ -1,649 +1,649 @@
1
- /**
2
- * @module orm/audit
3
- * @description Automatic audit logging for the ORM.
4
- * Tracks who changed what and when, with diff-based change logs.
5
- * Supports storing audit trails in the same database or a separate one
6
- * and provides querying capabilities for the audit trail.
7
- *
8
- * @example
9
- * const { AuditLog } = require('@zero-server/sdk');
10
- *
11
- * const audit = new AuditLog(db, {
12
- * actorField: 'userId', // field on req/context identifying the actor
13
- * include: [User, Post], // models to audit
14
- * });
15
- *
16
- * // Automatically tracks creates, updates, and deletes
17
- * await User.create({ name: 'Alice' }); // audit entry logged
18
- *
19
- * // Query audit trail
20
- * const trail = await audit.trail({ table: 'users', recordId: 1 });
21
- */
22
-
23
- const log = require('../debug')('zero:orm:audit');
24
-
25
- // -- AuditLog class ------------------------------------------
26
-
27
- /**
28
- * Automatic change tracking for ORM models.
29
- * Records who changed what and when, with diff-based change logs.
30
- */
31
- class AuditLog
32
- {
33
- /**
34
- * @constructor
35
- * @param {import('./index').Database} db - Database instance for storing audit entries.
36
- * @param {object} options - Audit configuration.
37
- * @param {string} [options.table='_audit_log'] - Table name for audit entries.
38
- * @param {Array<typeof import('./model')>} [options.include] - Models to audit (all registered if omitted).
39
- * @param {Array<typeof import('./model')>} [options.exclude] - Models to exclude from auditing.
40
- * @param {string[]} [options.excludeFields] - Fields to never log (e.g. passwords).
41
- * @param {string} [options.actorField] - Context property for the actor identifier.
42
- * @param {import('./index').Database} [options.storage] - Separate database for audit storage.
43
- * @param {boolean} [options.timestamps=true] - Include timestamps in audit entries.
44
- * @param {boolean} [options.diffs=true] - Store field-level diffs for updates.
45
- *
46
- * @example
47
- * const audit = new AuditLog(db, {
48
- * table: '_audit_log',
49
- * include: [User, Post],
50
- * excludeFields: ['password', 'token'],
51
- * diffs: true,
52
- * });
53
- */
54
- constructor(db, options = {})
55
- {
56
- if (!db) throw new Error('AuditLog requires a Database instance');
57
-
58
- /** @type {import('./index').Database} */
59
- this.db = db;
60
-
61
- /** @type {string} */
62
- this.tableName = options.table || '_audit_log';
63
-
64
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.tableName))
65
- {
66
- throw new Error(`Invalid audit table name: "${this.tableName}"`);
67
- }
68
-
69
- /** @type {Set<typeof import('./model')>|null} */
70
- this._include = options.include ? new Set(options.include) : null;
71
-
72
- /** @type {Set<typeof import('./model')>} */
73
- this._exclude = new Set(options.exclude || []);
74
-
75
- /** @type {Set<string>} */
76
- this._excludeFields = new Set(options.excludeFields || []);
77
-
78
- /** @type {string|null} */
79
- this._actorField = options.actorField || null;
80
-
81
- /** @type {import('./index').Database} */
82
- this._storage = options.storage || db;
83
-
84
- /** @type {boolean} */
85
- this._timestamps = options.timestamps !== false;
86
-
87
- /** @type {boolean} */
88
- this._diffs = options.diffs !== false;
89
-
90
- /** @type {string|null} Current actor for audit entries. */
91
- this._currentActor = null;
92
-
93
- /** @type {boolean} */
94
- this._initialized = false;
95
-
96
- /** @type {Set<typeof import('./model')>} Models currently being audited. */
97
- this._auditedModels = new Set();
98
-
99
- log('AuditLog created', { table: this.tableName });
100
- }
101
-
102
- // -- Setup -------------------------------------------
103
-
104
- /**
105
- * Initialize the audit log table and attach hooks to models.
106
- * Must be called after models are registered and synced.
107
- *
108
- * @returns {Promise<AuditLog>} this (for chaining)
109
- *
110
- * @example
111
- * await audit.install();
112
- */
113
- async install()
114
- {
115
- // Create the audit log table
116
- const adapter = this._storage.adapter;
117
-
118
- if (typeof adapter.execute === 'function')
119
- {
120
- // SQL adapter
121
- const sql =
122
- `CREATE TABLE IF NOT EXISTS "${this.tableName}" (` +
123
- `"id" INTEGER PRIMARY KEY ${adapter.constructor.name === 'PostgresAdapter' ? 'GENERATED ALWAYS AS IDENTITY' : 'AUTOINCREMENT'},` +
124
- `"action" TEXT NOT NULL,` +
125
- `"table_name" TEXT NOT NULL,` +
126
- `"record_id" TEXT,` +
127
- `"actor" TEXT,` +
128
- `"old_values" TEXT,` +
129
- `"new_values" TEXT,` +
130
- `"diff" TEXT,` +
131
- `"timestamp" TEXT NOT NULL DEFAULT (datetime('now'))` +
132
- `)`;
133
- await adapter.execute({ raw: sql });
134
- }
135
- else
136
- {
137
- // Memory/JSON adapter — ensure table structure
138
- if (typeof adapter.createTable === 'function')
139
- {
140
- const schema = {
141
- id: { type: 'integer', primaryKey: true, autoIncrement: true },
142
- action: { type: 'string', required: true },
143
- table_name: { type: 'string', required: true },
144
- record_id: { type: 'string' },
145
- actor: { type: 'string' },
146
- old_values: { type: 'text' },
147
- new_values: { type: 'text' },
148
- diff: { type: 'text' },
149
- timestamp: { type: 'string' },
150
- };
151
- await adapter.createTable(this.tableName, schema);
152
- }
153
- }
154
-
155
- // Attach hooks to models
156
- const models = this._include
157
- ? [...this._include]
158
- : [...this.db._models.values()];
159
-
160
- for (const ModelClass of models)
161
- {
162
- if (this._exclude.has(ModelClass)) continue;
163
- this._attachHooks(ModelClass);
164
- }
165
-
166
- this._initialized = true;
167
- log('AuditLog installed', { models: this._auditedModels.size });
168
- return this;
169
- }
170
-
171
- // -- Actor Management --------------------------------
172
-
173
- /**
174
- * Set the current actor (user) performing operations.
175
- *
176
- * @param {string} actor - Actor identifier (user ID, email, etc.).
177
- * @returns {AuditLog} this (for chaining)
178
- *
179
- * @example
180
- * audit.setActor('user-123');
181
- */
182
- setActor(actor)
183
- {
184
- this._currentActor = actor != null ? String(actor) : null;
185
- return this;
186
- }
187
-
188
- /**
189
- * Get the current actor.
190
- *
191
- * @returns {string|null} Current actor identifier.
192
- */
193
- getActor()
194
- {
195
- return this._currentActor;
196
- }
197
-
198
- /**
199
- * Execute a function within a specific actor context.
200
- *
201
- * @param {string} actor - Actor identifier.
202
- * @param {Function} fn - Async callback.
203
- * @returns {Promise<*>} Result of fn().
204
- *
205
- * @example
206
- * await audit.withActor('admin', async () => {
207
- * await User.create({ name: 'New User' });
208
- * });
209
- */
210
- async withActor(actor, fn)
211
- {
212
- const prev = this._currentActor;
213
- this.setActor(actor);
214
- try
215
- {
216
- return await fn();
217
- }
218
- finally
219
- {
220
- this._currentActor = prev;
221
- }
222
- }
223
-
224
- // -- Hook Attachment ---------------------------------
225
-
226
- /**
227
- * @private
228
- * Attach lifecycle hooks to a model for audit logging.
229
- */
230
- _attachHooks(ModelClass)
231
- {
232
- if (this._auditedModels.has(ModelClass)) return;
233
- this._auditedModels.add(ModelClass);
234
-
235
- const audit = this;
236
- const table = ModelClass.table || ModelClass.name;
237
-
238
- // Use model events if available
239
- if (typeof ModelClass.on === 'function')
240
- {
241
- ModelClass.on('created', (instance) =>
242
- {
243
- audit._logEntry('create', table, instance).catch(() => {});
244
- });
245
-
246
- ModelClass.on('updated', (instance) =>
247
- {
248
- audit._logEntry('update', table, instance).catch(() => {});
249
- });
250
-
251
- ModelClass.on('deleted', (instance) =>
252
- {
253
- audit._logEntry('delete', table, instance).catch(() => {});
254
- });
255
- }
256
- else
257
- {
258
- // Fallback: patch static methods
259
- const origCreate = ModelClass.create.bind(ModelClass);
260
- ModelClass.create = async function (data)
261
- {
262
- const result = await origCreate(data);
263
- await audit._logEntry('create', table, result);
264
- return result;
265
- };
266
- }
267
-
268
- log('hooks attached', table);
269
- }
270
-
271
- // -- Entry Logging -----------------------------------
272
-
273
- /**
274
- * @private
275
- * Log a single audit entry.
276
- */
277
- async _logEntry(action, tableName, instance)
278
- {
279
- try
280
- {
281
- const pk = this._extractPK(instance);
282
- const filtered = this._filterFields(instance);
283
-
284
- const entry = {
285
- action,
286
- table_name: tableName,
287
- record_id: pk != null ? String(pk) : null,
288
- actor: this._currentActor,
289
- timestamp: new Date().toISOString(),
290
- };
291
-
292
- if (action === 'create')
293
- {
294
- entry.old_values = null;
295
- entry.new_values = JSON.stringify(filtered);
296
- entry.diff = null;
297
- }
298
- else if (action === 'update')
299
- {
300
- const original = instance._original || {};
301
- const oldFiltered = this._filterFields(original);
302
- entry.old_values = JSON.stringify(oldFiltered);
303
- entry.new_values = JSON.stringify(filtered);
304
-
305
- if (this._diffs)
306
- {
307
- entry.diff = JSON.stringify(this._computeDiff(oldFiltered, filtered));
308
- }
309
- }
310
- else if (action === 'delete')
311
- {
312
- entry.old_values = JSON.stringify(filtered);
313
- entry.new_values = null;
314
- entry.diff = null;
315
- }
316
-
317
- await this._writeEntry(entry);
318
- }
319
- catch (err)
320
- {
321
- log('audit entry failed', err.message);
322
- }
323
- }
324
-
325
- /**
326
- * @private
327
- * Write an audit entry to storage.
328
- */
329
- async _writeEntry(entry)
330
- {
331
- const adapter = this._storage.adapter;
332
-
333
- if (typeof adapter.execute === 'function')
334
- {
335
- // SQL adapter
336
- await adapter.execute({
337
- action: 'insert',
338
- table: this.tableName,
339
- data: entry,
340
- });
341
- }
342
- else if (typeof adapter.insert === 'function')
343
- {
344
- await adapter.insert(this.tableName, entry);
345
- }
346
- }
347
-
348
- /**
349
- * @private
350
- * Extract primary key value from an instance.
351
- */
352
- _extractPK(instance)
353
- {
354
- if (!instance) return null;
355
-
356
- // Handle plain objects and model instances
357
- const data = typeof instance.toJSON === 'function' ? instance.toJSON() : instance;
358
- return data.id || data._id || null;
359
- }
360
-
361
- /**
362
- * @private
363
- * Filter out excluded fields from data.
364
- */
365
- _filterFields(data)
366
- {
367
- if (!data || typeof data !== 'object') return {};
368
-
369
- const source = typeof data.toJSON === 'function' ? data.toJSON() : { ...data };
370
- const result = {};
371
-
372
- for (const [key, value] of Object.entries(source))
373
- {
374
- if (key.startsWith('_')) continue;
375
- if (this._excludeFields.has(key)) continue;
376
- result[key] = value;
377
- }
378
-
379
- return result;
380
- }
381
-
382
- // -- Diff Computation --------------------------------
383
-
384
- /**
385
- * Compute a diff between old and new values.
386
- * Returns an array of `{ field, from, to }` objects.
387
- *
388
- * @param {object} oldValues - Previous data.
389
- * @param {object} newValues - Current data.
390
- * @returns {Array<{field: string, from: *, to: *}>}
391
- *
392
- * @example
393
- * const diff = audit.diff({ name: 'Alice' }, { name: 'Bob' });
394
- * // [{ field: 'name', from: 'Alice', to: 'Bob' }]
395
- */
396
- diff(oldValues, newValues)
397
- {
398
- return this._computeDiff(oldValues, newValues);
399
- }
400
-
401
- /**
402
- * @private
403
- */
404
- _computeDiff(oldValues, newValues)
405
- {
406
- const changes = [];
407
- const allKeys = new Set([
408
- ...Object.keys(oldValues || {}),
409
- ...Object.keys(newValues || {}),
410
- ]);
411
-
412
- for (const key of allKeys)
413
- {
414
- const oldVal = oldValues ? oldValues[key] : undefined;
415
- const newVal = newValues ? newValues[key] : undefined;
416
-
417
- // Deep equality via JSON comparison for objects/arrays
418
- const oldStr = JSON.stringify(oldVal);
419
- const newStr = JSON.stringify(newVal);
420
-
421
- if (oldStr !== newStr)
422
- {
423
- changes.push({ field: key, from: oldVal, to: newVal });
424
- }
425
- }
426
-
427
- return changes;
428
- }
429
-
430
- // -- Querying Audit Trail ----------------------------
431
-
432
- /**
433
- * Query the audit trail.
434
- *
435
- * @param {object} [options] - Filter options.
436
- * @param {string} [options.table] - Filter by table name.
437
- * @param {string} [options.action] - Filter by action (create, update, delete).
438
- * @param {string} [options.recordId] - Filter by record ID.
439
- * @param {string} [options.actor] - Filter by actor.
440
- * @param {string} [options.since] - ISO timestamp lower bound.
441
- * @param {string} [options.until] - ISO timestamp upper bound.
442
- * @param {number} [options.limit=100] - Maximum entries.
443
- * @param {number} [options.offset=0] - Skip entries.
444
- * @param {string} [options.order='desc'] - Sort order by timestamp.
445
- * @returns {Promise<Array>} Audit entries.
446
- *
447
- * @example
448
- * const entries = await audit.trail({ table: 'users', recordId: '1' });
449
- * const updates = await audit.trail({ action: 'update', limit: 50 });
450
- */
451
- async trail(options = {})
452
- {
453
- const { table, action, recordId, actor, since, until, limit = 100, offset = 0, order = 'desc' } = options;
454
- const adapter = this._storage.adapter;
455
-
456
- const where = [];
457
- if (table) where.push({ field: 'table_name', op: '=', value: table });
458
- if (action) where.push({ field: 'action', op: '=', value: action });
459
- if (recordId) where.push({ field: 'record_id', op: '=', value: String(recordId) });
460
- if (actor) where.push({ field: 'actor', op: '=', value: actor });
461
- if (since) where.push({ field: 'timestamp', op: '>=', value: since });
462
- if (until) where.push({ field: 'timestamp', op: '<=', value: until });
463
-
464
- const descriptor = {
465
- action: 'find',
466
- table: this.tableName,
467
- where,
468
- orderBy: [{ field: 'timestamp', direction: order }],
469
- limit,
470
- offset,
471
- };
472
-
473
- let rows;
474
- if (typeof adapter.execute === 'function')
475
- {
476
- rows = await adapter.execute(descriptor);
477
- }
478
- else if (typeof adapter.find === 'function')
479
- {
480
- rows = await adapter.find(this.tableName, descriptor);
481
- }
482
- else
483
- {
484
- rows = [];
485
- }
486
-
487
- // Parse JSON fields
488
- return (rows || []).map(row => ({
489
- ...row,
490
- old_values: row.old_values ? JSON.parse(row.old_values) : null,
491
- new_values: row.new_values ? JSON.parse(row.new_values) : null,
492
- diff: row.diff ? JSON.parse(row.diff) : null,
493
- }));
494
- }
495
-
496
- /**
497
- * Get the audit history for a specific record.
498
- *
499
- * @param {string} table - Table name.
500
- * @param {string|number} recordId - Record ID.
501
- * @param {object} [options] - Additional filter options.
502
- * @returns {Promise<Array>} Audit entries for the record.
503
- *
504
- * @example
505
- * const history = await audit.history('users', 1);
506
- */
507
- async history(table, recordId, options = {})
508
- {
509
- return this.trail({ ...options, table, recordId: String(recordId) });
510
- }
511
-
512
- /**
513
- * Get audit entries grouped by actor.
514
- *
515
- * @param {object} [options] - Filter options.
516
- * @returns {Promise<Map<string, Array>>} Map of actor → entries.
517
- */
518
- async byActor(options = {})
519
- {
520
- const entries = await this.trail({ ...options, limit: options.limit || 1000 });
521
- const grouped = new Map();
522
-
523
- for (const entry of entries)
524
- {
525
- const actor = entry.actor || '__unknown__';
526
- if (!grouped.has(actor)) grouped.set(actor, []);
527
- grouped.get(actor).push(entry);
528
- }
529
-
530
- return grouped;
531
- }
532
-
533
- /**
534
- * Count audit entries matching the given filters.
535
- *
536
- * @param {object} [options] - Same filter options as trail().
537
- * @returns {Promise<number>}
538
- *
539
- * @example
540
- * const count = await audit.count({ table: 'users', action: 'update' });
541
- */
542
- async count(options = {})
543
- {
544
- const { table, action, recordId, actor, since, until } = options;
545
- const adapter = this._storage.adapter;
546
-
547
- const where = [];
548
- if (table) where.push({ field: 'table_name', op: '=', value: table });
549
- if (action) where.push({ field: 'action', op: '=', value: action });
550
- if (recordId) where.push({ field: 'record_id', op: '=', value: String(recordId) });
551
- if (actor) where.push({ field: 'actor', op: '=', value: actor });
552
- if (since) where.push({ field: 'timestamp', op: '>=', value: since });
553
- if (until) where.push({ field: 'timestamp', op: '<=', value: until });
554
-
555
- if (typeof adapter.execute === 'function')
556
- {
557
- const result = await adapter.execute({
558
- action: 'count',
559
- table: this.tableName,
560
- where,
561
- });
562
- return typeof result === 'number' ? result : (result && result[0] ? result[0].count || 0 : 0);
563
- }
564
-
565
- // Fallback: fetch all and count
566
- const entries = await this.trail(options);
567
- return entries.length;
568
- }
569
-
570
- /**
571
- * Purge old audit entries.
572
- *
573
- * @param {object} options - Purge options.
574
- * @param {string} [options.before] - ISO timestamp; delete entries older than this.
575
- * @param {string} [options.table] - Only purge entries for this table.
576
- * @param {number} [options.keepLast] - Keep at least this many entries per record.
577
- * @returns {Promise<number>} Number of entries purged.
578
- *
579
- * @example
580
- * const purged = await audit.purge({ before: '2025-01-01T00:00:00Z' });
581
- */
582
- async purge(options = {})
583
- {
584
- const { before, table } = options;
585
- const adapter = this._storage.adapter;
586
-
587
- const where = [];
588
- if (before) where.push({ field: 'timestamp', op: '<', value: before });
589
- if (table) where.push({ field: 'table_name', op: '=', value: table });
590
-
591
- if (where.length === 0)
592
- {
593
- throw new Error('purge() requires at least one filter (before or table)');
594
- }
595
-
596
- if (typeof adapter.execute === 'function')
597
- {
598
- const result = await adapter.execute({
599
- action: 'delete',
600
- table: this.tableName,
601
- where,
602
- });
603
- const count = typeof result === 'number' ? result : (result && result.changes ? result.changes : 0);
604
- log('purged entries', count);
605
- return count;
606
- }
607
-
608
- return 0;
609
- }
610
-
611
- /**
612
- * Returns an HTTP middleware that sets the actor from the request.
613
- *
614
- * @param {object} [options] - Options.
615
- * @param {Function} [options.extract] - Custom `(req) => actorId` function.
616
- * @param {string} [options.header='x-user-id'] - Header to read actor from.
617
- * @returns {Function} Middleware `(req, res, next) => {}`.
618
- *
619
- * @example
620
- * app.use(audit.middleware({ extract: (req) => req.user?.id }));
621
- */
622
- middleware(options = {})
623
- {
624
- const { extract, header = 'x-user-id' } = options;
625
- const auditLog = this;
626
-
627
- return function auditMiddleware(req, res, next)
628
- {
629
- let actor;
630
- if (typeof extract === 'function')
631
- {
632
- actor = extract(req);
633
- }
634
- else if (header && req.headers)
635
- {
636
- actor = req.headers[header.toLowerCase()];
637
- }
638
-
639
- if (actor)
640
- {
641
- auditLog.setActor(String(actor));
642
- }
643
-
644
- next();
645
- };
646
- }
647
- }
648
-
649
- module.exports = { AuditLog };
1
+ /**
2
+ * @module orm/audit
3
+ * @description Automatic audit logging for the ORM.
4
+ * Tracks who changed what and when, with diff-based change logs.
5
+ * Supports storing audit trails in the same database or a separate one
6
+ * and provides querying capabilities for the audit trail.
7
+ *
8
+ * @example
9
+ * const { AuditLog } = require('@zero-server/sdk');
10
+ *
11
+ * const audit = new AuditLog(db, {
12
+ * actorField: 'userId', // field on req/context identifying the actor
13
+ * include: [User, Post], // models to audit
14
+ * });
15
+ *
16
+ * // Automatically tracks creates, updates, and deletes
17
+ * await User.create({ name: 'Alice' }); // audit entry logged
18
+ *
19
+ * // Query audit trail
20
+ * const trail = await audit.trail({ table: 'users', recordId: 1 });
21
+ */
22
+
23
+ const log = require('../debug')('zero:orm:audit');
24
+
25
+ // -- AuditLog class ------------------------------------------
26
+
27
+ /**
28
+ * Automatic change tracking for ORM models.
29
+ * Records who changed what and when, with diff-based change logs.
30
+ */
31
+ class AuditLog
32
+ {
33
+ /**
34
+ * @constructor
35
+ * @param {import('./index').Database} db - Database instance for storing audit entries.
36
+ * @param {object} options - Audit configuration.
37
+ * @param {string} [options.table='_audit_log'] - Table name for audit entries.
38
+ * @param {Array<typeof import('./model')>} [options.include] - Models to audit (all registered if omitted).
39
+ * @param {Array<typeof import('./model')>} [options.exclude] - Models to exclude from auditing.
40
+ * @param {string[]} [options.excludeFields] - Fields to never log (e.g. passwords).
41
+ * @param {string} [options.actorField] - Context property for the actor identifier.
42
+ * @param {import('./index').Database} [options.storage] - Separate database for audit storage.
43
+ * @param {boolean} [options.timestamps=true] - Include timestamps in audit entries.
44
+ * @param {boolean} [options.diffs=true] - Store field-level diffs for updates.
45
+ *
46
+ * @example
47
+ * const audit = new AuditLog(db, {
48
+ * table: '_audit_log',
49
+ * include: [User, Post],
50
+ * excludeFields: ['password', 'token'],
51
+ * diffs: true,
52
+ * });
53
+ */
54
+ constructor(db, options = {})
55
+ {
56
+ if (!db) throw new Error('AuditLog requires a Database instance');
57
+
58
+ /** @type {import('./index').Database} */
59
+ this.db = db;
60
+
61
+ /** @type {string} */
62
+ this.tableName = options.table || '_audit_log';
63
+
64
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.tableName))
65
+ {
66
+ throw new Error(`Invalid audit table name: "${this.tableName}"`);
67
+ }
68
+
69
+ /** @type {Set<typeof import('./model')>|null} */
70
+ this._include = options.include ? new Set(options.include) : null;
71
+
72
+ /** @type {Set<typeof import('./model')>} */
73
+ this._exclude = new Set(options.exclude || []);
74
+
75
+ /** @type {Set<string>} */
76
+ this._excludeFields = new Set(options.excludeFields || []);
77
+
78
+ /** @type {string|null} */
79
+ this._actorField = options.actorField || null;
80
+
81
+ /** @type {import('./index').Database} */
82
+ this._storage = options.storage || db;
83
+
84
+ /** @type {boolean} */
85
+ this._timestamps = options.timestamps !== false;
86
+
87
+ /** @type {boolean} */
88
+ this._diffs = options.diffs !== false;
89
+
90
+ /** @type {string|null} Current actor for audit entries. */
91
+ this._currentActor = null;
92
+
93
+ /** @type {boolean} */
94
+ this._initialized = false;
95
+
96
+ /** @type {Set<typeof import('./model')>} Models currently being audited. */
97
+ this._auditedModels = new Set();
98
+
99
+ log('AuditLog created', { table: this.tableName });
100
+ }
101
+
102
+ // -- Setup -------------------------------------------
103
+
104
+ /**
105
+ * Initialize the audit log table and attach hooks to models.
106
+ * Must be called after models are registered and synced.
107
+ *
108
+ * @returns {Promise<AuditLog>} this (for chaining)
109
+ *
110
+ * @example
111
+ * await audit.install();
112
+ */
113
+ async install()
114
+ {
115
+ // Create the audit log table
116
+ const adapter = this._storage.adapter;
117
+
118
+ if (typeof adapter.execute === 'function')
119
+ {
120
+ // SQL adapter
121
+ const sql =
122
+ `CREATE TABLE IF NOT EXISTS "${this.tableName}" (` +
123
+ `"id" INTEGER PRIMARY KEY ${adapter.constructor.name === 'PostgresAdapter' ? 'GENERATED ALWAYS AS IDENTITY' : 'AUTOINCREMENT'},` +
124
+ `"action" TEXT NOT NULL,` +
125
+ `"table_name" TEXT NOT NULL,` +
126
+ `"record_id" TEXT,` +
127
+ `"actor" TEXT,` +
128
+ `"old_values" TEXT,` +
129
+ `"new_values" TEXT,` +
130
+ `"diff" TEXT,` +
131
+ `"timestamp" TEXT NOT NULL DEFAULT (datetime('now'))` +
132
+ `)`;
133
+ await adapter.execute({ raw: sql });
134
+ }
135
+ else
136
+ {
137
+ // Memory/JSON adapter — ensure table structure
138
+ if (typeof adapter.createTable === 'function')
139
+ {
140
+ const schema = {
141
+ id: { type: 'integer', primaryKey: true, autoIncrement: true },
142
+ action: { type: 'string', required: true },
143
+ table_name: { type: 'string', required: true },
144
+ record_id: { type: 'string' },
145
+ actor: { type: 'string' },
146
+ old_values: { type: 'text' },
147
+ new_values: { type: 'text' },
148
+ diff: { type: 'text' },
149
+ timestamp: { type: 'string' },
150
+ };
151
+ await adapter.createTable(this.tableName, schema);
152
+ }
153
+ }
154
+
155
+ // Attach hooks to models
156
+ const models = this._include
157
+ ? [...this._include]
158
+ : [...this.db._models.values()];
159
+
160
+ for (const ModelClass of models)
161
+ {
162
+ if (this._exclude.has(ModelClass)) continue;
163
+ this._attachHooks(ModelClass);
164
+ }
165
+
166
+ this._initialized = true;
167
+ log('AuditLog installed', { models: this._auditedModels.size });
168
+ return this;
169
+ }
170
+
171
+ // -- Actor Management --------------------------------
172
+
173
+ /**
174
+ * Set the current actor (user) performing operations.
175
+ *
176
+ * @param {string} actor - Actor identifier (user ID, email, etc.).
177
+ * @returns {AuditLog} this (for chaining)
178
+ *
179
+ * @example
180
+ * audit.setActor('user-123');
181
+ */
182
+ setActor(actor)
183
+ {
184
+ this._currentActor = actor != null ? String(actor) : null;
185
+ return this;
186
+ }
187
+
188
+ /**
189
+ * Get the current actor.
190
+ *
191
+ * @returns {string|null} Current actor identifier.
192
+ */
193
+ getActor()
194
+ {
195
+ return this._currentActor;
196
+ }
197
+
198
+ /**
199
+ * Execute a function within a specific actor context.
200
+ *
201
+ * @param {string} actor - Actor identifier.
202
+ * @param {Function} fn - Async callback.
203
+ * @returns {Promise<*>} Result of fn().
204
+ *
205
+ * @example
206
+ * await audit.withActor('admin', async () => {
207
+ * await User.create({ name: 'New User' });
208
+ * });
209
+ */
210
+ async withActor(actor, fn)
211
+ {
212
+ const prev = this._currentActor;
213
+ this.setActor(actor);
214
+ try
215
+ {
216
+ return await fn();
217
+ }
218
+ finally
219
+ {
220
+ this._currentActor = prev;
221
+ }
222
+ }
223
+
224
+ // -- Hook Attachment ---------------------------------
225
+
226
+ /**
227
+ * @private
228
+ * Attach lifecycle hooks to a model for audit logging.
229
+ */
230
+ _attachHooks(ModelClass)
231
+ {
232
+ if (this._auditedModels.has(ModelClass)) return;
233
+ this._auditedModels.add(ModelClass);
234
+
235
+ const audit = this;
236
+ const table = ModelClass.table || ModelClass.name;
237
+
238
+ // Use model events if available
239
+ if (typeof ModelClass.on === 'function')
240
+ {
241
+ ModelClass.on('created', (instance) =>
242
+ {
243
+ audit._logEntry('create', table, instance).catch(() => {});
244
+ });
245
+
246
+ ModelClass.on('updated', (instance) =>
247
+ {
248
+ audit._logEntry('update', table, instance).catch(() => {});
249
+ });
250
+
251
+ ModelClass.on('deleted', (instance) =>
252
+ {
253
+ audit._logEntry('delete', table, instance).catch(() => {});
254
+ });
255
+ }
256
+ else
257
+ {
258
+ // Fallback: patch static methods
259
+ const origCreate = ModelClass.create.bind(ModelClass);
260
+ ModelClass.create = async function (data)
261
+ {
262
+ const result = await origCreate(data);
263
+ await audit._logEntry('create', table, result);
264
+ return result;
265
+ };
266
+ }
267
+
268
+ log('hooks attached', table);
269
+ }
270
+
271
+ // -- Entry Logging -----------------------------------
272
+
273
+ /**
274
+ * @private
275
+ * Log a single audit entry.
276
+ */
277
+ async _logEntry(action, tableName, instance)
278
+ {
279
+ try
280
+ {
281
+ const pk = this._extractPK(instance);
282
+ const filtered = this._filterFields(instance);
283
+
284
+ const entry = {
285
+ action,
286
+ table_name: tableName,
287
+ record_id: pk != null ? String(pk) : null,
288
+ actor: this._currentActor,
289
+ timestamp: new Date().toISOString(),
290
+ };
291
+
292
+ if (action === 'create')
293
+ {
294
+ entry.old_values = null;
295
+ entry.new_values = JSON.stringify(filtered);
296
+ entry.diff = null;
297
+ }
298
+ else if (action === 'update')
299
+ {
300
+ const original = instance._original || {};
301
+ const oldFiltered = this._filterFields(original);
302
+ entry.old_values = JSON.stringify(oldFiltered);
303
+ entry.new_values = JSON.stringify(filtered);
304
+
305
+ if (this._diffs)
306
+ {
307
+ entry.diff = JSON.stringify(this._computeDiff(oldFiltered, filtered));
308
+ }
309
+ }
310
+ else if (action === 'delete')
311
+ {
312
+ entry.old_values = JSON.stringify(filtered);
313
+ entry.new_values = null;
314
+ entry.diff = null;
315
+ }
316
+
317
+ await this._writeEntry(entry);
318
+ }
319
+ catch (err)
320
+ {
321
+ log('audit entry failed', err.message);
322
+ }
323
+ }
324
+
325
+ /**
326
+ * @private
327
+ * Write an audit entry to storage.
328
+ */
329
+ async _writeEntry(entry)
330
+ {
331
+ const adapter = this._storage.adapter;
332
+
333
+ if (typeof adapter.execute === 'function')
334
+ {
335
+ // SQL adapter
336
+ await adapter.execute({
337
+ action: 'insert',
338
+ table: this.tableName,
339
+ data: entry,
340
+ });
341
+ }
342
+ else if (typeof adapter.insert === 'function')
343
+ {
344
+ await adapter.insert(this.tableName, entry);
345
+ }
346
+ }
347
+
348
+ /**
349
+ * @private
350
+ * Extract primary key value from an instance.
351
+ */
352
+ _extractPK(instance)
353
+ {
354
+ if (!instance) return null;
355
+
356
+ // Handle plain objects and model instances
357
+ const data = typeof instance.toJSON === 'function' ? instance.toJSON() : instance;
358
+ return data.id || data._id || null;
359
+ }
360
+
361
+ /**
362
+ * @private
363
+ * Filter out excluded fields from data.
364
+ */
365
+ _filterFields(data)
366
+ {
367
+ if (!data || typeof data !== 'object') return {};
368
+
369
+ const source = typeof data.toJSON === 'function' ? data.toJSON() : { ...data };
370
+ const result = {};
371
+
372
+ for (const [key, value] of Object.entries(source))
373
+ {
374
+ if (key.startsWith('_')) continue;
375
+ if (this._excludeFields.has(key)) continue;
376
+ result[key] = value;
377
+ }
378
+
379
+ return result;
380
+ }
381
+
382
+ // -- Diff Computation --------------------------------
383
+
384
+ /**
385
+ * Compute a diff between old and new values.
386
+ * Returns an array of `{ field, from, to }` objects.
387
+ *
388
+ * @param {object} oldValues - Previous data.
389
+ * @param {object} newValues - Current data.
390
+ * @returns {Array<{field: string, from: *, to: *}>}
391
+ *
392
+ * @example
393
+ * const diff = audit.diff({ name: 'Alice' }, { name: 'Bob' });
394
+ * // [{ field: 'name', from: 'Alice', to: 'Bob' }]
395
+ */
396
+ diff(oldValues, newValues)
397
+ {
398
+ return this._computeDiff(oldValues, newValues);
399
+ }
400
+
401
+ /**
402
+ * @private
403
+ */
404
+ _computeDiff(oldValues, newValues)
405
+ {
406
+ const changes = [];
407
+ const allKeys = new Set([
408
+ ...Object.keys(oldValues || {}),
409
+ ...Object.keys(newValues || {}),
410
+ ]);
411
+
412
+ for (const key of allKeys)
413
+ {
414
+ const oldVal = oldValues ? oldValues[key] : undefined;
415
+ const newVal = newValues ? newValues[key] : undefined;
416
+
417
+ // Deep equality via JSON comparison for objects/arrays
418
+ const oldStr = JSON.stringify(oldVal);
419
+ const newStr = JSON.stringify(newVal);
420
+
421
+ if (oldStr !== newStr)
422
+ {
423
+ changes.push({ field: key, from: oldVal, to: newVal });
424
+ }
425
+ }
426
+
427
+ return changes;
428
+ }
429
+
430
+ // -- Querying Audit Trail ----------------------------
431
+
432
+ /**
433
+ * Query the audit trail.
434
+ *
435
+ * @param {object} [options] - Filter options.
436
+ * @param {string} [options.table] - Filter by table name.
437
+ * @param {string} [options.action] - Filter by action (create, update, delete).
438
+ * @param {string} [options.recordId] - Filter by record ID.
439
+ * @param {string} [options.actor] - Filter by actor.
440
+ * @param {string} [options.since] - ISO timestamp lower bound.
441
+ * @param {string} [options.until] - ISO timestamp upper bound.
442
+ * @param {number} [options.limit=100] - Maximum entries.
443
+ * @param {number} [options.offset=0] - Skip entries.
444
+ * @param {string} [options.order='desc'] - Sort order by timestamp.
445
+ * @returns {Promise<Array>} Audit entries.
446
+ *
447
+ * @example
448
+ * const entries = await audit.trail({ table: 'users', recordId: '1' });
449
+ * const updates = await audit.trail({ action: 'update', limit: 50 });
450
+ */
451
+ async trail(options = {})
452
+ {
453
+ const { table, action, recordId, actor, since, until, limit = 100, offset = 0, order = 'desc' } = options;
454
+ const adapter = this._storage.adapter;
455
+
456
+ const where = [];
457
+ if (table) where.push({ field: 'table_name', op: '=', value: table });
458
+ if (action) where.push({ field: 'action', op: '=', value: action });
459
+ if (recordId) where.push({ field: 'record_id', op: '=', value: String(recordId) });
460
+ if (actor) where.push({ field: 'actor', op: '=', value: actor });
461
+ if (since) where.push({ field: 'timestamp', op: '>=', value: since });
462
+ if (until) where.push({ field: 'timestamp', op: '<=', value: until });
463
+
464
+ const descriptor = {
465
+ action: 'find',
466
+ table: this.tableName,
467
+ where,
468
+ orderBy: [{ field: 'timestamp', direction: order }],
469
+ limit,
470
+ offset,
471
+ };
472
+
473
+ let rows;
474
+ if (typeof adapter.execute === 'function')
475
+ {
476
+ rows = await adapter.execute(descriptor);
477
+ }
478
+ else if (typeof adapter.find === 'function')
479
+ {
480
+ rows = await adapter.find(this.tableName, descriptor);
481
+ }
482
+ else
483
+ {
484
+ rows = [];
485
+ }
486
+
487
+ // Parse JSON fields
488
+ return (rows || []).map(row => ({
489
+ ...row,
490
+ old_values: row.old_values ? JSON.parse(row.old_values) : null,
491
+ new_values: row.new_values ? JSON.parse(row.new_values) : null,
492
+ diff: row.diff ? JSON.parse(row.diff) : null,
493
+ }));
494
+ }
495
+
496
+ /**
497
+ * Get the audit history for a specific record.
498
+ *
499
+ * @param {string} table - Table name.
500
+ * @param {string|number} recordId - Record ID.
501
+ * @param {object} [options] - Additional filter options.
502
+ * @returns {Promise<Array>} Audit entries for the record.
503
+ *
504
+ * @example
505
+ * const history = await audit.history('users', 1);
506
+ */
507
+ async history(table, recordId, options = {})
508
+ {
509
+ return this.trail({ ...options, table, recordId: String(recordId) });
510
+ }
511
+
512
+ /**
513
+ * Get audit entries grouped by actor.
514
+ *
515
+ * @param {object} [options] - Filter options.
516
+ * @returns {Promise<Map<string, Array>>} Map of actor → entries.
517
+ */
518
+ async byActor(options = {})
519
+ {
520
+ const entries = await this.trail({ ...options, limit: options.limit || 1000 });
521
+ const grouped = new Map();
522
+
523
+ for (const entry of entries)
524
+ {
525
+ const actor = entry.actor || '__unknown__';
526
+ if (!grouped.has(actor)) grouped.set(actor, []);
527
+ grouped.get(actor).push(entry);
528
+ }
529
+
530
+ return grouped;
531
+ }
532
+
533
+ /**
534
+ * Count audit entries matching the given filters.
535
+ *
536
+ * @param {object} [options] - Same filter options as trail().
537
+ * @returns {Promise<number>}
538
+ *
539
+ * @example
540
+ * const count = await audit.count({ table: 'users', action: 'update' });
541
+ */
542
+ async count(options = {})
543
+ {
544
+ const { table, action, recordId, actor, since, until } = options;
545
+ const adapter = this._storage.adapter;
546
+
547
+ const where = [];
548
+ if (table) where.push({ field: 'table_name', op: '=', value: table });
549
+ if (action) where.push({ field: 'action', op: '=', value: action });
550
+ if (recordId) where.push({ field: 'record_id', op: '=', value: String(recordId) });
551
+ if (actor) where.push({ field: 'actor', op: '=', value: actor });
552
+ if (since) where.push({ field: 'timestamp', op: '>=', value: since });
553
+ if (until) where.push({ field: 'timestamp', op: '<=', value: until });
554
+
555
+ if (typeof adapter.execute === 'function')
556
+ {
557
+ const result = await adapter.execute({
558
+ action: 'count',
559
+ table: this.tableName,
560
+ where,
561
+ });
562
+ return typeof result === 'number' ? result : (result && result[0] ? result[0].count || 0 : 0);
563
+ }
564
+
565
+ // Fallback: fetch all and count
566
+ const entries = await this.trail(options);
567
+ return entries.length;
568
+ }
569
+
570
+ /**
571
+ * Purge old audit entries.
572
+ *
573
+ * @param {object} options - Purge options.
574
+ * @param {string} [options.before] - ISO timestamp; delete entries older than this.
575
+ * @param {string} [options.table] - Only purge entries for this table.
576
+ * @param {number} [options.keepLast] - Keep at least this many entries per record.
577
+ * @returns {Promise<number>} Number of entries purged.
578
+ *
579
+ * @example
580
+ * const purged = await audit.purge({ before: '2025-01-01T00:00:00Z' });
581
+ */
582
+ async purge(options = {})
583
+ {
584
+ const { before, table } = options;
585
+ const adapter = this._storage.adapter;
586
+
587
+ const where = [];
588
+ if (before) where.push({ field: 'timestamp', op: '<', value: before });
589
+ if (table) where.push({ field: 'table_name', op: '=', value: table });
590
+
591
+ if (where.length === 0)
592
+ {
593
+ throw new Error('purge() requires at least one filter (before or table)');
594
+ }
595
+
596
+ if (typeof adapter.execute === 'function')
597
+ {
598
+ const result = await adapter.execute({
599
+ action: 'delete',
600
+ table: this.tableName,
601
+ where,
602
+ });
603
+ const count = typeof result === 'number' ? result : (result && result.changes ? result.changes : 0);
604
+ log('purged entries', count);
605
+ return count;
606
+ }
607
+
608
+ return 0;
609
+ }
610
+
611
+ /**
612
+ * Returns an HTTP middleware that sets the actor from the request.
613
+ *
614
+ * @param {object} [options] - Options.
615
+ * @param {Function} [options.extract] - Custom `(req) => actorId` function.
616
+ * @param {string} [options.header='x-user-id'] - Header to read actor from.
617
+ * @returns {Function} Middleware `(req, res, next) => {}`.
618
+ *
619
+ * @example
620
+ * app.use(audit.middleware({ extract: (req) => req.user?.id }));
621
+ */
622
+ middleware(options = {})
623
+ {
624
+ const { extract, header = 'x-user-id' } = options;
625
+ const auditLog = this;
626
+
627
+ return function auditMiddleware(req, res, next)
628
+ {
629
+ let actor;
630
+ if (typeof extract === 'function')
631
+ {
632
+ actor = extract(req);
633
+ }
634
+ else if (header && req.headers)
635
+ {
636
+ actor = req.headers[header.toLowerCase()];
637
+ }
638
+
639
+ if (actor)
640
+ {
641
+ auditLog.setActor(String(actor));
642
+ }
643
+
644
+ next();
645
+ };
646
+ }
647
+ }
648
+
649
+ module.exports = { AuditLog };