@stonecrop/stonecrop 0.30.0 → 0.32.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 (121) hide show
  1. package/dist/stonecrop.js +3548 -2740
  2. package/dist/stonecrop.js.map +1 -1
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/package.json +33 -27
  5. package/dist/src/client-action.d.ts +0 -31
  6. package/dist/src/client-action.d.ts.map +0 -1
  7. package/dist/src/client-action.js +0 -169
  8. package/dist/src/client-handler.d.ts +0 -43
  9. package/dist/src/client-handler.d.ts.map +0 -1
  10. package/dist/src/client-handler.js +0 -42
  11. package/dist/src/composables/lazy-link.d.ts +0 -25
  12. package/dist/src/composables/lazy-link.d.ts.map +0 -1
  13. package/dist/src/composables/lazy-link.js +0 -124
  14. package/dist/src/composables/operation-log.d.ts +0 -136
  15. package/dist/src/composables/operation-log.d.ts.map +0 -1
  16. package/dist/src/composables/operation-log.js +0 -224
  17. package/dist/src/composables/stonecrop.d.ts +0 -37
  18. package/dist/src/composables/stonecrop.d.ts.map +0 -1
  19. package/dist/src/composables/stonecrop.js +0 -433
  20. package/dist/src/doctype.d.ts +0 -243
  21. package/dist/src/doctype.d.ts.map +0 -1
  22. package/dist/src/doctype.js +0 -325
  23. package/dist/src/draft.d.ts +0 -35
  24. package/dist/src/draft.d.ts.map +0 -1
  25. package/dist/src/draft.js +0 -36
  26. package/dist/src/exceptions.d.ts +0 -14
  27. package/dist/src/exceptions.d.ts.map +0 -1
  28. package/dist/src/exceptions.js +0 -16
  29. package/dist/src/field-triggers.d.ts +0 -184
  30. package/dist/src/field-triggers.d.ts.map +0 -1
  31. package/dist/src/field-triggers.js +0 -577
  32. package/dist/src/index.d.ts +0 -25
  33. package/dist/src/index.d.ts.map +0 -1
  34. package/dist/src/index.js +0 -39
  35. package/dist/src/plugins/index.d.ts +0 -35
  36. package/dist/src/plugins/index.d.ts.map +0 -1
  37. package/dist/src/plugins/index.js +0 -98
  38. package/dist/src/registry.d.ts +0 -161
  39. package/dist/src/registry.d.ts.map +0 -1
  40. package/dist/src/registry.js +0 -384
  41. package/dist/src/schema-validator.d.ts +0 -78
  42. package/dist/src/schema-validator.d.ts.map +0 -1
  43. package/dist/src/schema-validator.js +0 -398
  44. package/dist/src/stonecrop.d.ts +0 -539
  45. package/dist/src/stonecrop.d.ts.map +0 -1
  46. package/dist/src/stonecrop.js +0 -610
  47. package/dist/src/stores/hst.d.ts +0 -92
  48. package/dist/src/stores/hst.d.ts.map +0 -1
  49. package/dist/src/stores/hst.js +0 -487
  50. package/dist/src/stores/index.d.ts +0 -9
  51. package/dist/src/stores/index.d.ts.map +0 -1
  52. package/dist/src/stores/index.js +0 -13
  53. package/dist/src/stores/operation-log.d.ts +0 -262
  54. package/dist/src/stores/operation-log.d.ts.map +0 -1
  55. package/dist/src/stores/operation-log.js +0 -571
  56. package/dist/src/stores/validation.d.ts +0 -83
  57. package/dist/src/stores/validation.d.ts.map +0 -1
  58. package/dist/src/stores/validation.js +0 -104
  59. package/dist/src/types/client-action.d.ts +0 -121
  60. package/dist/src/types/client-action.d.ts.map +0 -1
  61. package/dist/src/types/client-action.js +0 -0
  62. package/dist/src/types/composable.d.ts +0 -268
  63. package/dist/src/types/composable.d.ts.map +0 -1
  64. package/dist/src/types/composable.js +0 -0
  65. package/dist/src/types/doctype.d.ts +0 -34
  66. package/dist/src/types/doctype.d.ts.map +0 -1
  67. package/dist/src/types/doctype.js +0 -0
  68. package/dist/src/types/field-triggers.d.ts +0 -186
  69. package/dist/src/types/field-triggers.d.ts.map +0 -1
  70. package/dist/src/types/field-triggers.js +0 -4
  71. package/dist/src/types/hst.d.ts +0 -70
  72. package/dist/src/types/hst.d.ts.map +0 -1
  73. package/dist/src/types/hst.js +0 -0
  74. package/dist/src/types/index.d.ts +0 -11
  75. package/dist/src/types/index.d.ts.map +0 -1
  76. package/dist/src/types/index.js +0 -11
  77. package/dist/src/types/operation-log.d.ts +0 -163
  78. package/dist/src/types/operation-log.d.ts.map +0 -1
  79. package/dist/src/types/operation-log.js +0 -0
  80. package/dist/src/types/plugin.d.ts +0 -37
  81. package/dist/src/types/plugin.d.ts.map +0 -1
  82. package/dist/src/types/plugin.js +0 -0
  83. package/dist/src/types/registry.d.ts +0 -11
  84. package/dist/src/types/registry.d.ts.map +0 -1
  85. package/dist/src/types/registry.js +0 -0
  86. package/dist/src/types/schema-validator.d.ts +0 -66
  87. package/dist/src/types/schema-validator.d.ts.map +0 -1
  88. package/dist/src/types/schema-validator.js +0 -13
  89. package/dist/src/types/stonecrop.d.ts +0 -32
  90. package/dist/src/types/stonecrop.d.ts.map +0 -1
  91. package/dist/src/types/stonecrop.js +0 -0
  92. package/dist/stonecrop.tsbuildinfo +0 -1
  93. package/src/client-action.ts +0 -207
  94. package/src/client-handler.ts +0 -55
  95. package/src/composables/lazy-link.ts +0 -145
  96. package/src/composables/operation-log.ts +0 -257
  97. package/src/composables/stonecrop.ts +0 -556
  98. package/src/doctype.ts +0 -360
  99. package/src/draft.ts +0 -38
  100. package/src/exceptions.ts +0 -16
  101. package/src/field-triggers.ts +0 -686
  102. package/src/index.ts +0 -81
  103. package/src/plugins/index.ts +0 -113
  104. package/src/registry.ts +0 -433
  105. package/src/schema-validator.ts +0 -476
  106. package/src/stonecrop.ts +0 -721
  107. package/src/stores/hst.ts +0 -626
  108. package/src/stores/index.ts +0 -21
  109. package/src/stores/operation-log.ts +0 -675
  110. package/src/stores/validation.ts +0 -138
  111. package/src/types/client-action.ts +0 -121
  112. package/src/types/composable.ts +0 -288
  113. package/src/types/doctype.ts +0 -35
  114. package/src/types/field-triggers.ts +0 -201
  115. package/src/types/hst.ts +0 -77
  116. package/src/types/index.ts +0 -11
  117. package/src/types/operation-log.ts +0 -202
  118. package/src/types/plugin.ts +0 -38
  119. package/src/types/registry.ts +0 -10
  120. package/src/types/schema-validator.ts +0 -69
  121. package/src/types/stonecrop.ts +0 -33
