json-eval-rs 0.0.95

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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  ScrollView,
  useColorScheme,
  Switch,
  TouchableOpacity,
} from 'react-native';
import { useJSONEval } from '@json-eval-rs/react-native';

// Minimal form schema based on tests/fixtures/minimal_form.json
const schema = {
  "$schema": "https://raw.githubusercontent.com/QuadrantSynergyInternational/form-schema/refs/heads/main/schema.json",
  "$params": {
    "type": "illustration",
    "productCode": "MIN001",
    "productName": "Minimal Insurance Product",
    "constants": {
      "MAX_AGE": 100,
      "MIN_AGE": 1
    },
    "references": {
      "OCCUPATION_TABLE": [
        { "occupation": "OFFICE", "class": "1", "risk": "Low" },
        { "occupation": "PROFESSIONAL", "class": "1", "risk": "Low" },
        { "occupation": "MANUAL", "class": "2", "risk": "Medium" },
        { "occupation": "HIGH_RISK", "class": "3", "risk": "High" }
      ]
    }
  },
  "properties": {
    "illustration": {
      "type": "object",
      "properties": {
        "insured": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "title": "Name"
            },
            "date_of_birth": {
              "type": "string",
              "title": "Date of Birth",
              "dependents": [
                {
                  "$ref": "#/illustration/properties/insured/properties/age",
                  "value": {
                    "$evaluation": {
                      "DATEDIF": [
                        { "$ref": "$value" },
                        { "NOW": [] },
                        "Y"
                      ]
                    }
                  }
                }
              ]
            },
            "age": {
              "type": "number",
              "title": "Age (calculated)"
            },
            "is_smoker": {
              "type": "boolean",
              "title": "Is Smoker?",
              "dependents": [
                {
                  "$ref": "#/illustration/properties/insured/properties/occupation",
                  "clear": { "$evaluation": true }
                },
                {
                  "$ref": "#/illustration/properties/insured/properties/risk_category",
                  "value": {
                    "$evaluation": {
                      "if": [
                        { "$ref": "$value" },
                        "High",
                        "Standard"
                      ]
                    }
                  }
                }
              ]
            },
            "occupation": {
              "type": "string",
              "title": "Occupation",
              "dependents": [
                {
                  "$ref": "#/illustration/properties/insured/properties/occupation_class",
                  "value": {
                    "$evaluation": {
                      "if": [
                        { "==": [{ "$ref": "$value" }, "OFFICE"] },
                        "1",
                        {
                          "if": [
                            { "==": [{ "$ref": "$value" }, "PROFESSIONAL"] },
                            "1",
                            {
                              "if": [
                                { "==": [{ "$ref": "$value" }, "MANUAL"] },
                                "2",
                                "3"
                              ]
                            }
                          ]
                        }
                      ]
                    }
                  }
                }
              ]
            },
            "occupation_class": {
              "type": "string",
              "title": "Occupation Class (calculated)",
              "dependents": [
                {
                  "$ref": "#/illustration/properties/insured/properties/risk_category",
                  "value": {
                    "$evaluation": {
                      "if": [
                        { "==": [{ "$ref": "$value" }, "1"] },
                        "Low",
                        {
                          "if": [
                            { "==": [{ "$ref": "$value" }, "2"] },
                            "Medium",
                            "High"
                          ]
                        }
                      ]
                    }
                  }
                }
              ]
            },
            "risk_category": {
              "type": "string",
              "title": "Risk Category (calculated)"
            }
          }
        }
      }
    }
  }
};

