-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathregistry.test.ts
More file actions
848 lines (725 loc) · 38.3 KB
/
Copy pathregistry.test.ts
File metadata and controls
848 lines (725 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { SchemaRegistry, applySystemFields, reconcileManagedApiMethods, computeFQN, parseFQN } from './registry';
describe('SchemaRegistry', () => {
let registry: SchemaRegistry;
beforeEach(() => {
// Use multiTenant: false in the bulk of the suite so the existing
// assertions don't need to know about auto-injected system fields.
// applySystemFields() has its own dedicated suite below.
registry = new SchemaRegistry({ multiTenant: false });
});
// ==========================================
// computeFQN / parseFQN — convention tests
// ==========================================
describe('computeFQN', () => {
it('should return the short name unchanged (no namespace prefix)', () => {
expect(computeFQN('crm', 'account')).toBe('account');
expect(computeFQN('todo', 'task')).toBe('task');
});
it('should return the name for reserved namespaces', () => {
expect(computeFQN('base', 'user')).toBe('user');
expect(computeFQN('system', 'organization')).toBe('organization');
});
it('should return the name for undefined namespace', () => {
expect(computeFQN(undefined, 'task')).toBe('task');
});
});
describe('parseFQN', () => {
it('should parse legacy FQN with double-underscore', () => {
expect(parseFQN('crm__account')).toEqual({ namespace: 'crm', shortName: 'account' });
expect(parseFQN('todo__task')).toEqual({ namespace: 'todo', shortName: 'task' });
});
it('should parse unprefixed names', () => {
expect(parseFQN('user')).toEqual({ namespace: undefined, shortName: 'user' });
expect(parseFQN('task')).toEqual({ namespace: undefined, shortName: 'task' });
});
});
// ==========================================
// Namespace Management Tests
// ==========================================
describe('Namespace Management', () => {
it('should register namespace', () => {
registry.registerNamespace('crm', 'com.example.crm');
expect(registry.getNamespaceOwner('crm')).toBe('com.example.crm');
});
it('should allow same package to re-register namespace', () => {
registry.registerNamespace('crm', 'com.example.crm');
expect(() => {
registry.registerNamespace('crm', 'com.example.crm');
}).not.toThrow();
});
it('should allow multiple packages to share a namespace', () => {
registry.registerNamespace('sys', 'com.objectstack.auth');
registry.registerNamespace('sys', 'com.objectstack.security');
// First registered package returned for backwards compat
expect(registry.getNamespaceOwner('sys')).toBe('com.objectstack.auth');
expect(registry.getNamespaceOwners('sys')).toEqual([
'com.objectstack.auth',
'com.objectstack.security',
]);
});
it('should unregister namespace', () => {
registry.registerNamespace('crm', 'com.example.crm');
registry.unregisterNamespace('crm', 'com.example.crm');
expect(registry.getNamespaceOwner('crm')).toBeUndefined();
});
it('should keep namespace when one of multiple packages unregisters', () => {
registry.registerNamespace('sys', 'com.objectstack.auth');
registry.registerNamespace('sys', 'com.objectstack.setup');
registry.unregisterNamespace('sys', 'com.objectstack.setup');
expect(registry.getNamespaceOwner('sys')).toBe('com.objectstack.auth');
});
});
// ==========================================
// Object Ownership Tests
// ==========================================
describe('Object Ownership', () => {
it('should register owned object using object name as canonical key', () => {
const obj = { name: 'account', fields: { name: { type: 'text' } } };
const key = registry.registerObject(obj as any, 'com.example.crm', 'crm', 'own');
expect(key).toBe('account');
const resolved = registry.getObject('account');
expect(resolved).toBeDefined();
expect(resolved?.name).toBe('account');
});
it('should register object without namespace', () => {
const obj = { name: 'task', fields: {} };
const key = registry.registerObject(obj as any, 'com.example.app');
expect(key).toBe('task');
expect(registry.getObject('task')).toBeDefined();
});
it('should allow only one owner per object name', () => {
const obj = { name: 'shared', fields: {} };
registry.registerObject(obj as any, 'com.vendor.a', 'vendor_a', 'own');
const obj2 = { name: 'shared', fields: {} };
expect(() => {
registry.registerObject(obj2 as any, 'com.vendor.b', undefined, 'own');
}).toThrow(/already owned/);
});
it('should allow re-registration by same owner', () => {
const obj = { name: 'account', fields: { v1: { type: 'text' } } };
registry.registerObject(obj as any, 'com.example.crm', 'crm', 'own');
const obj2 = { name: 'account', fields: { v2: { type: 'text' } } };
expect(() => {
registry.registerObject(obj2 as any, 'com.example.crm', 'crm', 'own');
}).not.toThrow();
const resolved = registry.getObject('account');
expect(resolved?.fields).toHaveProperty('v2');
});
});
// ==========================================
// ADR-0079 — primary-title designation (designate-only, no synthesis)
// ==========================================
describe('ADR-0079 primary-title designation', () => {
it('designates nameField from an existing title-eligible field when none declared', () => {
// No `nameField` declared; `title` (text) is derivable → registry
// should DESIGNATE it on the owned object.
const obj = { name: 'ticket', fields: { notes: { type: 'text' }, title: { type: 'text' } } };
registry.registerObject(obj as any, 'com.example.crm', undefined, 'own');
const resolved = registry.getObject('ticket');
expect((resolved as any)?.nameField).toBe('title');
// designate-only: declared fields preserved, NO `name` column synthesized
// (system audit/tenant fields may be injected by applySystemFields).
expect(resolved?.fields).toHaveProperty('notes');
expect(resolved?.fields).toHaveProperty('title');
expect(resolved?.fields).not.toHaveProperty('name');
});
it('prefers a `name`-ish field and respects an explicit pointer', () => {
const named = { name: 'company', fields: { description: { type: 'text' }, company_name: { type: 'text' } } };
registry.registerObject(named as any, 'com.crm', undefined, 'own');
expect((registry.getObject('company') as any)?.nameField).toBe('company_name');
const explicit = { name: 'invoice', nameField: 'ref', fields: { ref: { type: 'text' }, memo: { type: 'text' } } };
registry.registerObject(explicit as any, 'com.fin', undefined, 'own');
expect((registry.getObject('invoice') as any)?.nameField).toBe('ref');
});
it('does NOT add a `name` column to a title-LESS object (no schema migration)', () => {
// currency/date/select/lookup → nothing title-eligible. The object
// must be left as-is: no `nameField`, no synthesized `name` field.
const obj = {
name: 'sys_ledger_entry',
fields: {
amount: { type: 'currency' },
posted_at: { type: 'datetime' },
status: { type: 'select' },
account: { type: 'lookup' },
},
};
registry.registerObject(obj as any, 'com.objectstack.system', undefined, 'own');
const resolved = registry.getObject('sys_ledger_entry');
// Nothing title-eligible (currency/date/select/lookup + injected
// audit lookups/datetimes are all ineligible) → no designation and,
// critically, NO `name` column synthesized (no schema migration).
expect((resolved as any)?.nameField).toBeUndefined();
expect(resolved?.fields).not.toHaveProperty('name');
// declared fields untouched
for (const f of ['amount', 'posted_at', 'status', 'account']) {
expect(resolved?.fields).toHaveProperty(f);
}
});
it('does NOT add a `name` column to a FIELDLESS object', () => {
const obj = { name: 'sys_empty', fields: {} };
registry.registerObject(obj as any, 'com.objectstack.system', undefined, 'own');
const resolved = registry.getObject('sys_empty');
expect((resolved as any)?.nameField).toBeUndefined();
expect(resolved?.fields).not.toHaveProperty('name');
});
});
// ==========================================
// Object Extension Tests
// ==========================================
describe('Object Extension', () => {
it('should merge extension fields into owner', () => {
const owner = { name: 'contact', fields: { email: { type: 'text' } } };
registry.registerObject(owner as any, 'com.base', 'base', 'own');
const ext = { name: 'contact', fields: { phone: { type: 'text' } } };
registry.registerObject(ext as any, 'com.crm', undefined, 'extend', 200);
const resolved = registry.getObject('contact');
expect(resolved?.fields).toHaveProperty('email');
expect(resolved?.fields).toHaveProperty('phone');
});
it('should apply priority order (higher wins)', () => {
const owner = { name: 'task', label: 'Task', fields: {} };
registry.registerObject(owner as any, 'com.base', 'base', 'own', 100);
const ext1 = { name: 'task', label: 'Extended Task', fields: {} };
registry.registerObject(ext1 as any, 'com.ext1', undefined, 'extend', 150);
const ext2 = { name: 'task', label: 'Final Task', fields: {} };
registry.registerObject(ext2 as any, 'com.ext2', undefined, 'extend', 250);
const resolved = registry.getObject('task');
expect(resolved?.label).toBe('Final Task');
});
it('should merge validations additively', () => {
const owner = { name: 'order', fields: {}, validations: [{ type: 'required', field: 'id' }] };
registry.registerObject(owner as any, 'com.base', 'base', 'own');
const ext = { name: 'order', fields: {}, validations: [{ type: 'required', field: 'status' }] };
registry.registerObject(ext as any, 'com.ext', undefined, 'extend');
const resolved = registry.getObject('order');
expect(resolved?.validations).toHaveLength(2);
});
it('should fail extension without owner', () => {
const ext = { name: 'phantom', fields: {} };
registry.registerObject(ext as any, 'com.ext', undefined, 'extend');
const resolved = registry.getObject('phantom');
expect(resolved).toBeUndefined();
});
});
// ==========================================
// Object Resolution Tests
// ==========================================
describe('Object Resolution', () => {
it('should resolve by canonical name', () => {
const obj = { name: 'deal', fields: {} };
registry.registerObject(obj as any, 'com.crm', 'crm', 'own');
expect(registry.resolveObject('deal')).toBeDefined();
});
it('should resolve system objects by their sys_ prefixed name', () => {
const obj = { name: 'sys_user', fields: {} };
registry.registerObject(obj as any, 'com.objectstack.system', 'sys', 'own');
expect(registry.getObject('sys_user')).toBeDefined();
});
it('should cache merged objects', () => {
const obj = { name: 'cached', fields: {} };
registry.registerObject(obj as any, 'com.test', 'test', 'own');
const first = registry.resolveObject('cached');
const second = registry.resolveObject('cached');
expect(first).toBe(second);
});
it('should invalidate cache on re-registration', () => {
const obj = { name: 'evolve', fields: { v1: { type: 'text' } } };
registry.registerObject(obj as any, 'com.test', 'test', 'own');
const first = registry.resolveObject('evolve');
const obj2 = { name: 'evolve', fields: { v2: { type: 'text' } } };
registry.registerObject(obj2 as any, 'com.test', 'test', 'own');
const second = registry.resolveObject('evolve');
expect(first).not.toBe(second);
expect(second?.fields).toHaveProperty('v2');
});
});
// ==========================================
// getAllObjects Tests
// ==========================================
describe('getAllObjects', () => {
it('should return all merged objects', () => {
registry.registerObject({ name: 'a', fields: {} } as any, 'com.pkg1', 'pkg1', 'own');
registry.registerObject({ name: 'b', fields: {} } as any, 'com.pkg2', 'pkg2', 'own');
const all = registry.getAllObjects();
expect(all).toHaveLength(2);
expect(all.map(o => o.name).sort()).toEqual(['a', 'b']);
});
it('should filter by packageId', () => {
registry.registerObject({ name: 'a', fields: {} } as any, 'com.pkg1', 'pkg1', 'own');
registry.registerObject({ name: 'b', fields: {} } as any, 'com.pkg2', 'pkg2', 'own');
const filtered = registry.getAllObjects('com.pkg1');
expect(filtered).toHaveLength(1);
expect(filtered[0].name).toBe('a');
});
it('should include objects where package is extender', () => {
registry.registerObject({ name: 'base_obj', fields: {} } as any, 'com.owner', 'base', 'own');
registry.registerObject({ name: 'base_obj', fields: { ext: { type: 'text' } } } as any, 'com.extender', undefined, 'extend');
const filtered = registry.getAllObjects('com.extender');
expect(filtered).toHaveLength(1);
});
});
// ==========================================
// Uninstall Tests
// ==========================================
describe('Uninstall', () => {
it('should remove owner contribution', () => {
registry.registerObject({ name: 'removable', fields: {} } as any, 'com.pkg', 'pkg', 'own');
expect(registry.getObject('removable')).toBeDefined();
registry.unregisterObjectsByPackage('com.pkg');
expect(registry.getObject('removable')).toBeUndefined();
});
it('should remove extension contribution', () => {
registry.registerObject({ name: 'target', fields: { base: { type: 'text' } } } as any, 'com.owner', 'base', 'own');
registry.registerObject({ name: 'target', fields: { ext: { type: 'text' } } } as any, 'com.ext', undefined, 'extend');
registry.unregisterObjectsByPackage('com.ext');
const resolved = registry.getObject('target');
expect(resolved?.fields).toHaveProperty('base');
expect(resolved?.fields).not.toHaveProperty('ext');
});
it('should prevent uninstall of owner with active extenders', () => {
registry.registerObject({ name: 'important', fields: {} } as any, 'com.owner', 'base', 'own');
registry.registerObject({ name: 'important', fields: {} } as any, 'com.ext', undefined, 'extend');
expect(() => {
registry.unregisterObjectsByPackage('com.owner');
}).toThrow(/extended by/);
});
it('should allow force uninstall of owner with extenders', () => {
registry.registerObject({ name: 'forced', fields: {} } as any, 'com.owner', 'base', 'own');
registry.registerObject({ name: 'forced', fields: {} } as any, 'com.ext', undefined, 'extend');
expect(() => {
registry.unregisterObjectsByPackage('com.owner', true);
}).not.toThrow();
});
});
// ==========================================
// Contributors API Tests
// ==========================================
describe('Contributors API', () => {
it('should return all contributors for object', () => {
registry.registerObject({ name: 'multi', fields: {} } as any, 'com.owner', 'pkg', 'own', 100);
registry.registerObject({ name: 'multi', fields: {} } as any, 'com.ext1', undefined, 'extend', 200);
registry.registerObject({ name: 'multi', fields: {} } as any, 'com.ext2', undefined, 'extend', 300);
const contribs = registry.getObjectContributors('multi');
expect(contribs).toHaveLength(3);
expect(contribs[0].priority).toBe(100);
expect(contribs[1].priority).toBe(200);
expect(contribs[2].priority).toBe(300);
});
it('should return owner contributor', () => {
registry.registerObject({ name: 'owned', fields: {} } as any, 'com.owner', 'pkg', 'own');
const owner = registry.getObjectOwner('owned');
expect(owner).toBeDefined();
expect(owner?.packageId).toBe('com.owner');
expect(owner?.ownership).toBe('own');
});
});
// ==========================================
// Generic Metadata Tests (Non-Object)
// ==========================================
describe('Generic Metadata', () => {
it('should register and retrieve generic items', () => {
const item = { name: 'test_action', type: 'custom' };
registry.registerItem('action', item, 'name', 'com.pkg');
const retrieved = registry.getItem('action', 'test_action');
expect(retrieved).toEqual(item);
});
it('should list items by type with package filter', () => {
registry.registerItem('action', { name: 'a1' }, 'name', 'com.pkg1');
registry.registerItem('action', { name: 'a2' }, 'name', 'com.pkg2');
const filtered = registry.listItems('action', 'com.pkg1');
expect(filtered).toHaveLength(1);
});
});
// ==========================================
// Package Management Tests
// ==========================================
describe('Package Management', () => {
it('should install package with namespace', () => {
const manifest = { id: 'com.test', name: 'Test', namespace: 'test', version: '1.0.0' };
const pkg = registry.installPackage(manifest as any);
expect(pkg.status).toBe('installed');
expect(registry.getNamespaceOwner('test')).toBe('com.test');
});
it('should uninstall package and release namespace', () => {
const manifest = { id: 'com.test', name: 'Test', namespace: 'test', version: '1.0.0' };
registry.installPackage(manifest as any);
registry.uninstallPackage('com.test');
expect(registry.getPackage('com.test')).toBeUndefined();
expect(registry.getNamespaceOwner('test')).toBeUndefined();
});
it('updatePackageManifest merges editable fields, preserving lifecycle state', () => {
registry.installPackage({ id: 'com.test', name: 'Old', version: '1.0.0' } as any);
registry.disablePackage('com.test'); // lifecycle state that must survive an edit
const updated = registry.updatePackageManifest('com.test', {
name: 'New Name',
description: 'now with a description',
version: '2.0.0',
});
expect(updated?.manifest.name).toBe('New Name');
expect((updated?.manifest as any).description).toBe('now with a description');
expect(updated?.manifest.version).toBe('2.0.0');
// Editing metadata must NOT re-enable a disabled package.
expect(updated?.enabled).toBe(false);
expect(updated?.status).toBe('disabled');
});
it('updatePackageManifest only overwrites the fields present in the patch', () => {
registry.installPackage({ id: 'com.test', name: 'Keep', version: '1.0.0' } as any);
const updated = registry.updatePackageManifest('com.test', { description: 'only this' });
expect(updated?.manifest.name).toBe('Keep');
expect(updated?.manifest.version).toBe('1.0.0');
expect((updated?.manifest as any).description).toBe('only this');
});
it('updatePackageManifest returns undefined for an unknown package', () => {
expect(registry.updatePackageManifest('nope', { name: 'x' })).toBeUndefined();
});
});
// ==========================================
// Reset Tests
// ==========================================
describe('Reset', () => {
it('should clear all state', () => {
registry.registerObject({ name: 'obj', fields: {} } as any, 'com.pkg', 'pkg', 'own');
registry.registerItem('action', { name: 'act' }, 'name');
registry.reset();
expect(registry.getAllObjects()).toHaveLength(0);
expect(registry.listItems('action')).toHaveLength(0);
});
});
// ==========================================
// listItems/getItem for 'object' type Tests
// ==========================================
describe('listItems and getItem for object type', () => {
it('listItems("object") should return all registered objects', () => {
registry.registerObject(
{ name: 'account', label: 'Account', fields: {} } as any,
'com.crm',
'crm',
'own'
);
registry.registerObject(
{ name: 'contact', label: 'Contact', fields: {} } as any,
'com.crm',
'crm',
'own'
);
const objects = registry.listItems('object');
expect(objects).toHaveLength(2);
expect(objects.map((o: any) => o.name).sort()).toEqual(['account', 'contact']);
});
it('listItems("objects") should return all registered objects (plural alias)', () => {
registry.registerObject(
{ name: 'task', label: 'Task', fields: {} } as any,
'com.todo',
'todo',
'own'
);
const objects = registry.listItems('objects');
expect(objects).toHaveLength(1);
expect((objects[0] as any).name).toBe('task');
});
it('getItem("object", name) should return object by canonical name', () => {
registry.registerObject(
{ name: 'lead', label: 'Lead', fields: { status: { type: 'text' } } } as any,
'com.crm',
'crm',
'own'
);
const obj = registry.getItem('object', 'lead');
expect(obj).toBeDefined();
expect((obj as any).name).toBe('lead');
expect((obj as any).label).toBe('Lead');
});
it('getItem("object", name) should return object by name', () => {
registry.registerObject(
{ name: 'opportunity', label: 'Opportunity', fields: {} } as any,
'com.crm',
'crm',
'own'
);
const obj = registry.getItem('object', 'opportunity');
expect(obj).toBeDefined();
expect((obj as any).name).toBe('opportunity');
});
it('listItems("object", packageId) should filter by package', () => {
registry.registerObject(
{ name: 'account', fields: {} } as any,
'com.crm',
'crm',
'own'
);
registry.registerObject(
{ name: 'task', fields: {} } as any,
'com.todo',
'todo',
'own'
);
const crmObjects = registry.listItems('object', 'com.crm');
expect(crmObjects).toHaveLength(1);
expect((crmObjects[0] as any).name).toBe('account');
const todoObjects = registry.listItems('object', 'com.todo');
expect(todoObjects).toHaveLength(1);
expect((todoObjects[0] as any).name).toBe('task');
});
});
});
// ==========================================
// applySystemFields — system field auto-injection
// ==========================================
describe('applySystemFields', () => {
const baseLead: any = { name: 'lead', label: 'Lead', fields: { first_name: { type: 'text' } } };
it('injects an indexed organization_id when multiTenant is true and field is missing', () => {
const out = applySystemFields(baseLead, { multiTenant: true });
expect(out.fields.organization_id).toBeDefined();
expect(out.fields.organization_id.type).toBe('lookup');
expect(out.fields.organization_id.reference).toBe('sys_organization');
// Multi-tenant stacks index the column (per-tenant filtering).
expect(out.fields.organization_id.indexed).toBe(true);
// author-declared field still present
expect(out.fields.first_name).toBeDefined();
});
it('still injects organization_id when multiTenant is false, but unindexed', () => {
// The COLUMN is always provisioned (decoupled from the tenant flag) so
// sudo writers can always stamp it; only the index is gated, since a
// single-tenant DB never filters by organization.
const out = applySystemFields(baseLead, { multiTenant: false });
expect(out.fields.organization_id).toBeDefined();
expect(out.fields.organization_id.type).toBe('lookup');
expect(out.fields.organization_id.indexed).toBe(false);
// audit fields are tenant-independent — still injected
expect(out.fields.created_at).toBeDefined();
expect(out.fields.updated_at).toBeDefined();
});
it('does NOT overwrite an author-declared organization_id', () => {
const declared: any = {
name: 'lead',
fields: { organization_id: { type: 'text', label: 'Org Code' } },
};
const out = applySystemFields(declared, { multiTenant: true });
// organization_id preserved; audit fields still injected
expect(out.fields.organization_id.label).toBe('Org Code');
expect(out.fields.created_at).toBeDefined();
});
it('respects systemFields: false opt-out', () => {
const opted: any = { ...baseLead, systemFields: false };
const out = applySystemFields(opted, { multiTenant: true });
expect(out).toBe(opted);
expect(out.fields.organization_id).toBeUndefined();
expect(out.fields.created_at).toBeUndefined();
});
it('respects systemFields.tenant: false opt-out (audit fields still injected)', () => {
const opted: any = { ...baseLead, systemFields: { tenant: false } };
const out = applySystemFields(opted, { multiTenant: true });
expect(out.fields.organization_id).toBeUndefined();
expect(out.fields.created_at).toBeDefined();
expect(out.fields.updated_by).toBeDefined();
});
it('respects systemFields.audit: false opt-out (tenant field still injected)', () => {
const opted: any = { ...baseLead, systemFields: { audit: false } };
const out = applySystemFields(opted, { multiTenant: true });
expect(out.fields.organization_id).toBeDefined();
expect(out.fields.created_at).toBeUndefined();
expect(out.fields.created_by).toBeUndefined();
expect(out.fields.updated_at).toBeUndefined();
expect(out.fields.updated_by).toBeUndefined();
});
it('skips externally-managed objects (managedBy set)', () => {
const sysUser: any = { name: 'sys_user', managedBy: 'better-auth', fields: { email: { type: 'text' } } };
const out = applySystemFields(sysUser, { multiTenant: true });
expect(out).toBe(sysUser);
expect(out.fields.organization_id).toBeUndefined();
expect(out.fields.created_at).toBeUndefined();
});
it('injects all four audit fields with the expected shape', () => {
const out = applySystemFields(baseLead, { multiTenant: false });
expect(out.fields.created_at).toMatchObject({
type: 'datetime', system: true, readonly: true,
});
expect(out.fields.created_by).toMatchObject({
type: 'lookup', reference: 'sys_user', system: true, readonly: true,
});
expect(out.fields.updated_at).toMatchObject({
type: 'datetime', system: true, readonly: true,
});
expect(out.fields.updated_by).toMatchObject({
type: 'lookup', reference: 'sys_user', system: true, readonly: true,
});
});
it('does NOT overwrite author-declared audit fields', () => {
const declared: any = {
name: 'lead',
fields: {
created_at: { type: 'text', label: 'Custom Created' },
updated_by: { type: 'text', label: 'Custom Updater' },
},
};
const out = applySystemFields(declared, { multiTenant: false });
expect(out.fields.created_at.type).toBe('text');
expect(out.fields.created_at.label).toBe('Custom Created');
expect(out.fields.updated_by.type).toBe('text');
// The missing ones are still injected as system fields
expect(out.fields.created_by).toMatchObject({ system: true });
expect(out.fields.updated_at).toMatchObject({ system: true });
});
// ── owner_id — canonical, reassignable record owner ──────────────────
it('injects owner_id by default on a business object (reassignable, not readonly)', () => {
const out = applySystemFields(baseLead, { multiTenant: false });
expect(out.fields.owner_id).toMatchObject({
type: 'lookup', reference: 'sys_user', system: true, readonly: false,
});
// Unlike the audit *_by lookups, owner is editable (ownership transfers).
expect(out.fields.owner_id.readonly).toBe(false);
});
it('does NOT inject owner_id for managedBy tables', () => {
const platform: any = { name: 'sys_audit_log', managedBy: 'platform', fields: { msg: { type: 'text' } } };
const out = applySystemFields(platform, { multiTenant: false });
expect(out.fields.owner_id).toBeUndefined();
});
it('does NOT inject owner_id for sys_* objects', () => {
const sysish: any = { name: 'sys_widget', fields: { msg: { type: 'text' } } };
const out = applySystemFields(sysish, { multiTenant: false });
expect(out.fields.owner_id).toBeUndefined();
// audit/tenant fields are still injected for non-managed sys_ objects
expect(out.fields.created_at).toBeDefined();
});
it('respects ownership: "org" / "none" opt-out (audit + tenant still injected)', () => {
for (const ownership of ['org', 'none'] as const) {
const opted: any = { ...baseLead, ownership };
const out = applySystemFields(opted, { multiTenant: false });
expect(out.fields.owner_id).toBeUndefined();
expect(out.fields.created_at).toBeDefined();
}
});
it('does NOT overwrite an author-declared owner_id', () => {
const declared: any = {
name: 'lead',
fields: { owner_id: { type: 'lookup', reference: 'sys_user', label: 'Custom Owner', readonly: true } },
};
const out = applySystemFields(declared, { multiTenant: false });
expect(out.fields.owner_id.label).toBe('Custom Owner');
expect(out.fields.owner_id.readonly).toBe(true);
});
it('SchemaRegistry({ multiTenant: true }) auto-injects on registerObject', () => {
const reg = new SchemaRegistry({ multiTenant: true });
reg.registerObject({ name: 'lead', fields: { first_name: { type: 'text' } } } as any, 'crm', 'crm', 'own');
const stored = (reg as any).objectContributors.get('lead')[0].definition;
expect(stored.fields.organization_id).toBeDefined();
expect(stored.fields.organization_id.reference).toBe('sys_organization');
expect(stored.fields.created_at).toMatchObject({ system: true, readonly: true });
expect(stored.fields.updated_by).toMatchObject({ system: true, readonly: true });
});
});
// ==========================================
// reconcileManagedApiMethods — #1591 / ADR-0092 / ADR-0103
// Registration-time consistency: ANY managed object may not advertise generic
// write verbs its resolved affordances don't grant. Scope generalized from
// better-auth to every managed bucket in ADR-0103.
// ==========================================
describe('reconcileManagedApiMethods', () => {
const managed = (extra: any = {}): any => ({
name: 'sys_thing',
managedBy: 'better-auth',
enable: { apiEnabled: true, apiMethods: ['get', 'list', 'create', 'update', 'delete'] },
...extra,
});
it('strips create/update/delete from a better-auth object with no write affordances', () => {
const warn = vi.fn();
const out = reconcileManagedApiMethods(managed(), { warn });
expect(out).not.toBe(managed()); // new object
expect(out.enable.apiMethods).toEqual(['get', 'list']);
// Warning names the object and the stripped verbs.
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0][0]).toContain('sys_thing');
expect(warn.mock.calls[0][0]).toContain('create');
});
it('keeps update when userActions.edit grants the edit affordance (sys_user case)', () => {
const warn = vi.fn();
const out = reconcileManagedApiMethods(
managed({ userActions: { edit: true }, enable: { apiEnabled: true, apiMethods: ['get', 'list', 'create', 'update', 'delete'] } }),
{ warn },
);
// update survives (edit affordance granted); create/delete still stripped.
expect(out.enable.apiMethods).toEqual(['get', 'list', 'update']);
expect(warn).toHaveBeenCalledTimes(1);
});
it('is a no-op (same reference, no warning) when nothing needs stripping', () => {
const warn = vi.fn();
const already: any = managed({ enable: { apiEnabled: true, apiMethods: ['get', 'list'] } });
const out = reconcileManagedApiMethods(already, { warn });
expect(out).toBe(already);
expect(warn).not.toHaveBeenCalled();
});
it('never touches read verbs', () => {
const out = reconcileManagedApiMethods(
managed({ enable: { apiEnabled: true, apiMethods: ['get', 'delete'] } }),
{ warn: vi.fn() },
);
expect(out.enable.apiMethods).toEqual(['get']);
});
it('leaves platform-bucket objects untouched (grant full CRUD → nothing stripped)', () => {
const warn = vi.fn();
const platform: any = {
name: 'sys_business_unit',
managedBy: 'platform',
enable: { apiEnabled: true, apiMethods: ['get', 'list', 'create', 'update', 'delete'] },
};
const out = reconcileManagedApiMethods(platform, { warn });
expect(out).toBe(platform);
expect(out.enable.apiMethods).toEqual(['get', 'list', 'create', 'update', 'delete']);
expect(warn).not.toHaveBeenCalled();
});
it('leaves unmanaged objects (no managedBy) untouched', () => {
const warn = vi.fn();
const plain: any = {
name: 'crm_lead',
enable: { apiEnabled: true, apiMethods: ['get', 'list', 'create', 'update', 'delete'] },
};
const out = reconcileManagedApiMethods(plain, { warn });
expect(out).toBe(plain);
expect(warn).not.toHaveBeenCalled();
});
// ADR-0103 — the scope generalization: engine-owned system/append-only
// objects derive to reads, while the writable set keeps its verbs.
it('strips write verbs from a system-bucket object with no write affordances (engine-owned)', () => {
const warn = vi.fn();
const engineOwned: any = {
name: 'sys_automation_run',
managedBy: 'system',
enable: { apiEnabled: true, apiMethods: ['get', 'list', 'create', 'update', 'delete'] },
};
const out = reconcileManagedApiMethods(engineOwned, { warn });
expect(out.enable.apiMethods).toEqual(['get', 'list']);
expect(warn).toHaveBeenCalledTimes(1);
expect(warn.mock.calls[0][0]).toContain("managedBy:'system'");
});
it('strips write verbs from an append-only object with no write affordances', () => {
const warn = vi.fn();
const appendOnly: any = {
name: 'sys_email',
managedBy: 'append-only',
enable: { apiEnabled: true, apiMethods: ['get', 'list', 'update'] },
};
const out = reconcileManagedApiMethods(appendOnly, { warn });
expect(out.enable.apiMethods).toEqual(['get', 'list']);
expect(warn).toHaveBeenCalledTimes(1);
});
it('keeps CRUD on a system-bucket object whose userActions open the writes (writable set)', () => {
const warn = vi.fn();
const writable: any = {
name: 'sys_user_position',
managedBy: 'system',
userActions: { create: true, edit: true, delete: true },
enable: { apiEnabled: true, apiMethods: ['get', 'list', 'create', 'update', 'delete'] },
};
const out = reconcileManagedApiMethods(writable, { warn });
expect(out).toBe(writable); // nothing stripped
expect(out.enable.apiMethods).toEqual(['get', 'list', 'create', 'update', 'delete']);
expect(warn).not.toHaveBeenCalled();
});
it('applies on registerObject (the contradiction cannot be stored)', () => {
const reg = new SchemaRegistry({ multiTenant: false });
reg.registerObject(managed(), 'sys', 'sys', 'own');
const stored = (reg as any).objectContributors.get('sys_thing')[0].definition;
expect(stored.enable.apiMethods).toEqual(['get', 'list']);
});
});