@object-ui/core 0.5.0 → 3.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 (96) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +28 -0
  3. package/dist/__benchmarks__/core.bench.d.ts +8 -0
  4. package/dist/__benchmarks__/core.bench.js +53 -0
  5. package/dist/actions/ActionRunner.d.ts +228 -4
  6. package/dist/actions/ActionRunner.js +397 -45
  7. package/dist/actions/TransactionManager.d.ts +193 -0
  8. package/dist/actions/TransactionManager.js +410 -0
  9. package/dist/actions/index.d.ts +1 -0
  10. package/dist/actions/index.js +1 -0
  11. package/dist/adapters/ApiDataSource.d.ts +69 -0
  12. package/dist/adapters/ApiDataSource.js +293 -0
  13. package/dist/adapters/ValueDataSource.d.ts +55 -0
  14. package/dist/adapters/ValueDataSource.js +287 -0
  15. package/dist/adapters/index.d.ts +3 -0
  16. package/dist/adapters/index.js +5 -2
  17. package/dist/adapters/resolveDataSource.d.ts +40 -0
  18. package/dist/adapters/resolveDataSource.js +59 -0
  19. package/dist/data-scope/DataScopeManager.d.ts +127 -0
  20. package/dist/data-scope/DataScopeManager.js +229 -0
  21. package/dist/data-scope/index.d.ts +10 -0
  22. package/dist/data-scope/index.js +10 -0
  23. package/dist/errors/index.d.ts +75 -0
  24. package/dist/errors/index.js +224 -0
  25. package/dist/evaluator/ExpressionEvaluator.d.ts +11 -1
  26. package/dist/evaluator/ExpressionEvaluator.js +32 -8
  27. package/dist/evaluator/FormulaFunctions.d.ts +58 -0
  28. package/dist/evaluator/FormulaFunctions.js +350 -0
  29. package/dist/evaluator/index.d.ts +1 -0
  30. package/dist/evaluator/index.js +1 -0
  31. package/dist/index.d.ts +6 -0
  32. package/dist/index.js +6 -2
  33. package/dist/query/query-ast.d.ts +2 -2
  34. package/dist/query/query-ast.js +3 -3
  35. package/dist/registry/Registry.d.ts +10 -0
  36. package/dist/registry/Registry.js +9 -2
  37. package/dist/registry/WidgetRegistry.d.ts +120 -0
  38. package/dist/registry/WidgetRegistry.js +275 -0
  39. package/dist/theme/ThemeEngine.d.ts +105 -0
  40. package/dist/theme/ThemeEngine.js +469 -0
  41. package/dist/theme/index.d.ts +8 -0
  42. package/dist/theme/index.js +8 -0
  43. package/dist/utils/debug.d.ts +31 -0
  44. package/dist/utils/debug.js +62 -0
  45. package/dist/validation/index.d.ts +1 -1
  46. package/dist/validation/index.js +1 -1
  47. package/dist/validation/validation-engine.d.ts +19 -1
  48. package/dist/validation/validation-engine.js +74 -3
  49. package/dist/validation/validators/index.d.ts +1 -1
  50. package/dist/validation/validators/index.js +1 -1
  51. package/dist/validation/validators/object-validation-engine.d.ts +2 -2
  52. package/dist/validation/validators/object-validation-engine.js +1 -1
  53. package/package.json +4 -3
  54. package/src/__benchmarks__/core.bench.ts +64 -0
  55. package/src/actions/ActionRunner.ts +577 -55
  56. package/src/actions/TransactionManager.ts +521 -0
  57. package/src/actions/__tests__/ActionRunner.params.test.ts +134 -0
  58. package/src/actions/__tests__/ActionRunner.test.ts +711 -0
  59. package/src/actions/__tests__/TransactionManager.test.ts +447 -0
  60. package/src/actions/index.ts +1 -0
  61. package/src/adapters/ApiDataSource.ts +349 -0
  62. package/src/adapters/ValueDataSource.ts +332 -0
  63. package/src/adapters/__tests__/ApiDataSource.test.ts +418 -0
  64. package/src/adapters/__tests__/ValueDataSource.test.ts +325 -0
  65. package/src/adapters/__tests__/resolveDataSource.test.ts +144 -0
  66. package/src/adapters/index.ts +6 -1
  67. package/src/adapters/resolveDataSource.ts +79 -0
  68. package/src/builder/__tests__/schema-builder.test.ts +235 -0
  69. package/src/data-scope/DataScopeManager.ts +269 -0
  70. package/src/data-scope/__tests__/DataScopeManager.test.ts +211 -0
  71. package/src/data-scope/index.ts +16 -0
  72. package/src/errors/__tests__/errors.test.ts +292 -0
  73. package/src/errors/index.ts +270 -0
  74. package/src/evaluator/ExpressionEvaluator.ts +34 -8
  75. package/src/evaluator/FormulaFunctions.ts +398 -0
  76. package/src/evaluator/__tests__/ExpressionContext.test.ts +110 -0
  77. package/src/evaluator/__tests__/FormulaFunctions.test.ts +447 -0
  78. package/src/evaluator/index.ts +1 -0
  79. package/src/index.ts +6 -3
  80. package/src/query/__tests__/window-functions.test.ts +1 -1
  81. package/src/query/query-ast.ts +3 -3
  82. package/src/registry/Registry.ts +19 -2
  83. package/src/registry/WidgetRegistry.ts +316 -0
  84. package/src/registry/__tests__/WidgetRegistry.test.ts +321 -0
  85. package/src/theme/ThemeEngine.ts +530 -0
  86. package/src/theme/__tests__/ThemeEngine.test.ts +668 -0
  87. package/src/theme/index.ts +24 -0
  88. package/src/utils/__tests__/debug.test.ts +83 -0
  89. package/src/utils/debug.ts +66 -0
  90. package/src/validation/__tests__/object-validation-engine.test.ts +1 -1
  91. package/src/validation/__tests__/schema-validator.test.ts +118 -0
  92. package/src/validation/index.ts +1 -1
  93. package/src/validation/validation-engine.ts +70 -3
  94. package/src/validation/validators/index.ts +1 -1
  95. package/src/validation/validators/object-validation-engine.ts +2 -2
  96. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,193 @@
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
+ * @object-ui/core - Transaction Manager
10
+ *
11
+ * Provides transaction wrapper for multi-step operations via @objectstack/client.
12
+ * Supports optimistic UI updates with rollback on failure and batch operation
13
+ * progress tracking with connection-aware retry.
14
+ *
15
+ * @module actions
16
+ * @packageDocumentation
17
+ */
18
+ import type { DataSource, TransactionConfig, TransactionResult, ActionResult, UIActionSchema } from '@object-ui/types';
19
+ /**
20
+ * Operation within a transaction (recorded for rollback)
21
+ */
22
+ export interface TransactionOperation {
23
+ /** Operation type */
24
+ type: 'create' | 'update' | 'delete';
25
+ /** Target resource name */
26
+ resource: string;
27
+ /** Record ID (for update/delete) */
28
+ id?: string | number;
29
+ /** Data payload */
30
+ data?: Record<string, any>;
31
+ /** Previous state (for rollback) */
32
+ previousState?: Record<string, any>;
33
+ /** Result of the operation */
34
+ result?: any;
35
+ }
36
+ /**
37
+ * Optimistic update entry for UI state management
38
+ */
39
+ export interface OptimisticUpdate {
40
+ /** Unique update ID */
41
+ id: string;
42
+ /** Operation type */
43
+ type: 'create' | 'update' | 'delete';
44
+ /** Target resource */
45
+ resource: string;
46
+ /** Record ID */
47
+ recordId?: string | number;
48
+ /** Optimistic data to display */
49
+ optimisticData: Record<string, any>;
50
+ /** Previous data (for rollback) */
51
+ previousData?: Record<string, any>;
52
+ /** Whether the update has been confirmed by server */
53
+ confirmed: boolean;
54
+ /** Whether the update was rolled back */
55
+ rolledBack: boolean;
56
+ }
57
+ /**
58
+ * Progress event for batch transaction operations
59
+ */
60
+ export interface TransactionProgressEvent {
61
+ /** Transaction name */
62
+ transactionName: string;
63
+ /** Total operations to execute */
64
+ total: number;
65
+ /** Completed operations */
66
+ completed: number;
67
+ /** Failed operations */
68
+ failed: number;
69
+ /** Progress percentage (0-100) */
70
+ percentage: number;
71
+ /** Current operation description */
72
+ currentOperation?: string;
73
+ }
74
+ /**
75
+ * Progress callback type
76
+ */
77
+ export type TransactionProgressCallback = (event: TransactionProgressEvent) => void;
78
+ /**
79
+ * Transaction manager for executing multi-step operations with rollback support
80
+ */
81
+ export declare class TransactionManager {
82
+ private dataSource;
83
+ private operations;
84
+ private optimisticUpdates;
85
+ private progressListeners;
86
+ private maxRetries;
87
+ private retryDelay;
88
+ constructor(dataSource: DataSource, options?: {
89
+ maxRetries?: number;
90
+ retryDelay?: number;
91
+ });
92
+ /**
93
+ * Register a progress listener
94
+ */
95
+ onProgress(listener: TransactionProgressCallback): () => void;
96
+ /**
97
+ * Execute a set of operations within a logical transaction.
98
+ * If any operation fails, previously completed operations are rolled back.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const result = await manager.executeTransaction({
103
+ * name: 'Create Order',
104
+ * actions: [createOrderAction, updateInventoryAction, sendNotificationAction],
105
+ * retryOnConflict: true,
106
+ * maxRetries: 3,
107
+ * }, actionExecutor);
108
+ * ```
109
+ */
110
+ executeTransaction(config: TransactionConfig, actionExecutor: (action: UIActionSchema) => Promise<ActionResult>): Promise<TransactionResult>;
111
+ /**
112
+ * Apply an optimistic update to the UI and return a handle for confirmation/rollback.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * const update = manager.applyOptimisticUpdate({
117
+ * type: 'update',
118
+ * resource: 'orders',
119
+ * recordId: '123',
120
+ * optimisticData: { status: 'completed' },
121
+ * previousData: { status: 'pending' },
122
+ * });
123
+ *
124
+ * try {
125
+ * await dataSource.update('orders', '123', { status: 'completed' });
126
+ * manager.confirmOptimisticUpdate(update.id);
127
+ * } catch (error) {
128
+ * manager.rollbackOptimisticUpdate(update.id);
129
+ * }
130
+ * ```
131
+ */
132
+ applyOptimisticUpdate(params: {
133
+ type: 'create' | 'update' | 'delete';
134
+ resource: string;
135
+ recordId?: string | number;
136
+ optimisticData: Record<string, any>;
137
+ previousData?: Record<string, any>;
138
+ }): OptimisticUpdate;
139
+ /**
140
+ * Confirm an optimistic update (server operation succeeded)
141
+ */
142
+ confirmOptimisticUpdate(updateId: string): boolean;
143
+ /**
144
+ * Rollback an optimistic update (server operation failed)
145
+ * Returns the previous data that should be restored in the UI.
146
+ */
147
+ rollbackOptimisticUpdate(updateId: string): Record<string, any> | undefined;
148
+ /**
149
+ * Get all pending (unconfirmed, non-rolled-back) optimistic updates
150
+ */
151
+ getPendingUpdates(): OptimisticUpdate[];
152
+ /**
153
+ * Clear all optimistic updates
154
+ */
155
+ clearOptimisticUpdates(): void;
156
+ /**
157
+ * Execute a batch of data operations with progress tracking and retry.
158
+ *
159
+ * @example
160
+ * ```ts
161
+ * const results = await manager.executeBatch('orders', 'update', items, {
162
+ * onProgress: (event) => console.log(`${event.percentage}% complete`),
163
+ * });
164
+ * ```
165
+ */
166
+ executeBatch<T = any>(resource: string, operation: 'create' | 'update' | 'delete', items: Partial<T>[], options?: {
167
+ onProgress?: TransactionProgressCallback;
168
+ retryOnError?: boolean;
169
+ maxRetries?: number;
170
+ }): Promise<{
171
+ success: boolean;
172
+ results: T[];
173
+ errors: Array<{
174
+ index: number;
175
+ error: string;
176
+ }>;
177
+ total: number;
178
+ succeeded: number;
179
+ failed: number;
180
+ }>;
181
+ /**
182
+ * Record an operation for potential rollback
183
+ */
184
+ recordOperation(op: TransactionOperation): void;
185
+ /**
186
+ * Rollback all recorded operations in reverse order
187
+ */
188
+ private rollbackOperations;
189
+ /**
190
+ * Emit progress event to all listeners
191
+ */
192
+ private emitProgress;
193
+ }
@@ -0,0 +1,410 @@
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
+ * Transaction manager for executing multi-step operations with rollback support
10
+ */
11
+ export class TransactionManager {
12
+ constructor(dataSource, options) {
13
+ Object.defineProperty(this, "dataSource", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: void 0
18
+ });
19
+ Object.defineProperty(this, "operations", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: []
24
+ });
25
+ Object.defineProperty(this, "optimisticUpdates", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: new Map()
30
+ });
31
+ Object.defineProperty(this, "progressListeners", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: []
36
+ });
37
+ Object.defineProperty(this, "maxRetries", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "retryDelay", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ this.dataSource = dataSource;
50
+ this.maxRetries = options?.maxRetries ?? 3;
51
+ this.retryDelay = options?.retryDelay ?? 1000;
52
+ }
53
+ /**
54
+ * Register a progress listener
55
+ */
56
+ onProgress(listener) {
57
+ this.progressListeners.push(listener);
58
+ return () => {
59
+ const idx = this.progressListeners.indexOf(listener);
60
+ if (idx > -1)
61
+ this.progressListeners.splice(idx, 1);
62
+ };
63
+ }
64
+ /**
65
+ * Execute a set of operations within a logical transaction.
66
+ * If any operation fails, previously completed operations are rolled back.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * const result = await manager.executeTransaction({
71
+ * name: 'Create Order',
72
+ * actions: [createOrderAction, updateInventoryAction, sendNotificationAction],
73
+ * retryOnConflict: true,
74
+ * maxRetries: 3,
75
+ * }, actionExecutor);
76
+ * ```
77
+ */
78
+ async executeTransaction(config, actionExecutor) {
79
+ const transactionId = generateId();
80
+ const actions = config.actions || [];
81
+ const maxRetries = config.maxRetries ?? this.maxRetries;
82
+ const actionResults = [];
83
+ this.operations = [];
84
+ let completed = 0;
85
+ let failed = 0;
86
+ const emitProgress = (currentOp) => {
87
+ this.emitProgress({
88
+ transactionName: config.name || transactionId,
89
+ total: actions.length,
90
+ completed,
91
+ failed,
92
+ percentage: actions.length > 0 ? ((completed + failed) / actions.length) * 100 : 0,
93
+ currentOperation: currentOp,
94
+ });
95
+ };
96
+ try {
97
+ for (const action of actions) {
98
+ emitProgress(action.label || action.name);
99
+ let result;
100
+ let lastError;
101
+ // Retry loop for conflict handling
102
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
103
+ try {
104
+ result = await actionExecutor(action);
105
+ if (result.success) {
106
+ break;
107
+ }
108
+ else {
109
+ lastError = result.error;
110
+ // Only retry on conflict if enabled
111
+ if (config.retryOnConflict && attempt < maxRetries) {
112
+ await delay(this.retryDelay * Math.pow(2, attempt));
113
+ continue;
114
+ }
115
+ break;
116
+ }
117
+ }
118
+ catch (error) {
119
+ lastError = error.message;
120
+ if (config.retryOnConflict && attempt < maxRetries) {
121
+ await delay(this.retryDelay * Math.pow(2, attempt));
122
+ continue;
123
+ }
124
+ result = { success: false, error: lastError };
125
+ break;
126
+ }
127
+ }
128
+ if (!result) {
129
+ result = { success: false, error: lastError || 'Unknown error' };
130
+ }
131
+ actionResults.push(result);
132
+ if (result.success) {
133
+ completed++;
134
+ emitProgress();
135
+ }
136
+ else {
137
+ failed++;
138
+ emitProgress();
139
+ // Transaction failed - rollback previous operations
140
+ await this.rollbackOperations();
141
+ return {
142
+ success: false,
143
+ transactionId,
144
+ actionResults,
145
+ error: result.error || `Action "${action.name}" failed`,
146
+ rolledBack: true,
147
+ };
148
+ }
149
+ }
150
+ return {
151
+ success: true,
152
+ transactionId,
153
+ actionResults,
154
+ };
155
+ }
156
+ catch (error) {
157
+ await this.rollbackOperations();
158
+ return {
159
+ success: false,
160
+ transactionId,
161
+ actionResults,
162
+ error: error.message,
163
+ rolledBack: true,
164
+ };
165
+ }
166
+ }
167
+ /**
168
+ * Apply an optimistic update to the UI and return a handle for confirmation/rollback.
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * const update = manager.applyOptimisticUpdate({
173
+ * type: 'update',
174
+ * resource: 'orders',
175
+ * recordId: '123',
176
+ * optimisticData: { status: 'completed' },
177
+ * previousData: { status: 'pending' },
178
+ * });
179
+ *
180
+ * try {
181
+ * await dataSource.update('orders', '123', { status: 'completed' });
182
+ * manager.confirmOptimisticUpdate(update.id);
183
+ * } catch (error) {
184
+ * manager.rollbackOptimisticUpdate(update.id);
185
+ * }
186
+ * ```
187
+ */
188
+ applyOptimisticUpdate(params) {
189
+ const update = {
190
+ id: generateId(),
191
+ type: params.type,
192
+ resource: params.resource,
193
+ recordId: params.recordId,
194
+ optimisticData: params.optimisticData,
195
+ previousData: params.previousData,
196
+ confirmed: false,
197
+ rolledBack: false,
198
+ };
199
+ this.optimisticUpdates.set(update.id, update);
200
+ return update;
201
+ }
202
+ /**
203
+ * Confirm an optimistic update (server operation succeeded)
204
+ */
205
+ confirmOptimisticUpdate(updateId) {
206
+ const update = this.optimisticUpdates.get(updateId);
207
+ if (!update)
208
+ return false;
209
+ update.confirmed = true;
210
+ return true;
211
+ }
212
+ /**
213
+ * Rollback an optimistic update (server operation failed)
214
+ * Returns the previous data that should be restored in the UI.
215
+ */
216
+ rollbackOptimisticUpdate(updateId) {
217
+ const update = this.optimisticUpdates.get(updateId);
218
+ if (!update)
219
+ return undefined;
220
+ update.rolledBack = true;
221
+ return update.previousData;
222
+ }
223
+ /**
224
+ * Get all pending (unconfirmed, non-rolled-back) optimistic updates
225
+ */
226
+ getPendingUpdates() {
227
+ return Array.from(this.optimisticUpdates.values()).filter(u => !u.confirmed && !u.rolledBack);
228
+ }
229
+ /**
230
+ * Clear all optimistic updates
231
+ */
232
+ clearOptimisticUpdates() {
233
+ this.optimisticUpdates.clear();
234
+ }
235
+ /**
236
+ * Execute a batch of data operations with progress tracking and retry.
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * const results = await manager.executeBatch('orders', 'update', items, {
241
+ * onProgress: (event) => console.log(`${event.percentage}% complete`),
242
+ * });
243
+ * ```
244
+ */
245
+ async executeBatch(resource, operation, items, options) {
246
+ const maxRetries = options?.maxRetries ?? this.maxRetries;
247
+ const retryOnError = options?.retryOnError ?? true;
248
+ const results = [];
249
+ const errors = [];
250
+ let completed = 0;
251
+ let failed = 0;
252
+ const emitProgress = (currentOp) => {
253
+ const event = {
254
+ transactionName: `batch-${operation}`,
255
+ total: items.length,
256
+ completed,
257
+ failed,
258
+ percentage: items.length > 0 ? ((completed + failed) / items.length) * 100 : 0,
259
+ currentOperation: currentOp,
260
+ };
261
+ this.emitProgress(event);
262
+ options?.onProgress?.(event);
263
+ };
264
+ // Try bulk operation first if available
265
+ if (this.dataSource.bulk) {
266
+ try {
267
+ const bulkResult = await this.dataSource.bulk(resource, operation, items);
268
+ return {
269
+ success: true,
270
+ results: bulkResult,
271
+ errors: [],
272
+ total: items.length,
273
+ succeeded: items.length,
274
+ failed: 0,
275
+ };
276
+ }
277
+ catch {
278
+ // Fall through to individual processing
279
+ }
280
+ }
281
+ // Individual processing with retry
282
+ for (let i = 0; i < items.length; i++) {
283
+ const item = items[i];
284
+ let lastError;
285
+ let success = false;
286
+ for (let attempt = 0; attempt <= (retryOnError ? maxRetries : 0); attempt++) {
287
+ try {
288
+ let result;
289
+ switch (operation) {
290
+ case 'create':
291
+ result = await this.dataSource.create(resource, item);
292
+ break;
293
+ case 'update': {
294
+ const id = item.id;
295
+ if (!id)
296
+ throw new Error(`Missing ID for item at index ${i}`);
297
+ result = await this.dataSource.update(resource, id, item);
298
+ break;
299
+ }
300
+ case 'delete': {
301
+ const deleteId = item.id;
302
+ if (!deleteId)
303
+ throw new Error(`Missing ID for item at index ${i}`);
304
+ await this.dataSource.delete(resource, deleteId);
305
+ result = item;
306
+ break;
307
+ }
308
+ }
309
+ results.push(result);
310
+ completed++;
311
+ success = true;
312
+ emitProgress();
313
+ break;
314
+ }
315
+ catch (error) {
316
+ lastError = error.message;
317
+ if (retryOnError && attempt < maxRetries) {
318
+ await delay(this.retryDelay * Math.pow(2, attempt));
319
+ continue;
320
+ }
321
+ }
322
+ }
323
+ if (!success) {
324
+ errors.push({ index: i, error: lastError || 'Unknown error' });
325
+ failed++;
326
+ emitProgress();
327
+ }
328
+ }
329
+ return {
330
+ success: errors.length === 0,
331
+ results,
332
+ errors,
333
+ total: items.length,
334
+ succeeded: completed,
335
+ failed,
336
+ };
337
+ }
338
+ /**
339
+ * Record an operation for potential rollback
340
+ */
341
+ recordOperation(op) {
342
+ this.operations.push(op);
343
+ }
344
+ /**
345
+ * Rollback all recorded operations in reverse order
346
+ */
347
+ async rollbackOperations() {
348
+ const ops = [...this.operations].reverse();
349
+ for (const op of ops) {
350
+ try {
351
+ switch (op.type) {
352
+ case 'create':
353
+ // Undo create -> delete the created record
354
+ if (op.result?.id) {
355
+ await this.dataSource.delete(op.resource, op.result.id);
356
+ }
357
+ break;
358
+ case 'update':
359
+ // Undo update -> restore previous state
360
+ if (op.id && op.previousState) {
361
+ await this.dataSource.update(op.resource, op.id, op.previousState);
362
+ }
363
+ break;
364
+ case 'delete':
365
+ // Undo delete -> re-create with previous state
366
+ if (op.previousState) {
367
+ await this.dataSource.create(op.resource, op.previousState);
368
+ }
369
+ break;
370
+ }
371
+ }
372
+ catch (error) {
373
+ // Rollback errors are logged but don't throw
374
+ console.error(`Rollback failed for ${op.type} on ${op.resource}:`, error);
375
+ }
376
+ }
377
+ this.operations = [];
378
+ }
379
+ /**
380
+ * Emit progress event to all listeners
381
+ */
382
+ emitProgress(event) {
383
+ for (const listener of this.progressListeners) {
384
+ try {
385
+ listener(event);
386
+ }
387
+ catch (error) {
388
+ console.error('Error in transaction progress listener:', error);
389
+ }
390
+ }
391
+ }
392
+ }
393
+ // ==========================================================================
394
+ // Helpers
395
+ // ==========================================================================
396
+ /**
397
+ * Generate a unique transaction ID using crypto when available
398
+ */
399
+ function generateId() {
400
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
401
+ return `txn_${crypto.randomUUID()}`;
402
+ }
403
+ return `txn_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
404
+ }
405
+ /**
406
+ * Promise-based delay
407
+ */
408
+ function delay(ms) {
409
+ return new Promise(resolve => setTimeout(resolve, ms));
410
+ }
@@ -6,3 +6,4 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  export * from './ActionRunner.js';
9
+ export * from './TransactionManager.js';
@@ -6,3 +6,4 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  export * from './ActionRunner.js';
9
+ export * from './TransactionManager.js';
@@ -0,0 +1,69 @@
1
+ /**
2
+ * ObjectUI — ApiDataSource
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
+ * A DataSource adapter for the `provider: 'api'` ViewData mode.
9
+ * Makes raw HTTP requests using the HttpRequest configs from ViewData.
10
+ */
11
+ import type { DataSource, QueryParams, QueryResult, HttpRequest } from '@object-ui/types';
12
+ export interface ApiDataSourceConfig {
13
+ /** HttpRequest config for read operations (find, findOne) */
14
+ read?: HttpRequest;
15
+ /** HttpRequest config for write operations (create, update, delete) */
16
+ write?: HttpRequest;
17
+ /** Custom fetch implementation (defaults to globalThis.fetch) */
18
+ fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
19
+ /** Default headers applied to all requests */
20
+ defaultHeaders?: Record<string, string>;
21
+ }
22
+ /**
23
+ * ApiDataSource — a DataSource adapter for raw HTTP APIs.
24
+ *
25
+ * Used when `ViewData.provider === 'api'`. The read and write HttpRequest
26
+ * configs define the endpoints; all CRUD methods map onto HTTP verbs.
27
+ *
28
+ * Read operations use the `read` config, write operations use the `write` config.
29
+ * Both fall back to each other when one is not provided.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const ds = new ApiDataSource({
34
+ * read: { url: '/api/contacts', method: 'GET' },
35
+ * write: { url: '/api/contacts', method: 'POST' },
36
+ * });
37
+ *
38
+ * const result = await ds.find('contacts', { $top: 10 });
39
+ * ```
40
+ */
41
+ export declare class ApiDataSource<T = any> implements DataSource<T> {
42
+ private readConfig;
43
+ private writeConfig;
44
+ private fetchFn;
45
+ private defaultHeaders;
46
+ constructor(config: ApiDataSourceConfig);
47
+ private request;
48
+ find(_resource: string, params?: QueryParams): Promise<QueryResult<T>>;
49
+ findOne(_resource: string, id: string | number, params?: QueryParams): Promise<T | null>;
50
+ create(_resource: string, data: Partial<T>): Promise<T>;
51
+ update(_resource: string, id: string | number, data: Partial<T>): Promise<T>;
52
+ delete(_resource: string, id: string | number): Promise<boolean>;
53
+ getObjectSchema(_objectName: string): Promise<any>;
54
+ getView(_objectName: string, _viewId: string): Promise<any | null>;
55
+ getApp(_appId: string): Promise<any | null>;
56
+ /**
57
+ * Normalize various API response shapes into a QueryResult.
58
+ *
59
+ * Supported shapes:
60
+ * - `T[]` → wrap in QueryResult
61
+ * - `{ data: T[] }` → extract data
62
+ * - `{ items: T[] }` → extract items
63
+ * - `{ results: T[] }` → extract results
64
+ * - `{ records: T[] }` → extract records (Salesforce-style)
65
+ * - `{ value: T[] }` → extract value (OData-style)
66
+ * - Full QueryResult (has data + totalCount) → return as-is
67
+ */
68
+ private normalizeQueryResult;
69
+ }