export default function InsuranceFormScreen() {
  const isDarkMode = useColorScheme() === 'dark';
  const [name, setName] = useState('John Doe');
  const [dateOfBirth, setDateOfBirth] = useState('1990-01-01');
  const [age, setAge] = useState<number | null>(null);
  const [isSmoker, setIsSmoker] = useState(false);
  const [occupation, setOccupation] = useState('OFFICE');
  const [occupationClass, setOccupationClass] = useState('');
  const [riskCategory, setRiskCategory] = useState('');
  const [productInfo, setProductInfo] = useState<any>(null);
  const [evaluatedSchema, setEvaluatedSchema] = useState<any>(null);
  const [showParams, setShowParams] = useState(false);
  
  const evalInstance = useJSONEval({ schema });

  // Initial evaluation
  useEffect(() => {
    if (!evalInstance) return;

    const initialize = async () => {
      try {
        const data = {
          illustration: {
            insured: {
              name,
              date_of_birth: dateOfBirth,
              is_smoker: isSmoker,
              occupation,
            }
          }
        };

        await evalInstance.evaluate({ data });
        
        // Get evaluated schema WITHOUT $params
        const schemaWithoutParams = await evalInstance.getEvaluatedSchemaWithoutParams();
        setEvaluatedSchema(schemaWithoutParams);

        // Get $params by path using dot notation
        const params = await evalInstance.getEvaluatedSchemaByPath('$params');
        setProductInfo(params);

        // Get calculated values
        const ageValue = await evalInstance.getEvaluatedSchemaByPath('illustration.properties.insured.properties.age.value');
        const classValue = await evalInstance.getEvaluatedSchemaByPath('illustration.properties.insured.properties.occupation_class.value');
        const riskValue = await evalInstance.getEvaluatedSchemaByPath('illustration.properties.insured.properties.risk_category.value');

        setAge(ageValue);
        setOccupationClass(classValue || '');
        setRiskCategory(riskValue || '');
      } catch (error) {
        console.error('Initialization error:', error);
      }
    };

    initialize();
  }, [evalInstance]);

  // Handle date of birth change with dot notation
  const handleDateChange = async (newDate: string) => {
    setDateOfBirth(newDate);
    if (!evalInstance) return;

    try {
      const data = {
        illustration: {
          insured: {
            name,
            date_of_birth: newDate,
            is_smoker: isSmoker,
            occupation,
          }
        }
      };

      // Use dot notation for path! Much simpler than full schema path
      const result = await evalInstance.evaluateDependents({
        changedPath: 'illustration.insured.date_of_birth',  // Dot notation!
        data,
      });

      // Process dependent changes
      if (result && Array.isArray(result)) {
        result.forEach((change: any) => {
          if (change.$ref?.includes('age') && change.value != null) {
            setAge(change.value);
          }
        });
      }
    } catch (error) {
      console.error('Date change error:', error);
    }
  };

  // Handle smoker change
  const handleSmokerChange = async (value: boolean) => {
    setIsSmoker(value);
    if (!evalInstance) return;

    try {
      const data = {
        illustration: {
          insured: {
            name,
            date_of_birth: dateOfBirth,
            is_smoker: value,
            occupation,
          }
        }
      };

      // Use dot notation for path
      const result = await evalInstance.evaluateDependents({
        changedPath: 'illustration.insured.is_smoker',  // Dot notation!
        data,
      });

      // Process dependent changes (clears occupation, updates risk)
      if (result && Array.isArray(result)) {
        result.forEach((change: any) => {
          if (change.$ref?.includes('occupation') && change.clear) {
            setOccupation('');
          }
          if (change.$ref?.includes('risk_category') && change.value) {
            setRiskCategory(change.value);
          }
        });
      }
    } catch (error) {
      console.error('Smoker change error:', error);
    }
  };

  // Handle occupation change (triggers transitive dependencies)
  const handleOccupationChange = async (value: string) => {
    setOccupation(value);
    if (!evalInstance) return;

    try {
      const data = {
        illustration: {
          insured: {
            name,
            date_of_birth: dateOfBirth,
            is_smoker: isSmoker,
            occupation: value,
          }
        }
      };

      // Use dot notation - automatically processes transitively!
      const result = await evalInstance.evaluateDependents({
        changedPath: 'illustration.insured.occupation',  // Dot notation!
        data,
      });

      // Process transitive changes (occupation -> occupation_class -> risk_category)
      if (result && Array.isArray(result)) {
        result.forEach((change: any) => {
          if (change.$ref?.includes('occupation_class') && change.value) {
            setOccupationClass(change.value);
          }
          if (change.$ref?.includes('risk_category') && change.value) {
            setRiskCategory(change.value);
          }
        });
      }
    } catch (error) {
      console.error('Occupation change error:', error);
    }
  };

  const inputStyle = [
    styles.input,
    { 
      backgroundColor: isDarkMode ? '#2a2a2a' : '#fff',
      color: isDarkMode ? '#fff' : '#000',
      borderColor: isDarkMode ? '#444' : '#ddd',
    },
  ];

  const readOnlyStyle = [
    ...inputStyle,
    { backgroundColor: isDarkMode ? '#1a1a1a' : '#f5f5f5' },
  ];

  return (
    <ScrollView style={[styles.container, { backgroundColor: isDarkMode ? '#000' : '#f9fafb' }]}>
      <View style={styles.content}>
        <Text style={[styles.title, { color: isDarkMode ? '#fff' : '#000' }]}>
          Insurance Form with Dependencies
        </Text>
        <Text style={[styles.description, { color: isDarkMode ? '#aaa' : '#666' }]}>
          Using minimal_form.json with dot notation paths
        </Text>

        {/* Product Info Section */}
        {productInfo && (
          <View style={[styles.infoBox, { backgroundColor: isDarkMode ? '#1a1a1a' : '#f0f9ff' }]}>
            <Text style={[styles.infoTitle, { color: isDarkMode ? '#60a5fa' : '#2563eb' }]}>
              Product Information ($params)
            </Text>
            <Text style={[styles.infoText, { color: isDarkMode ? '#aaa' : '#666' }]}>
              {productInfo.productName} ({productInfo.productCode})
            </Text>
            <Text style={[styles.infoText, { color: isDarkMode ? '#aaa' : '#666' }]}>
              Type: {productInfo.type}
            </Text>
            <TouchableOpacity onPress={() => setShowParams(!showParams)}>
              <Text style={[styles.linkText, { color: isDarkMode ? '#60a5fa' : '#2563eb' }]}>
                {showParams ? 'Hide' : 'Show'} Full Params
              </Text>
            </TouchableOpacity>
            {showParams && (
              <Text style={[styles.jsonText, { color: isDarkMode ? '#aaa' : '#666' }]}>
                {JSON.stringify(productInfo, null, 2)}
              </Text>
            )}
          </View>
        )}

        {/* Form Fields */}
        <View style={styles.section}>
          <Text style={[styles.sectionTitle, { color: isDarkMode ? '#fff' : '#000' }]}>
            Insured Person Details
          </Text>

          <View style={styles.field}>
            <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
              Name
            </Text>
            <TextInput
              style={inputStyle}
              value={name}
              onChangeText={setName}
            />
          </View>

          <View style={styles.field}>
            <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
              Date of Birth
            </Text>
            <TextInput
              style={inputStyle}
              value={dateOfBirth}
              onChangeText={handleDateChange}
              placeholder="YYYY-MM-DD"
            />
          </View>

          <View style={styles.field}>
            <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
              Age (calculated via DATEDIF)
            </Text>
            <TextInput
              style={readOnlyStyle}
              value={age?.toString() || 'Calculating...'}
              editable={false}
            />
            <Text style={[styles.helperText, { color: isDarkMode ? '#888' : '#999' }]}>
              Automatically calculated from date of birth
            </Text>
          </View>

          <View style={styles.field}>
            <View style={styles.switchRow}>
              <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
                Is Smoker?
              </Text>
              <Switch
                value={isSmoker}
                onValueChange={handleSmokerChange}
              />
            </View>
            <Text style={[styles.helperText, { color: isDarkMode ? '#888' : '#999' }]}>
              Clears occupation and updates risk category
            </Text>
          </View>

          <View style={styles.field}>
            <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
              Occupation
            </Text>
            <View style={styles.buttonRow}>
              {['OFFICE', 'PROFESSIONAL', 'MANUAL', 'HIGH_RISK'].map((occ) => (
                <TouchableOpacity
                  key={occ}
                  style={[
                    styles.button,
                    occupation === occ && styles.buttonActive,
                    { borderColor: isDarkMode ? '#444' : '#ddd' }
                  ]}
                  onPress={() => handleOccupationChange(occ)}
                >
                  <Text style={[
                    styles.buttonText,
                    { color: isDarkMode ? '#fff' : '#000' },
                    occupation === occ && styles.buttonTextActive
                  ]}>
                    {occ.replace('_', ' ')}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
            <Text style={[styles.helperText, { color: isDarkMode ? '#888' : '#999' }]}>
              Triggers transitive dependency chain
            </Text>
          </View>

          <View style={styles.field}>
            <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
              Occupation Class (calculated)
            </Text>
            <TextInput
              style={readOnlyStyle}
              value={occupationClass || 'N/A'}
              editable={false}
            />
            <Text style={[styles.helperText, { color: isDarkMode ? '#888' : '#999' }]}>
              Depends on occupation
            </Text>
          </View>

          <View style={styles.field}>
            <Text style={[styles.label, { color: isDarkMode ? '#fff' : '#000' }]}>
              Risk Category (calculated)
            </Text>
            <TextInput
              style={readOnlyStyle}
              value={riskCategory || 'N/A'}
              editable={false}
            />
            <Text style={[styles.helperText, { color: isDarkMode ? '#888' : '#999' }]}>
              Depends on occupation class and smoker status
            </Text>
          </View>
        </View>

        {/* API Demo Box */}
        <View style={[styles.demoBox, { backgroundColor: isDarkMode ? '#1a1a1a' : '#f9fafb' }]}>
          <Text style={[styles.demoTitle, { color: isDarkMode ? '#fff' : '#000' }]}>
            🎯 API Features Demonstrated
          </Text>
          <Text style={[styles.demoText, { color: isDarkMode ? '#aaa' : '#666' }]}>
            ✅ Dot notation paths: "illustration.insured.name"{'\n'}
            ✅ getEvaluatedSchemaWithoutParams(){'\n'}
            ✅ getEvaluatedSchemaByPath() for $params access{'\n'}
            ✅ Transitive dependencies (auto-processed){'\n'}
            ✅ Clear and value dependents{'\n'}
            ✅ Real-time field calculations
          </Text>
        </View>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  description: {
    fontSize: 14,
    marginBottom: 24,
  },
  infoBox: {
    padding: 16,
    borderRadius: 8,
    marginBottom: 24,
  },
  infoTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 8,
  },
  infoText: {
    fontSize: 14,
    marginBottom: 4,
  },
  linkText: {
    fontSize: 14,
    fontWeight: '600',
    marginTop: 8,
  },
  jsonText: {
    fontSize: 12,
    fontFamily: 'monospace',
    marginTop: 8,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 16,
  },
  field: {
    marginBottom: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    marginBottom: 8,
  },
  input: {
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 16,
  },
  switchRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  buttonRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  button: {
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 6,
    borderWidth: 1,
  },
  buttonActive: {
    backgroundColor: '#3b82f6',
    borderColor: '#3b82f6',
  },
  buttonText: {
    fontSize: 12,
  },
  buttonTextActive: {
    color: '#fff',
  },
  helperText: {
    fontSize: 12,
    marginTop: 4,
    fontStyle: 'italic',
  },
  demoBox: {
    padding: 16,
    borderRadius: 8,
    marginTop: 24,
  },
  demoTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
  },
  demoText: {
    fontSize: 13,
    lineHeight: 20,
  },
});