@object-ui/core 0.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +11 -0
  3. package/dist/actions/ActionRunner.d.ts +228 -4
  4. package/dist/actions/ActionRunner.js +397 -45
  5. package/dist/actions/TransactionManager.d.ts +193 -0
  6. package/dist/actions/TransactionManager.js +410 -0
  7. package/dist/actions/index.d.ts +1 -0
  8. package/dist/actions/index.js +1 -0
  9. package/dist/adapters/ApiDataSource.d.ts +69 -0
  10. package/dist/adapters/ApiDataSource.js +293 -0
  11. package/dist/adapters/ValueDataSource.d.ts +55 -0
  12. package/dist/adapters/ValueDataSource.js +287 -0
  13. package/dist/adapters/index.d.ts +3 -0
  14. package/dist/adapters/index.js +5 -2
  15. package/dist/adapters/resolveDataSource.d.ts +40 -0
  16. package/dist/adapters/resolveDataSource.js +59 -0
  17. package/dist/data-scope/DataScopeManager.d.ts +127 -0
  18. package/dist/data-scope/DataScopeManager.js +229 -0
  19. package/dist/data-scope/index.d.ts +10 -0
  20. package/dist/data-scope/index.js +10 -0
  21. package/dist/evaluator/ExpressionEvaluator.d.ts +11 -1
  22. package/dist/evaluator/ExpressionEvaluator.js +32 -8
  23. package/dist/evaluator/FormulaFunctions.d.ts +58 -0
  24. package/dist/evaluator/FormulaFunctions.js +350 -0
  25. package/dist/evaluator/index.d.ts +1 -0
  26. package/dist/evaluator/index.js +1 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +4 -2
  29. package/dist/query/query-ast.d.ts +2 -2
  30. package/dist/query/query-ast.js +3 -3
  31. package/dist/registry/Registry.d.ts +10 -0
  32. package/dist/registry/Registry.js +2 -1
  33. package/dist/registry/WidgetRegistry.d.ts +120 -0
  34. package/dist/registry/WidgetRegistry.js +275 -0
  35. package/dist/theme/ThemeEngine.d.ts +82 -0
  36. package/dist/theme/ThemeEngine.js +400 -0
  37. package/dist/theme/index.d.ts +8 -0
  38. package/dist/theme/index.js +8 -0
  39. package/dist/validation/index.d.ts +1 -1
  40. package/dist/validation/index.js +1 -1
  41. package/dist/validation/validation-engine.d.ts +19 -1
  42. package/dist/validation/validation-engine.js +67 -2
  43. package/dist/validation/validators/index.d.ts +1 -1
  44. package/dist/validation/validators/index.js +1 -1
  45. package/dist/validation/validators/object-validation-engine.d.ts +2 -2
  46. package/dist/validation/validators/object-validation-engine.js +1 -1
  47. package/package.json +4 -3
  48. package/src/actions/ActionRunner.ts +577 -55
  49. package/src/actions/TransactionManager.ts +521 -0
  50. package/src/actions/__tests__/ActionRunner.params.test.ts +134 -0
  51. package/src/actions/__tests__/ActionRunner.test.ts +711 -0
  52. package/src/actions/__tests__/TransactionManager.test.ts +447 -0
  53. package/src/actions/index.ts +1 -0
  54. package/src/adapters/ApiDataSource.ts +349 -0
  55. package/src/adapters/ValueDataSource.ts +332 -0
  56. package/src/adapters/__tests__/ApiDataSource.test.ts +418 -0
  57. package/src/adapters/__tests__/ValueDataSource.test.ts +325 -0
  58. package/src/adapters/__tests__/resolveDataSource.test.ts +144 -0
  59. package/src/adapters/index.ts +6 -1
  60. package/src/adapters/resolveDataSource.ts +79 -0
  61. package/src/builder/__tests__/schema-builder.test.ts +235 -0
  62. package/src/data-scope/DataScopeManager.ts +269 -0
  63. package/src/data-scope/__tests__/DataScopeManager.test.ts +211 -0
  64. package/src/data-scope/index.ts +16 -0
  65. package/src/evaluator/ExpressionEvaluator.ts +34 -8
  66. package/src/evaluator/FormulaFunctions.ts +398 -0
  67. package/src/evaluator/__tests__/ExpressionContext.test.ts +110 -0
  68. package/src/evaluator/__tests__/FormulaFunctions.test.ts +447 -0
  69. package/src/evaluator/index.ts +1 -0
  70. package/src/index.ts +4 -3
  71. package/src/query/__tests__/window-functions.test.ts +1 -1
  72. package/src/query/query-ast.ts +3 -3
  73. package/src/registry/Registry.ts +12 -1
  74. package/src/registry/WidgetRegistry.ts +316 -0
  75. package/src/registry/__tests__/WidgetRegistry.test.ts +321 -0
  76. package/src/theme/ThemeEngine.ts +452 -0
  77. package/src/theme/__tests__/ThemeEngine.test.ts +606 -0
  78. package/src/theme/index.ts +22 -0
  79. package/src/validation/__tests__/object-validation-engine.test.ts +1 -1
  80. package/src/validation/__tests__/schema-validator.test.ts +118 -0
  81. package/src/validation/index.ts +1 -1
  82. package/src/validation/validation-engine.ts +61 -2
  83. package/src/validation/validators/index.ts +1 -1
  84. package/src/validation/validators/object-validation-engine.ts +2 -2
  85. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,447 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
