json-eval-rs 0.0.92

High-performance JSON Logic evaluator with schema validation and dependency tracking. Built on blazing-fast Rust engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use super::JSONEval;
use crate::jsoneval::path_utils;
use crate::time_block;

use serde_json::Value;
use std::mem;

impl JSONEval {
    /// Resolve layout references with optional evaluation
    ///
    /// # Arguments
    ///
    /// * `evaluate` - If true, runs evaluation before resolving layout. If false, only resolves layout.
    ///
    /// # Returns
    ///
    /// A Result indicating success or an error message.
    pub fn resolve_layout(&mut self, evaluate: bool) -> Result<(), String> {
        if evaluate {
            // Use existing data
            let data_str = serde_json::to_string(&self.data)
                .map_err(|e| format!("Failed to serialize data: {}", e))?;
            self.evaluate(&data_str, None, None, None)?;
        }

        self.resolve_layout_internal();
        Ok(())
    }

    fn resolve_layout_internal(&mut self) {
        time_block!("  resolve_layout_internal()", {
            // Use cached layout paths (collected at parse time)
            let layout_paths = self.layout_paths.clone();

            time_block!("    resolve_layout_elements", {
                for layout_path in layout_paths.iter() {
                    self.resolve_layout_elements(layout_path);
                }
            });

            // After resolving all references, propagate parent hidden/disabled to children
            time_block!("    propagate_parent_conditions", {
                for layout_path in layout_paths.iter() {
                    self.propagate_parent_conditions(layout_path);
                }
            });

            // Sync layout hidden state to schema definitions
            // This ensures validation (which checks schema) respects layout hiding
            time_block!("    sync_layout_hidden_to_schema", {
                self.sync_layout_hidden_to_schema(&layout_paths);
            });
        });
    }

    /// Resolve $ref references in layout elements (recursively)
    fn resolve_layout_elements(&mut self, layout_elements_path: &str) {
        // Normalize path from schema format (#/) to JSON pointer format (/)
        let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);

        // Always read elements from original schema (not evaluated_schema)
        // This ensures we get fresh $ref entries on re-evaluation
        let elements = if let Some(Value::Array(arr)) = self.schema.pointer(&normalized_path) {
            arr.clone()
        } else {
            return;
        };

        // Extract the parent path from normalized_path
        let parent_path = normalized_path
            .trim_start_matches('/')
            .replace("/elements", "")
            .replace('/', ".");

        // Process elements
        let mut resolved_elements = Vec::with_capacity(elements.len());
        for (index, element) in elements.iter().enumerate() {
            let element_path = if parent_path.is_empty() {
                format!("elements.{}", index)
            } else {
                format!("{}.elements.{}", parent_path, index)
            };
            let resolved = self.resolve_element_ref_recursive(element.clone(), &element_path);
            resolved_elements.push(resolved);
        }

