@object-ui/core 3.3.0 → 3.3.1

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 (99) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +20 -1
  3. package/dist/actions/ActionRunner.d.ts +9 -0
  4. package/dist/actions/ActionRunner.js +41 -4
  5. package/dist/adapters/ValueDataSource.js +3 -1
  6. package/dist/utils/filter-converter.js +25 -5
  7. package/package.json +32 -8
  8. package/.turbo/turbo-build.log +0 -4
  9. package/src/__benchmarks__/core.bench.ts +0 -64
  10. package/src/__tests__/protocols/DndProtocol.test.ts +0 -186
  11. package/src/__tests__/protocols/KeyboardProtocol.test.ts +0 -177
  12. package/src/__tests__/protocols/NotificationProtocol.test.ts +0 -142
  13. package/src/__tests__/protocols/ResponsiveProtocol.test.ts +0 -176
  14. package/src/__tests__/protocols/SharingProtocol.test.ts +0 -188
  15. package/src/actions/ActionEngine.ts +0 -268
  16. package/src/actions/ActionRunner.ts +0 -717
  17. package/src/actions/TransactionManager.ts +0 -521
  18. package/src/actions/UndoManager.ts +0 -215
  19. package/src/actions/__tests__/ActionEngine.test.ts +0 -206
  20. package/src/actions/__tests__/ActionRunner.params.test.ts +0 -134
  21. package/src/actions/__tests__/ActionRunner.test.ts +0 -711
  22. package/src/actions/__tests__/TransactionManager.test.ts +0 -447
  23. package/src/actions/__tests__/UndoManager.test.ts +0 -320
  24. package/src/actions/index.ts +0 -12
  25. package/src/adapters/ApiDataSource.ts +0 -376
  26. package/src/adapters/README.md +0 -180
  27. package/src/adapters/ValueDataSource.ts +0 -459
  28. package/src/adapters/__tests__/ApiDataSource.test.ts +0 -418
  29. package/src/adapters/__tests__/ValueDataSource.test.ts +0 -571
  30. package/src/adapters/__tests__/resolveDataSource.test.ts +0 -144
  31. package/src/adapters/index.ts +0 -15
  32. package/src/adapters/resolveDataSource.ts +0 -79
  33. package/src/builder/__tests__/schema-builder.test.ts +0 -235
  34. package/src/builder/schema-builder.ts +0 -584
  35. package/src/data-scope/DataScopeManager.ts +0 -269
  36. package/src/data-scope/ViewDataProvider.ts +0 -282
  37. package/src/data-scope/__tests__/DataScopeManager.test.ts +0 -211
  38. package/src/data-scope/__tests__/ViewDataProvider.test.ts +0 -270
  39. package/src/data-scope/index.ts +0 -24
  40. package/src/errors/__tests__/errors.test.ts +0 -292
  41. package/src/errors/index.ts +0 -269
  42. package/src/evaluator/ExpressionCache.ts +0 -206
  43. package/src/evaluator/ExpressionContext.ts +0 -118
  44. package/src/evaluator/ExpressionEvaluator.ts +0 -315
  45. package/src/evaluator/FormulaFunctions.ts +0 -398
  46. package/src/evaluator/SafeExpressionParser.ts +0 -893
  47. package/src/evaluator/__tests__/ExpressionCache.test.ts +0 -135
  48. package/src/evaluator/__tests__/ExpressionContext.test.ts +0 -110
  49. package/src/evaluator/__tests__/ExpressionEvaluator.test.ts +0 -558
  50. package/src/evaluator/__tests__/FormulaFunctions.test.ts +0 -447
  51. package/src/evaluator/index.ts +0 -13
  52. package/src/index.ts +0 -38
  53. package/src/protocols/DndProtocol.ts +0 -168
  54. package/src/protocols/KeyboardProtocol.ts +0 -181
  55. package/src/protocols/NotificationProtocol.ts +0 -150
  56. package/src/protocols/ResponsiveProtocol.ts +0 -210
  57. package/src/protocols/SharingProtocol.ts +0 -185
  58. package/src/protocols/index.ts +0 -13
  59. package/src/query/__tests__/query-ast.test.ts +0 -211
  60. package/src/query/__tests__/window-functions.test.ts +0 -275
  61. package/src/query/index.ts +0 -7
  62. package/src/query/query-ast.ts +0 -341
  63. package/src/registry/PluginScopeImpl.ts +0 -259
  64. package/src/registry/PluginSystem.ts +0 -206
  65. package/src/registry/Registry.ts +0 -219
  66. package/src/registry/WidgetRegistry.ts +0 -316
  67. package/src/registry/__tests__/PluginSystem.test.ts +0 -309
  68. package/src/registry/__tests__/Registry.test.ts +0 -293
  69. package/src/registry/__tests__/WidgetRegistry.test.ts +0 -321
  70. package/src/registry/__tests__/plugin-scope-integration.test.ts +0 -283
  71. package/src/theme/ThemeEngine.ts +0 -530
  72. package/src/theme/__tests__/ThemeEngine.test.ts +0 -668
  73. package/src/theme/index.ts +0 -24
  74. package/src/types/index.ts +0 -21
  75. package/src/utils/__tests__/debug-collector.test.ts +0 -102
  76. package/src/utils/__tests__/debug.test.ts +0 -134
  77. package/src/utils/__tests__/expand-fields.test.ts +0 -120
  78. package/src/utils/__tests__/extract-records.test.ts +0 -50
  79. package/src/utils/__tests__/filter-converter.test.ts +0 -118
  80. package/src/utils/__tests__/merge-views-into-objects.test.ts +0 -110
  81. package/src/utils/__tests__/normalize-quick-filter.test.ts +0 -123
  82. package/src/utils/debug-collector.ts +0 -100
  83. package/src/utils/debug.ts +0 -148
  84. package/src/utils/expand-fields.ts +0 -76
  85. package/src/utils/extract-records.ts +0 -33
  86. package/src/utils/filter-converter.ts +0 -133
  87. package/src/utils/merge-views-into-objects.ts +0 -36
  88. package/src/utils/normalize-quick-filter.ts +0 -78
  89. package/src/validation/__tests__/object-validation-engine.test.ts +0 -567
  90. package/src/validation/__tests__/schema-validator.test.ts +0 -118
  91. package/src/validation/__tests__/validation-engine.test.ts +0 -102
  92. package/src/validation/index.ts +0 -10
  93. package/src/validation/schema-validator.ts +0 -344
  94. package/src/validation/validation-engine.ts +0 -528
  95. package/src/validation/validators/index.ts +0 -25
  96. package/src/validation/validators/object-validation-engine.ts +0 -722
  97. package/tsconfig.json +0 -15
  98. package/tsconfig.tsbuildinfo +0 -1
  99. package/vitest.config.ts +0 -2