@@ -1,686 +0,0 @@
1
- import type { Map as ImmutableMap } from 'immutable'
2
- import { useOperationLogStore } from './stores/operation-log'
3
- import type {
4
- FieldAction,
5
- FieldActionFunction,
6
- FieldChangeContext,
7
- FieldTriggerExecutionResult,
8
- FieldTriggerOptions,
9
- ActionExecutionResult,
10
- TransitionChangeContext,
11
- TransitionActionFunction,
12
- TransitionExecutionResult,
13
- } from './types/field-triggers'
14
-
15
- /**
16
- * Field trigger execution engine integrated with Registry
17
- * Singleton pattern following Registry implementation
18
- * @public
19
- */
20
- export class FieldTriggerEngine {
21
- /**
22
- * The root FieldTriggerEngine instance
23
- */
24
- static _root: FieldTriggerEngine
25
-
26
- private options!: FieldTriggerOptions & { defaultTimeout: number; debug: boolean; enableRollback: boolean }
27
- private doctypeActions = new Map<string, Map<string, string[]>>() // doctype -> action/field -> functions
28
- private doctypeTransitions = new Map<string, Map<string, string[]>>() // doctype -> transition -> functions
29
- private fieldRollbackConfig = new Map<string, Map<string, boolean>>() // doctype -> field -> rollback enabled
30
- private globalActions = new Map<string, FieldActionFunction>() // action name -> function
31
- private globalTransitionActions = new Map<string, TransitionActionFunction>() // transition action name -> function
32
-
33
- /**
34
- * Creates a new FieldTriggerEngine instance (singleton pattern)
35
- * @param options - Configuration options for the field trigger engine
36
- */
37
- constructor(options: FieldTriggerOptions = {}) {
38
- if (FieldTriggerEngine._root) {
39
- return FieldTriggerEngine._root
40
- }
41
- FieldTriggerEngine._root = this
42
- this.options = {
43
- defaultTimeout: options.defaultTimeout ?? 5000,
44
- debug: options.debug ?? false,
45
- enableRollback: options.enableRollback ?? true,
46
- errorHandler: options.errorHandler,
47
- }
48
- return this
49
- }
50
-
51
- /**
52
- * Register a global action function
53
- * @param name - The name of the action
54
- * @param fn - The action function
55
- */
56
- registerAction(name: string, fn: FieldActionFunction): void {
57
- this.globalActions.set(name, fn)
58
- }
59
-
60
- /**
61
- * Look up a registered action function by name.
62
- * Returns `undefined` if the action has not been registered.
63
- * @param name - The action name
64
- */
65
- getAction(name: string): FieldActionFunction | undefined {
66
- return this.globalActions.get(name)
67
- }
68
-
69
- /**
70
- * Register a global XState transition action function
71
- * @param name - The name of the transition action
72
- * @param fn - The transition action function
73
- */
74
- registerTransitionAction(name: string, fn: TransitionActionFunction): void {
75
- this.globalTransitionActions.set(name, fn)
76
- }
77
-
78
- /**
79
- * Configure rollback behavior for a specific field trigger
80
- * @param doctype - The doctype name
81
- * @param fieldname - The field name
82
- * @param enableRollback - Whether to enable rollback
83
- */
84
- setFieldRollback(doctype: string, fieldname: string, enableRollback: boolean): void {
85
- if (!this.fieldRollbackConfig.has(doctype)) {
86
- this.fieldRollbackConfig.set(doctype, new Map())
87
- }
88
- this.fieldRollbackConfig.get(doctype)!.set(fieldname, enableRollback)
89
- }
90
-
91
- /**
92
- * Get rollback configuration for a specific field trigger
93
- */
94
- private getFieldRollback(doctype: string, fieldname: string): boolean | undefined {
95
- return this.fieldRollbackConfig.get(doctype)?.get(fieldname)
96
- }
97
-
98
- /**
99
- * Register actions from a doctype - both regular actions and field triggers
100
- * Separates XState transitions (uppercase) from field triggers (lowercase)
101
- * @param doctype - The doctype name
102
- * @param actions - The actions to register (supports Immutable Map, Map, or plain object)
103
- */
104
- registerDoctypeActions(
105
- doctype: string,
106
- actions: ImmutableMap<string, string[]> | Map<string, string[]> | Record<string, string[]> | undefined
107
- ): void {
108
- if (!actions) return
109
-
110
- const actionMap = new Map<string, string[]>()
111
- const transitionMap = new Map<string, string[]>()
112
-
113
- // Convert from different Map types to regular Map
114
- // Check for Immutable.js Map first (has entrySeq method)
115
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Immutable.js interop: runtime duck-type check follows
116
- const immutableActions = actions as ImmutableMap<string, string[]>
117
- if (typeof immutableActions.entrySeq === 'function') {
118
- // Immutable Map
119
- immutableActions.entrySeq().forEach(([key, value]: [string, string[]]) => {
120
- this.categorizeAction(key, value, actionMap, transitionMap)
121
- })
122
- } else if (actions instanceof Map) {
123
- // Regular Map
124
- for (const [key, value] of actions) {
125
- this.categorizeAction(key, value, actionMap, transitionMap)
126
- }
127
- } else if (actions && typeof actions === 'object') {
128
- // Plain object
129
- Object.entries(actions).forEach(([key, value]) => {
130
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Object.entries value type is unknown at runtime; guarded by typeof object check above
131
- this.categorizeAction(key, value as string[], actionMap, transitionMap)
132
- })
133
- }
134
-
135
- // Always set the maps, even if empty
136
- this.doctypeActions.set(doctype, actionMap)
137
- this.doctypeTransitions.set(doctype, transitionMap)
138
- }
139
-
140
- /**
141
- * Categorize an action as either a field trigger or XState transition
142
- * Uses uppercase convention: UPPERCASE = transition, lowercase/mixed = field trigger
143
- */
144
- private categorizeAction(
145
- key: string,
146
- value: string[],
147
- actionMap: Map<string, string[]>,
148
- transitionMap: Map<string, string[]>
149
- ): void {
150
- // Check if the key is all uppercase (XState transition convention)
151
- if (this.isTransitionKey(key)) {
152
- transitionMap.set(key, value)
153
- } else {
154
- actionMap.set(key, value)
155
- }
156
- }
157
-
158
- /**
159
- * Determine if a key represents an XState transition
160
- * Transitions are identified by being all uppercase
161
- */
162
- private isTransitionKey(key: string): boolean {
163
- // Must be all uppercase letters/numbers/underscores
164
- return /^[A-Z0-9_]+$/.test(key) && key.length > 0
165
- }
166
-
167
- /**
168
- * Execute field triggers for a changed field
169
- * @param context - The field change context
170
- * @param options - Execution options (timeout and enableRollback)
171
- */
172
- async executeFieldTriggers(
173
- context: FieldChangeContext,
174
- options: { timeout?: number; enableRollback?: boolean } = {}
175
- ): Promise<FieldTriggerExecutionResult> {
176
- const { doctype, fieldname } = context
177
- const triggers = this.findFieldTriggers(doctype, fieldname)
178
-
179
- if (triggers.length === 0) {
180
- return {
181
- path: context.path,
182
- actionResults: [],
183
- totalExecutionTime: 0,
184
- allSucceeded: true,
185
- stoppedOnError: false,
186
- rolledBack: false,
187
- }
188
- }
189
-
190
- const startTime = performance.now()
191
- const actionResults: ActionExecutionResult[] = []
192
- let stoppedOnError = false
193
- let rolledBack = false
194
- let snapshot: any = undefined
195
-
196
- // Determine if rollback is enabled (priority: execution option > field config > global setting)
197
- const fieldRollbackConfig = this.getFieldRollback(doctype, fieldname)
198
- const rollbackEnabled = options.enableRollback ?? fieldRollbackConfig ?? this.options.enableRollback
199
-
200
- // Capture snapshot before executing actions if rollback is enabled
201
- if (rollbackEnabled && context.store) {
202
- snapshot = this.captureSnapshot(context)
203
- }
204
-
205
- // Execute actions sequentially — each action may depend on state set by the previous; stop-on-error semantics require sequential execution
206
- for (const actionName of triggers) {
207
- try {
208
- // oxlint-disable-next-line eslint/no-await-in-loop -- intentionally sequential; actions are order-dependent and stop on first failure
209
- const actionResult = await this.executeAction(actionName, context, options.timeout)
210
- actionResults.push(actionResult)
211
-
212
- if (!actionResult.success) {
213
- stoppedOnError = true
214
- break
215
- }
216
- } catch (error) {
217
- const actionError = error instanceof Error ? error : new Error(String(error))
218
- const errorResult: ActionExecutionResult = {
219
- success: false,
220
- error: actionError,
221
- executionTime: 0,
222
- action: actionName,
223
- }
224
- actionResults.push(errorResult)
225
- stoppedOnError = true
226
- break
227
- }
228
- }
229
-
230
- // Perform rollback if enabled, errors occurred, and we have a snapshot
231
- if (rollbackEnabled && stoppedOnError && snapshot && context.store) {
232
- try {
233
- this.restoreSnapshot(context, snapshot)
234
- rolledBack = true
235
- } catch (rollbackError) {
236
- console.error('[FieldTriggers] Rollback failed:', rollbackError)
237
- }
238
- }
239
-
240
- const totalExecutionTime = performance.now() - startTime
241
-
242
- // Call global error handler if configured and errors occurred
243
- const failedResults = actionResults.filter(r => !r.success && r.error != null)
244
- if (failedResults.length > 0 && this.options.errorHandler) {
245
- for (const failedResult of failedResults) {
246
- try {
247
- if (failedResult.error) {
248
- this.options.errorHandler(failedResult.error, context, failedResult.action)
249
- }
250
- } catch (handlerError) {
251
- console.error('[FieldTriggers] Error in global error handler:', handlerError)
252
- }
253
- }
254
- }
255
-
256
- const result: FieldTriggerExecutionResult = {
257
- path: context.path,
258
- actionResults,
259
- totalExecutionTime,
260
- allSucceeded: actionResults.every(r => r.success),
261
- stoppedOnError,
262
- rolledBack,
263
- snapshot: this.options.debug && rollbackEnabled ? snapshot : undefined, // Only include snapshot in debug mode if rollback is enabled
264
- }
265
-
266
- return result
267
- }
268
-
269
- /**
270
- * Execute XState transition actions
271
- * Similar to field triggers but specifically for FSM state transitions
272
- * @param context - The transition change context
273
- * @param options - Execution options (timeout)
274
- */
275
- async executeTransitionActions(
276
- context: TransitionChangeContext,
277
- options: { timeout?: number } = {}
278
- ): Promise<TransitionExecutionResult[]> {
279
- const { doctype, transition } = context
280
- const transitionActions = this.findTransitionActions(doctype, transition)
281
-
282
- if (transitionActions.length === 0) {
283
- return []
284
- }
285
-
286
- const results: TransitionExecutionResult[] = []
287
-
288
- // Execute transition actions sequentially — transitions are state-machine steps; order and stop-on-error are required
289
- for (const actionName of transitionActions) {
290
- try {
291
- // oxlint-disable-next-line eslint/no-await-in-loop -- intentionally sequential; transition actions are order-dependent and stop on first failure
292
- const actionResult = await this.executeTransitionAction(actionName, context, options.timeout)
293
- results.push(actionResult)
294
-
295
- if (!actionResult.success) {
296
- // Stop on first error for transitions
297
- break
298
- }
299
- } catch (error) {
300
- const actionError = error instanceof Error ? error : new Error(String(error))
301
- const errorResult: TransitionExecutionResult = {
302
- success: false,
303
- error: actionError,
304
- executionTime: 0,
305
- action: actionName,
306
- transition,
307
- }
308
- results.push(errorResult)
309
- break
310
- }
311
- }
312
-
313
- // Call global error handler if configured and errors occurred
314
- const failedResults = results.filter(r => !r.success)
315
- if (failedResults.length > 0 && this.options.errorHandler) {
316
- for (const failedResult of failedResults) {
317
- try {
318
- // Call with FieldChangeContext (base context type)
319
- if (failedResult.error) {
320
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- action result carries string name; FieldAction cast required by errorHandler signature
321
- this.options.errorHandler(failedResult.error, context, failedResult.action as unknown as FieldAction)
322
- }
323
- } catch (handlerError) {
324
- console.error('[FieldTriggers] Error in global error handler:', handlerError)
325
- }
326
- }
327
- }
328
-
329
- return results
330
- }
331
-
332
- /**
333
- * Find transition actions for a specific doctype and transition
334
- */
335
- private findTransitionActions(doctype: string, transition: string): string[] {
336
- const doctypeTransitions = this.doctypeTransitions.get(doctype)
337
- if (!doctypeTransitions) return []
338
-
339
- return doctypeTransitions.get(transition) || []
340
- }
341
-
342
- /**
343
- * Execute a single transition action by name
344
- */
345
- private async executeTransitionAction(
346
- actionName: string,
347
- context: TransitionChangeContext,
348
- timeout?: number
349
- ): Promise<TransitionExecutionResult> {
350
- const startTime = performance.now()
351
- const actionTimeout = timeout ?? this.options.defaultTimeout
352
-
353
- try {
354
- // Look up action in transition-specific registry first, then fall back to global
355
- let actionFn = this.globalTransitionActions.get(actionName)
356
-
357
- // If not found in transition registry, try regular action registry
358
- // This allows sharing actions between field triggers and transitions
359
- if (!actionFn) {
360
- const regularActionFn = this.globalActions.get(actionName)
361
- if (regularActionFn) {
362
- // Wrap regular action to accept TransitionChangeContext
363
- actionFn = regularActionFn
364
- }
365
- }
366
-
367
- if (!actionFn) {
368
- throw new Error(`Transition action "${actionName}" not found in registry`)
369
- }
370
-
371
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- actionFn may be FieldActionFunction set from globalActions fallback; polymorphic function type
372
- await this.executeWithTimeout(actionFn as FieldActionFunction, context, actionTimeout)
373
- const executionTime = performance.now() - startTime
374
-
375
- return {
376
- success: true,
377
- executionTime,
378
- action: actionName,
379
- transition: context.transition,
380
- }
381
- } catch (error) {
382
- const executionTime = performance.now() - startTime
383
- const actionError = error instanceof Error ? error : new Error(String(error))
384
-
385
- return {
386
- success: false,
387
- error: actionError,
388
- executionTime,
389
- action: actionName,
390
- transition: context.transition,
391
- }
392
- }
393
- }
394
-
395
- /**
396
- * Find field triggers for a specific doctype and field
397
- * Field triggers are identified by keys that look like field paths (contain dots or match field names)
398
- */
399
- private findFieldTriggers(doctype: string, fieldname: string): string[] {
400
- const doctypeActions = this.doctypeActions.get(doctype)
401
- if (!doctypeActions) return []
402
-
403
- const triggers: string[] = []
404
-
405
- for (const [key, actionNames] of doctypeActions) {
406
- // Check if this key is a field trigger pattern
407
- if (this.isFieldTriggerKey(key, fieldname)) {
408
- triggers.push(...actionNames)
409
- }
410
- }
411
-
412
- return triggers
413
- }
414
-
415
- /**
416
- * Determine if an action key represents a field trigger
417
- * Field triggers can be:
418
- * - Exact field name match: "emailAddress"
419
- * - Wildcard patterns: "emailAddress.*", "*.is_primary"
420
- * - Nested field paths: "address.street", "contact.email"
421
- */
422
- private isFieldTriggerKey(key: string, fieldname: string): boolean {
423
- // Exact match
424
- if (key === fieldname) return true
425
-
426
- // Contains dots - likely a field path pattern
427
- if (key.includes('.')) {
428
- return this.matchFieldPattern(key, fieldname)
429
- }
430
-
431
- // Contains wildcards
432
- if (key.includes('*')) {
433
- return this.matchFieldPattern(key, fieldname)
434
- }
435
-
436
- return false
437
- }
438
-
439
- /**
440
- * Match a field pattern against a field name
441
- * Supports wildcards (*) for dynamic segments
442
- */
443
- private matchFieldPattern(pattern: string, fieldname: string): boolean {
444
- const patternParts = pattern.split('.')
445
- const fieldParts = fieldname.split('.')
446
-
447
- if (patternParts.length !== fieldParts.length) {
448
- return false
449
- }
450
-
451
- for (let i = 0; i < patternParts.length; i++) {
452
- const patternPart = patternParts[i]
453
- const fieldPart = fieldParts[i]
454
-
455
- if (patternPart === '*') {
456
- // Wildcard matches any segment
457
- continue
458
- } else if (patternPart !== fieldPart) {
459
- // Exact match required
460
- return false
461
- }
462
- }
463
-
464
- return true
465
- }
466
-
467
- /**
468
- * Execute a single action by name
469
- */
470
- private async executeAction(
471
- actionName: string,
472
- context: FieldChangeContext,
473
- timeout?: number
474
- ): Promise<ActionExecutionResult> {
475
- const startTime = performance.now()
476
- const actionTimeout = timeout ?? this.options.defaultTimeout
477
-
478
- try {
479
- // Look up action in global registry
480
- const actionFn = this.globalActions.get(actionName)
481
- if (!actionFn) {
482
- throw new Error(`Action "${actionName}" not found in registry`)
483
- }
484
-
485
- await this.executeWithTimeout(actionFn, context, actionTimeout)
486
- const executionTime = performance.now() - startTime
487
-
488
- return {
489
- success: true,
490
- executionTime,
491
- action: actionName,
492
- }
493
- } catch (error) {
494
- const executionTime = performance.now() - startTime
495
- const actionError = error instanceof Error ? error : new Error(String(error))
496
-
497
- return {
498
- success: false,
499
- error: actionError,
500
- executionTime,
501
- action: actionName,
502
- }
503
- }
504
- }
505
-
506
- /**
507
- * Execute a function with timeout
508
- */
509
- private async executeWithTimeout(
510
- fn: FieldActionFunction,
511
- context: FieldChangeContext,
512
- timeout: number
513
- ): Promise<unknown> {
514
- return new Promise((resolve, reject) => {
515
- const timeoutId = setTimeout(() => {
516
- reject(new Error(`Action timeout after ${timeout}ms`))
517
- }, timeout)
518
-
519
- Promise.resolve(fn(context))
520
- .then(result => {
521
- clearTimeout(timeoutId)
522
- return resolve(result)
523
- })
524
- .catch(error => {
525
- clearTimeout(timeoutId)
526
- reject(error instanceof Error ? error : new Error(String(error)))
527
- })
528
- })
529
- }
530
-
531
- /**
532
- * Capture a snapshot of the record state before executing actions
533
- * This creates a deep copy of the record data for potential rollback
534
- */
535
- private captureSnapshot(context: FieldChangeContext): any {
536
- if (!context.store || !context.doctype || !context.recordId) {
537
- return undefined
538
- }
539
-
540
- try {
541
- // Get the record path (doctype.recordId)
542
- const recordPath = `${context.doctype}.${context.recordId}`
543
-
544
- // Get the current record data
545
- const recordData = context.store.get(recordPath)
546
-
547
- if (!recordData || typeof recordData !== 'object') {
548
- return undefined
549
- }
550
-
551
- // Create a deep copy to avoid reference issues
552
- return JSON.parse(JSON.stringify(recordData))
553
- } catch (error) {
554
- if (this.options.debug) {
555
- console.warn('[FieldTriggers] Failed to capture snapshot:', error)
556
- }
557
- return undefined
558
- }
559
- }
560
-
561
- /**
562
- * Restore a previously captured snapshot
563
- * This reverts the record to its state before actions were executed
564
- */
565
- private restoreSnapshot(context: FieldChangeContext, snapshot: any): void {
566
- if (!context.store || !context.doctype || !context.recordId || !snapshot) {
567
- return
568
- }
569
-
570
- try {
571
- // Get the record path (doctype.recordId)
572
- const recordPath = `${context.doctype}.${context.recordId}`
573
-
574
- // Restore the entire record from snapshot
575
- context.store.set(recordPath, snapshot)
576
-
577
- if (this.options.debug) {
578
- // oxlint-disable-next-line no-console
579
- console.log(`[FieldTriggers] Rolled back ${recordPath} to previous state`)
580
- }
581
- } catch (error) {
582
- console.error('[FieldTriggers] Failed to restore snapshot:', error)
583
- throw error
584
- }
585
- }
586
- }
587
-
588
- /**
589
- * Get or create the global field trigger engine singleton
590
- * @param options - Optional configuration for the field trigger engine
591
- * @public
592
- */
593
- export function getGlobalTriggerEngine(options?: FieldTriggerOptions): FieldTriggerEngine {
594
- return new FieldTriggerEngine(options)
595
- }
596
-
597
- /**
598
- * Register a global action function that can be used in field triggers
599
- * @param name - The name of the action to register
600
- * @param fn - The action function to execute when the trigger fires
601
- * @public
602
- */
603
- export function registerGlobalAction(name: string, fn: FieldActionFunction): void {
604
- const engine = getGlobalTriggerEngine()
605
- engine.registerAction(name, fn)
606
- }
607
-
608
- /**
609
- * Register a global XState transition action function
610
- * @param name - The name of the transition action to register
611
- * @param fn - The transition action function to execute
612
- * @public
613
- */
614
- export function registerTransitionAction(name: string, fn: TransitionActionFunction): void {
615
- const engine = getGlobalTriggerEngine()
616
- engine.registerTransitionAction(name, fn)
617
- }
618
-
619
- /**
620
- * Configure rollback behavior for a specific field trigger
621
- * @param doctype - The doctype name
622
- * @param fieldname - The field name
623
- * @param enableRollback - Whether to enable automatic rollback for this field
624
- * @public
625
- */
626
- export function setFieldRollback(doctype: string, fieldname: string, enableRollback: boolean): void {
627
- const engine = getGlobalTriggerEngine()
628
- engine.setFieldRollback(doctype, fieldname, enableRollback)
629
- }
630
-
631
- /**
632
- * Manually trigger an XState transition for a specific doctype/record
633
- * This can be called directly when you need to execute transition actions programmatically
634
- * @param doctype - The doctype name
635
- * @param transition - The XState transition name to trigger
636
- * @param options - Optional configuration for the transition
637
- * @public
638
- */
639
- export async function triggerTransition(
640
- doctype: string,
641
- transition: string,
642
- options?: {
643
- recordId?: string
644
- currentState?: string
645
- targetState?: string
646
- fsmContext?: Record<string, any>
647
- path?: string
648
- }
649
- ): Promise<any> {
650
- const engine = getGlobalTriggerEngine()
651
-
652
- const context: TransitionChangeContext = {
653
- path: options?.path || (options?.recordId ? `${doctype}.${options.recordId}` : doctype),
654
- fieldname: '',
655
- beforeValue: undefined,
656
- afterValue: undefined,
657
- operation: 'set',
658
- doctype,
659
- recordId: options?.recordId,
660
- timestamp: new Date(),
661
- transition,
662
- currentState: options?.currentState,
663
- targetState: options?.targetState,
664
- fsmContext: options?.fsmContext,
665
- }
666
-
667
- return await engine.executeTransitionActions(context)
668
- }
669
-
670
- /**
671
- * Mark a specific operation as irreversible.
672
- * Used to prevent undo of critical operations like publishing or deletion.
673
- * @param operationId - The ID of the operation to mark as irreversible
674
- * @param reason - Human-readable reason why the operation cannot be undone
675
- * @public
676
- */
677
- export function markOperationIrreversible(operationId: string | undefined, reason: string): void {
678
- if (!operationId) return
679
-
680
- try {
681
- const store = useOperationLogStore()
682
- store.markIrreversible(operationId, reason)
683
- } catch {
684
- // Operation log is optional
685
- }
686
- }