@zero-server/orm 0.9.0 → 0.9.2

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 (42) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1 -1
  3. package/index.js +35 -35
  4. package/lib/debug.js +372 -0
  5. package/lib/orm/adapters/json.js +290 -0
  6. package/lib/orm/adapters/memory.js +764 -0
  7. package/lib/orm/adapters/mongo.js +764 -0
  8. package/lib/orm/adapters/mysql.js +933 -0
  9. package/lib/orm/adapters/postgres.js +1144 -0
  10. package/lib/orm/adapters/redis.js +1534 -0
  11. package/lib/orm/adapters/sql-base.js +212 -0
  12. package/lib/orm/adapters/sqlite.js +858 -0
  13. package/lib/orm/audit.js +649 -0
  14. package/lib/orm/cache.js +394 -0
  15. package/lib/orm/geo.js +387 -0
  16. package/lib/orm/index.js +784 -0
  17. package/lib/orm/migrate.js +432 -0
  18. package/lib/orm/model.js +1706 -0
  19. package/lib/orm/plugin.js +375 -0
  20. package/lib/orm/procedures.js +836 -0
  21. package/lib/orm/profiler.js +233 -0
  22. package/lib/orm/query.js +1772 -0
  23. package/lib/orm/replicas.js +241 -0
  24. package/lib/orm/schema.js +307 -0
  25. package/lib/orm/search.js +380 -0
  26. package/lib/orm/seed/data/commerce.js +136 -0
  27. package/lib/orm/seed/data/internet.js +111 -0
  28. package/lib/orm/seed/data/locations.js +204 -0
  29. package/lib/orm/seed/data/names.js +338 -0
  30. package/lib/orm/seed/data/person.js +128 -0
  31. package/lib/orm/seed/data/phone.js +211 -0
  32. package/lib/orm/seed/data/words.js +134 -0
  33. package/lib/orm/seed/factory.js +178 -0
  34. package/lib/orm/seed/fake.js +1186 -0
  35. package/lib/orm/seed/index.js +18 -0
  36. package/lib/orm/seed/rng.js +71 -0
  37. package/lib/orm/seed/seeder.js +125 -0
  38. package/lib/orm/seed/unique.js +68 -0
  39. package/lib/orm/snapshot.js +366 -0
  40. package/lib/orm/tenancy.js +605 -0
  41. package/lib/orm/views.js +350 -0
  42. package/package.json +12 -3
@@ -0,0 +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 };