        // Write back the resolved elements
        if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
            *target = Value::Array(resolved_elements);
        }
    }

    /// Recursively resolve $ref in an element and its nested elements
    /// path_context: The dotted path to the current element (e.g., "form.$layout.elements.0")
    fn resolve_element_ref_recursive(&self, element: Value, path_context: &str) -> Value {
        // First resolve the current element's $ref
        let resolved = self.resolve_element_ref(element);

        // Then recursively resolve any nested elements arrays
        if let Value::Object(mut map) = resolved {
            // Ensure all layout elements have metadata fields
            if !map.contains_key("$parentHide") {
                map.insert("$parentHide".to_string(), Value::Bool(false));
            }

            // Set path metadata for direct layout elements (without $ref)
            if !map.contains_key("$fullpath") {
                map.insert(
                    "$fullpath".to_string(),
                    Value::String(path_context.to_string()),
                );
            }

            if !map.contains_key("$path") {
                let last_segment = path_context.split('.').last().unwrap_or(path_context);
                map.insert("$path".to_string(), Value::String(last_segment.to_string()));
            }

            // Check if this object has an "elements" array
            if let Some(Value::Array(elements)) = map.get("elements") {
                let mut resolved_nested = Vec::with_capacity(elements.len());
                for (index, nested_element) in elements.iter().enumerate() {
                    let nested_path = format!("{}.elements.{}", path_context, index);
                    resolved_nested.push(
                        self.resolve_element_ref_recursive(nested_element.clone(), &nested_path),
                    );
                }
                map.insert("elements".to_string(), Value::Array(resolved_nested));
            }

            return Value::Object(map);
        }

        resolved
    }

    /// Resolve $ref in a single element
    fn resolve_element_ref(&self, element: Value) -> Value {
        match element {
            Value::Object(mut map) => {
                // Check if element has $ref
                if let Some(Value::String(ref_path)) = map.get("$ref").cloned() {
                    // Convert ref_path to dotted notation for metadata storage
                    let dotted_path = path_utils::pointer_to_dot_notation(&ref_path);

                    // Extract last segment for $path
                    let last_segment = dotted_path.split('.').last().unwrap_or(&dotted_path);

                    // Inject metadata fields with dotted notation
                    map.insert("$fullpath".to_string(), Value::String(dotted_path.clone()));
                    map.insert("$path".to_string(), Value::String(last_segment.to_string()));
                    map.insert("$parentHide".to_string(), Value::Bool(false));

                    // Normalize to JSON pointer for actual lookup
                    let normalized_path = if ref_path.starts_with('#') || ref_path.starts_with('/')
                    {
                        path_utils::normalize_to_json_pointer(&ref_path).into_owned()
                    } else {
                        let schema_pointer = path_utils::dot_notation_to_schema_pointer(&ref_path);
                        let schema_path =
                            path_utils::normalize_to_json_pointer(&schema_pointer).into_owned();

                        if self.evaluated_schema.pointer(&schema_path).is_some() {
                            schema_path
                        } else {
                            format!("/properties/{}", ref_path.replace('.', "/properties/"))
                        }
                    };

                    // Get the referenced value
                    if let Some(referenced_value) = self.evaluated_schema.pointer(&normalized_path)
                    {
                        let resolved = referenced_value.clone();

                        if let Value::Object(mut resolved_map) = resolved {
                            map.remove("$ref");

                            // Special case: if resolved has $layout, flatten it
                            if let Some(Value::Object(layout_obj)) = resolved_map.remove("$layout")
                            {
                                let mut result = layout_obj.clone();

                                // properties are now preserved and will be merged below

                                // Merge remaining resolved_map properties
                                for (key, value) in resolved_map {
                                    if key != "type" || !result.contains_key("type") {
                                        result.insert(key, value);
                                    }
                                }

                                // Finally, merge element override properties
                                for (key, value) in map {
                                    result.insert(key, value);
                                }

                                return Value::Object(result);
                            } else {
                                // Normal merge: element properties override referenced properties
                                for (key, value) in map {
                                    resolved_map.insert(key, value);
                                }

                                return Value::Object(resolved_map);
                            }
                        } else {
                            return resolved;
                        }
                    }
                }

                Value::Object(map)
            }
            _ => element,
        }
    }

    /// Propagate parent hidden/disabled conditions to children recursively
    fn propagate_parent_conditions(&mut self, layout_elements_path: &str) {
        let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);

        // Extract elements array to avoid borrow checker issues
        let elements =
            if let Some(Value::Array(arr)) = self.evaluated_schema.pointer_mut(&normalized_path) {
                mem::take(arr)
            } else {
                return;
            };

        // Process elements
        let mut updated_elements = Vec::with_capacity(elements.len());
        for element in elements {
            updated_elements.push(self.apply_parent_conditions(element, false, false));
        }

        // Write back  the updated elements
        if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
            *target = Value::Array(updated_elements);
        }
    }

    /// Recursively apply parent hidden/disabled conditions to an element and its children
    fn apply_parent_conditions(
        &self,
        element: Value,
        parent_hidden: bool,
        parent_disabled: bool,
    ) -> Value {
        if let Value::Object(mut map) = element {
            // Get current element's condition
            let mut element_hidden = parent_hidden;
            let mut element_disabled = parent_disabled;

            // Check condition field (from $ref elements)
            if let Some(Value::Object(condition)) = map.get("condition") {
                if let Some(Value::Bool(hidden)) = condition.get("hidden") {
                    element_hidden = element_hidden || *hidden;
                }
                if let Some(Value::Bool(disabled)) = condition.get("disabled") {
                    element_disabled = element_disabled || *disabled;
                }
            }

            // Check hideLayout field (from direct layout elements)
            if let Some(Value::Object(hide_layout)) = map.get("hideLayout") {
                if let Some(Value::Bool(all)) = hide_layout.get("all") {
                    if *all {
                        element_hidden = true;
                    }
                }
            }

            // Update condition to include parent state (for field elements)
            if parent_hidden || parent_disabled {
                // Update condition field if it exists or if this is a field element
                if map.contains_key("condition")
                    || map.contains_key("$ref")
                    || map.contains_key("$fullpath")
                {
                    let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
                        c.clone()
                    } else {
                        serde_json::Map::new()
                    };

                    if parent_hidden {
                        condition.insert("hidden".to_string(), Value::Bool(true));
                        element_hidden = true;
                    }
                    if parent_disabled {
                        condition.insert("disabled".to_string(), Value::Bool(true));
                        element_disabled = true;
                    }

                    map.insert("condition".to_string(), Value::Object(condition));
                }

                // Update hideLayout for direct layout elements
                if parent_hidden && (map.contains_key("hideLayout") || map.contains_key("type")) {
                    let mut hide_layout = if let Some(Value::Object(h)) = map.get("hideLayout") {
                        h.clone()
                    } else {
                        serde_json::Map::new()
                    };

                    // Set hideLayout.all to true when parent is hidden
                    hide_layout.insert("all".to_string(), Value::Bool(true));
                    map.insert("hideLayout".to_string(), Value::Object(hide_layout));
                }
            }

            // Update $parentHide flag if element has it
            if map.contains_key("$parentHide") {
                map.insert("$parentHide".to_string(), Value::Bool(parent_hidden));
            }

            // Recursively process children if elements array exists
            if let Some(Value::Array(elements)) = map.get("elements") {
                let mut updated_children = Vec::with_capacity(elements.len());
                for child in elements {
                    updated_children.push(self.apply_parent_conditions(
                        child.clone(),
                        element_hidden,
                        element_disabled,
                    ));
                }
                map.insert("elements".to_string(), Value::Array(updated_children));
            }

            return Value::Object(map);
        }

        element
    }

    /// Sync hidden state from layout elements to their schema definitions
    fn sync_layout_hidden_to_schema(&mut self, layout_paths: &[String]) {
        let mut hidden_paths = Vec::new();

        // Collect all schema paths that are effectively hidden in the layout
        for layout_path in layout_paths {
            let normalized_path = path_utils::normalize_to_json_pointer(layout_path);
            if let Some(Value::Array(elements)) = self.evaluated_schema.pointer(&normalized_path) {
                for element in elements {
                    self.collect_hidden_paths_recursive(element, &mut hidden_paths);
                }
            }
        }

        // Apply hidden state to schema definitions
        for schema_path_dot in hidden_paths {
            let schema_pointer = path_utils::dot_notation_to_schema_pointer(&schema_path_dot);
            let normalized_pointer = path_utils::normalize_to_json_pointer(&schema_pointer);

            if let Some(schema_node) = self.evaluated_schema.pointer_mut(&normalized_pointer) {
                if let Value::Object(map) = schema_node {
                    // Update condition.hidden = true
                    let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
                        c.clone()
                    } else {
                        serde_json::Map::new()
                    };

                    condition.insert("hidden".to_string(), Value::Bool(true));
                    map.insert("condition".to_string(), Value::Object(condition));
                }
            } else {
                // Try with /properties prefix if direct lookup fails
                let alt_pointer = format!("/properties{}", normalized_pointer);
                if let Some(schema_node) = self.evaluated_schema.pointer_mut(&alt_pointer) {
                    if let Value::Object(map) = schema_node {
                        let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
                            c.clone()
                        } else {
                            serde_json::Map::new()
                        };

                        condition.insert("hidden".to_string(), Value::Bool(true));
                        map.insert("condition".to_string(), Value::Object(condition));
                    }
                }
            }
        }
    }

    fn collect_hidden_paths_recursive(&self, element: &Value, hidden_paths: &mut Vec<String>) {
        if let Value::Object(map) = element {
            // Check if this element is effectively hidden
            let is_hidden = if let Some(Value::Object(condition)) = map.get("condition") {
                condition
                    .get("hidden")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false)
            } else {
                false
            };

            if is_hidden {
                // If hidden and has $fullpath, verify it points to a schema definition
                if let Some(Value::String(fullpath)) = map.get("fullpath") {
                    hidden_paths.push(fullpath.clone());
                } else if let Some(Value::String(fullpath)) = map.get("$fullpath") {
                    hidden_paths.push(fullpath.clone());
                }
            }

            // Recurse children
            if let Some(Value::Array(elements)) = map.get("elements") {
                for child in elements {
                    self.collect_hidden_paths_recursive(child, hidden_paths);
                }
            }
        }
    }
}