form0-core 0.1.8 → 0.1.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "form0-core",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/"
6
6
  },
@@ -1,7 +1,12 @@
1
1
  import { runExpression } from './evaluator.js';
2
- import { flattenFields } from '../utilities/field-helpers.js';
3
2
  import { ContextResolver } from './context-resolver.js';
4
3
  import { WarningSystem } from './warning-system.js';
4
+ import {
5
+ buildCalculationDependencyPlan,
6
+ buildCalculationExecutionContext,
7
+ extractStaticFieldReferences,
8
+ } from '../utilities/calculation-dependencies.js';
9
+ import { areStructuredValuesEqual } from '../utilities/value-equality.js';
5
10
 
6
11
  export function evaluateCalculatedFields(
7
12
  schema,
@@ -10,69 +15,68 @@ export function evaluateCalculatedFields(
10
15
  securityConfig,
11
16
  contextResolver = null,
12
17
  warningSystem = null,
13
- runtimeDiagnostics = null
18
+ runtimeDiagnostics = null,
19
+ calculationPlan = null
14
20
  ) {
15
- const fields = flattenFields(schema.elements);
16
-
17
- // Initialize context resolver and warning system if not provided (backward compatibility)
18
21
  const resolver = contextResolver || new ContextResolver(schema);
19
22
  const warnings = warningSystem || new WarningSystem();
23
+ const plan = calculationPlan || buildCalculationDependencyPlan(schema, resolver);
20
24
 
21
- fields.forEach((field) => {
22
- if (field.type === 'CalculatedField' && field.calculate) {
23
- try {
24
- // Create execution context for this calculation
25
- const executionContext = {
26
- type: 'calculation',
27
- fieldName: field.data_name,
28
- parentPath: resolver.getFieldInfo(field.data_name)?.parentPath || [],
29
- };
30
-
31
- const context = buildScopedContext(
32
- values,
33
- helpers,
34
- executionContext,
35
- resolver,
36
- warnings,
37
- field.calculate
38
- );
39
- values[field.data_name] = runExpression(
40
- field.calculate,
41
- context,
42
- securityConfig,
43
- false,
44
- schema,
45
- {
46
- suppressConsoleWarning: Array.isArray(runtimeDiagnostics),
47
- onError: (error) => {
48
- if (!Array.isArray(runtimeDiagnostics)) {
49
- return;
50
- }
51
-
52
- runtimeDiagnostics.push({
53
- fieldName: field.data_name,
54
- message:
55
- error instanceof Error && error.message
56
- ? error.message
57
- : 'Unknown calculation runtime error.',
58
- });
59
- },
60
- }
61
- );
62
- } catch (e) {
63
- if (Array.isArray(runtimeDiagnostics)) {
64
- runtimeDiagnostics.push({
65
- fieldName: field.data_name,
66
- message:
67
- e instanceof Error && e.message
68
- ? e.message
69
- : 'Unknown calculation runtime error.',
70
- });
71
- }
72
- if (!Array.isArray(runtimeDiagnostics)) {
73
- console.warn(`Calculation failed for ${field.data_name}:`, e.message);
74
- }
75
- }
25
+ emitDependencyPlanWarnings(plan, warnings, runtimeDiagnostics);
26
+
27
+ if (plan.totalCalculatedFieldCount === 0) {
28
+ return;
29
+ }
30
+
31
+ if (plan.hasDynamicDependencies) {
32
+ evaluateFieldSequenceUntilStable(
33
+ plan.orderedFieldNames,
34
+ plan,
35
+ schema,
36
+ values,
37
+ helpers,
38
+ securityConfig,
39
+ resolver,
40
+ warnings,
41
+ runtimeDiagnostics
42
+ );
43
+ return;
44
+ }
45
+
46
+ plan.orderedComponentIds.forEach((componentId) => {
47
+ const component = plan.componentsById.get(componentId);
48
+ if (!component || component.fieldNames.length === 0) {
49
+ return;
50
+ }
51
+
52
+ if (component.isCyclic) {
53
+ evaluateFieldSequenceUntilStable(
54
+ component.fieldNames,
55
+ plan,
56
+ schema,
57
+ values,
58
+ helpers,
59
+ securityConfig,
60
+ resolver,
61
+ warnings,
62
+ runtimeDiagnostics
63
+ );
64
+ return;
65
+ }
66
+
67
+ const fieldName = component.fieldNames[0];
68
+ const node = plan.nodesByDataName.get(fieldName);
69
+ if (node?.field) {
70
+ evaluateCalculatedField(
71
+ node.field,
72
+ schema,
73
+ values,
74
+ helpers,
75
+ securityConfig,
76
+ resolver,
77
+ warnings,
78
+ runtimeDiagnostics
79
+ );
76
80
  }
77
81
  });
78
82
  }
@@ -87,43 +91,32 @@ function buildScopedContext(
87
91
  ) {
88
92
  const ctx = { ...helpers };
89
93
 
90
- // Find which fields are actually referenced in the expression
91
- const referencedFields = extractFieldReferences(expressionCode);
92
-
93
- // Track problematic fields that are actually accessed
94
+ const referencedFields = extractStaticFieldReferences(expressionCode);
94
95
  const restrictedAccessedFields = [];
95
96
  const notFoundAccessedFields = [];
96
97
 
97
- // Add scoped field access
98
98
  for (const [fieldName, value] of Object.entries(values)) {
99
99
  const accessLevel = contextResolver.resolveFieldAccess(executionContext, fieldName);
100
100
 
101
101
  if (accessLevel === 'accessible') {
102
102
  ctx[`$${fieldName}`] = value;
103
103
  } else if (accessLevel === 'restricted') {
104
- // Only add restricted fields to context if they're actually referenced
105
104
  if (referencedFields.has(fieldName)) {
106
105
  ctx[`$${fieldName}`] = undefined;
107
106
  restrictedAccessedFields.push(fieldName);
108
107
  }
109
- // If not referenced, don't add to context at all
110
108
  }
111
- // 'not_found' fields are not added to context at all
112
109
  }
113
110
 
114
- // Check for not_found fields that are actually referenced
115
111
  for (const fieldName of referencedFields) {
116
- // Check if this field was processed above (exists in values)
117
112
  if (!(fieldName in values)) {
118
113
  const accessLevel = contextResolver.resolveFieldAccess(executionContext, fieldName);
119
114
  if (accessLevel === 'not_found') {
120
115
  notFoundAccessedFields.push(fieldName);
121
- // Don't add to context - it will be undefined when accessed
122
116
  }
123
117
  }
124
118
  }
125
119
 
126
- // Emit warnings for restricted fields that are actually accessed
127
120
  restrictedAccessedFields.forEach((fieldName) => {
128
121
  const warning = contextResolver.generateAccessWarning(
129
122
  executionContext,
@@ -133,7 +126,6 @@ function buildScopedContext(
133
126
  warningSystem.emitWarning(warning);
134
127
  });
135
128
 
136
- // Emit warnings for not_found fields that are actually accessed
137
129
  notFoundAccessedFields.forEach((fieldName) => {
138
130
  const warning = contextResolver.generateAccessWarning(executionContext, fieldName, 'not_found');
139
131
  warningSystem.emitWarning(warning);
@@ -142,93 +134,225 @@ function buildScopedContext(
142
134
  return ctx;
143
135
  }
144
136
 
145
- /**
146
- * Extract field references from expression code (simple regex-based approach)
147
- * Skips field references inside EVAL() calls to avoid false positives from dynamic field construction
148
- * @param {string} code - The expression/code to analyze
149
- * @returns {Set<string>} Set of field names referenced in the code
150
- */
151
- function extractFieldReferences(code) {
152
- const fieldReferences = new Set();
153
-
154
- // Remove content inside EVAL() calls to avoid false positives
155
- // This handles complex patterns like EVAL('string' + variable + 'more')
156
- const cleanedCode = removeEvalContents(code);
157
-
158
- // Simple regex to find $fieldname patterns in the cleaned code
159
- // This matches $ followed by valid JavaScript identifier characters
160
- const fieldRegex = /\$([a-zA-Z_][a-zA-Z0-9_]*)/g;
161
- let match;
162
-
163
- while ((match = fieldRegex.exec(cleanedCode)) !== null) {
164
- fieldReferences.add(match[1]); // Add the field name (without $)
137
+ function pushRuntimeDiagnostic(
138
+ runtimeDiagnostics,
139
+ fieldName,
140
+ message,
141
+ severity = 'error',
142
+ dedupeKey = null
143
+ ) {
144
+ if (!Array.isArray(runtimeDiagnostics)) {
145
+ return;
165
146
  }
166
147
 
167
- return fieldReferences;
148
+ if (
149
+ dedupeKey &&
150
+ runtimeDiagnostics.some(
151
+ (diagnostic) =>
152
+ diagnostic?.fieldName === fieldName &&
153
+ diagnostic?.message === message &&
154
+ diagnostic?.dedupeKey === dedupeKey
155
+ )
156
+ ) {
157
+ return;
158
+ }
159
+
160
+ runtimeDiagnostics.push({
161
+ fieldName,
162
+ message,
163
+ severity,
164
+ dedupeKey,
165
+ });
168
166
  }
169
167
 
170
- /**
171
- * Remove EVAL() function calls and their contents from code
172
- * Handles nested parentheses and complex expressions inside EVAL()
173
- * @param {string} code - The code to clean
174
- * @returns {string} Code with EVAL() contents removed
175
- */
176
- function removeEvalContents(code) {
177
- let result = '';
178
- let i = 0;
179
-
180
- while (i < code.length) {
181
- // Look for EVAL pattern
182
- const evalMatch = code.substring(i).match(/^EVAL\s*\(/);
183
- if (evalMatch) {
184
- // Found EVAL(, add "EVAL()" to result and skip the entire call
185
- result += 'EVAL()';
186
- i += evalMatch[0].length;
187
-
188
- // Skip everything until we find the matching closing parenthesis
189
- let parenCount = 1;
190
- let inSingleQuote = false;
191
- let inDoubleQuote = false;
192
- let inBacktick = false;
193
-
194
- while (i < code.length && parenCount > 0) {
195
- const char = code[i];
196
-
197
- // Handle string literals (ignore parentheses inside strings)
198
- if (char === "'" && !inDoubleQuote && !inBacktick) {
199
- inSingleQuote = !inSingleQuote;
200
- } else if (char === '"' && !inSingleQuote && !inBacktick) {
201
- inDoubleQuote = !inDoubleQuote;
202
- } else if (char === '`' && !inSingleQuote && !inDoubleQuote) {
203
- inBacktick = !inBacktick;
204
- }
205
-
206
- // Only count parentheses when not inside strings
207
- if (!inSingleQuote && !inDoubleQuote && !inBacktick) {
208
- if (char === '(') {
209
- parenCount++;
210
- } else if (char === ')') {
211
- parenCount--;
212
- }
213
- }
214
-
215
- i++;
216
- }
217
- } else {
218
- // Not an EVAL call, add character to result
219
- result += code[i];
220
- i++;
168
+ function emitDependencyPlanWarnings(plan, warningSystem, runtimeDiagnostics) {
169
+ plan.dynamicFieldNames.forEach((fieldName) => {
170
+ const message = `CalculatedField '${fieldName}' uses dynamic field access. Runtime evaluation falls back to bounded stabilization.`;
171
+ warningSystem.emitWarning({
172
+ type: 'calculation_dependency',
173
+ reason: 'dynamic_dependencies',
174
+ message,
175
+ suggestion: 'Prefer direct $field references when possible to enable dependency ordering.',
176
+ executionContext: {
177
+ type: 'calculation',
178
+ fieldName,
179
+ },
180
+ fieldContext: {
181
+ fieldName,
182
+ dynamic: true,
183
+ },
184
+ });
185
+ pushRuntimeDiagnostic(
186
+ runtimeDiagnostics,
187
+ fieldName,
188
+ message,
189
+ 'warning',
190
+ `dynamic:${fieldName}`
191
+ );
192
+ });
193
+
194
+ plan.cyclicComponentIds.forEach((componentId) => {
195
+ const component = plan.componentsById.get(componentId);
196
+ if (!component?.isCyclic) {
197
+ return;
221
198
  }
199
+
200
+ const fieldNames = component.fieldNames;
201
+ const message = `CalculatedField dependency cycle detected: ${fieldNames.join(' -> ')}. Runtime evaluation will use bounded stabilization.`;
202
+ warningSystem.emitWarning({
203
+ type: 'calculation_dependency',
204
+ reason: 'cyclic_dependencies',
205
+ message,
206
+ suggestion:
207
+ 'Remove the cycle or break it with a source field so calculated values can be evaluated deterministically.',
208
+ executionContext: {
209
+ type: 'calculation',
210
+ fieldName: fieldNames[0] || null,
211
+ },
212
+ fieldContext: {
213
+ fieldNames: [...fieldNames],
214
+ cyclic: true,
215
+ },
216
+ });
217
+
218
+ fieldNames.forEach((fieldName) => {
219
+ pushRuntimeDiagnostic(
220
+ runtimeDiagnostics,
221
+ fieldName,
222
+ message,
223
+ 'warning',
224
+ `cycle:${componentId}`
225
+ );
226
+ });
227
+ });
228
+ }
229
+
230
+ function evaluateCalculatedField(
231
+ field,
232
+ schema,
233
+ values,
234
+ helpers,
235
+ securityConfig,
236
+ resolver,
237
+ warnings,
238
+ runtimeDiagnostics
239
+ ) {
240
+ if (!field?.data_name || !field.calculate) {
241
+ return { changed: false, hasError: false };
222
242
  }
223
243
 
224
- return result;
244
+ try {
245
+ const executionContext = buildCalculationExecutionContext(schema, field.data_name, resolver);
246
+ const context = buildScopedContext(
247
+ values,
248
+ helpers,
249
+ executionContext,
250
+ resolver,
251
+ warnings,
252
+ field.calculate
253
+ );
254
+ const previousValue = values[field.data_name];
255
+ const nextValue = runExpression(field.calculate, context, securityConfig, false, schema, {
256
+ suppressConsoleWarning: Array.isArray(runtimeDiagnostics),
257
+ onError: (error) => {
258
+ pushRuntimeDiagnostic(
259
+ runtimeDiagnostics,
260
+ field.data_name,
261
+ error instanceof Error && error.message
262
+ ? error.message
263
+ : 'Unknown calculation runtime error.'
264
+ );
265
+ },
266
+ });
267
+ values[field.data_name] = nextValue;
268
+
269
+ return {
270
+ changed: !areStructuredValuesEqual(previousValue, nextValue),
271
+ hasError: false,
272
+ };
273
+ } catch (error) {
274
+ pushRuntimeDiagnostic(
275
+ runtimeDiagnostics,
276
+ field.data_name,
277
+ error instanceof Error && error.message ? error.message : 'Unknown calculation runtime error.'
278
+ );
279
+
280
+ if (!Array.isArray(runtimeDiagnostics)) {
281
+ console.warn(`Calculation failed for ${field.data_name}:`, error?.message);
282
+ }
283
+
284
+ return { changed: false, hasError: true };
285
+ }
225
286
  }
226
287
 
227
- // Legacy function for backward compatibility
228
- function buildContext(values, helpers) {
229
- const ctx = {};
230
- for (const key in values) {
231
- ctx[`$${key}`] = values[key];
288
+ function evaluateFieldSequenceUntilStable(
289
+ fieldNames,
290
+ plan,
291
+ schema,
292
+ values,
293
+ helpers,
294
+ securityConfig,
295
+ resolver,
296
+ warnings,
297
+ runtimeDiagnostics
298
+ ) {
299
+ const maxPasses = Math.max(2, plan.totalCalculatedFieldCount);
300
+ let stillChangingFieldNames = [];
301
+
302
+ for (let pass = 0; pass < maxPasses; pass += 1) {
303
+ stillChangingFieldNames = [];
304
+
305
+ fieldNames.forEach((fieldName) => {
306
+ const node = plan.nodesByDataName.get(fieldName);
307
+ if (!node?.field) {
308
+ return;
309
+ }
310
+
311
+ const result = evaluateCalculatedField(
312
+ node.field,
313
+ schema,
314
+ values,
315
+ helpers,
316
+ securityConfig,
317
+ resolver,
318
+ warnings,
319
+ runtimeDiagnostics
320
+ );
321
+
322
+ if (result.changed) {
323
+ stillChangingFieldNames.push(fieldName);
324
+ }
325
+ });
326
+
327
+ if (stillChangingFieldNames.length === 0) {
328
+ return;
329
+ }
232
330
  }
233
- return { ...ctx, ...helpers };
331
+
332
+ const message = `Calculated fields did not stabilize within ${maxPasses} evaluation passes: ${stillChangingFieldNames.join(', ')}.`;
333
+ warnings.emitWarning({
334
+ type: 'calculation_dependency',
335
+ reason: 'non_converging_runtime',
336
+ message,
337
+ suggestion:
338
+ 'Review the involved CalculatedField expressions for dependency cycles or dynamic references that never settle.',
339
+ executionContext: {
340
+ type: 'calculation',
341
+ fieldName: stillChangingFieldNames[0] || null,
342
+ },
343
+ fieldContext: {
344
+ fieldNames: [...stillChangingFieldNames],
345
+ maxPasses,
346
+ },
347
+ });
348
+
349
+ stillChangingFieldNames.forEach((fieldName) => {
350
+ pushRuntimeDiagnostic(
351
+ runtimeDiagnostics,
352
+ fieldName,
353
+ message,
354
+ 'warning',
355
+ `non-converging:${fieldNames.join(',')}`
356
+ );
357
+ });
234
358
  }
@@ -12,6 +12,7 @@ import { FIELD_SPECS } from '../schema/field-specs.js';
12
12
  import { ContextResolver } from './context-resolver.js';
13
13
  import { WarningSystem } from './warning-system.js';
14
14
  import { expandBuildingPlanSchema } from '../schema/building-plan-expander.js';
15
+ import { buildCalculationDependencyPlan } from '../utilities/calculation-dependencies.js';
15
16
 
16
17
  export function createFormEngine({
17
18
  schema,
@@ -94,6 +95,7 @@ export function createFormEngine({
94
95
 
95
96
  // Initialize context resolution system
96
97
  const contextResolver = new ContextResolver(form);
98
+ const calculationPlan = buildCalculationDependencyPlan(form, contextResolver);
97
99
  const sharedWarningSystem = warningSystem || new WarningSystem();
98
100
 
99
101
  // Initialize event system with context resolution
@@ -128,7 +130,8 @@ export function createFormEngine({
128
130
  security,
129
131
  contextResolver,
130
132
  sharedWarningSystem,
131
- runtimeDiagnostics
133
+ runtimeDiagnostics,
134
+ calculationPlan
132
135
  );
133
136
  evaluateRequirement(form, values, required);
134
137
  evaluateVisibility(form, values, visible);
@@ -0,0 +1,311 @@
1
+ import { ContextResolver } from '../engine/context-resolver.js';
2
+ import { flattenFields } from './field-helpers.js';
3
+
4
+ function sortFieldNames(fieldNames, orderByFieldName) {
5
+ return [...fieldNames].sort(
6
+ (left, right) => orderByFieldName.get(left) - orderByFieldName.get(right)
7
+ );
8
+ }
9
+
10
+ function buildStronglyConnectedComponents(nodesByDataName, orderByFieldName) {
11
+ const indices = new Map();
12
+ const lowLinks = new Map();
13
+ const stack = [];
14
+ const onStack = new Set();
15
+ const components = [];
16
+ let currentIndex = 0;
17
+
18
+ function strongConnect(fieldName) {
19
+ indices.set(fieldName, currentIndex);
20
+ lowLinks.set(fieldName, currentIndex);
21
+ currentIndex += 1;
22
+ stack.push(fieldName);
23
+ onStack.add(fieldName);
24
+
25
+ const node = nodesByDataName.get(fieldName);
26
+ if (node) {
27
+ for (const dependency of node.dependencies) {
28
+ if (!indices.has(dependency)) {
29
+ strongConnect(dependency);
30
+ lowLinks.set(fieldName, Math.min(lowLinks.get(fieldName), lowLinks.get(dependency)));
31
+ } else if (onStack.has(dependency)) {
32
+ lowLinks.set(fieldName, Math.min(lowLinks.get(fieldName), indices.get(dependency)));
33
+ }
34
+ }
35
+ }
36
+
37
+ if (lowLinks.get(fieldName) !== indices.get(fieldName)) {
38
+ return;
39
+ }
40
+
41
+ const componentFieldNames = [];
42
+ while (stack.length > 0) {
43
+ const stackFieldName = stack.pop();
44
+ onStack.delete(stackFieldName);
45
+ componentFieldNames.push(stackFieldName);
46
+ if (stackFieldName === fieldName) {
47
+ break;
48
+ }
49
+ }
50
+
51
+ components.push(sortFieldNames(componentFieldNames, orderByFieldName));
52
+ }
53
+
54
+ const sortedFieldNames = sortFieldNames(nodesByDataName.keys(), orderByFieldName);
55
+ sortedFieldNames.forEach((fieldName) => {
56
+ if (!indices.has(fieldName)) {
57
+ strongConnect(fieldName);
58
+ }
59
+ });
60
+
61
+ return components;
62
+ }
63
+
64
+ function topologicallyOrderComponents(componentIds, componentEdges) {
65
+ const inDegree = new Map(componentIds.map((componentId) => [componentId, 0]));
66
+
67
+ componentEdges.forEach((targets) => {
68
+ targets.forEach((targetId) => {
69
+ inDegree.set(targetId, (inDegree.get(targetId) || 0) + 1);
70
+ });
71
+ });
72
+
73
+ const queue = componentIds.filter((componentId) => (inDegree.get(componentId) || 0) === 0);
74
+ const ordered = [];
75
+
76
+ while (queue.length > 0) {
77
+ const componentId = queue.shift();
78
+ ordered.push(componentId);
79
+
80
+ for (const targetId of componentEdges.get(componentId) || []) {
81
+ const nextDegree = (inDegree.get(targetId) || 0) - 1;
82
+ inDegree.set(targetId, nextDegree);
83
+ if (nextDegree === 0) {
84
+ queue.push(targetId);
85
+ }
86
+ }
87
+ }
88
+
89
+ if (ordered.length === componentIds.length) {
90
+ return ordered;
91
+ }
92
+
93
+ return [...componentIds];
94
+ }
95
+
96
+ export function normalizeCalculationFormSchema(schema) {
97
+ if (schema && Array.isArray(schema.elements)) {
98
+ return schema;
99
+ }
100
+
101
+ if (schema && schema.form && Array.isArray(schema.form.elements)) {
102
+ return schema.form;
103
+ }
104
+
105
+ throw new Error('Expected a form schema or a root schema containing form.elements');
106
+ }
107
+
108
+ export function hasDynamicCalculationDependencies(code) {
109
+ return /\bEVAL\s*\(/.test(typeof code === 'string' ? code : '');
110
+ }
111
+
112
+ export function removeEvalContents(code) {
113
+ const source = typeof code === 'string' ? code : '';
114
+ let result = '';
115
+ let i = 0;
116
+
117
+ while (i < source.length) {
118
+ const evalMatch = source.substring(i).match(/^EVAL\s*\(/);
119
+ if (evalMatch) {
120
+ result += 'EVAL()';
121
+ i += evalMatch[0].length;
122
+
123
+ let parenCount = 1;
124
+ let inSingleQuote = false;
125
+ let inDoubleQuote = false;
126
+ let inBacktick = false;
127
+
128
+ while (i < source.length && parenCount > 0) {
129
+ const char = source[i];
130
+
131
+ if (char === "'" && !inDoubleQuote && !inBacktick) {
132
+ inSingleQuote = !inSingleQuote;
133
+ } else if (char === '"' && !inSingleQuote && !inBacktick) {
134
+ inDoubleQuote = !inDoubleQuote;
135
+ } else if (char === '`' && !inSingleQuote && !inDoubleQuote) {
136
+ inBacktick = !inBacktick;
137
+ }
138
+
139
+ if (!inSingleQuote && !inDoubleQuote && !inBacktick) {
140
+ if (char === '(') {
141
+ parenCount += 1;
142
+ } else if (char === ')') {
143
+ parenCount -= 1;
144
+ }
145
+ }
146
+
147
+ i += 1;
148
+ }
149
+ } else {
150
+ result += source[i];
151
+ i += 1;
152
+ }
153
+ }
154
+
155
+ return result;
156
+ }
157
+
158
+ export function extractStaticFieldReferenceMatches(code) {
159
+ const cleanedCode = removeEvalContents(code);
160
+ const fieldRegex = /\$([a-zA-Z_][a-zA-Z0-9_]*)/g;
161
+ const matches = [];
162
+ let match;
163
+
164
+ while ((match = fieldRegex.exec(cleanedCode)) !== null) {
165
+ matches.push({
166
+ fieldName: match[1],
167
+ reference: `$${match[1]}`,
168
+ index: match.index,
169
+ length: match[0].length,
170
+ });
171
+ }
172
+
173
+ return matches;
174
+ }
175
+
176
+ export function extractStaticFieldReferences(code) {
177
+ return new Set(extractStaticFieldReferenceMatches(code).map((match) => match.fieldName));
178
+ }
179
+
180
+ export function buildCalculationExecutionContext(form, fieldDataName, resolver) {
181
+ return {
182
+ type: 'calculation',
183
+ fieldName: fieldDataName,
184
+ parentPath: resolver.getFieldInfo(fieldDataName)?.parentPath || [],
185
+ };
186
+ }
187
+
188
+ export function buildCalculationDependencyPlan(schema, contextResolver = null) {
189
+ const form = normalizeCalculationFormSchema(schema);
190
+ const resolver = contextResolver || new ContextResolver(form);
191
+ const fields = flattenFields(form.elements).filter((field) => field && typeof field === 'object');
192
+ const fieldsByDataName = new Map(
193
+ fields
194
+ .filter((field) => typeof field.data_name === 'string' && field.data_name.length > 0)
195
+ .map((field) => [field.data_name, field])
196
+ );
197
+
198
+ const orderByFieldName = new Map();
199
+ fields.forEach((field, index) => {
200
+ if (typeof field?.data_name === 'string') {
201
+ orderByFieldName.set(field.data_name, index);
202
+ }
203
+ });
204
+
205
+ const nodesByDataName = new Map();
206
+ fields.forEach((field) => {
207
+ if (field.type !== 'CalculatedField' || typeof field.data_name !== 'string') {
208
+ return;
209
+ }
210
+
211
+ const fieldName = field.data_name;
212
+ const executionContext = buildCalculationExecutionContext(form, fieldName, resolver);
213
+ const directReferences = extractStaticFieldReferences(field.calculate || '');
214
+ const dependencies = new Set();
215
+
216
+ directReferences.forEach((referenceFieldName) => {
217
+ const accessInfo = resolver.resolveFieldAccessInfo(executionContext, referenceFieldName);
218
+ if (accessInfo.level !== 'accessible') {
219
+ return;
220
+ }
221
+
222
+ const dependencyField = fieldsByDataName.get(referenceFieldName);
223
+ if (dependencyField?.type === 'CalculatedField') {
224
+ dependencies.add(referenceFieldName);
225
+ }
226
+ });
227
+
228
+ nodesByDataName.set(fieldName, {
229
+ field,
230
+ fieldName,
231
+ dependencies,
232
+ directReferences,
233
+ hasDynamicDependencies: hasDynamicCalculationDependencies(field.calculate || ''),
234
+ });
235
+ });
236
+
237
+ const componentFieldGroups = buildStronglyConnectedComponents(nodesByDataName, orderByFieldName);
238
+ const componentIdByFieldName = new Map();
239
+ const componentsById = new Map();
240
+
241
+ componentFieldGroups.forEach((fieldNames, componentIndex) => {
242
+ const componentId = `component_${componentIndex}`;
243
+ fieldNames.forEach((fieldName) => {
244
+ componentIdByFieldName.set(fieldName, componentId);
245
+ });
246
+ componentsById.set(componentId, {
247
+ id: componentId,
248
+ fieldNames,
249
+ hasDynamicDependencies: false,
250
+ isCyclic: false,
251
+ });
252
+ });
253
+
254
+ nodesByDataName.forEach((node) => {
255
+ node.componentId = componentIdByFieldName.get(node.fieldName);
256
+ });
257
+
258
+ componentsById.forEach((component) => {
259
+ component.hasDynamicDependencies = component.fieldNames.some(
260
+ (fieldName) => nodesByDataName.get(fieldName)?.hasDynamicDependencies
261
+ );
262
+ component.isCyclic =
263
+ component.fieldNames.length > 1 ||
264
+ component.fieldNames.some((fieldName) =>
265
+ nodesByDataName.get(fieldName)?.dependencies.has(fieldName)
266
+ );
267
+ });
268
+
269
+ const componentEdges = new Map(
270
+ Array.from(componentsById.keys(), (componentId) => [componentId, new Set()])
271
+ );
272
+
273
+ nodesByDataName.forEach((node) => {
274
+ const targetComponentId = node.componentId;
275
+ node.dependencies.forEach((dependencyFieldName) => {
276
+ const dependencyComponentId = componentIdByFieldName.get(dependencyFieldName);
277
+ if (!dependencyComponentId || dependencyComponentId === targetComponentId) {
278
+ return;
279
+ }
280
+ componentEdges.get(dependencyComponentId).add(targetComponentId);
281
+ });
282
+ });
283
+
284
+ const orderedComponentIds = topologicallyOrderComponents(
285
+ Array.from(componentsById.keys()),
286
+ componentEdges
287
+ );
288
+ const orderedFieldNames = orderedComponentIds.flatMap(
289
+ (componentId) => componentsById.get(componentId)?.fieldNames || []
290
+ );
291
+ const dynamicFieldNames = orderedFieldNames.filter(
292
+ (fieldName) => nodesByDataName.get(fieldName)?.hasDynamicDependencies
293
+ );
294
+ const cyclicComponentIds = orderedComponentIds.filter(
295
+ (componentId) => componentsById.get(componentId)?.isCyclic
296
+ );
297
+
298
+ return {
299
+ form,
300
+ fieldsByDataName,
301
+ nodesByDataName,
302
+ componentsById,
303
+ componentIdByFieldName,
304
+ orderedComponentIds,
305
+ orderedFieldNames,
306
+ hasDynamicDependencies: dynamicFieldNames.length > 0,
307
+ dynamicFieldNames,
308
+ cyclicComponentIds,
309
+ totalCalculatedFieldCount: orderedFieldNames.length,
310
+ };
311
+ }
@@ -8,6 +8,13 @@ import { createFormEngine } from '../engine/form-engine.js';
8
8
  import { WarningSystem } from '../engine/warning-system.js';
9
9
  import { DEFAULT_SECURITY_CONFIG } from '../security/config.js';
10
10
  import { validateExpression } from '../security/validation.js';
11
+ import {
12
+ buildCalculationDependencyPlan,
13
+ buildCalculationExecutionContext,
14
+ extractStaticFieldReferenceMatches,
15
+ hasDynamicCalculationDependencies,
16
+ normalizeCalculationFormSchema,
17
+ } from './calculation-dependencies.js';
11
18
  import {
12
19
  isMultilineCalculationExpression,
13
20
  normalizeInlineCalculationExpression,
@@ -53,67 +60,10 @@ const CALCULATION_BUILTIN_METADATA_BY_NAME = new Map(
53
60
  CALCULATION_BUILTIN_CATALOG.map((definition) => [definition.name, definition])
54
61
  );
55
62
 
56
- function normalizeFormSchema(schema) {
57
- if (schema && Array.isArray(schema.elements)) {
58
- return schema;
59
- }
60
-
61
- if (schema && schema.form && Array.isArray(schema.form.elements)) {
62
- return schema.form;
63
- }
64
-
65
- throw new Error('Expected a form schema or a root schema containing form.elements');
66
- }
67
-
68
63
  function isBuiltinCallMatchAllowed(functionName) {
69
64
  return COMMON_GLOBAL_FUNCTIONS.has(functionName);
70
65
  }
71
66
 
72
- function removeEvalContents(code) {
73
- let result = '';
74
- let i = 0;
75
-
76
- while (i < code.length) {
77
- const evalMatch = code.substring(i).match(/^EVAL\s*\(/);
78
- if (evalMatch) {
79
- result += 'EVAL()';
80
- i += evalMatch[0].length;
81
-
82
- let parenCount = 1;
83
- let inSingleQuote = false;
84
- let inDoubleQuote = false;
85
- let inBacktick = false;
86
-
87
- while (i < code.length && parenCount > 0) {
88
- const char = code[i];
89
-
90
- if (char === "'" && !inDoubleQuote && !inBacktick) {
91
- inSingleQuote = !inSingleQuote;
92
- } else if (char === '"' && !inSingleQuote && !inBacktick) {
93
- inDoubleQuote = !inDoubleQuote;
94
- } else if (char === '`' && !inSingleQuote && !inDoubleQuote) {
95
- inBacktick = !inBacktick;
96
- }
97
-
98
- if (!inSingleQuote && !inDoubleQuote && !inBacktick) {
99
- if (char === '(') {
100
- parenCount++;
101
- } else if (char === ')') {
102
- parenCount--;
103
- }
104
- }
105
-
106
- i++;
107
- }
108
- } else {
109
- result += code[i];
110
- i++;
111
- }
112
- }
113
-
114
- return result;
115
- }
116
-
117
67
  function extractFunctionCalls(code) {
118
68
  const functionCallPattern = /\b([A-Z_][A-Z0-9_]*)\s*\(/g;
119
69
  const matches = [];
@@ -130,32 +80,6 @@ function extractFunctionCalls(code) {
130
80
  return matches;
131
81
  }
132
82
 
133
- function extractFieldReferenceMatches(code) {
134
- const cleanedCode = removeEvalContents(code);
135
- const fieldRegex = /\$([a-zA-Z_][a-zA-Z0-9_]*)/g;
136
- const matches = [];
137
- let match;
138
-
139
- while ((match = fieldRegex.exec(cleanedCode)) !== null) {
140
- matches.push({
141
- fieldName: match[1],
142
- reference: `$${match[1]}`,
143
- index: match.index,
144
- length: match[0].length,
145
- });
146
- }
147
-
148
- return matches;
149
- }
150
-
151
- function buildExecutionContext(form, fieldDataName, resolver) {
152
- return {
153
- type: 'calculation',
154
- fieldName: fieldDataName,
155
- parentPath: resolver.getFieldInfo(fieldDataName)?.parentPath || [],
156
- };
157
- }
158
-
159
83
  function cloneCatalogDefinition(definition) {
160
84
  return {
161
85
  ...definition,
@@ -254,7 +178,7 @@ function cloneSimulationSchema(schema) {
254
178
  }
255
179
 
256
180
  return {
257
- form: deepClone(normalizeFormSchema(schema)),
181
+ form: deepClone(normalizeCalculationFormSchema(schema)),
258
182
  };
259
183
  }
260
184
 
@@ -383,9 +307,9 @@ export function getCalculationReferenceCatalog({
383
307
  fieldDataName,
384
308
  includeRestricted = false,
385
309
  }) {
386
- const form = normalizeFormSchema(schema);
310
+ const form = normalizeCalculationFormSchema(schema);
387
311
  const resolver = new ContextResolver(form);
388
- const executionContext = buildExecutionContext(form, fieldDataName, resolver);
312
+ const executionContext = buildCalculationExecutionContext(form, fieldDataName, resolver);
389
313
 
390
314
  return flattenFields(form.elements)
391
315
  .filter((field) => field && typeof field === 'object')
@@ -431,9 +355,14 @@ export function analyzeCalculationExpression({
431
355
  const setResultCalls = [];
432
356
 
433
357
  const normalizedExpression = typeof expression === 'string' ? expression : '';
434
- const form = normalizeFormSchema(schema);
358
+ const baseForm = normalizeCalculationFormSchema(schema);
359
+ const form = deepClone(baseForm);
360
+ const targetField = findFieldByDataName(form.elements, fieldDataName);
361
+ if (targetField && targetField.type === 'CalculatedField') {
362
+ targetField.calculate = normalizedExpression;
363
+ }
435
364
  const resolver = new ContextResolver(form);
436
- const executionContext = buildExecutionContext(form, fieldDataName, resolver);
365
+ const executionContext = buildCalculationExecutionContext(form, fieldDataName, resolver);
437
366
 
438
367
  if (normalizedExpression.trim().length === 0) {
439
368
  addIssue(
@@ -590,7 +519,7 @@ export function analyzeCalculationExpression({
590
519
  );
591
520
  }
592
521
 
593
- for (const reference of extractFieldReferenceMatches(normalizedExpression)) {
522
+ for (const reference of extractStaticFieldReferenceMatches(normalizedExpression)) {
594
523
  if (!referencedFieldNames.has(reference.fieldName)) {
595
524
  referencedFieldNames.add(reference.fieldName);
596
525
  referencedFields.push(reference.fieldName);
@@ -633,6 +562,39 @@ export function analyzeCalculationExpression({
633
562
  }
634
563
  }
635
564
 
565
+ if (hasDynamicCalculationDependencies(normalizedExpression)) {
566
+ addIssue(
567
+ issues,
568
+ issueKeys,
569
+ createIssue({
570
+ code: 'dynamic_calculation_dependency',
571
+ severity: 'warning',
572
+ message:
573
+ 'This expression uses dynamic field access through EVAL(). Runtime evaluation will fall back to bounded stabilization.',
574
+ })
575
+ );
576
+ }
577
+
578
+ if (targetField?.type === 'CalculatedField') {
579
+ const dependencyPlan = buildCalculationDependencyPlan(form, resolver);
580
+ const targetNode = dependencyPlan.nodesByDataName.get(fieldDataName);
581
+ const targetComponent = targetNode?.componentId
582
+ ? dependencyPlan.componentsById.get(targetNode.componentId)
583
+ : null;
584
+
585
+ if (targetComponent?.isCyclic) {
586
+ addIssue(
587
+ issues,
588
+ issueKeys,
589
+ createIssue({
590
+ code: 'calculated_field_cycle',
591
+ severity: 'error',
592
+ message: `CalculatedField dependency cycle detected: ${targetComponent.fieldNames.join(' -> ')}.`,
593
+ })
594
+ );
595
+ }
596
+ }
597
+
636
598
  return {
637
599
  valid: !issues.some((issue) => issue.severity === 'error'),
638
600
  issues,
@@ -673,23 +635,20 @@ export function createCalculationPreviewSession({
673
635
  security = DEFAULT_SECURITY_CONFIG,
674
636
  }) {
675
637
  const simulationSchema = cloneSimulationSchema(schema);
676
- const form = normalizeFormSchema(simulationSchema);
638
+ const form = normalizeCalculationFormSchema(simulationSchema);
677
639
  const targetField = findFieldByDataName(form.elements, fieldDataName);
678
640
 
679
641
  if (!targetField) {
680
642
  return {
681
643
  run: () =>
682
- createSimulationErrorResult(
683
- `Field '${fieldDataName}' does not exist in the form schema.`
684
- ),
644
+ createSimulationErrorResult(`Field '${fieldDataName}' does not exist in the form schema.`),
685
645
  dispose: () => {},
686
646
  };
687
647
  }
688
648
 
689
649
  if (targetField.type !== 'CalculatedField') {
690
650
  return {
691
- run: () =>
692
- createSimulationErrorResult(`Field '${fieldDataName}' is not a CalculatedField.`),
651
+ run: () => createSimulationErrorResult(`Field '${fieldDataName}' is not a CalculatedField.`),
693
652
  dispose: () => {},
694
653
  };
695
654
  }
@@ -739,9 +698,13 @@ export function createCalculationPreviewSession({
739
698
 
740
699
  const simulatedResult = engineState.values[fieldDataName];
741
700
  const runtimeError =
742
- runtimeDiagnostics.find((diagnostic) => diagnostic.fieldName === fieldDataName)
701
+ runtimeDiagnostics.find(
702
+ (diagnostic) =>
703
+ diagnostic.fieldName === fieldDataName &&
704
+ (diagnostic.severity || 'error') !== 'warning'
705
+ )?.message ||
706
+ runtimeDiagnostics.find((diagnostic) => (diagnostic.severity || 'error') !== 'warning')
743
707
  ?.message ||
744
- runtimeDiagnostics[0]?.message ||
745
708
  null;
746
709
 
747
710
  return {
@@ -0,0 +1,54 @@
1
+ function isPlainObject(value) {
2
+ if (!value || typeof value !== 'object') {
3
+ return false;
4
+ }
5
+
6
+ return Object.prototype.toString.call(value) === '[object Object]';
7
+ }
8
+
9
+ export function areStructuredValuesEqual(left, right) {
10
+ if (Object.is(left, right)) {
11
+ return true;
12
+ }
13
+
14
+ if (left instanceof Date && right instanceof Date) {
15
+ return left.getTime() === right.getTime();
16
+ }
17
+
18
+ if (Array.isArray(left) && Array.isArray(right)) {
19
+ if (left.length !== right.length) {
20
+ return false;
21
+ }
22
+
23
+ for (let index = 0; index < left.length; index += 1) {
24
+ if (!areStructuredValuesEqual(left[index], right[index])) {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ return true;
30
+ }
31
+
32
+ if (isPlainObject(left) && isPlainObject(right)) {
33
+ const leftKeys = Object.keys(left);
34
+ const rightKeys = Object.keys(right);
35
+
36
+ if (leftKeys.length !== rightKeys.length) {
37
+ return false;
38
+ }
39
+
40
+ for (const key of leftKeys) {
41
+ if (!Object.prototype.hasOwnProperty.call(right, key)) {
42
+ return false;
43
+ }
44
+
45
+ if (!areStructuredValuesEqual(left[key], right[key])) {
46
+ return false;
47
+ }
48
+ }
49
+
50
+ return true;
51
+ }
52
+
53
+ return false;
54
+ }