@@ -1,717 +0,0 @@
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 - Action Runner
11
- *
12
- * Executes actions defined in ActionSchema and EventHandler.
13
- * Supports all spec v2.0.1 action types: script, url, modal, flow, api.
14
- * Features: conditional execution, confirmation, toast notifications,
15
- * redirect handling, action chaining, custom handler registration.
16
- */
17
-
18
- import { ExpressionEvaluator } from '../evaluator/ExpressionEvaluator';
19
-
20
- export interface ActionResult {
21
- success: boolean;
22
- data?: any;
23
- error?: string;
24
- reload?: boolean;
25
- close?: boolean;
26
- redirect?: string;
27
- /** Modal schema to render (for type: 'modal') */
28
- modal?: any;
29
- }
30
-
31
- export interface ActionContext {
32
- data?: Record<string, any>;
33
- record?: any;
34
- selectedRecords?: Record<string, any>[];
35
- user?: any;
36
- [key: string]: any;
37
- }
38
-
39
- /**
40
- * API configuration for complex requests.
41
- */
42
- export interface ApiConfig {
43
- /** API endpoint URL */
44
- url: string;
45
- /** HTTP method */
46
- method?: string;
47
- /** Request headers */
48
- headers?: Record<string, string>;
49
- /** Request body (will be JSON-stringified if object) */
50
- body?: any;
51
- /** Query parameters */
52
- queryParams?: Record<string, string>;
53
- /** Response type */
54
- responseType?: 'json' | 'text' | 'blob';
55
- }
56
-
57
- /**
58
- * Action definition accepted by the runner.
59
- * Compatible with both UIActionSchema (spec v2.0.1) and legacy crud.ts ActionSchema.
60
- */
61
- export interface ActionDef {
62
- /** Action type identifier: 'script' | 'url' | 'modal' | 'flow' | 'api' | 'navigation' | custom */
63
- type?: string;
64
- /** Legacy action type field */
65
- actionType?: string;
66
- /** Action name (from UIActionSchema) */
67
- name?: string;
68
- /** Display label */
69
- label?: string;
70
- /** Confirmation text — shows a confirm dialog before executing */
71
- confirmText?: string;
72
- /** Structured confirmation (from crud.ts) */
73
- confirm?: { title?: string; message?: string; confirmText?: string; cancelText?: string };
74
- /** Condition expression — if falsy, skip action */
75
- condition?: string;
76
- /** Disabled expression — if truthy, skip action */
77
- disabled?: string | boolean;
78
- /** API endpoint (string URL or complex config) */
79
- api?: string | ApiConfig;
80
- /** API endpoint URL (spec v2.0.1 alias) */
81
- endpoint?: string;
82
- /** HTTP method */
83
- method?: string;
84
- /** Navigation target */
85
- navigate?: any;
86
- /** onClick callback (legacy) */
87
- onClick?: () => void | Promise<void>;
88
- /** Whether to reload data after success */
89
- reload?: boolean;
90
- /** Whether to close dialog after success */
91
- close?: boolean;
92
- /** Redirect URL expression */
93
- redirect?: string;
94
- /** Toast configuration */
95
- toast?: { showOnSuccess?: boolean; showOnError?: boolean; duration?: number };
96
- /** Success message (from UIActionSchema) */
97
- successMessage?: string;
98
- /** Error message (from UIActionSchema) */
99
- errorMessage?: string;
100
- /** Whether to refresh data after execution (from UIActionSchema) */
101
- refreshAfter?: boolean;
102
- /** Params object (for custom handlers) */
103
- params?: Record<string, any>;
104
- /** ActionParam definitions to collect from user before execution (from spec ActionSchema.params) */
105
- actionParams?: ActionParamDef[];
106
- /** Script/expression to execute (for type: 'script') */
107
- execute?: string;
108
- /** Target URL or identifier (for type: 'url', 'modal', 'flow') */
109
- target?: string;
110
- /** Modal schema to open (for type: 'modal') */
111
- modal?: any;
112
- /** Chained actions to execute after this one */
113
- chain?: ActionDef[];
114
- /** Chain execution mode */
115
- chainMode?: 'sequential' | 'parallel';
116
- /** Callback on success */
117
- onSuccess?: ActionDef | ActionDef[];
118
- /** Callback on failure */
119
- onFailure?: ActionDef | ActionDef[];
120
- /** Any additional properties */
121
- [key: string]: any;
122
- }
123
-
124
- export type ActionHandler = (
125
- action: ActionDef,
126
- context: ActionContext
127
- ) => Promise<ActionResult> | ActionResult;
128
-
129
- /**
130
- * Confirmation handler — replaces window.confirm.
131
- * Consumers can provide an async implementation (e.g., Shadcn AlertDialog).
132
- */
133
- export type ConfirmationHandler = (message: string, options?: {
134
- title?: string;
135
- confirmText?: string;
136
- cancelText?: string;
137
- }) => Promise<boolean>;
138
-
139
- /**
140
- * Toast handler — consumers can wire to Sonner or any toast library.
141
- */
142
- export type ToastHandler = (message: string, options?: {
143
- type?: 'success' | 'error' | 'info' | 'warning';
144
- duration?: number;
145
- }) => void;
146
-
147
- /**
148
- * Modal handler — consumers provide to render modal dialogs.
149
- */
150
- export type ModalHandler = (schema: any, context: ActionContext) => Promise<ActionResult>;
151
-
152
- /**
153
- * Navigation handler — consumers provide for SPA-aware routing.
154
- */
155
- export type NavigationHandler = (url: string, options?: {
156
- external?: boolean;
157
- newTab?: boolean;
158
- replace?: boolean;
159
- }) => void;
160
-
161
- /**
162
- * Param collection handler — consumers provide to show a dialog
163
- * for collecting ActionParam values before action execution.
164
- * Returns collected values, or null if cancelled.
165
- */
166
- export type ParamCollectionHandler = (params: ActionParamDef[]) => Promise<Record<string, any> | null>;
167
-
168
- /**
169
- * ActionParam definition accepted by the runner.
170
- * Compatible with @objectstack/spec ActionParam.
171
- */
172
- export interface ActionParamDef {
173
- name: string;
174
- label: string;
175
- type: string;
176
- required?: boolean;
177
- options?: Array<{ label: string; value: string }>;
178
- defaultValue?: unknown;
179
- helpText?: string;
180
- placeholder?: string;
181
- validation?: string;
182
- }
183
-
184
- export class ActionRunner {
185
- private handlers = new Map<string, ActionHandler>();
186
- private evaluator: ExpressionEvaluator;
187
- private context: ActionContext;
188
- private confirmHandler: ConfirmationHandler;
189
- private toastHandler: ToastHandler | null;
190
- private modalHandler: ModalHandler | null;
191
- private navigationHandler: NavigationHandler | null;
192
- private paramCollectionHandler: ParamCollectionHandler | null;
193
-
194
- constructor(context: ActionContext = {}) {
195
- this.context = context;
196
- this.evaluator = new ExpressionEvaluator(context);
197
- // Default confirmation: window.confirm (can be overridden)
198
- this.confirmHandler = async (message: string) => window.confirm(message);
199
- this.toastHandler = null;
200
- this.modalHandler = null;
201
- this.navigationHandler = null;
202
- this.paramCollectionHandler = null;
203
- }
204
-
205
- /**
206
- * Set a custom confirmation handler (e.g., Shadcn AlertDialog).
207
- */
208
- setConfirmHandler(handler: ConfirmationHandler): void {
209
- this.confirmHandler = handler;
210
- }
211
-
212
- /**
213
- * Set a custom toast handler (e.g., Sonner).
214
- */
215
- setToastHandler(handler: ToastHandler): void {
216
- this.toastHandler = handler;
217
- }
218
-
219
- /**
220
- * Set a modal handler (e.g., render a Dialog via React state).
221
- */
222
- setModalHandler(handler: ModalHandler): void {
223
- this.modalHandler = handler;
224
- }
225
-
226
- /**
227
- * Set a navigation handler (e.g., React Router navigate).
228
- */
229
- setNavigationHandler(handler: NavigationHandler): void {
230
- this.navigationHandler = handler;
231
- }
232
-
233
- /**
234
- * Set a param collection handler — shows a dialog to collect
235
- * ActionParam values before action execution.
236
- */
237
- setParamCollectionHandler(handler: ParamCollectionHandler): void {
238
- this.paramCollectionHandler = handler;
239
- }
240
-
241
- registerHandler(actionName: string, handler: ActionHandler): void {
242
- this.handlers.set(actionName, handler);
243
- }
244
-
245
- unregisterHandler(actionName: string): void {
246
- this.handlers.delete(actionName);
247
- }
248
-
249
- async execute(action: ActionDef): Promise<ActionResult> {
250
- try {
251
- // Resolve the action type
252
- const actionType = action.type || action.actionType || action.name || '';
253
-
254
- // Conditional execution
255
- if (action.condition) {
256
- const shouldExecute = this.evaluator.evaluateCondition(action.condition);
257
- if (!shouldExecute) {
258
- return { success: false, error: 'Action condition not met' };
259
- }
260
- }
261
-
262
- if (action.disabled) {
263
- const isDisabled = typeof action.disabled === 'string'
264
- ? this.evaluator.evaluateCondition(action.disabled)
265
- : action.disabled;
266
-
267
- if (isDisabled) {
268
- return { success: false, error: 'Action is disabled' };
269
- }
270
- }
271
-
272
- // Confirmation (structured or simple)
273
- const confirmMessage = action.confirm?.message || action.confirmText;
274
- if (confirmMessage) {
275
- const confirmed = await this.confirmHandler(
276
- this.evaluator.evaluate(confirmMessage) as string,
277
- action.confirm ? {
278
- title: action.confirm.title,
279
- confirmText: action.confirm.confirmText,
280
- cancelText: action.confirm.cancelText,
281
- } : undefined,
282
- );
283
- if (!confirmed) {
284
- return { success: false, error: 'Action cancelled by user' };
285
- }
286
- }
287
-
288
- // Param collection: if the action defines ActionParam[] to collect,
289
- // show a dialog to gather user input before executing.
290
- if (action.actionParams && Array.isArray(action.actionParams) && action.actionParams.length > 0) {
291
- if (this.paramCollectionHandler) {
292
- const collected = await this.paramCollectionHandler(action.actionParams);
293
- if (collected === null) {
294
- return { success: false, error: 'Action cancelled by user (params)' };
295
- }
296
- // Merge collected params into action.params
297
- action.params = { ...(action.params || {}), ...collected };
298
- }
299
- }
300
-
301
- // Check for a registered custom handler first
302
- if (actionType && this.handlers.has(actionType)) {
303
- const handler = this.handlers.get(actionType)!;
304
- const result = await handler(action, this.context);
305
- await this.handlePostExecution(action, result);
306
- return result;
307
- }
308
-
309
- // Built-in action execution by type
310
- let result: ActionResult;
311
-
312
- switch (actionType) {
313
- case 'script':
314
- result = await this.executeScript(action);
315
- break;
316
- case 'url':
317
- result = await this.executeUrl(action);
318
- break;
319
- case 'modal':
320
- result = await this.executeModal(action);
321
- break;
322
- case 'flow':
323
- result = await this.executeFlow(action);
324
- break;
325
- case 'api':
326
- result = await this.executeAPI(action);
327
- break;
328
- case 'navigation':
329
- result = await this.executeNavigation(action);
330
- break;
331
- default:
332
- // Legacy fallback: check for navigate, api, or onClick
333
- if (action.navigate) {
334
- result = await this.executeNavigation(action);
335
- } else if (action.api || action.endpoint) {
336
- result = await this.executeAPI(action);
337
- } else if (action.onClick) {
338
- await action.onClick();
339
- result = { success: true };
340
- } else {
341
- result = await this.executeActionSchema(action);
342
- }
343
- }
344
-
345
- await this.handlePostExecution(action, result);
346
- return result;
347
- } catch (error) {
348
- const result: ActionResult = { success: false, error: (error as Error).message };
349
- await this.handlePostExecution(action, result);
350
- return result;
351
- }
352
- }
353
-
354
- /**
355
- * Execute multiple actions in sequence or parallel.
356
- */
357
- async executeChain(
358
- actions: ActionDef[],
359
- mode: 'sequential' | 'parallel' = 'sequential'
360
- ): Promise<ActionResult> {
361
- if (actions.length === 0) {
362
- return { success: true };
363
- }
364
-
365
- if (mode === 'parallel') {
366
- const results = await Promise.allSettled(
367
- actions.map(a => this.execute(a))
368
- );
369
- const failures = results.filter(
370
- r => r.status === 'rejected' || (r.status === 'fulfilled' && !r.value.success)
371
- );
372
- if (failures.length > 0) {
373
- const firstFail = results.find(
374
- r => r.status === 'fulfilled' && !r.value.success
375
- ) as PromiseFulfilledResult<ActionResult> | undefined;
376
- return {
377
- success: false,
378
- error: firstFail?.value?.error || 'One or more parallel actions failed',
379
- };
380
- }
381
- const lastResult = results[results.length - 1];
382
- return lastResult.status === 'fulfilled'
383
- ? lastResult.value
384
- : { success: false, error: 'Action failed' };
385
- }
386
-
387
- // Sequential execution — stop on first failure
388
- let lastResult: ActionResult = { success: true };
389
- for (const action of actions) {
390
- lastResult = await this.execute(action);
391
- if (!lastResult.success) {
392
- return lastResult;
393
- }
394
- }
395
- return lastResult;
396
- }
397
-
398
- /**
399
- * Post-execution: emit toast notifications, handle chaining, callbacks.
400
- */
401
- private async handlePostExecution(action: ActionDef, result: ActionResult): Promise<void> {
402
- // Toast notifications
403
- if (this.toastHandler) {
404
- const showToast = action.toast ?? { showOnSuccess: true, showOnError: true };
405
- const duration = action.toast?.duration;
406
-
407
- if (result.success && showToast.showOnSuccess !== false) {
408
- const message = action.successMessage || 'Action completed successfully';
409
- this.toastHandler(message, { type: 'success', duration });
410
- }
411
-
412
- if (!result.success && showToast.showOnError !== false && result.error) {
413
- const message = action.errorMessage || result.error;
414
- this.toastHandler(message, { type: 'error', duration });
415
- }
416
- }
417
-
418
- // Apply refreshAfter from UIActionSchema
419
- if (action.refreshAfter && result.success) {
420
- result.reload = true;
421
- }
422
-
423
- // Execute chained actions
424
- if (action.chain && action.chain.length > 0 && result.success) {
425
- const chainResult = await this.executeChain(
426
- action.chain,
427
- action.chainMode || 'sequential'
428
- );
429
- // Merge chain result
430
- if (!chainResult.success) {
431
- result.success = false;
432
- result.error = chainResult.error;
433
- }
434
- if (chainResult.data) result.data = chainResult.data;
435
- if (chainResult.redirect) result.redirect = chainResult.redirect;
436
- if (chainResult.reload) result.reload = true;
437
- }
438
-
439
- // Execute onSuccess/onFailure callbacks
440
- if (result.success && action.onSuccess) {
441
- const callbacks = Array.isArray(action.onSuccess) ? action.onSuccess : [action.onSuccess];
442
- await this.executeChain(callbacks, 'sequential');
443
- }
444
- if (!result.success && action.onFailure) {
445
- const callbacks = Array.isArray(action.onFailure) ? action.onFailure : [action.onFailure];
446
- await this.executeChain(callbacks, 'sequential');
447
- }
448
- }
449
-
450
- /**
451
- * Execute script action — evaluates client-side expression via ExpressionEvaluator.
452
- * Supports ${} template expressions referencing data, record, user context.
453
- */
454
- private async executeScript(action: ActionDef): Promise<ActionResult> {
455
- const script = action.execute || action.target;
456
- if (!script) {
457
- return { success: false, error: 'No script provided for script action' };
458
- }
459
-
460
- try {
461
- const result = this.evaluator.evaluate(`\${${script}}`);
462
- return { success: true, data: result };
463
- } catch (error) {
464
- return { success: false, error: `Script execution failed: ${(error as Error).message}` };
465
- }
466
- }
467
-
468
- /**
469
- * Execute URL action — navigate to a URL.
470
- * Uses navigationHandler for SPA routing, falls back to window.location.
471
- */
472
- private async executeUrl(action: ActionDef): Promise<ActionResult> {
473
- const rawUrl = action.target || action.redirect;
474
- if (!rawUrl) {
475
- return { success: false, error: 'No URL provided for url action' };
476
- }
477
-
478
- const url = this.evaluator.evaluate(rawUrl) as string;
479
-
480
- if (!this.isValidUrl(url)) {
481
- return {
482
- success: false,
483
- error: 'Invalid URL scheme. Only http://, https://, and relative URLs are allowed.',
484
- };
485
- }
486
-
487
- const isExternal = url.startsWith('http://') || url.startsWith('https://');
488
- const newTab = action.params?.newTab ?? isExternal;
489
-
490
- if (this.navigationHandler) {
491
- this.navigationHandler(url, { external: isExternal, newTab });
492
- return { success: true };
493
- }
494
-
495
- if (newTab) {
496
- window.open(url, '_blank', 'noopener,noreferrer');
497
- } else {
498
- return { success: true, redirect: url };
499
- }
500
-
501
- return { success: true };
502
- }
503
-
504
- /**
505
- * Execute modal action — open a dialog.
506
- * Delegates to the registered modalHandler; returns modal schema if no handler.
507
- */
508
- private async executeModal(action: ActionDef): Promise<ActionResult> {
509
- const modalSchema = action.modal || action.target || action.params?.schema;
510
- if (!modalSchema) {
511
- return { success: false, error: 'No modal schema or target provided for modal action' };
512
- }
513
-
514
- if (this.modalHandler) {
515
- return await this.modalHandler(modalSchema, this.context);
516
- }
517
-
518
- // Return the modal schema for the consumer to render
519
- return { success: true, modal: modalSchema };
520
- }
521
-
522
- /**
523
- * Execute flow action — trigger a workflow/automation.
524
- * Delegates to a registered 'flow' handler; otherwise returns not-implemented.
525
- */
526
- private async executeFlow(action: ActionDef): Promise<ActionResult> {
527
- const flowName = action.target || action.name;
528
- if (!flowName) {
529
- return { success: false, error: 'No flow target provided for flow action' };
530
- }
531
-
532
- // Check for a registered flow handler (consumers register via registerHandler)
533
- if (this.handlers.has('flow')) {
534
- const handler = this.handlers.get('flow')!;
535
- return await handler(action, this.context);
536
- }
537
-
538
- return {
539
- success: false,
540
- error: `Flow handler not registered. Cannot execute flow: ${flowName}`,
541
- };
542
- }
543
-
544
- private async executeActionSchema(action: ActionDef): Promise<ActionResult> {
545
- const result: ActionResult = { success: true };
546
-
547
- if (action.api || action.endpoint) {
548
- const apiResult = await this.executeAPI(action);
549
- if (!apiResult.success) return apiResult;
550
- result.data = apiResult.data;
551
- }
552
-
553
- if (action.onClick) {
554
- await action.onClick();
555
- }
556
-
557
- result.reload = action.reload !== false;
558
- result.close = action.close !== false;
559
-
560
- if (action.redirect) {
561
- result.redirect = this.evaluator.evaluate(action.redirect) as string;
562
- }
563
-
564
- return result;
565
- }
566
-
567
- /**
568
- * Execute navigation action
569
- */
570
- private async executeNavigation(action: ActionDef): Promise<ActionResult> {
571
- const nav = action.navigate || action;
572
- const to = this.evaluator.evaluate(nav.to || nav.target) as string;
573
-
574
- if (!this.isValidUrl(to)) {
575
- return {
576
- success: false,
577
- error: 'Invalid URL scheme. Only http://, https://, and relative URLs are allowed.',
578
- };
579
- }
580
-
581
- const isExternal = nav.external || (typeof to === 'string' && (
582
- to.startsWith('http://') || to.startsWith('https://')
583
- ));
584
-
585
- if (this.navigationHandler) {
586
- this.navigationHandler(to, {
587
- external: isExternal,
588
- newTab: nav.newTab ?? isExternal,
589
- replace: nav.replace,
590
- });
591
- return { success: true };
592
- }
593
-
594
- if (isExternal) {
595
- window.open(to, '_blank', 'noopener,noreferrer');
596
- } else {
597
- return { success: true, redirect: to };
598
- }
599
-
600
- return { success: true };
601
- }
602
-
603
- /**
604
- * Execute API action — supports both simple string endpoint and complex ApiConfig.
605
- */
606
- private async executeAPI(action: ActionDef): Promise<ActionResult> {
607
- // Resolve the endpoint: api (string/object), endpoint, or target
608
- const apiConfig = action.api || action.endpoint || action.target;
609
-
610
- if (!apiConfig) {
611
- return { success: false, error: 'No API endpoint provided' };
612
- }
613
-
614
- try {
615
- let url: string;
616
- let method: string;
617
- let headers: Record<string, string> = { 'Content-Type': 'application/json' };
618
- let body: any = undefined;
619
- let responseType: 'json' | 'text' | 'blob' = 'json';
620
-
621
- if (typeof apiConfig === 'string') {
622
- // Simple string endpoint
623
- url = apiConfig;
624
- method = action.method || 'POST';
625
- body = JSON.stringify(action.params || this.context.data || {});
626
- } else {
627
- // Complex ApiConfig
628
- const config = apiConfig as ApiConfig;
629
- url = config.url;
630
- method = config.method || action.method || 'POST';
631
- headers = { ...headers, ...config.headers };
632
- responseType = config.responseType || 'json';
633
-
634
- // Build query params
635
- if (config.queryParams) {
636
- const searchParams = new URLSearchParams(config.queryParams);
637
- url = `${url}${url.includes('?') ? '&' : '?'}${searchParams.toString()}`;
638
- }
639
-
640
- // Build body
641
- if (config.body) {
642
- body = typeof config.body === 'string'
643
- ? config.body
644
- : JSON.stringify(config.body);
645
- } else if (method !== 'GET' && method !== 'HEAD') {
646
- body = JSON.stringify(action.params || this.context.data || {});
647
- }
648
- }
649
-
650
- const fetchInit: RequestInit = { method, headers };
651
- if (body && method !== 'GET' && method !== 'HEAD') {
652
- fetchInit.body = body;
653
- }
654
-
655
- const response = await fetch(url, fetchInit);
656
-
657
- if (!response.ok) {
658
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
659
- }
660
-
661
- let data: any;
662
- switch (responseType) {
663
- case 'text':
664
- data = await response.text();
665
- break;
666
- case 'blob':
667
- data = await response.blob();
668
- break;
669
- default:
670
- data = await response.json();
671
- }
672
-
673
- return { success: true, data };
674
- } catch (error) {
675
- return { success: false, error: (error as Error).message };
676
- }
677
- }
678
-
679
- /**
680
- * Validate URL to prevent javascript: or data: protocol injection.
681
- */
682
- private isValidUrl(url: unknown): boolean {
683
- return typeof url === 'string' && (
684
- url.startsWith('http://') ||
685
- url.startsWith('https://') ||
686
- url.startsWith('/') ||
687
- url.startsWith('./')
688
- );
689
- }
690
-
691
- updateContext(newContext: Partial<ActionContext>): void {
692
- this.context = { ...this.context, ...newContext };
693
- this.evaluator.updateContext(newContext);
694
- }
695
-
696
- getContext(): ActionContext {
697
- return this.context;
698
- }
699
-
700
- /**
701
- * Get the expression evaluator (for components that need to evaluate visibility, etc.)
702
- */
703
- getEvaluator(): ExpressionEvaluator {
704
- return this.evaluator;
705
- }
706
- }
707
-
708
- /**
709
- * Convenience function to execute a single action with a one-off runner.
710
- */
711
- export async function executeAction(
712
- action: ActionDef,
713
- context: ActionContext = {}
714
- ): Promise<ActionResult> {
715
- const runner = new ActionRunner(context);
716
- return await runner.execute(action);
717
- }