@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.
- package/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +28 -0
- package/dist/__benchmarks__/core.bench.d.ts +8 -0
- package/dist/__benchmarks__/core.bench.js +53 -0
- package/dist/actions/ActionRunner.d.ts +228 -4
- package/dist/actions/ActionRunner.js +397 -45
- package/dist/actions/TransactionManager.d.ts +193 -0
- package/dist/actions/TransactionManager.js +410 -0
- package/dist/actions/index.d.ts +1 -0
- package/dist/actions/index.js +1 -0
- package/dist/adapters/ApiDataSource.d.ts +69 -0
- package/dist/adapters/ApiDataSource.js +293 -0
- package/dist/adapters/ValueDataSource.d.ts +55 -0
- package/dist/adapters/ValueDataSource.js +287 -0
- package/dist/adapters/index.d.ts +3 -0
- package/dist/adapters/index.js +5 -2
- package/dist/adapters/resolveDataSource.d.ts +40 -0
- package/dist/adapters/resolveDataSource.js +59 -0
- package/dist/data-scope/DataScopeManager.d.ts +127 -0
- package/dist/data-scope/DataScopeManager.js +229 -0
- package/dist/data-scope/index.d.ts +10 -0
- package/dist/data-scope/index.js +10 -0
- package/dist/errors/index.d.ts +75 -0
- package/dist/errors/index.js +224 -0
- package/dist/evaluator/ExpressionEvaluator.d.ts +11 -1
- package/dist/evaluator/ExpressionEvaluator.js +32 -8
- package/dist/evaluator/FormulaFunctions.d.ts +58 -0
- package/dist/evaluator/FormulaFunctions.js +350 -0
- package/dist/evaluator/index.d.ts +1 -0
- package/dist/evaluator/index.js +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -2
- package/dist/query/query-ast.d.ts +2 -2
- package/dist/query/query-ast.js +3 -3
- package/dist/registry/Registry.d.ts +10 -0
- package/dist/registry/Registry.js +9 -2
- package/dist/registry/WidgetRegistry.d.ts +120 -0
- package/dist/registry/WidgetRegistry.js +275 -0
- package/dist/theme/ThemeEngine.d.ts +105 -0
- package/dist/theme/ThemeEngine.js +469 -0
- package/dist/theme/index.d.ts +8 -0
- package/dist/theme/index.js +8 -0
- package/dist/utils/debug.d.ts +31 -0
- package/dist/utils/debug.js +62 -0
- package/dist/validation/index.d.ts +1 -1
- package/dist/validation/index.js +1 -1
- package/dist/validation/validation-engine.d.ts +19 -1
- package/dist/validation/validation-engine.js +74 -3
- package/dist/validation/validators/index.d.ts +1 -1
- package/dist/validation/validators/index.js +1 -1
- package/dist/validation/validators/object-validation-engine.d.ts +2 -2
- package/dist/validation/validators/object-validation-engine.js +1 -1
- package/package.json +4 -3
- package/src/__benchmarks__/core.bench.ts +64 -0
- package/src/actions/ActionRunner.ts +577 -55
- package/src/actions/TransactionManager.ts +521 -0
- package/src/actions/__tests__/ActionRunner.params.test.ts +134 -0
- package/src/actions/__tests__/ActionRunner.test.ts +711 -0
- package/src/actions/__tests__/TransactionManager.test.ts +447 -0
- package/src/actions/index.ts +1 -0
- package/src/adapters/ApiDataSource.ts +349 -0
- package/src/adapters/ValueDataSource.ts +332 -0
- package/src/adapters/__tests__/ApiDataSource.test.ts +418 -0
- package/src/adapters/__tests__/ValueDataSource.test.ts +325 -0
- package/src/adapters/__tests__/resolveDataSource.test.ts +144 -0
- package/src/adapters/index.ts +6 -1
- package/src/adapters/resolveDataSource.ts +79 -0
- package/src/builder/__tests__/schema-builder.test.ts +235 -0
- package/src/data-scope/DataScopeManager.ts +269 -0
- package/src/data-scope/__tests__/DataScopeManager.test.ts +211 -0
- package/src/data-scope/index.ts +16 -0
- package/src/errors/__tests__/errors.test.ts +292 -0
- package/src/errors/index.ts +270 -0
- package/src/evaluator/ExpressionEvaluator.ts +34 -8
- package/src/evaluator/FormulaFunctions.ts +398 -0
- package/src/evaluator/__tests__/ExpressionContext.test.ts +110 -0
- package/src/evaluator/__tests__/FormulaFunctions.test.ts +447 -0
- package/src/evaluator/index.ts +1 -0
- package/src/index.ts +6 -3
- package/src/query/__tests__/window-functions.test.ts +1 -1
- package/src/query/query-ast.ts +3 -3
- package/src/registry/Registry.ts +19 -2
- package/src/registry/WidgetRegistry.ts +316 -0
- package/src/registry/__tests__/WidgetRegistry.test.ts +321 -0
- package/src/theme/ThemeEngine.ts +530 -0
- package/src/theme/__tests__/ThemeEngine.test.ts +668 -0
- package/src/theme/index.ts +24 -0
- package/src/utils/__tests__/debug.test.ts +83 -0
- package/src/utils/debug.ts +66 -0
- package/src/validation/__tests__/object-validation-engine.test.ts +1 -1
- package/src/validation/__tests__/schema-validator.test.ts +118 -0
- package/src/validation/index.ts +1 -1
- package/src/validation/validation-engine.ts +70 -3
- package/src/validation/validators/index.ts +1 -1
- package/src/validation/validators/object-validation-engine.ts +2 -2
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,521 @@
|
|
|
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
|
+
/**
|
|
10
|
+
* @object-ui/core - Transaction Manager
|
|
11
|
+
*
|
|
12
|
+
* Provides transaction wrapper for multi-step operations via @objectstack/client.
|
|
13
|
+
* Supports optimistic UI updates with rollback on failure and batch operation
|
|
14
|
+
* progress tracking with connection-aware retry.
|
|
15
|
+
*
|
|
16
|
+
* @module actions
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type {
|
|
21
|
+
DataSource,
|
|
22
|
+
TransactionConfig,
|
|
23
|
+
TransactionResult,
|
|
24
|
+
ActionResult,
|
|
25
|
+
UIActionSchema,
|
|
26
|
+
} from '@object-ui/types';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Operation within a transaction (recorded for rollback)
|
|
30
|
+
*/
|
|
31
|
+
export interface TransactionOperation {
|
|
32
|
+
/** Operation type */
|
|
33
|
+
type: 'create' | 'update' | 'delete';
|
|
34
|
+
/** Target resource name */
|
|
35
|
+
resource: string;
|
|
36
|
+
/** Record ID (for update/delete) */
|
|
37
|
+
id?: string | number;
|
|
38
|
+
/** Data payload */
|
|
39
|
+
data?: Record<string, any>;
|
|
40
|
+
/** Previous state (for rollback) */
|
|
41
|
+
previousState?: Record<string, any>;
|
|
42
|
+
/** Result of the operation */
|
|
43
|
+
result?: any;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Optimistic update entry for UI state management
|
|
48
|
+
*/
|
|
49
|
+
export interface OptimisticUpdate {
|
|
50
|
+
/** Unique update ID */
|
|
51
|
+
id: string;
|
|
52
|
+
/** Operation type */
|
|
53
|
+
type: 'create' | 'update' | 'delete';
|
|
54
|
+
/** Target resource */
|
|
55
|
+
resource: string;
|
|
56
|
+
/** Record ID */
|
|
57
|
+
recordId?: string | number;
|
|
58
|
+
/** Optimistic data to display */
|
|
59
|
+
optimisticData: Record<string, any>;
|
|
60
|
+
/** Previous data (for rollback) */
|
|
61
|
+
previousData?: Record<string, any>;
|
|
62
|
+
/** Whether the update has been confirmed by server */
|
|
63
|
+
confirmed: boolean;
|
|
64
|
+
/** Whether the update was rolled back */
|
|
65
|
+
rolledBack: boolean;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Progress event for batch transaction operations
|
|
70
|
+
*/
|
|
71
|
+
export interface TransactionProgressEvent {
|
|
72
|
+
/** Transaction name */
|
|
73
|
+
transactionName: string;
|
|
74
|
+
/** Total operations to execute */
|
|
75
|
+
total: number;
|
|
76
|
+
/** Completed operations */
|
|
77
|
+
completed: number;
|
|
78
|
+
/** Failed operations */
|
|
79
|
+
failed: number;
|
|
80
|
+
/** Progress percentage (0-100) */
|
|
81
|
+
percentage: number;
|
|
82
|
+
/** Current operation description */
|
|
83
|
+
currentOperation?: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Progress callback type
|
|
88
|
+
*/
|
|
89
|
+
export type TransactionProgressCallback = (event: TransactionProgressEvent) => void;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Transaction manager for executing multi-step operations with rollback support
|
|
93
|
+
*/
|
|
94
|
+
export class TransactionManager {
|
|
95
|
+
private dataSource: DataSource;
|
|
96
|
+
private operations: TransactionOperation[] = [];
|
|
97
|
+
private optimisticUpdates: Map<string, OptimisticUpdate> = new Map();
|
|
98
|
+
private progressListeners: TransactionProgressCallback[] = [];
|
|
99
|
+
private maxRetries: number;
|
|
100
|
+
private retryDelay: number;
|
|
101
|
+
|
|
102
|
+
constructor(
|
|
103
|
+
dataSource: DataSource,
|
|
104
|
+
options?: {
|
|
105
|
+
maxRetries?: number;
|
|
106
|
+
retryDelay?: number;
|
|
107
|
+
},
|
|
108
|
+
) {
|
|
109
|
+
this.dataSource = dataSource;
|
|
110
|
+
this.maxRetries = options?.maxRetries ?? 3;
|
|
111
|
+
this.retryDelay = options?.retryDelay ?? 1000;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Register a progress listener
|
|
116
|
+
*/
|
|
117
|
+
onProgress(listener: TransactionProgressCallback): () => void {
|
|
118
|
+
this.progressListeners.push(listener);
|
|
119
|
+
return () => {
|
|
120
|
+
const idx = this.progressListeners.indexOf(listener);
|
|
121
|
+
if (idx > -1) this.progressListeners.splice(idx, 1);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Execute a set of operations within a logical transaction.
|
|
127
|
+
* If any operation fails, previously completed operations are rolled back.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```ts
|
|
131
|
+
* const result = await manager.executeTransaction({
|
|
132
|
+
* name: 'Create Order',
|
|
133
|
+
* actions: [createOrderAction, updateInventoryAction, sendNotificationAction],
|
|
134
|
+
* retryOnConflict: true,
|
|
135
|
+
* maxRetries: 3,
|
|
136
|
+
* }, actionExecutor);
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
async executeTransaction(
|
|
140
|
+
config: TransactionConfig,
|
|
141
|
+
actionExecutor: (action: UIActionSchema) => Promise<ActionResult>,
|
|
142
|
+
): Promise<TransactionResult> {
|
|
143
|
+
const transactionId = generateId();
|
|
144
|
+
const actions = config.actions || [];
|
|
145
|
+
const maxRetries = config.maxRetries ?? this.maxRetries;
|
|
146
|
+
const actionResults: ActionResult[] = [];
|
|
147
|
+
|
|
148
|
+
this.operations = [];
|
|
149
|
+
let completed = 0;
|
|
150
|
+
let failed = 0;
|
|
151
|
+
|
|
152
|
+
const emitProgress = (currentOp?: string) => {
|
|
153
|
+
this.emitProgress({
|
|
154
|
+
transactionName: config.name || transactionId,
|
|
155
|
+
total: actions.length,
|
|
156
|
+
completed,
|
|
157
|
+
failed,
|
|
158
|
+
percentage: actions.length > 0 ? ((completed + failed) / actions.length) * 100 : 0,
|
|
159
|
+
currentOperation: currentOp,
|
|
160
|
+
});
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
for (const action of actions) {
|
|
165
|
+
emitProgress(action.label || action.name);
|
|
166
|
+
|
|
167
|
+
let result: ActionResult | undefined;
|
|
168
|
+
let lastError: string | undefined;
|
|
169
|
+
|
|
170
|
+
// Retry loop for conflict handling
|
|
171
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
172
|
+
try {
|
|
173
|
+
result = await actionExecutor(action);
|
|
174
|
+
|
|
175
|
+
if (result.success) {
|
|
176
|
+
break;
|
|
177
|
+
} else {
|
|
178
|
+
lastError = result.error;
|
|
179
|
+
// Only retry on conflict if enabled
|
|
180
|
+
if (config.retryOnConflict && attempt < maxRetries) {
|
|
181
|
+
await delay(this.retryDelay * Math.pow(2, attempt));
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
} catch (error) {
|
|
187
|
+
lastError = (error as Error).message;
|
|
188
|
+
if (config.retryOnConflict && attempt < maxRetries) {
|
|
189
|
+
await delay(this.retryDelay * Math.pow(2, attempt));
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
result = { success: false, error: lastError };
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (!result) {
|
|
198
|
+
result = { success: false, error: lastError || 'Unknown error' };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
actionResults.push(result);
|
|
202
|
+
|
|
203
|
+
if (result.success) {
|
|
204
|
+
completed++;
|
|
205
|
+
emitProgress();
|
|
206
|
+
} else {
|
|
207
|
+
failed++;
|
|
208
|
+
emitProgress();
|
|
209
|
+
|
|
210
|
+
// Transaction failed - rollback previous operations
|
|
211
|
+
await this.rollbackOperations();
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
success: false,
|
|
215
|
+
transactionId,
|
|
216
|
+
actionResults,
|
|
217
|
+
error: result.error || `Action "${action.name}" failed`,
|
|
218
|
+
rolledBack: true,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
success: true,
|
|
225
|
+
transactionId,
|
|
226
|
+
actionResults,
|
|
227
|
+
};
|
|
228
|
+
} catch (error) {
|
|
229
|
+
await this.rollbackOperations();
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
success: false,
|
|
233
|
+
transactionId,
|
|
234
|
+
actionResults,
|
|
235
|
+
error: (error as Error).message,
|
|
236
|
+
rolledBack: true,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Apply an optimistic update to the UI and return a handle for confirmation/rollback.
|
|
243
|
+
*
|
|
244
|
+
* @example
|
|
245
|
+
* ```ts
|
|
246
|
+
* const update = manager.applyOptimisticUpdate({
|
|
247
|
+
* type: 'update',
|
|
248
|
+
* resource: 'orders',
|
|
249
|
+
* recordId: '123',
|
|
250
|
+
* optimisticData: { status: 'completed' },
|
|
251
|
+
* previousData: { status: 'pending' },
|
|
252
|
+
* });
|
|
253
|
+
*
|
|
254
|
+
* try {
|
|
255
|
+
* await dataSource.update('orders', '123', { status: 'completed' });
|
|
256
|
+
* manager.confirmOptimisticUpdate(update.id);
|
|
257
|
+
* } catch (error) {
|
|
258
|
+
* manager.rollbackOptimisticUpdate(update.id);
|
|
259
|
+
* }
|
|
260
|
+
* ```
|
|
261
|
+
*/
|
|
262
|
+
applyOptimisticUpdate(params: {
|
|
263
|
+
type: 'create' | 'update' | 'delete';
|
|
264
|
+
resource: string;
|
|
265
|
+
recordId?: string | number;
|
|
266
|
+
optimisticData: Record<string, any>;
|
|
267
|
+
previousData?: Record<string, any>;
|
|
268
|
+
}): OptimisticUpdate {
|
|
269
|
+
const update: OptimisticUpdate = {
|
|
270
|
+
id: generateId(),
|
|
271
|
+
type: params.type,
|
|
272
|
+
resource: params.resource,
|
|
273
|
+
recordId: params.recordId,
|
|
274
|
+
optimisticData: params.optimisticData,
|
|
275
|
+
previousData: params.previousData,
|
|
276
|
+
confirmed: false,
|
|
277
|
+
rolledBack: false,
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
this.optimisticUpdates.set(update.id, update);
|
|
281
|
+
return update;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Confirm an optimistic update (server operation succeeded)
|
|
286
|
+
*/
|
|
287
|
+
confirmOptimisticUpdate(updateId: string): boolean {
|
|
288
|
+
const update = this.optimisticUpdates.get(updateId);
|
|
289
|
+
if (!update) return false;
|
|
290
|
+
update.confirmed = true;
|
|
291
|
+
return true;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Rollback an optimistic update (server operation failed)
|
|
296
|
+
* Returns the previous data that should be restored in the UI.
|
|
297
|
+
*/
|
|
298
|
+
rollbackOptimisticUpdate(updateId: string): Record<string, any> | undefined {
|
|
299
|
+
const update = this.optimisticUpdates.get(updateId);
|
|
300
|
+
if (!update) return undefined;
|
|
301
|
+
update.rolledBack = true;
|
|
302
|
+
return update.previousData;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Get all pending (unconfirmed, non-rolled-back) optimistic updates
|
|
307
|
+
*/
|
|
308
|
+
getPendingUpdates(): OptimisticUpdate[] {
|
|
309
|
+
return Array.from(this.optimisticUpdates.values()).filter(
|
|
310
|
+
u => !u.confirmed && !u.rolledBack,
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Clear all optimistic updates
|
|
316
|
+
*/
|
|
317
|
+
clearOptimisticUpdates(): void {
|
|
318
|
+
this.optimisticUpdates.clear();
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Execute a batch of data operations with progress tracking and retry.
|
|
323
|
+
*
|
|
324
|
+
* @example
|
|
325
|
+
* ```ts
|
|
326
|
+
* const results = await manager.executeBatch('orders', 'update', items, {
|
|
327
|
+
* onProgress: (event) => console.log(`${event.percentage}% complete`),
|
|
328
|
+
* });
|
|
329
|
+
* ```
|
|
330
|
+
*/
|
|
331
|
+
async executeBatch<T = any>(
|
|
332
|
+
resource: string,
|
|
333
|
+
operation: 'create' | 'update' | 'delete',
|
|
334
|
+
items: Partial<T>[],
|
|
335
|
+
options?: {
|
|
336
|
+
onProgress?: TransactionProgressCallback;
|
|
337
|
+
retryOnError?: boolean;
|
|
338
|
+
maxRetries?: number;
|
|
339
|
+
},
|
|
340
|
+
): Promise<{
|
|
341
|
+
success: boolean;
|
|
342
|
+
results: T[];
|
|
343
|
+
errors: Array<{ index: number; error: string }>;
|
|
344
|
+
total: number;
|
|
345
|
+
succeeded: number;
|
|
346
|
+
failed: number;
|
|
347
|
+
}> {
|
|
348
|
+
const maxRetries = options?.maxRetries ?? this.maxRetries;
|
|
349
|
+
const retryOnError = options?.retryOnError ?? true;
|
|
350
|
+
const results: T[] = [];
|
|
351
|
+
const errors: Array<{ index: number; error: string }> = [];
|
|
352
|
+
let completed = 0;
|
|
353
|
+
let failed = 0;
|
|
354
|
+
|
|
355
|
+
const emitProgress = (currentOp?: string) => {
|
|
356
|
+
const event: TransactionProgressEvent = {
|
|
357
|
+
transactionName: `batch-${operation}`,
|
|
358
|
+
total: items.length,
|
|
359
|
+
completed,
|
|
360
|
+
failed,
|
|
361
|
+
percentage: items.length > 0 ? ((completed + failed) / items.length) * 100 : 0,
|
|
362
|
+
currentOperation: currentOp,
|
|
363
|
+
};
|
|
364
|
+
this.emitProgress(event);
|
|
365
|
+
options?.onProgress?.(event);
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
// Try bulk operation first if available
|
|
369
|
+
if (this.dataSource.bulk) {
|
|
370
|
+
try {
|
|
371
|
+
const bulkResult = await this.dataSource.bulk(resource, operation, items);
|
|
372
|
+
return {
|
|
373
|
+
success: true,
|
|
374
|
+
results: bulkResult as T[],
|
|
375
|
+
errors: [],
|
|
376
|
+
total: items.length,
|
|
377
|
+
succeeded: items.length,
|
|
378
|
+
failed: 0,
|
|
379
|
+
};
|
|
380
|
+
} catch {
|
|
381
|
+
// Fall through to individual processing
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Individual processing with retry
|
|
386
|
+
for (let i = 0; i < items.length; i++) {
|
|
387
|
+
const item = items[i];
|
|
388
|
+
let lastError: string | undefined;
|
|
389
|
+
let success = false;
|
|
390
|
+
|
|
391
|
+
for (let attempt = 0; attempt <= (retryOnError ? maxRetries : 0); attempt++) {
|
|
392
|
+
try {
|
|
393
|
+
let result: any;
|
|
394
|
+
switch (operation) {
|
|
395
|
+
case 'create':
|
|
396
|
+
result = await this.dataSource.create(resource, item);
|
|
397
|
+
break;
|
|
398
|
+
case 'update': {
|
|
399
|
+
const id = (item as Record<string, any>).id;
|
|
400
|
+
if (!id) throw new Error(`Missing ID for item at index ${i}`);
|
|
401
|
+
result = await this.dataSource.update(resource, id, item);
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
case 'delete': {
|
|
405
|
+
const deleteId = (item as Record<string, any>).id;
|
|
406
|
+
if (!deleteId) throw new Error(`Missing ID for item at index ${i}`);
|
|
407
|
+
await this.dataSource.delete(resource, deleteId);
|
|
408
|
+
result = item;
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
results.push(result);
|
|
414
|
+
completed++;
|
|
415
|
+
success = true;
|
|
416
|
+
emitProgress();
|
|
417
|
+
break;
|
|
418
|
+
} catch (error) {
|
|
419
|
+
lastError = (error as Error).message;
|
|
420
|
+
if (retryOnError && attempt < maxRetries) {
|
|
421
|
+
await delay(this.retryDelay * Math.pow(2, attempt));
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (!success) {
|
|
428
|
+
errors.push({ index: i, error: lastError || 'Unknown error' });
|
|
429
|
+
failed++;
|
|
430
|
+
emitProgress();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
return {
|
|
435
|
+
success: errors.length === 0,
|
|
436
|
+
results,
|
|
437
|
+
errors,
|
|
438
|
+
total: items.length,
|
|
439
|
+
succeeded: completed,
|
|
440
|
+
failed,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Record an operation for potential rollback
|
|
446
|
+
*/
|
|
447
|
+
recordOperation(op: TransactionOperation): void {
|
|
448
|
+
this.operations.push(op);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Rollback all recorded operations in reverse order
|
|
453
|
+
*/
|
|
454
|
+
private async rollbackOperations(): Promise<void> {
|
|
455
|
+
const ops = [...this.operations].reverse();
|
|
456
|
+
|
|
457
|
+
for (const op of ops) {
|
|
458
|
+
try {
|
|
459
|
+
switch (op.type) {
|
|
460
|
+
case 'create':
|
|
461
|
+
// Undo create -> delete the created record
|
|
462
|
+
if (op.result?.id) {
|
|
463
|
+
await this.dataSource.delete(op.resource, op.result.id);
|
|
464
|
+
}
|
|
465
|
+
break;
|
|
466
|
+
case 'update':
|
|
467
|
+
// Undo update -> restore previous state
|
|
468
|
+
if (op.id && op.previousState) {
|
|
469
|
+
await this.dataSource.update(op.resource, op.id, op.previousState);
|
|
470
|
+
}
|
|
471
|
+
break;
|
|
472
|
+
case 'delete':
|
|
473
|
+
// Undo delete -> re-create with previous state
|
|
474
|
+
if (op.previousState) {
|
|
475
|
+
await this.dataSource.create(op.resource, op.previousState);
|
|
476
|
+
}
|
|
477
|
+
break;
|
|
478
|
+
}
|
|
479
|
+
} catch (error) {
|
|
480
|
+
// Rollback errors are logged but don't throw
|
|
481
|
+
console.error(`Rollback failed for ${op.type} on ${op.resource}:`, error);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
this.operations = [];
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Emit progress event to all listeners
|
|
490
|
+
*/
|
|
491
|
+
private emitProgress(event: TransactionProgressEvent): void {
|
|
492
|
+
for (const listener of this.progressListeners) {
|
|
493
|
+
try {
|
|
494
|
+
listener(event);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
console.error('Error in transaction progress listener:', error);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// ==========================================================================
|
|
503
|
+
// Helpers
|
|
504
|
+
// ==========================================================================
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Generate a unique transaction ID using crypto when available
|
|
508
|
+
*/
|
|
509
|
+
function generateId(): string {
|
|
510
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
511
|
+
return `txn_${crypto.randomUUID()}`;
|
|
512
|
+
}
|
|
513
|
+
return `txn_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Promise-based delay
|
|
518
|
+
*/
|
|
519
|
+
function delay(ms: number): Promise<void> {
|
|
520
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
521
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
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 { ActionRunner, type ActionContext } from '../ActionRunner';
|
|
11
|
+
|
|
12
|
+
describe('ActionRunner — ParamCollectionHandler', () => {
|
|
13
|
+
let runner: ActionRunner;
|
|
14
|
+
let context: ActionContext;
|
|
15
|
+
|
|
16
|
+
beforeEach(() => {
|
|
17
|
+
context = {
|
|
18
|
+
data: { id: 1, name: 'Test' },
|
|
19
|
+
record: { id: 1, status: 'active' },
|
|
20
|
+
user: { id: 'u1', role: 'admin' },
|
|
21
|
+
};
|
|
22
|
+
runner = new ActionRunner(context);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
// ==========================================================================
|
|
26
|
+
// Param collection before execution
|
|
27
|
+
// ==========================================================================
|
|
28
|
+
|
|
29
|
+
describe('param collection', () => {
|
|
30
|
+
it('should call paramCollectionHandler when actionParams are defined', async () => {
|
|
31
|
+
const paramHandler = vi.fn().mockResolvedValue({ owner_email: 'alice@example.com' });
|
|
32
|
+
runner.setParamCollectionHandler(paramHandler);
|
|
33
|
+
|
|
34
|
+
const onClick = vi.fn();
|
|
35
|
+
await runner.execute({
|
|
36
|
+
onClick,
|
|
37
|
+
actionParams: [
|
|
38
|
+
{ name: 'owner_email', label: 'Owner Email', type: 'text', required: true },
|
|
39
|
+
],
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
expect(paramHandler).toHaveBeenCalledOnce();
|
|
43
|
+
expect(paramHandler).toHaveBeenCalledWith([
|
|
44
|
+
{ name: 'owner_email', label: 'Owner Email', type: 'text', required: true },
|
|
45
|
+
]);
|
|
46
|
+
expect(onClick).toHaveBeenCalledOnce();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('should cancel action when paramCollectionHandler returns null', async () => {
|
|
50
|
+
const paramHandler = vi.fn().mockResolvedValue(null);
|
|
51
|
+
runner.setParamCollectionHandler(paramHandler);
|
|
52
|
+
|
|
53
|
+
const onClick = vi.fn();
|
|
54
|
+
const result = await runner.execute({
|
|
55
|
+
onClick,
|
|
56
|
+
actionParams: [
|
|
57
|
+
{ name: 'owner_email', label: 'Owner Email', type: 'text', required: true },
|
|
58
|
+
],
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
expect(paramHandler).toHaveBeenCalledOnce();
|
|
62
|
+
expect(result.success).toBe(false);
|
|
63
|
+
expect(result.error).toBe('Action cancelled by user (params)');
|
|
64
|
+
expect(onClick).not.toHaveBeenCalled();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should merge collected params into action.params', async () => {
|
|
68
|
+
const paramHandler = vi.fn().mockResolvedValue({
|
|
69
|
+
owner_email: 'alice@example.com',
|
|
70
|
+
notify: true,
|
|
71
|
+
});
|
|
72
|
+
runner.setParamCollectionHandler(paramHandler);
|
|
73
|
+
|
|
74
|
+
const handler = vi.fn().mockResolvedValue({ success: true });
|
|
75
|
+
runner.registerHandler('custom_action', handler);
|
|
76
|
+
|
|
77
|
+
await runner.execute({
|
|
78
|
+
type: 'custom_action',
|
|
79
|
+
params: { existing: 'value' },
|
|
80
|
+
actionParams: [
|
|
81
|
+
{ name: 'owner_email', label: 'Owner Email', type: 'text' },
|
|
82
|
+
{ name: 'notify', label: 'Notify', type: 'boolean' },
|
|
83
|
+
],
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
expect(handler).toHaveBeenCalledOnce();
|
|
87
|
+
const calledAction = handler.mock.calls[0][0];
|
|
88
|
+
expect(calledAction.params).toEqual({
|
|
89
|
+
existing: 'value',
|
|
90
|
+
owner_email: 'alice@example.com',
|
|
91
|
+
notify: true,
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('should skip param collection when no paramCollectionHandler is set', async () => {
|
|
96
|
+
const onClick = vi.fn();
|
|
97
|
+
const result = await runner.execute({
|
|
98
|
+
onClick,
|
|
99
|
+
actionParams: [
|
|
100
|
+
{ name: 'test', label: 'Test', type: 'text' },
|
|
101
|
+
],
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// Should proceed normally without param collection
|
|
105
|
+
expect(result.success).toBe(true);
|
|
106
|
+
expect(onClick).toHaveBeenCalledOnce();
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('should skip param collection when actionParams is empty', async () => {
|
|
110
|
+
const paramHandler = vi.fn();
|
|
111
|
+
runner.setParamCollectionHandler(paramHandler);
|
|
112
|
+
|
|
113
|
+
const onClick = vi.fn();
|
|
114
|
+
await runner.execute({
|
|
115
|
+
onClick,
|
|
116
|
+
actionParams: [],
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
expect(paramHandler).not.toHaveBeenCalled();
|
|
120
|
+
expect(onClick).toHaveBeenCalledOnce();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('should skip param collection when actionParams is not provided', async () => {
|
|
124
|
+
const paramHandler = vi.fn();
|
|
125
|
+
runner.setParamCollectionHandler(paramHandler);
|
|
126
|
+
|
|
127
|
+
const onClick = vi.fn();
|
|
128
|
+
await runner.execute({ onClick });
|
|
129
|
+
|
|
130
|
+
expect(paramHandler).not.toHaveBeenCalled();
|
|
131
|
+
expect(onClick).toHaveBeenCalledOnce();
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
});
|