10
+ import type { DataSource, ActionResult, ActionSchema } from '@object-ui/types';
11
+ import {
12
+ TransactionManager,
13
+ type TransactionProgressEvent,
14
+ } from '../TransactionManager';
15
+
16
+ function createMockDataSource(): DataSource {
17
+ return {
18
+ find: vi.fn().mockResolvedValue({ data: [], total: 0 }),
19
+ findOne: vi.fn().mockResolvedValue(null),
20
+ create: vi.fn().mockImplementation((_res, data) =>
21
+ Promise.resolve({ id: 'new-1', ...data }),
22
+ ),
23
+ update: vi.fn().mockImplementation((_res, _id, data) =>
24
+ Promise.resolve({ id: _id, ...data }),
25
+ ),
26
+ delete: vi.fn().mockResolvedValue(true),
27
+ getObjectSchema: vi.fn().mockResolvedValue({}),
28
+ };
29
+ }
30
+
31
+ function makeAction(name: string): ActionSchema {
32
+ return { name, label: name, type: 'script' };
33
+ }
34
+
35
+ function makeExecutor(results: Record<string, ActionResult>): (action: ActionSchema) => Promise<ActionResult> {
36
+ return async (action) => results[action.name] || { success: true };
37
+ }
38
+
39
+ describe('TransactionManager', () => {
40
+ let ds: DataSource;
41
+ let manager: TransactionManager;
42
+
43
+ beforeEach(() => {
44
+ ds = createMockDataSource();
45
+ manager = new TransactionManager(ds, { maxRetries: 2, retryDelay: 10 });
46
+ });
47
+
48
+ describe('executeTransaction', () => {
49
+ it('should execute all actions successfully', async () => {
50
+ const executor = makeExecutor({
51
+ 'step1': { success: true, data: { id: 1 } },
52
+ 'step2': { success: true, data: { id: 2 } },
53
+ });
54
+
55
+ const result = await manager.executeTransaction(
56
+ {
57
+ name: 'test-txn',
58
+ actions: [makeAction('step1'), makeAction('step2')],
59
+ },
60
+ executor,
61
+ );
62
+
63
+ expect(result.success).toBe(true);
64
+ expect(result.actionResults).toHaveLength(2);
65
+ expect(result.rolledBack).toBeUndefined();
66
+ });
67
+
68
+ it('should return failure and mark as rolled back on action failure', async () => {
69
+ const executor = makeExecutor({
70
+ 'step1': { success: true },
71
+ 'step2': { success: false, error: 'Step 2 failed' },
72
+ });
73
+
74
+ const result = await manager.executeTransaction(
75
+ {
76
+ name: 'failing-txn',
77
+ actions: [makeAction('step1'), makeAction('step2')],
78
+ },
79
+ executor,
80
+ );
81
+
82
+ expect(result.success).toBe(false);
83
+ expect(result.rolledBack).toBe(true);
84
+ expect(result.error).toContain('Step 2 failed');
85
+ });
86
+
87
+ it('should retry on conflict when configured', async () => {
88
+ let attempts = 0;
89
+ const executor = async () => {
90
+ attempts++;
91
+ if (attempts < 3) {
92
+ return { success: false, error: 'Conflict' };
93
+ }
94
+ return { success: true };
95
+ };
96
+
97
+ const result = await manager.executeTransaction(
98
+ {
99
+ name: 'retry-txn',
100
+ actions: [makeAction('conflicting')],
101
+ retryOnConflict: true,
102
+ maxRetries: 3,
103
+ },
104
+ executor,
105
+ );
106
+
107
+ expect(result.success).toBe(true);
108
+ expect(attempts).toBe(3);
109
+ });
110
+
111
+ it('should emit progress events', async () => {
112
+ const progressEvents: TransactionProgressEvent[] = [];
113
+ manager.onProgress(event => progressEvents.push({ ...event }));
114
+
115
+ const executor = makeExecutor({
116
+ 'a': { success: true },
117
+ 'b': { success: true },
118
+ });
119
+
120
+ await manager.executeTransaction(
121
+ {
122
+ name: 'progress-txn',
123
+ actions: [makeAction('a'), makeAction('b')],
124
+ },
125
+ executor,
126
+ );
127
+
128
+ expect(progressEvents.length).toBeGreaterThan(0);
129
+ const lastEvent = progressEvents[progressEvents.length - 1];
130
+ expect(lastEvent.completed).toBe(2);
131
+ expect(lastEvent.percentage).toBe(100);
132
+ });
133
+
134
+ it('should handle empty actions list', async () => {
135
+ const result = await manager.executeTransaction(
136
+ { name: 'empty', actions: [] },
137
+ async () => ({ success: true }),
138
+ );
139
+
140
+ expect(result.success).toBe(true);
141
+ expect(result.actionResults).toHaveLength(0);
142
+ });
143
+
144
+ it('should handle executor throwing errors', async () => {
145
+ const executor = async () => {
146
+ throw new Error('Executor crashed');
147
+ };
148
+
149
+ const result = await manager.executeTransaction(
150
+ {
151
+ name: 'error-txn',
152
+ actions: [makeAction('crash')],
153
+ },
154
+ executor,
155
+ );
156
+
157
+ expect(result.success).toBe(false);
158
+ expect(result.error).toContain('Executor crashed');
159
+ });
160
+
161
+ it('should generate unique transaction IDs', async () => {
162
+ const executor = async () => ({ success: true });
163
+
164
+ const result1 = await manager.executeTransaction(
165
+ { name: 'txn1', actions: [] },
166
+ executor,
167
+ );
168
+ const result2 = await manager.executeTransaction(
169
+ { name: 'txn2', actions: [] },
170
+ executor,
171
+ );
172
+
173
+ expect(result1.transactionId).not.toBe(result2.transactionId);
174
+ });
175
+ });
176
+
177
+ describe('Optimistic Updates', () => {
178
+ it('should apply and confirm optimistic updates', () => {
179
+ const update = manager.applyOptimisticUpdate({
180
+ type: 'update',
181
+ resource: 'orders',
182
+ recordId: '123',
183
+ optimisticData: { status: 'completed' },
184
+ previousData: { status: 'pending' },
185
+ });
186
+
187
+ expect(update.confirmed).toBe(false);
188
+ expect(update.rolledBack).toBe(false);
189
+
190
+ const confirmed = manager.confirmOptimisticUpdate(update.id);
191
+ expect(confirmed).toBe(true);
192
+ });
193
+
194
+ it('should rollback optimistic updates and return previous data', () => {
195
+ const previousData = { status: 'pending', amount: 100 };
196
+ const update = manager.applyOptimisticUpdate({
197
+ type: 'update',
198
+ resource: 'orders',
199
+ recordId: '456',
200
+ optimisticData: { status: 'shipped' },
201
+ previousData,
202
+ });
203
+
204
+ const restored = manager.rollbackOptimisticUpdate(update.id);
205
+ expect(restored).toEqual(previousData);
206
+ });
207
+
208
+ it('should return undefined for unknown update rollback', () => {
209
+ const restored = manager.rollbackOptimisticUpdate('nonexistent');
210
+ expect(restored).toBeUndefined();
211
+ });
212
+
213
+ it('should track pending updates', () => {
214
+ manager.applyOptimisticUpdate({
215
+ type: 'create',
216
+ resource: 'items',
217
+ optimisticData: { name: 'New Item' },
218
+ });
219
+
220
+ const update2 = manager.applyOptimisticUpdate({
221
+ type: 'update',
222
+ resource: 'items',
223
+ recordId: '1',
224
+ optimisticData: { name: 'Updated' },
225
+ });
226
+
227
+ expect(manager.getPendingUpdates()).toHaveLength(2);
228
+
229
+ manager.confirmOptimisticUpdate(update2.id);
230
+ expect(manager.getPendingUpdates()).toHaveLength(1);
231
+ });
232
+
233
+ it('should clear all optimistic updates', () => {
234
+ manager.applyOptimisticUpdate({
235
+ type: 'create',
236
+ resource: 'items',
237
+ optimisticData: { name: 'test' },
238
+ });
239
+
240
+ manager.clearOptimisticUpdates();
241
+ expect(manager.getPendingUpdates()).toHaveLength(0);
242
+ });
243
+ });
244
+
245
+ describe('executeBatch', () => {
246
+ it('should process all items successfully', async () => {
247
+ const items = [{ name: 'A' }, { name: 'B' }, { name: 'C' }];
248
+
249
+ const result = await manager.executeBatch('items', 'create', items);
250
+
251
+ expect(result.success).toBe(true);
252
+ expect(result.succeeded).toBe(3);
253
+ expect(result.failed).toBe(0);
254
+ expect(ds.create).toHaveBeenCalledTimes(3);
255
+ });
256
+
257
+ it('should handle update operations', async () => {
258
+ const items = [
259
+ { id: '1', name: 'Updated A' },
260
+ { id: '2', name: 'Updated B' },
261
+ ];
262
+
263
+ const result = await manager.executeBatch('items', 'update', items);
264
+
265
+ expect(result.success).toBe(true);
266
+ expect(result.succeeded).toBe(2);
267
+ expect(ds.update).toHaveBeenCalledTimes(2);
268
+ });
269
+
270
+ it('should handle delete operations', async () => {
271
+ const items = [{ id: '1' }, { id: '2' }];
272
+
273
+ const result = await manager.executeBatch('items', 'delete', items);
274
+
275
+ expect(result.success).toBe(true);
276
+ expect(result.succeeded).toBe(2);
277
+ expect(ds.delete).toHaveBeenCalledTimes(2);
278
+ });
279
+
280
+ it('should report errors for items missing IDs on update', async () => {
281
+ const items = [
282
+ { id: '1', name: 'A' },
283
+ { name: 'B' }, // Missing ID
284
+ ];
285
+
286
+ const result = await manager.executeBatch('items', 'update', items);
287
+
288
+ expect(result.success).toBe(false);
289
+ expect(result.succeeded).toBe(1);
290
+ expect(result.failed).toBe(1);
291
+ expect(result.errors[0].error).toContain('Missing ID');
292
+ });
293
+
294
+ it('should retry failed operations when configured', async () => {
295
+ let callCount = 0;
296
+ (ds.create as any).mockImplementation(() => {
297
+ callCount++;
298
+ if (callCount <= 2) throw new Error('Temporary failure');
299
+ return Promise.resolve({ id: 'new', name: 'test' });
300
+ });
301
+
302
+ const result = await manager.executeBatch(
303
+ 'items',
304
+ 'create',
305
+ [{ name: 'test' }],
306
+ { retryOnError: true, maxRetries: 3 },
307
+ );
308
+
309
+ expect(result.success).toBe(true);
310
+ expect(callCount).toBe(3);
311
+ });
312
+
313
+ it('should emit progress events', async () => {
314
+ const progressEvents: TransactionProgressEvent[] = [];
315
+
316
+ await manager.executeBatch(
317
+ 'items',
318
+ 'create',
319
+ [{ name: 'A' }, { name: 'B' }],
320
+ { onProgress: event => progressEvents.push({ ...event }) },
321
+ );
322
+
323
+ expect(progressEvents.length).toBeGreaterThan(0);
324
+ });
325
+
326
+ it('should try bulk operation first if available', async () => {
327
+ ds.bulk = vi.fn().mockResolvedValue([{ id: '1' }, { id: '2' }]);
328
+
329
+ const result = await manager.executeBatch('items', 'create', [
330
+ { name: 'A' },
331
+ { name: 'B' },
332
+ ]);
333
+
334
+ expect(result.success).toBe(true);
335
+ expect(ds.bulk).toHaveBeenCalled();
336
+ expect(ds.create).not.toHaveBeenCalled();
337
+ });
338
+
339
+ it('should fall back to individual processing when bulk fails', async () => {
340
+ ds.bulk = vi.fn().mockRejectedValue(new Error('Bulk not supported'));
341
+
342
+ const result = await manager.executeBatch('items', 'create', [
343
+ { name: 'A' },
344
+ ]);
345
+
346
+ expect(result.success).toBe(true);
347
+ expect(ds.create).toHaveBeenCalled();
348
+ });
349
+ });
350
+
351
+ describe('Rollback Operations', () => {
352
+ it('should rollback created records on transaction failure', async () => {
353
+ let step = 0;
354
+ const executor = async (action: ActionSchema) => {
355
+ step++;
356
+ if (step === 1) {
357
+ // First action succeeds and records an operation
358
+ manager.recordOperation({
359
+ type: 'create',
360
+ resource: 'orders',
361
+ result: { id: 'created-1' },
362
+ });
363
+ return { success: true };
364
+ }
365
+ return { success: false, error: 'Failed' };
366
+ };
367
+
368
+ await manager.executeTransaction(
369
+ { name: 'rollback-test', actions: [makeAction('step1'), makeAction('fail')] },
370
+ executor,
371
+ );
372
+
373
+ // The created record should be deleted during rollback
374
+ expect(ds.delete).toHaveBeenCalledWith('orders', 'created-1');
375
+ });
376
+
377
+ it('should rollback updated records by restoring previous state', async () => {
378
+ let step = 0;
379
+ const executor = async () => {
380
+ step++;
381
+ if (step === 1) {
382
+ manager.recordOperation({
383
+ type: 'update',
384
+ resource: 'orders',
385
+ id: '100',
386
+ previousState: { status: 'pending' },
387
+ });
388
+ return { success: true };
389
+ }
390
+ return { success: false, error: 'Failed' };
391
+ };
392
+
393
+ await manager.executeTransaction(
394
+ { name: 'rollback-update', actions: [makeAction('step1'), makeAction('fail')] },
395
+ executor,
396
+ );
397
+
398
+ expect(ds.update).toHaveBeenCalledWith('orders', '100', { status: 'pending' });
399
+ });
400
+
401
+ it('should rollback deleted records by re-creating them', async () => {
402
+ let step = 0;
403
+ const executor = async () => {
404
+ step++;
405
+ if (step === 1) {
406
+ manager.recordOperation({
407
+ type: 'delete',
408
+ resource: 'orders',
409
+ id: '200',
410
+ previousState: { id: '200', name: 'Test Order' },
411
+ });
412
+ return { success: true };
413
+ }
414
+ return { success: false, error: 'Failed' };
415
+ };
416
+
417
+ await manager.executeTransaction(
418
+ { name: 'rollback-delete', actions: [makeAction('step1'), makeAction('fail')] },
419
+ executor,
420
+ );
421
+
422
+ expect(ds.create).toHaveBeenCalledWith('orders', { id: '200', name: 'Test Order' });
423
+ });
424
+ });
425
+
426
+ describe('Progress Listener Management', () => {
427
+ it('should support unsubscribe from progress events', async () => {
428
+ const events: TransactionProgressEvent[] = [];
429
+ const unsubscribe = manager.onProgress(e => events.push(e));
430
+
431
+ await manager.executeTransaction(
432
+ { name: 'txn', actions: [makeAction('a')] },
433
+ async () => ({ success: true }),
434
+ );
435
+
436
+ const count1 = events.length;
437
+ unsubscribe();
438
+
439
+ await manager.executeTransaction(
440
+ { name: 'txn2', actions: [makeAction('b')] },
441
+ async () => ({ success: true }),
442
+ );
443
+
444
+ expect(events.length).toBe(count1);
445
+ });
446
+ });
447
+ });
@@ -7,3 +7,4 @@
7
7
  */
8
8
 
9
9
  export * from './ActionRunner.js';
10
+ export * from './TransactionManager.js';