pdf-xfa 1.2.0

XFA engine — extraction, layout rendering, font resolution. Experimental and under active development.
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
//! Sandboxed JavaScript runtime adapter for [`super::XfaJsRuntime`].
//!
//! Compiled in only when the `xfa-js-sandboxed` Cargo feature is enabled.
//! The adapter is written against [`xfa_js_sandboxed::engine::JsEngine`]; the
//! engine behind it is QuickJS compiled to WebAssembly and interpreted by
//! `wasmi`, so no native C code runs.
//!
//! - No capability-bearing globals: `fetch`, `require`, `process`, ... are
//!   removed in [`XfaJsRuntime::init`]; `Date.now` returns 0 and
//!   `Math.random` is undefined.
//! - Scripts are evaluated as strict code and reach the form only through
//!   the host functions registered in [`host_natives`].
//! - Per-script time budget: the wall-clock deadline (polled by the guest's
//!   interrupt handler) plus a fuel budget in the interpreter as a backstop;
//!   exceeding either gives [`SandboxError::Timeout`].
//! - Heap limit: QuickJS' allocation limit inside the guest, with the guest's
//!   linear memory capped just above it; hitting it gives
//!   [`SandboxError::OutOfMemory`].
//! - The engine boots on the first script, not in [`XfaJsRuntime::init`], and a
//!   finished boot is restored from a snapshot for every later runtime.
//! - Every engine call is wrapped in `std::panic::catch_unwind`.

// Copyright (c) 2026 Innovation Trigger B.V.
//
// PDFluent is available under two licences, at your option: the GNU AGPLv3, or
// the PDFluent Commercial Licence. See the LICENSE file in this repository --
// that file travels with the copy you received, which a URL does not.

use std::cell::{Cell, RefCell};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::rc::Rc;
use std::time::{Duration, Instant};

use xfa_js_sandboxed::engine::{
    Args, Boot, DefaultEngine, Fail, Guard, In, JsEngine, Limits, Native, Out, Ret,
};
use xfa_layout_engine::form::{FormNodeId, FormTree};

use super::regex_guard::{scan_script_for_redos, RegexScanVerdict};
use super::{
    activity_allowed_for_sandbox_with_gate, walltime_fallback_multiplier, HostBindings,
    RuntimeMetadata, RuntimeOutcome, SandboxError, XfaJsRuntime, DEFAULT_MEMORY_BUDGET_BYTES,
    DEFAULT_TIME_BUDGET_MS, MAX_SCRIPT_BODY_BYTES, MAX_VARIABLES_SCRIPT_BODY_BYTES,
};

/// Sandboxed runtime adapter. One instance is reusable across many
/// documents; callers MUST invoke [`XfaJsRuntime::reset_for_new_document`]
/// at the start of each flatten.
pub struct SandboxedRuntime {
    engine: RefCell<DefaultEngine>,
    metadata: RuntimeMetadata,
    time_budget: Duration,
    memory_budget_bytes: usize,
    /// Start of the currently executing script, if any.
    script_started: RefCell<Option<Instant>>,
    /// QF1-E / SEC-01 — multiplier on `time_budget` used by the wall-time
    /// fallback. Snapshotted at construction time from
    /// [`super::walltime_fallback_multiplier`] so tests can toggle the env
    /// var per-instance without racing other tests.
    walltime_fallback_multiplier: u32,
    host: Rc<RefCell<HostBindings>>,
    /// `init()` was called; the engine is booted on first use, so a form
    /// without scripts never pays for it.
    init_called: Cell<bool>,
    bindings_registered: Cell<bool>,
}

impl std::fmt::Debug for SandboxedRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SandboxedRuntime")
            .field("metadata", &self.metadata)
            .field("time_budget_ms", &self.time_budget.as_millis())
            .field("memory_budget_bytes", &self.memory_budget_bytes)
            .finish()
    }
}

fn parse_node_id_csv(raw: &str) -> Vec<FormNodeId> {
    raw.split(',')
        .filter_map(|part| part.trim().parse::<usize>().ok())
        .map(FormNodeId)
        .collect()
}

fn ids(v: Vec<FormNodeId>) -> Ret {
    Ret::Ints(v.into_iter().map(|n| n.0 as i32).collect())
}

fn node_ret(v: Option<FormNodeId>) -> Ret {
    Ret::Int(v.map(|n| n.0 as i64).unwrap_or(-1))
}

fn chain_of(csv: Option<String>) -> Vec<String> {
    csv.map(|s| s.split(',').map(|p| p.trim().to_string()).collect())
        .unwrap_or_default()
}

/// The host functions the JS binding layer (`PHASE_C_BINDINGS_JS`) calls.
/// Argument and return conventions mirror what the bindings expect: ids are
/// numbers (-1 = none), lists are arrays, a missing optional argument is
/// treated like an empty/absent value.
fn host_natives(host: &Rc<RefCell<HostBindings>>) -> Vec<(&'static str, Native)> {
    let mut v: Vec<(&'static str, Native)> = Vec::new();
    macro_rules! nat {
        ($name:literal, |$h:ident, $a:ident| $body:expr) => {{
            let hh = Rc::clone(host);
            v.push((
                $name,
                Box::new(move |$a: &Args| -> Ret {
                    let $h = &hh;
                    $body
                }),
            ));
        }};
    }

    nat!("resolveNodeId", |h, a| {
        let Some(path) = a.opt_str(0) else {
            let _ = h.borrow_mut().resolve_node("");
            return Ret::Int(-1);
        };
        node_ret(h.borrow_mut().resolve_node(&path))
    });
    nat!("resolveNodeIds", |h, a| {
        let Some(path) = a.opt_str(0) else {
            let _ = h.borrow_mut().resolve_nodes("");
            return Ret::Ints(Vec::new());
        };
        ids(h.borrow_mut().resolve_nodes(&path))
    });
    nat!("generation", |h, _a| Ret::Int(
        h.borrow().generation() as i64
    ));
    nat!("currentNodeId", |h, _a| node_ret(h.borrow().current_node()));
    nat!("resolveImplicitNodeId", |h, a| {
        let cur = a.i32(0);
        if cur < 0 {
            return Ret::Int(-1);
        }
        let Some(name) = a.opt_str(1) else {
            return Ret::Int(-1);
        };
        node_ret(
            h.borrow_mut()
                .resolve_implicit(FormNodeId(cur as usize), &name),
        )
    });
    nat!("resolveImplicitNodeIds", |h, a| {
        let cur = a.i32(0);
        let Some(name) = a.opt_str(1).filter(|_| cur >= 0) else {
            return Ret::Ints(Vec::new());
        };
        ids(h
            .borrow_mut()
            .resolve_implicit_candidates(FormNodeId(cur as usize), &name))
    });
    nat!("resolveImplicitNodeIdsQuiet", |h, a| {
        let cur = a.i32(0);
        let Some(name) = a.opt_str(1).filter(|_| cur >= 0) else {
            return Ret::Ints(Vec::new());
        };
        ids(h
            .borrow_mut()
            .resolve_implicit_candidates_quiet(FormNodeId(cur as usize), &name))
    });
    nat!("resolveChildNodeId", |h, a| {
        let parent = a.i32(0);
        if parent < 0 {
            return Ret::Int(-1);
        }
        let Some(name) = a.opt_str(1) else {
            return Ret::Int(-1);
        };
        node_ret(
            h.borrow_mut()
                .resolve_child(FormNodeId(parent as usize), &name),
        )
    });
    nat!("resolveChildNodeIds", |h, a| {
        let (Some(parents), Some(name)) = (a.opt_str(0), a.opt_str(1)) else {
            return Ret::Ints(Vec::new());
        };
        ids(h
            .borrow_mut()
            .resolve_child_candidates(&parse_node_id_csv(&parents), &name))
    });
    nat!("resolveChildNodeIdsQuiet", |h, a| {
        let (Some(parents), Some(name)) = (a.opt_str(0), a.opt_str(1)) else {
            return Ret::Ints(Vec::new());
        };
        ids(h
            .borrow_mut()
            .resolve_child_candidates_quiet(&parse_node_id_csv(&parents), &name))
    });
    nat!("resolveImplicitNodeIdsHinted", |h, a| {
        let cur = a.i32(0);
        let Some(name) = a.opt_str(1).filter(|_| cur >= 0) else {
            return Ret::Ints(Vec::new());
        };
        let hint = a.opt_str(2).unwrap_or_default();
        ids(h.borrow_mut().resolve_implicit_candidates_hinted(
            FormNodeId(cur as usize),
            &name,
            &hint,
        ))
    });
    nat!("resolveChildNodeIdsHinted", |h, a| {
        let (Some(parents), Some(name)) = (a.opt_str(0), a.opt_str(1)) else {
            return Ret::Ints(Vec::new());
        };
        let hint = a.opt_str(2).unwrap_or_default();
        ids(h.borrow_mut().resolve_child_candidates_hinted(
            &parse_node_id_csv(&parents),
            &name,
            &hint,
        ))
    });
    nat!("resolveScopedNodeIds", |h, a| {
        let (Some(scope), Some(name)) = (a.opt_str(0), a.opt_str(1)) else {
            return Ret::Ints(Vec::new());
        };
        ids(h
            .borrow_mut()
            .resolve_scoped_candidates(&parse_node_id_csv(&scope), &name))
    });
    nat!("resolveWithFullChain", |h, a| {
        let parents = a
            .opt_str(0)
            .map(|s| parse_node_id_csv(&s))
            .unwrap_or_default();
        let cur = a.i32(1);
        let chain = chain_of(a.opt_str(2));
        let origin = (cur >= 0).then(|| FormNodeId(cur as usize));
        ids(h
            .borrow_mut()
            .resolve_with_full_chain(&parents, &chain, origin))
    });
    nat!("resolveWithFullChainStrict", |h, a| {
        let parents = a
            .opt_str(0)
            .map(|s| parse_node_id_csv(&s))
            .unwrap_or_default();
        let cur = a.i32(1);
        let chain = chain_of(a.opt_str(2));
        let origin = (cur >= 0).then(|| FormNodeId(cur as usize));
        ids(h
            .borrow_mut()
            .resolve_with_full_chain_strict(&parents, &chain, origin))
    });
    nat!("getRawValue", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Undefined;
        }
        h.borrow_mut()
            .get_raw_value(FormNodeId(id as usize), g as u64)
            .into()
    });
    nat!("setRawValue", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(
            h.borrow_mut()
                .set_raw_value(FormNodeId(id as usize), a.str(2), g as u64),
        )
    });
    nat!("getPresence", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Str("visible".to_string());
        }
        Ret::Str(
            h.borrow_mut()
                .get_presence(FormNodeId(id as usize), g as u64),
        )
    });
    nat!("setPresence", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(
            h.borrow_mut()
                .set_presence(FormNodeId(id as usize), a.str(2), g as u64),
        )
    });
    nat!("isInteractive", |h, _a| Ret::Bool(h.borrow().interactive()));
    nat!("instanceCount", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(0);
        }
        h.borrow_mut()
            .instance_count_for_handle(FormNodeId(id as usize), g as u64)
            .into()
    });
    nat!("hasZeroInstanceRun", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        let Some(name) = a.opt_str(2) else {
            return Ret::Bool(false);
        };
        Ret::Bool(
            h.borrow_mut()
                .has_zero_instance_run(FormNodeId(id as usize), g as u64, &name),
        )
    });
    nat!("nodeIndex", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(0);
        }
        h.borrow_mut()
            .instance_index_for_handle(FormNodeId(id as usize), g as u64)
            .into()
    });
    nat!("nodeName", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Str(String::new());
        }
        Ret::Str(
            h.borrow()
                .node_name(FormNodeId(id as usize), g as u64)
                .unwrap_or_default(),
        )
    });
    nat!("occurResolve", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(
            h.borrow_mut()
                .occur_resolve(FormNodeId(id as usize), g as u64),
        )
    });
    nat!("occurRead", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(-1);
        }
        Ret::Int(
            h.borrow_mut()
                .occur_read(FormNodeId(id as usize), g as u64, &a.str(2)),
        )
    });
    nat!("occurCapture", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(h.borrow_mut().occur_capture(
            FormNodeId(id as usize),
            g as u64,
            &a.str(2),
            a.i64(3),
        ))
    });
    nat!("nodeIsContainer", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(
            h.borrow_mut()
                .node_is_container(FormNodeId(id as usize), g as u64),
        )
    });
    nat!("parentOfNode", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(-1);
        }
        node_ret(
            h.borrow_mut()
                .parent_of_node(FormNodeId(id as usize), g as u64),
        )
    });
    nat!("instanceSet", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(-1);
        }
        let n = a.opt_i32(2).unwrap_or(0).max(0) as u32;
        Ret::Int(
            h.borrow_mut()
                .instance_set_for_handle(FormNodeId(id as usize), g as u64, n)
                .map(|c| c as i64)
                .unwrap_or(-1),
        )
    });
    nat!("instanceAdd", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(-1);
        }
        node_ret(
            h.borrow_mut()
                .instance_add_for_handle(FormNodeId(id as usize), g as u64)
                .ok(),
        )
    });
    nat!("instanceRemove", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        let index = a.opt_i32(2).unwrap_or(0).max(0) as u32;
        Ret::Bool(
            h.borrow_mut()
                .instance_remove_for_handle(FormNodeId(id as usize), g as u64, index)
                .is_ok(),
        )
    });
    nat!("listClear", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(
            h.borrow_mut()
                .list_clear_for_handle(FormNodeId(id as usize), g as u64)
                .is_ok(),
        )
    });
    nat!("listAdd", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Bool(false);
        }
        Ret::Bool(
            h.borrow_mut()
                .list_add_for_handle(FormNodeId(id as usize), g as u64, a.str(2), a.opt_str(3))
                .is_ok(),
        )
    });
    nat!("boundItem", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Str(a.str(2));
        }
        Ret::Str(
            h.borrow_mut()
                .bound_item_for_handle(FormNodeId(id as usize), g as u64, a.str(2)),
        )
    });
    nat!("getDisplayItems", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Strs(Vec::new());
        }
        Ret::Strs(
            h.borrow_mut()
                .get_display_items(FormNodeId(id as usize), g as u64),
        )
    });
    nat!("numPages", |h, _a| h.borrow_mut().num_pages().into());
    nat!("bindingError", |h, _a| {
        h.borrow_mut().metadata_binding_error();
        Ret::Undefined
    });
    nat!("resolveFailure", |h, _a| {
        h.borrow_mut().metadata_resolve_failure();
        Ret::Undefined
    });
    nat!("somDataRootHit", |h, _a| {
        h.borrow_mut().metadata_som_data_root_hit();
        Ret::Undefined
    });
    nat!("somItemsPathHit", |h, _a| {
        h.borrow_mut().metadata_som_items_path_hit();
        Ret::Undefined
    });
    nat!("unsupportedHostCall", |h, _a| {
        h.borrow_mut().metadata_unsupported_host_call();
        Ret::Undefined
    });
    nat!("probeSkip", |h, _a| {
        h.borrow_mut().metadata_probe_skip();
        Ret::Undefined
    });
    nat!("dataChildren", |h, a| {
        let raw = a.i32(0);
        if raw < 0 {
            return Ret::Ints(Vec::new());
        }
        Ret::Ints(
            h.borrow_mut()
                .data_children(raw as usize)
                .into_iter()
                .map(|x| x as i32)
                .collect(),
        )
    });
    nat!("dataValue", |h, a| {
        let raw = a.i32(0);
        if raw < 0 {
            return Ret::Undefined;
        }
        h.borrow_mut().data_value(raw as usize).into()
    });
    nat!("dataChildByName", |h, a| {
        let parent = a.i32(0);
        if parent < 0 {
            return Ret::Int(-1);
        }
        let Some(name) = a.opt_str(1) else {
            return Ret::Int(-1);
        };
        Ret::Int(
            h.borrow_mut()
                .data_child_by_name(parent as usize, &name)
                .map(|x| x as i64)
                .unwrap_or(-1),
        )
    });
    nat!("dataBoundRecord", |h, a| {
        let (id, g) = (a.i32(0), a.i64(1));
        if id < 0 || g < 0 {
            return Ret::Int(-1);
        }
        Ret::Int(
            h.borrow_mut()
                .data_bound_record(FormNodeId(id as usize), g as u64)
                .map(|x| x as i64)
                .unwrap_or(-1),
        )
    });
    nat!("dataResolveNode", |h, a| {
        let Some(path) = a.opt_str(0) else {
            return Ret::Int(-1);
        };
        Ret::Int(
            h.borrow_mut()
                .data_resolve_node(&path)
                .map(|x| x as i64)
                .unwrap_or(-1),
        )
    });
    nat!("isDeclaredAbsentNode", |h, a| {
        let Some(name) = a.opt_str(0) else {
            return Ret::Bool(false);
        };
        Ret::Bool(h.borrow().is_declared_absent_node(&name))
    });
    nat!("dataResolveNodes", |h, a| {
        let Some(path) = a.opt_str(0) else {
            return Ret::Ints(Vec::new());
        };
        Ret::Ints(
            h.borrow_mut()
                .data_resolve_nodes(&path)
                .into_iter()
                .map(|x| x as i32)
                .collect(),
        )
    });
    v
}

/// Script that builds the binding layer from the host functions (installed
/// as `__xfa_host`), publishes `xfa`/`app`/`form` as globals and returns the
/// bridge object (kept by the engine; never visible to scripts).
fn bridge_script() -> String {
    format!(
        "(function(){{\n var b = ({factory})(globalThis.__xfa_host);\n \
         delete globalThis.__xfa_host;\n \
         globalThis.xfa = b.xfa; globalThis.app = b.app; globalThis.form = b.form;\n \
         return b;\n}})()",
        factory = PHASE_C_BINDINGS_JS
    )
}

/// Removes capability-bearing globals and replaces the non-deterministic
/// ones (defence in depth; the engines do not provide most of them).
const HARDEN_JS: &str = r#"(function(){
  ["fetch","XMLHttpRequest","WebSocket","process","require","Deno","Bun"]
    .forEach(function(k){ globalThis[k] = undefined; });
  Date.now = function(){ return 0; };
  Math.random = undefined;
})()"#;

impl SandboxedRuntime {
    /// Construct a new sandboxed runtime with default budgets.
    pub fn new() -> Result<Self, SandboxError> {
        let engine = DefaultEngine::new(&Limits {
            memory_bytes: DEFAULT_MEMORY_BUDGET_BYTES,
            time_budget: Duration::from_millis(DEFAULT_TIME_BUDGET_MS),
        })
        .map_err(|e| SandboxError::ScriptError(format!("js engine init: {e}")))?;
        Ok(Self {
            engine: RefCell::new(engine),
            metadata: RuntimeMetadata::default(),
            time_budget: Duration::from_millis(DEFAULT_TIME_BUDGET_MS),
            memory_budget_bytes: DEFAULT_MEMORY_BUDGET_BYTES,
            script_started: RefCell::new(None),
            walltime_fallback_multiplier: walltime_fallback_multiplier(),
            host: Rc::new(RefCell::new(HostBindings::new())),
            init_called: Cell::new(false),
            bindings_registered: Cell::new(false),
        })
    }

    /// Override the per-script wall-clock budget. Must be called before any
    /// `execute_script` invocation; takes effect on the next call.
    pub fn with_time_budget(mut self, budget: Duration) -> Self {
        self.time_budget = budget;
        self.engine.get_mut().set_time_budget(budget);
        self
    }

    /// Override the per-document memory budget. Must be called before any
    /// `execute_script` invocation; takes effect on the next document.
    pub fn with_memory_budget(mut self, bytes: usize) -> Self {
        self.memory_budget_bytes = bytes;
        self.engine.get_mut().set_memory_limit(bytes);
        self
    }

    /// QF1-E / SEC-01 — override the wall-time fallback multiplier. The
    /// default is read from
    /// [`super::ENV_WALLTIME_FALLBACK_MULTIPLIER`] / falls back to
    /// [`super::WALLTIME_FALLBACK_MULTIPLIER_DEFAULT`]. Values below `2`
    /// are clamped to `2` so a clean timeout cannot be re-labelled as
    /// `WallTimeExceeded` by accident. Tests use this to deterministically
    /// pin the multiplier without racing the process-global env var.
    pub fn with_walltime_fallback_multiplier(mut self, multiplier: u32) -> Self {
        self.walltime_fallback_multiplier = multiplier.max(2);
        self
    }

    /// Arm the wall-clock deadline for the next evaluation.
    fn set_deadline(&self) {
        let now = Instant::now();
        *self.script_started.borrow_mut() = Some(now);
        self.engine.borrow_mut().set_guard(Guard {
            deadline: Some(now + self.time_budget),
            cancel: None,
        });
    }

    fn clear_deadline(&self) {
        self.engine.borrow_mut().set_guard(Guard::default());
    }

    /// True when the running script has been going longer than its budget.
    fn deadline_elapsed(&self) -> bool {
        self.script_started
            .borrow()
            .is_some_and(|s| s.elapsed() >= self.time_budget)
    }

    /// QF1-E / SEC-01 — classify a timeout-shaped error as either the
    /// primary [`SandboxError::Timeout`] (stopped within multiplier ×
    /// budget) or the defence-in-depth [`SandboxError::WallTimeExceeded`]
    /// (elapsed ≥ multiplier × budget at classification time). The latter
    /// only appears when the engine was trapped in work it cannot interrupt.
    fn classify_timeout_or_walltime(&self) -> SandboxError {
        let Some(start) = *self.script_started.borrow() else {
            return SandboxError::Timeout;
        };
        let elapsed = start.elapsed();
        let threshold = self
            .time_budget
            .saturating_mul(self.walltime_fallback_multiplier);
        if elapsed >= threshold {
            SandboxError::WallTimeExceeded(format!(
                "{} ms ≥ {mult}× budget ({budget_ms} ms)",
                elapsed.as_millis(),
                mult = self.walltime_fallback_multiplier,
                budget_ms = self.time_budget.as_millis()
            ))
        } else {
            SandboxError::Timeout
        }
    }

    /// The document-independent setup: harden the globals, install the host
    /// functions, build the binding layer. One `boot` call, so an engine that
    /// can snapshot restores the finished state instead of re-running it.
    fn boot_engine(&self) -> Result<(), String> {
        if self.bindings_registered.get() {
            return Ok(());
        }
        let natives = host_natives(&self.host);
        let bridge = bridge_script();
        self.engine
            .borrow_mut()
            .boot(vec![
                Boot::Eval(HARDEN_JS),
                Boot::Install("__xfa_host", natives),
                Boot::EvalKeep(&bridge, "bridge"),
            ])
            .map_err(|f| format!("binding factory: {f}"))?;
        self.bindings_registered.set(true);
        Ok(())
    }

    /// Phase D-ι: extract top-level `var X` and `function X(` identifiers
    /// from a `<variables>` `<script>` body. Used to build the wrapper
    /// IIFE that returns the form-level global object. Best-effort regex
    /// scan — handles the common XFA authoring patterns; complex
    /// destructuring would be missed and the corresponding identifier
    /// would simply not appear in the namespace object.
    fn extract_top_level_idents(body: &str) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        // Strip line and block comments to avoid extracting commented-out idents.
        let stripped = strip_js_comments(body);
        for token_kind in [
            ("var", false),
            ("let", false),
            ("const", false),
            ("function", true),
        ] {
            let kw = token_kind.0;
            let is_fn = token_kind.1;
            let mut search = stripped.as_str();
            while let Some(idx) = search.find(kw) {
                let (before, after) = search.split_at(idx);
                let head_ok = before
                    .chars()
                    .last()
                    .is_none_or(|c| !c.is_alphanumeric() && c != '_' && c != '$');
                let tail_after_kw = &after[kw.len()..];
                let tail_ok = tail_after_kw
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_whitespace());
                if !(head_ok && tail_ok) {
                    search = &after[1..];
                    continue;
                }
                // Skip whitespace, then read an identifier.
                let after_ws = tail_after_kw.trim_start();
                let mut chars = after_ws.chars();
                let ident: String = std::iter::once(chars.next())
                    .chain(chars.map(Some))
                    .map_while(|c| c.filter(|c| c.is_alphanumeric() || *c == '_' || *c == '$'))
                    .collect();
                if ident.is_empty() || ident.chars().next().is_some_and(|c| c.is_ascii_digit()) {
                    search = &after[kw.len()..];
                    continue;
                }
                if is_fn {
                    let after_ident = after_ws
                        .trim_start_matches(|c: char| c.is_alphanumeric() || c == '_' || c == '$');
                    if !after_ident.trim_start().starts_with('(') {
                        search = &after[kw.len()..];
                        continue;
                    }
                }
                if seen.insert(ident.clone()) {
                    out.push(ident);
                }
                search = &after[kw.len()..];
            }
        }
        out
    }

    /// Phase D-ι: register a `<variables>` `<script name="name">` block
    /// as a form-level global. Called by the dispatch layer after
    /// `set_form_handle` so subsequent event/calculate scripts see the
    /// namespace.
    ///
    /// Variables-script bodies are evaluated through the same engine as
    /// event scripts, so they MUST run under the same per-script time
    /// budget and the same body-size cap. Returns `Ok(true)` when the
    /// JS-side `setVariablesScript` bound the namespace, `Ok(false)` when it
    /// returned `false` (eval failure caught JS-side), or `Err` on a
    /// Rust-side skip (cap / REDOS / timeout / panic).
    fn register_variables_script(
        &self,
        name: &str,
        body: &str,
        subform_scope: Option<&str>,
        expose_global: bool,
    ) -> Result<bool, SandboxError> {
        if self.bindings_registered_check().is_err() {
            return Ok(false);
        }
        // W2-B: variables-scripts use a higher body-size cap than event
        // scripts because they are form-level helper libraries (XFA 3.3
        // §5.5); real government forms ship 100-500 KB libraries.
        if body.len() > MAX_VARIABLES_SCRIPT_BODY_BYTES {
            return Err(SandboxError::BodyTooLarge);
        }
        // W3-A — REDOS-01 mitigation also gates variables-scripts.
        if let RegexScanVerdict::Reject { reason } = scan_script_for_redos(body) {
            return Err(SandboxError::RegexRejected(reason));
        }
        let idents = Self::extract_top_level_idents(body);
        let scope = subform_scope.unwrap_or("").to_string();
        self.set_deadline();
        let result = catch_unwind(AssertUnwindSafe(|| {
            self.engine.borrow_mut().call_kept(
                "bridge",
                "setVariablesScript",
                vec![
                    In::Str(name.to_string()),
                    In::Str(body.to_string()),
                    In::Strs(idents),
                    In::Str(scope),
                    In::Bool(expose_global),
                ],
            )
        }));
        let timed_out = self.deadline_elapsed();
        let classified = self.classify_timeout_or_walltime();
        self.clear_deadline();
        match result {
            Ok(Ok(Out::Bool(ok))) => Ok(ok),
            Ok(Ok(_)) => Ok(false),
            Ok(Err(Fail::Limit(_))) => Err(classified),
            Ok(Err(_)) if timed_out => Err(classified),
            Ok(Err(e)) => Err(SandboxError::ScriptError(format!(
                "variables-script `{name}` register: {e:?}"
            ))),
            Err(_) => Err(SandboxError::PanicCaptured(format!(
                "panic registering variables-script `{name}`"
            ))),
        }
    }

    /// Boot the engine if `init()` asked for it and it has not happened yet.
    /// `Err` when `init()` was never called or the boot failed.
    fn bindings_registered_check(&self) -> Result<(), ()> {
        if self.bindings_registered.get() {
            return Ok(());
        }
        if !self.init_called.get() {
            return Err(());
        }
        self.boot_engine().map_err(|e| {
            log::debug!("script engine boot failed: {e}");
        })
    }

    /// W3-D RETRY: register one `<variables><text name="X">value</text>`
    /// data item (XFA 3.3 §5.5.2) as a form-level mutable string container.
    /// Sister of [`Self::register_variables_script`] but with no body cap,
    /// no REDOS scan, and no time budget — data items carry text payloads,
    /// not JavaScript code. Idempotent per `(subform_scope, name)`.
    fn register_variables_data_item(
        &self,
        name: &str,
        initial: &str,
        subform_scope: Option<&str>,
    ) -> Result<(), SandboxError> {
        if self.bindings_registered_check().is_err() {
            return Ok(());
        }
        let result = catch_unwind(AssertUnwindSafe(|| {
            self.engine.borrow_mut().call_kept(
                "bridge",
                "setVariablesDataItem",
                vec![
                    In::Str(name.to_string()),
                    In::Str(initial.to_string()),
                    In::Str(subform_scope.unwrap_or("").to_string()),
                ],
            )
        }));
        match result {
            Ok(Ok(_)) => Ok(()),
            Ok(Err(e)) => Err(SandboxError::ScriptError(format!(
                "variables data item `{name}` register: {e:?}"
            ))),
            Err(_) => Err(SandboxError::PanicCaptured(format!(
                "panic registering variables data item `{name}`"
            ))),
        }
    }

    fn clear_variables_scripts_global(&self) -> Result<(), SandboxError> {
        // Nothing to clear in an engine that was never booted.
        if !self.bindings_registered.get() {
            return Ok(());
        }
        let result = catch_unwind(AssertUnwindSafe(|| {
            self.engine
                .borrow_mut()
                .call_kept("bridge", "clearVariablesScripts", vec![])
        }));
        match result {
            Ok(Ok(_)) => Ok(()),
            Ok(Err(e)) => Err(SandboxError::ScriptError(format!(
                "variables-script clear: {e:?}"
            ))),
            Err(_) => Err(SandboxError::PanicCaptured(
                "panic clearing variables-scripts".to_string(),
            )),
        }
    }
}

/// Phase D-ι: strip `//` and `/* */` comments from a JS source body so
/// the regex scan for top-level `var` / `function` declarations does not
/// match commented-out tokens. Conservative — preserves strings (so a
/// `"//"` substring inside a string literal is left alone). XFA scripts
/// almost never have comments inside string literals, but the guard
/// matters for correctness.
fn strip_js_comments(src: &str) -> String {
    let mut out = String::with_capacity(src.len());
    let bytes = src.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b == b'"' || b == b'\'' {
            // Copy string literal verbatim.
            let quote = b;
            out.push(b as char);
            i += 1;
            while i < bytes.len() {
                let c = bytes[i];
                out.push(c as char);
                if c == b'\\' && i + 1 < bytes.len() {
                    out.push(bytes[i + 1] as char);
                    i += 2;
                    continue;
                }
                i += 1;
                if c == quote {
                    break;
                }
            }
            continue;
        }
        if b == b'/' && i + 1 < bytes.len() {
            let n = bytes[i + 1];
            if n == b'/' {
                // Line comment.
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
                continue;
            }
            if n == b'*' {
                // Block comment.
                i += 2;
                while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                    i += 1;
                }
                i = (i + 2).min(bytes.len());
                continue;
            }
        }
        out.push(b as char);
        i += 1;
    }
    out
}

const PHASE_C_BINDINGS_JS: &str = r##"
(function(host) {
  function protoGuard() {
    return Object.freeze(Object.create(null));
  }

  function nullProtoObject() {
    var obj = Object.create(null);
    Object.defineProperty(obj, "__proto__", {
      value: protoGuard(),
      enumerable: false,
      configurable: false,
      writable: false
    });
    return obj;
  }

  function lookupObject() {
    return Object.create(null);
  }

  var deferredGlobalNames = lookupObject();
  [
    "app", "arguments", "Array", "Boolean", "Bun", "console", "Date",
    "decodeURI", "decodeURIComponent", "Deno", "encodeURI",
    "encodeURIComponent", "Error", "eval", "EvalError", "fetch",
    "Function", "globalThis", "Infinity", "isFinite", "isNaN", "JSON",
    "Map", "Math", "NaN", "Number", "Object", "parseFloat", "parseInt",
    "process", "RangeError", "ReferenceError", "RegExp", "require",
    "Set", "String", "Symbol", "SyntaxError", "TypeError", "undefined",
    "URIError", "WeakMap", "WeakSet", "WebSocket", "XMLHttpRequest",
    // JS2-01 (Sprint 2 Batch B): `form` is a top-level alias of `xfa.form`.
    // It must defer to globalThis so the host SOM resolver does not first
    // try to resolve `form` as a form-tree node, find nothing, and then
    // surface a `js_resolve_failure` for what is really a viewer global.
    "xfa", "event", "form"
  ].forEach(function(name) {
    deferredGlobalNames[name] = true;
  });

  var reservedHandleProperties = lookupObject();
  [
    "__defineGetter__", "__defineSetter__", "__lookupGetter__",
    "__lookupSetter__", "__proto__", "constructor", "hasOwnProperty",
    "isPrototypeOf", "propertyIsEnumerable", "then", "toJSON",
    "toLocaleString", "toString", "valueOf"
  ].forEach(function(name) {
    reservedHandleProperties[name] = true;
  });

  function shouldDeferGlobalName(name, localNames) {
    return name.charAt(0) === "_" ||
      localNames[name] === true ||
      deferredGlobalNames[name] === true;
  }

  // Properties that must NOT be deferred so their specific implementations run.
  var handlePropertyExclusions = lookupObject();
  ["rawValue", "somExpression", "isNull", "clearItems", "addItem", "boundItem",
   "$record", "nodes", "value", "length", "item", "choiceList", "#items"].forEach(function(name) {
    handlePropertyExclusions[name] = true;
  });

  function shouldDeferHandleProperty(name) {
    if (handlePropertyExclusions[name] === true) {
      return false;
    }
    return name.charAt(0) === "_" || reservedHandleProperties[name] === true;
  }

  function collectLocalNames(body) {
    var locals = lookupObject();
    var match;
    var decls = /\b(?:var|let|const)\s+([^;]+)/g;
    while ((match = decls.exec(body)) !== null) {
      match[1].split(",").forEach(function(part) {
        var ident = /^\s*([A-Za-z_$][0-9A-Za-z_$]*)/.exec(part);
        if (ident) {
          locals[ident[1]] = true;
        }
      });
    }
    var funcs = /\bfunction\s+([A-Za-z_$][0-9A-Za-z_$]*)/g;
    while ((match = funcs.exec(body)) !== null) {
      locals[match[1]] = true;
    }
    return locals;
  }

  // XFA-DATA-M3C: `<handle>.ui` returns the ui-config sub-object that
  // Adobe templates expose for choiceList / textEdit / checkButton widget
  // tweaking. During static flatten the widget tree is not materialised, so
  // we hand back a minimal stub whose `choiceList` is an empty frozen
  // array (matching the bare `handle.choiceList` fallback). Property
  // writes are absorbed silently so scripts like
  // `field.ui.choiceList.commitOn = "exit"` complete without TypeError.
  function makeUiStub() {
    var stub = nullProtoObject();
    Object.defineProperty(stub, "choiceList", {
      enumerable: true,
      configurable: false,
      get: function() { return Object.freeze([]); }
    });
    Object.defineProperty(stub, "textEdit", {
      enumerable: true,
      configurable: false,
      get: function() { return Object.freeze({}); }
    });
    Object.defineProperty(stub, "checkButton", {
      enumerable: true,
      configurable: false,
      get: function() { return Object.freeze({}); }
    });
    return new Proxy(stub, {
      get: function(target, prop) {
        if (typeof prop !== "string") return undefined;
        if (prop in target) return target[prop];
        // Sub-property writes / reads are absorbed: scripts walking
        // unknown widget config (e.g. `ui.imageEdit.<x>`) get a chainable
        // viewer-stub rather than crashing on undefined.
        return makeViewerStub();
      },
      set: function(_t, _p, _v) { return true; },
      has: function(_t, _p) { return true; }
    });
  }

  // D5: minimal `node.occur` handle. Reads `min`/`max`/`initial` from the
  // structural template (host.occurRead; -1 = unlimited/unknown). Writes to
  // `min`/`max` are CAPTURED (host.occurCapture) as mutation intent and then
  // discarded — no layout/pagination effect in D5. This stops
  // `subform.occur.min = N` from throwing `cannot set property 'min' of
  // undefined` so the script proceeds; the captured intent is for the next
  // milestone's bounded apply path.
  function makeOccurHandle(id, generation) {
    var occ = nullProtoObject();
    function defineOccurProp(name) {
      Object.defineProperty(occ, name, {
        enumerable: true,
        configurable: false,
        get: function() {
          return host.occurRead(id, generation, name);
        },
        set: function(value) {
          var n = (typeof value === "number") ? value : parseInt(value, 10);
          if (isNaN(n)) { n = 0; }
          host.occurCapture(id, generation, name, n);
        }
      });
    }
    defineOccurProp("min");
    defineOccurProp("max");
    defineOccurProp("initial");
    return occ;
  }

  function makeInstanceManager(id, generation) {
    var manager = nullProtoObject();
    Object.defineProperty(manager, "count", {
      enumerable: true,
      configurable: false,
      get: function() {
        return host.instanceCount(id, generation);
      }
    });
    Object.defineProperty(manager, "setInstances", {
      enumerable: true,
      configurable: false,
      writable: false,
      value: function(n) {
        return host.instanceSet(id, generation, n);
      }
    });
    Object.defineProperty(manager, "addInstance", {
      enumerable: true,
      configurable: false,
      writable: false,
      value: function() {
        var newId = host.instanceAdd(id, generation);
        return newId < 0 ? null : makeHandle(newId, generation);
      }
    });
    Object.defineProperty(manager, "removeInstance", {
      enumerable: true,
      configurable: false,
      writable: false,
      value: function(idx) {
        return host.instanceRemove(id, generation, idx);
      }
    });
    return Object.freeze(manager);
  }

  function makeEmptyInstanceManager() {
    var manager = nullProtoObject();
    Object.defineProperty(manager, "count", {
      enumerable: true,
      configurable: false,
      value: 0
    });
    Object.defineProperty(manager, "setInstances", {
      enumerable: true,
      configurable: false,
      writable: false,
      value: function() { return 0; }
    });
    Object.defineProperty(manager, "addInstance", {
      enumerable: true,
      configurable: false,
      writable: false,
      value: function() { return null; }
    });
    Object.defineProperty(manager, "removeInstance", {
      enumerable: true,
      configurable: false,
      writable: false,
      value: function() { return false; }
    });
    return Object.freeze(manager);
  }

  function uniqueNodeIds(ids) {
    var out = [];
    if (!ids) return out;
    for (var i = 0; i < ids.length; i++) {
      var id = ids[i] | 0;
      if (id < 0) continue;
      var seen = false;
      for (var j = 0; j < out.length; j++) {
        if (out[j] === id) {
          seen = true;
          break;
        }
      }
      if (!seen) out.push(id);
    }
    return out;
  }

  function nodeIdListArg(ids) {
    return uniqueNodeIds(ids).join(",");
  }

  function resolveHandleChildIds(ids, prop) {
    var list = nodeIdListArg(ids);
    if (list.length === 0) return [];
    var childIds = uniqueNodeIds(host.resolveChildNodeIds(list, prop));
    if (childIds.length > 0) return childIds;
    return uniqueNodeIds(host.resolveScopedNodeIds(list, prop));
  }

  function makeNodeHandleFromIds(ids, generation) {
    var unique = uniqueNodeIds(ids);
    if (unique.length === 0) return undefined;
    if (unique.length === 1) return makeHandle(unique[0], generation);
    return makeCandidateSet(unique, generation);
  }

  // Phase D-θ: single-segment SOM lookahead. The proxy chain `F.P1.X.rawValue`
  // can resolve the leading `F.P1` correctly yet pick the wrong `P1` when
  // multiple same-named siblings exist — the resolver lacks the next-segment
  // context needed to disambiguate. These helpers return a one-step deferred
  // wrapper that, on its next property access, asks the host's hinted
  // resolver to drop candidates whose subtree does not contain the lookahead
  // name. Terminal properties (rawValue, instanceManager, …) bypass the hint
  // path entirely so single-token reads remain byte-for-byte identical.
  function isTerminalHandleProp(name) {
    if (handlePropertyExclusions[name] === true) return true;
    if (reservedHandleProperties[name] === true) return true;
    if (name.charAt(0) === "_") return true;
    switch (name) {
      case "rawValue":
      case "somExpression":
      case "instanceManager":
      case "index":
      case "setInstances":
      case "addInstance":
      case "removeInstance":
      case "isNull":
      case "clearItems":
      case "addItem":
      case "boundItem":
      case "#items":
      case "$record":
      case "variables":
      case "nodes":
      case "length":
      case "value":
      case "item":
        return true;
      default:
        return false;
    }
  }

  function makeImplicitDeferred(currentId, name, eagerIds, generation) {
    function realize(hint) {
      if (!hint) return eagerIds;
      var refined = uniqueNodeIds(host.resolveImplicitNodeIdsHinted(currentId, name, hint));
      return refined.length > 0 ? refined : eagerIds;
    }
    var sentinel = nullProtoObject();
    return new Proxy(sentinel, {
      get: function(target, prop, receiver) {
        if (typeof prop !== "string") {
          return Reflect.get(target, prop, receiver);
        }
        // XFA-DATA2-02: short-circuit caption / resolveNode pair before any
        // host call. See captionSentinel + handleResolveNode definitions.
        if (prop === "caption") { return captionSentinel; }
        if (prop === "resolveNode") { return handleResolveNode; }
        if (prop === "resolveNodes") { return handleResolveNodes; }
        var ids = isTerminalHandleProp(prop) ? eagerIds : realize(prop);
        var handle = makeNodeHandleFromIds(ids, generation);
        if (handle === undefined) return undefined;
        return handle[prop];
      },
      set: function(_target, prop, value) {
        var handle = makeNodeHandleFromIds(eagerIds, generation);
        if (handle === undefined) return true;
        handle[prop] = value;
        return true;
      },
      has: function(_target, prop) {
        if (typeof prop !== "string") return Reflect.has(sentinel, prop);
        return true;
      }
    });
  }

  function makeChildDeferred(parentIds, childName, eagerChildIds, generation) {
    var parentList = nodeIdListArg(parentIds);
    function realize(hint) {
      if (!hint || parentList.length === 0) return eagerChildIds;
      var refined = uniqueNodeIds(host.resolveChildNodeIdsHinted(parentList, childName, hint));
      return refined.length > 0 ? refined : eagerChildIds;
    }
    var sentinel = nullProtoObject();
    return new Proxy(sentinel, {
      get: function(target, prop, receiver) {
        if (typeof prop !== "string") {
          return Reflect.get(target, prop, receiver);
        }
        // XFA-DATA2-02: short-circuit caption / resolveNode pair before any
        // host call. See captionSentinel + handleResolveNode definitions.
        if (prop === "caption") { return captionSentinel; }
        if (prop === "resolveNode") { return handleResolveNode; }
        if (prop === "resolveNodes") { return handleResolveNodes; }
        var ids = isTerminalHandleProp(prop) ? eagerChildIds : realize(prop);
        var handle = makeNodeHandleFromIds(ids, generation);
        if (handle === undefined) return undefined;
        return handle[prop];
      },
      set: function(_target, prop, value) {
        var handle = makeNodeHandleFromIds(eagerChildIds, generation);
        if (handle === undefined) return true;
        handle[prop] = value;
        return true;
      },
      has: function(_target, prop) {
        if (typeof prop !== "string") return Reflect.has(sentinel, prop);
        return true;
      }
    });
  }

  function makeChainHandle(parentIds, childName, generation) {
    var eagerChildIds = resolveHandleChildIds(parentIds, childName);
    if (eagerChildIds.length === 0) return undefined;
    if (eagerChildIds.length === 1) {
      // Singleton child with a single parent leaves the host resolver no
      // alternatives to filter even when a hint is provided — same-name
      // sibling disambiguation is impossible. Skip the wrapper so the
      // common path keeps its original Proxy identity and resolve budget.
      return makeHandle(eagerChildIds[0], generation);
    }
    // Phase D-θ.2: same-name siblings exist; defer through the full-chain
    // accumulator so a deeper segment (still unread) can disambiguate.
    return makeChainProxy(parentIds, [childName], eagerChildIds, generation, -1);
  }

  // Phase D-θ.2: lazy chain proxy. Accumulates a SOM chain (string[]) as the
  // script walks property access; on the first terminal property read it
  // asks the host to resolve the FULL accumulated chain in one call,
  // letting the host backtrack and pick the same-name candidate at any
  // depth whose subtree actually completes the chain.
  //
  // Compared to D-θ.1 (single-segment hint), this lets `A.B.C.D.rawValue`
  // pick the correct same-name `A` not only when one is the parent of `B`
  // but specifically the one whose subtree contains the full B.C.D chain.
  //
  // Parameters:
  //   parentIds            — entry parent set; empty array means implicit walk.
  //   chain                — string[] of segments accumulated so far (>=1).
  //   eagerIds             — fallback ids returned if the host's full-chain
  //                          resolve produces no candidate at any depth
  //                          (preserves D-θ.1 byte-for-byte behaviour for
  //                          chains the host cannot improve on).
  //   generation           — handle generation to bind to.
  //   currentId            — implicit-walk anchor (used when parentIds is empty).
  //
  // Terminal property names trigger immediate resolution. Non-terminal
  // string property names return a NEW chain proxy with the property name
  // appended; no host call happens at that point.
  function makeChainProxy(parentIds, chain, eagerIds, generation, currentId) {
    var sentinel = nullProtoObject();
    function fullChain(extraSeg) {
      var parentCsv = nodeIdListArg(parentIds);
      var chainArr = chain;
      if (extraSeg !== undefined) {
        chainArr = chain.slice();
        chainArr.push(extraSeg);
      }
      var chainCsv = chainArr.join(",");
      var resolved = uniqueNodeIds(
        host.resolveWithFullChain(parentCsv, currentId | 0, chainCsv)
      );
      if (resolved.length === 0) return eagerIds;
      return resolved;
    }
    return new Proxy(sentinel, {
      get: function(target, prop, receiver) {
        if (typeof prop !== "string") {
          // Symbol.toPrimitive and similar non-string keys must force
          // terminal resolution so coercion (e.g. via Number(handle)) sees
          // the resolved candidate's primitive view rather than the proxy
          // sentinel itself.
          var primIds = fullChain();
          var primHandle = makeNodeHandleFromIds(primIds, generation);
          if (primHandle === undefined) {
            return Reflect.get(target, prop, receiver);
          }
          return primHandle[prop];
        }
        // XFA-DATA2-02: caption / resolveNode / resolveNodes short-circuit on
        // the chain proxy. Without this branch the chain accumulator would
        // append "caption" as a non-terminal segment, call
        // resolveWithFullChainStrict, miss, and return `undefined` —
        // `field.caption.value` then TypeErrors. Same null/empty-list
        // contract as the global pair.
        if (prop === "caption") {
          return captionSentinel;
        }
        if (prop === "resolveNode") {
          return handleResolveNode;
        }
        if (prop === "resolveNodes") {
          return handleResolveNodes;
        }
        if (isTerminalHandleProp(prop)) {
          var ids = fullChain();
          var handle = makeNodeHandleFromIds(ids, generation);
          if (handle === undefined) return undefined;
          return handle[prop];
        }
        // Non-terminal: probe the extended chain in STRICT mode. If the
        // host cannot complete `[chain..., prop]` at full depth anywhere
        // in the form, return `undefined` — mirroring the eager D-θ.1
        // behaviour where `A.B` resolved to `undefined` when no `A.B`
        // existed. When the probe succeeds, return a new chain proxy
        // with the segment appended; the lazy accumulation lets a
        // deeper segment still disambiguate which same-name `A` to keep.
        //
        // D-θ.2 probe-skip: when there is exactly one parent and the chain
        // so far has exactly one segment, no same-name sibling ambiguity is
        // possible — the parent uniquely identifies the node, and there are
        // no alternative subtrees for the host to choose between.  In that
        // case the strict probe would always return the same set as eagerIds,
        // so we skip the host round-trip and immediately build the next proxy
        // using eagerIds as the fallback.  The host-call budget is preserved
        // and disambiguation is unaffected because a single-parent / single-
        // segment chain cannot be disambiguated further by the host anyway.
        var nextChain = chain.slice();
        nextChain.push(prop);
        if (parentIds.length === 1 && chain.length === 1) {
          host.probeSkip();
          return makeChainProxy(parentIds, nextChain, eagerIds, generation, currentId);
        }
        var probe = host.resolveWithFullChainStrict(
          nodeIdListArg(parentIds),
          currentId | 0,
          nextChain.join(",")
        );
        if (!probe || probe.length === 0) {
          return undefined;
        }
        // The probe result becomes the new eager-fallback so future
        // probes that the host cannot improve on still degrade
        // gracefully. We must NOT collapse to a single makeHandle here:
        // the chain may continue to grow and disambiguate further.
        var nextEager = uniqueNodeIds(probe);
        return makeChainProxy(parentIds, nextChain, nextEager, generation, currentId);
      },
      set: function(_target, prop, value) {
        // Writes are always terminal: resolve the full chain and forward.
        var ids = fullChain();
        var handle = makeNodeHandleFromIds(ids, generation);
        if (handle === undefined) return true;
        handle[prop] = value;
        return true;
      },
      has: function(_target, prop) {
        if (typeof prop !== "string") return Reflect.has(sentinel, prop);
        return true;
      }
    });
  }

  function makeCandidateSet(ids, generation) {
    var candidates = uniqueNodeIds(ids);
    if (candidates.length === 0) return undefined;
    var firstId = candidates[0];
    var obj = nullProtoObject();
    return new Proxy(obj, {
      get: function(target, prop, receiver) {
        if (typeof prop !== "string") {
          return Reflect.get(target, prop, receiver);
        }
        if (prop === "rawValue") {
          var value = host.getRawValue(firstId, generation);
          return value === undefined ? null : value;
        }
        if (prop === "presence" && host.isInteractive()) {
          return host.getPresence(firstId, generation);
        }
        if (prop === "somExpression") {
          return "xfa[0].form[0].placeholder";
        }
        if (prop === "instanceManager") {
          return makeInstanceManager(firstId, generation);
        }
        if (prop === "occur") {
          host.occurResolve(firstId, generation);
          return makeOccurHandle(firstId, generation);
        }
        if (prop === "index") {
          return host.nodeIndex(firstId, generation);
        }
        // XFA-DATA-M3C: `<candidateSet>.parent` walks one form-tree level up
        // from the leading candidate. Same semantics as `<handle>.parent`;
        // see makeHandle for rationale.
        if (prop === "parent") {
          var parentId = host.parentOfNode(firstId, generation);
          if (parentId < 0) return undefined;
          return makeHandle(parentId, generation);
        }
        if (prop === "setInstances") {
          return function(n) {
            return host.instanceSet(firstId, generation, n);
          };
        }
        if (prop === "addInstance") {
          return function() {
            var newId = host.instanceAdd(firstId, generation);
            // WP-3 F3: return a chainable null-safe sentinel rather than null
            // so scripts that immediately access `.index` / `.value` on the
            // newly-added handle do not throw when the instance manager
            // refuses (min/max reached, unbound).
            return newId < 0 ? makeNullDataHandle() : makeHandle(newId, generation);
          };
        }
        if (prop === "removeInstance") {
          return function(idx) {
            return host.instanceRemove(firstId, generation, idx);
          };
        }
        if (prop === "isNull") {
          var raw = host.getRawValue(firstId, generation);
          return raw === undefined || raw === null || raw === "";
        }
        if (prop === "clearItems") {
          return function() {
            return host.listClear(firstId, generation);
          };
        }
        if (prop === "addItem") {
          return function(display, save) {
            if (save === undefined) {
              return host.listAdd(firstId, generation, String(display));
            }
            return host.listAdd(firstId, generation, String(display), String(save));
          };
        }
        if (prop === "boundItem") {
          return function(displayValue) {
            var coerced = displayValue === null || displayValue === undefined ?
              "" : String(displayValue);
            return host.boundItem(firstId, generation, coerced);
          };
        }
        if (prop === "$record") {
          var recRaw = host.dataBoundRecord(firstId, generation);
          if (recRaw < 0) return makeNullDataHandle();
          return makeDataHandle(recRaw);
        }
        if (prop === "variables") {
          var csNodeName = host.nodeName(firstId, generation);
          if (typeof csNodeName === "string" && csNodeName.length > 0 &&
              subformVariables[csNodeName] !== undefined) {
            return subformVariables[csNodeName];
          }
          return Object.create(null);
        }
        if (prop.charAt(0) === "_" && prop.length > 1) {
          var bareName = prop.substring(1);
          var imIds = uniqueNodeIds(
            host.resolveChildNodeIdsQuiet(nodeIdListArg(candidates), bareName)
          );
          if (imIds.length > 0) {
            return makeInstanceManager(imIds[0], generation);
          }
          for (var imIdx = 0; imIdx < candidates.length; imIdx++) {
            if (host.hasZeroInstanceRun(candidates[imIdx], generation, bareName)) {
              return makeEmptyInstanceManager();
            }
          }
          // XFA-DATA-M3C: same fallthrough as makeHandle underscore branch —
          // expose an empty instanceManager for schema-optional same-named
          // siblings that the merged tree omits, keeping schema-bound
          // scripts chainable. Restricted to container candidates so
          // field/draw candidate sets keep the original `undefined`
          // semantics for underscored property reads.
          if (host.nodeIsContainer(firstId, generation)) {
            return makeEmptyInstanceManager();
          }
        }
        // WP-3: choiceList is a listbox/combobox property not surfaced through
        // the FormTree. Return an empty frozen array.
        if (prop === "choiceList") {
          return Object.freeze([]);
        }
        // BE-1: `#items` on a candidate-set — mirrors the makeHandle path.
        // Uses the first candidate as the representative field id (same
        // convention as boundItem / clearItems / addItem above).
        if (prop === "#items") {
          var csDisplayItems = host.getDisplayItems(firstId, generation);
          if (csDisplayItems.length > 0) {
            host.somItemsPathHit();
          }
          return makeItemsSubstitute(csDisplayItems);
        }
        // XFA-DATA-M3C: `<candidateSet>.ui` returns the widget-config stub.
        // See makeUiStub on makeHandle for rationale.
        if (prop === "ui") {
          return makeUiStub();
        }
        if (prop === "formattedValue") {
          var fvc = host.getRawValue(firstId, generation);
          return fvc === undefined || fvc === null ? "" : String(fvc);
        }
        if (prop === "execEvent") {
          return function() { return undefined; };
        }
        // XFA-DATA2-02: caption / resolveNode / resolveNodes intercept on the
        // candidate-set path. Same rationale as makeHandle: skip the child
        // resolver host call and its resolve_failures bump, return a frozen
        // sentinel + the chainable method pair. Null contract preserved.
        if (prop === "caption") {
          return captionSentinel;
        }
        if (prop === "resolveNode") {
          return handleResolveNode;
        }
        if (prop === "resolveNodes") {
          return handleResolveNodes;
        }
        if (shouldDeferHandleProperty(prop)) {
          return undefined;
        }
        return makeChainHandle(candidates, prop, generation);
      },
      set: function(_target, prop, value) {
        // WP-3: `value` is an alias for rawValue on the set side.
        if (prop === "rawValue" || prop === "value") {
          host.setRawValue(firstId, generation, value);
        } else if (prop === "presence" && host.isInteractive()) {
          // Phase 2: visibility toggle. Gated so static flatten falls through
          // to the historical silent-absorb (return true) — byte-identical.
          host.setPresence(firstId, generation, value);
        }
        return true;
      },
      has: function(target, prop) {
        if (typeof prop !== "string") {
          return Reflect.has(target, prop);
        }
        return prop === "rawValue" ||
          prop === "presence" ||
          prop === "somExpression" ||
          prop === "instanceManager" ||
          prop === "index" ||
          prop === "parent" ||
          prop === "setInstances" ||
          prop === "addInstance" ||
          prop === "removeInstance" ||
          prop === "isNull" ||
          prop === "clearItems" ||
          prop === "addItem" ||
          prop === "boundItem" ||
          Reflect.has(target, prop);
      }
    });
  }

  // XFA-DATA2-02: shared caption sentinel — singleton, frozen, null-safe.
  //
  // XFA templates commonly inspect `field.caption.value` or
  // `field.caption.text` to drive labels and conditional formatting. The
  // merged FormTree does not carry the optional `<caption>` sub-element, so
  // looking up `caption` as a normal child name would call
  // `resolve_child_candidates` → NoMatch → bump `resolve_failures`, return
  // `undefined`, and the very next `.value` access would throw TypeError
  // ("cannot read property 'value' of undefined") and abort the rest of the
  // script's initializers.
  //
  // We intercept `caption` BEFORE the child-resolver call and return a
  // chainable sentinel whose terminal reads are empty strings and whose
  // deeper reads keep chaining via `makeNullDataHandle`. This is purely
  // read-side: writes are silently absorbed (caption sub-element is a
  // viewer-only field, never a flatten mutation channel). The sentinel is
  // allocated once at factory build-time and frozen, so per-call access is
  // an `Object.freeze`d Proxy hit with no heap allocation.
  var captionSentinel = (function() {
    var base = nullProtoObject();
    Object.defineProperty(base, "value",   { enumerable: true, configurable: false,
      get: function() { return ""; }, set: function(_v) { /* viewer-only */ } });
    Object.defineProperty(base, "text",    { enumerable: true, configurable: false,
      get: function() { return ""; }, set: function(_v) { /* viewer-only */ } });
    Object.defineProperty(base, "name",    { enumerable: true, configurable: false,
      get: function() { return "caption"; } });
    Object.defineProperty(base, "rawValue",{ enumerable: true, configurable: false,
      get: function() { return ""; }, set: function(_v) { /* viewer-only */ } });
    Object.defineProperty(base, "isNull",  { enumerable: true, configurable: false,
      get: function() { return true; } });
    return new Proxy(base, {
      get: function(target, prop) {
        if (prop in target || typeof prop !== "string") return target[prop];
        // Unknown reads stay chainable so `caption.font.typeface` etc. do
        // not throw. The sentinel is read-only and write-absorbing.
        return makeNullDataHandle();
      },
      set: function(_t, _p, _v) { return true; },
      has: function() { return true; }
    });
  })();

  // XFA-DATA2-02: shared `resolveNode` / `resolveNodes` instance methods.
  //
  // Beyond the global `xfa.resolveNode(path)`, XFA scripts also call these
  // as methods on individual handles (`field.resolveNode("Subform.X")`,
  // `subform.resolveNodes("$.field[*]")`). Without an explicit shortcut these
  // property reads would fall through to `makeChainHandle`, miss in the
  // child resolver and inflate `js_resolve_failures` — the very pattern the
  // 60df78fe corpus replay flagged.
  //
  // Behaviour mirrors the global pair, including the data-path routing for
  // `data.`, `$data.`, and `xfa.datasets.data.` prefixes. The Cluster C
  // null-return contract is preserved: a miss in the host returns native
  // `null` for the singular form and a frozen empty array for the plural.
  // BE-1: XFA-compatible substitute for the <items> element returned by
  // resolveNode("FieldName.#items").  In a live viewer the result is an XFA
  // node whose .nodes collection contains one <text> child per option label;
  // each child exposes .value / .rawValue.  Scripts iterate:
  //   for (var i=0; i<items.nodes.length; i++) { items.nodes.item(i).value }
  // We materialise that shape from the host display-strings array so existing
  // scripts complete without TypeError and can read the label list.
  function makeItemsSubstitute(displayStrings) {
    var nodes = [];
    for (var k = 0; k < displayStrings.length; k++) {
      (function(label) {
        var textNode = nullProtoObject();
        Object.defineProperty(textNode, "value", {
          enumerable: true, configurable: false, writable: false, value: label
        });
        Object.defineProperty(textNode, "rawValue", {
          enumerable: false, configurable: false, writable: false, value: label
        });
        nodes.push(Object.freeze(textNode));
      })(displayStrings[k]);
    }
    var frozenNodes = Object.freeze(nodes);
    var nodesCollection = nullProtoObject();
    Object.defineProperty(nodesCollection, "length", {
      enumerable: true, configurable: false, get: function() { return frozenNodes.length; }
    });
    Object.defineProperty(nodesCollection, "item", {
      enumerable: false, configurable: false, writable: false,
      value: function(idx) { return frozenNodes[idx] || null; }
    });
    var substitute = nullProtoObject();
    Object.defineProperty(substitute, "nodes", {
      enumerable: true, configurable: false, writable: false, value: Object.freeze(nodesCollection)
    });
    Object.defineProperty(substitute, "length", {
      enumerable: true, configurable: false, get: function() { return frozenNodes.length; }
    });
    return Object.freeze(substitute);
  }

  function handleResolveNode(path) {
    if (typeof path === "string" &&
        (path.indexOf("data.") === 0 || path.indexOf("$data.") === 0 ||
         path.indexOf("xfa.datasets.data.") === 0)) {
      var rawId = host.dataResolveNode(path);
      if (rawId < 0) return null;
      return makeDataHandle(rawId);
    }
    // BE-1: intercept `FieldName.#items` (XFA 3.3 §7.7 / §8.1).
    // `#items` is the SOM class reference for a choiceList's <items> element.
    // The form-tree resolver has no node for it; we resolve the field part,
    // fetch its display labels, and return an XFA-compatible substitute.
    // Guard: path.length > 7 prevents false-positive when lastIndexOf returns
    // -1 and path.length-7 is also -1 (paths shorter than 8 chars).
    if (typeof path === "string" && path.length > 7 &&
        path.lastIndexOf(".#items") === path.length - 7) {
      var fieldPath = path.substring(0, path.length - 7);
      var fid = host.resolveNodeId(fieldPath);
      if (fid >= 0) {
        var displayItems = host.getDisplayItems(fid, host.generation());
        if (displayItems.length > 0) {
          host.somItemsPathHit();
        }
        return makeItemsSubstitute(displayItems);
      }
      return null;
    }
    var nid = host.resolveNodeId(path);
    if (nid < 0) return null;
    return makeHandle(nid, host.generation());
  }
  function handleResolveNodes(path) {
    if (typeof path === "string" &&
        (path.indexOf("data.") === 0 || path.indexOf("$data.") === 0 ||
         path.indexOf("xfa.datasets.data.") === 0)) {
      var rawIds = host.dataResolveNodes(path);
      var out = [];
      for (var i = 0; i < rawIds.length; i++) out.push(makeDataHandle(rawIds[i]));
      return Object.freeze(out);
    }
    var generation = host.generation();
    var ids = host.resolveNodeIds(path);
    var out2 = [];
    for (var j = 0; j < ids.length; j++) {
      out2.push(makeHandle(ids[j], generation));
    }
    return Object.freeze(out2);
  }

  function makeHandle(id, generation) {
    var obj = nullProtoObject();
    Object.defineProperty(obj, "rawValue", {
      enumerable: true,
      configurable: false,
      get: function() {
        var value = host.getRawValue(id, generation);
        return value === undefined ? null : value;
      },
      set: function(value) {
        host.setRawValue(id, generation, value);
      }
    });
    // Phase 2: presence read/write on a SOM-resolved handle. Gated on
    // interactive mode; when off, the read falls through to the historical
    // chain-proxy behaviour and the write is silently absorbed (static-flatten
    // byte-identity).
    Object.defineProperty(obj, "presence", {
      // Non-enumerable so the handle surface stays narrow (Object.keys → just
      // rawValue); `presence` is still accessible by name.
      enumerable: false,
      configurable: false,
      get: function() {
        return host.isInteractive()
          ? host.getPresence(id, generation)
          : makeChainHandle([id], "presence", generation);
      },
      set: function(value) {
        if (host.isInteractive()) {
          host.setPresence(id, generation, value);
        }
      }
    });
    // Phase C-α: defensive stub. Real Adobe forms call
    // `this.somExpression` to obtain the SOM path string. We don't expose
    // the real SOM path (introspection capability), but returning a
    // placeholder lets viewer-tweak scripts (e.g. acroSOM substr(15))
    // proceed without ReferenceError. Mutations via this handle still
    // require the rawValue setter, which is the only side-effect channel.
    Object.defineProperty(obj, "somExpression", {
      enumerable: false,
      configurable: false,
      get: function() {
        return "xfa[0].form[0].placeholder";
      }
    });
    return new Proxy(obj, {
      get: function(target, prop, receiver) {
        if (typeof prop !== "string") {
          return Reflect.get(target, prop, receiver);
        }
        if (prop === "rawValue" || prop === "presence" || prop === "somExpression") {
          return Reflect.get(target, prop, receiver);
        }
        if (prop === "instanceManager") {
          return makeInstanceManager(id, generation);
        }
        if (prop === "occur") {
          host.occurResolve(id, generation);
          return makeOccurHandle(id, generation);
        }
        if (prop === "index") {
          return host.nodeIndex(id, generation);
        }
        // XFA-DATA-M3C: `<handle>.parent` returns the form-tree parent.
        // Adobe scripts commonly chain `parent.somExpression`,
        // `parent.index`, or `parent._Sibling.setInstances(...)` to walk
        // one level up from a field or subform without authoring an
        // explicit SOM path.
        if (prop === "parent") {
          var parentId = host.parentOfNode(id, generation);
          if (parentId < 0) return undefined;
          return makeHandle(parentId, generation);
        }
        if (prop === "setInstances") {
          return function(n) {
            return host.instanceSet(id, generation, n);
          };
        }
        if (prop === "addInstance") {
          return function() {
            var newId = host.instanceAdd(id, generation);
            // WP-3 F3: chainable null-safe sentinel on failure (see candidateSet).
            return newId < 0 ? makeNullDataHandle() : makeHandle(newId, generation);
          };
        }
        if (prop === "removeInstance") {
          return function(idx) {
            return host.instanceRemove(id, generation, idx);
          };
        }
        if (prop === "isNull") {
          var value = host.getRawValue(id, generation);
          return value === undefined || value === null || value === "";
        }
        if (prop === "clearItems") {
          return function() {
            return host.listClear(id, generation);
          };
        }
        if (prop === "addItem") {
          return function(display, save) {
            if (save === undefined) {
              return host.listAdd(id, generation, String(display));
            }
            return host.listAdd(id, generation, String(display), String(save));
          };
        }
        // XFA 3.3 §App A `boundItem` — listbox display→save lookup. Used as
        // `field.boundItem(xfa.event.newText)` to translate a user-visible
        // option label into its underlying save value. Falls back to the
        // input string when no match exists (Adobe behaviour).
        if (prop === "boundItem") {
          return function(displayValue) {
            var coerced;
            if (displayValue === null || displayValue === undefined) {
              coerced = "";
            } else {
              coerced = String(displayValue);
            }
            return host.boundItem(id, generation, coerced);
          };
        }
        if (prop === "$record") {
          var recRaw = host.dataBoundRecord(id, generation);
          if (recRaw < 0) return makeNullDataHandle();
          return makeDataHandle(recRaw);
        }
        // Phase D-ι.2: `subformHandle.variables` returns the namespace object
        // holding all `<variables><script>` entries registered for this
        // subform by name. Enables `Page2.variables.ValidationScript.fn()`.
        if (prop === "variables") {
          var nodeName = host.nodeName(id, generation);
          if (typeof nodeName === "string" && nodeName.length > 0 &&
              subformVariables[nodeName] !== undefined) {
            return subformVariables[nodeName];
          }
          return Object.create(null);
        }
        // XFA 3.3 §6.4.3.2 underscore shorthand: `_<name>` on a subform
        // refers to the instanceManager of the same-named child subform.
        // Used in the wild as `parent._child.setInstances(N)`. This MUST
        // run before `shouldDeferHandleProperty`, which otherwise returns
        // `undefined` for every underscore-prefixed property and makes the
        // shorthand unreachable for real bound subforms.
        if (prop.charAt(0) === "_" && prop.length > 1) {
          var bareName = prop.substring(1);
          var imChildIds = uniqueNodeIds(host.resolveChildNodeIdsQuiet(String(id), bareName));
          if (imChildIds.length > 0) {
            return makeInstanceManager(imChildIds[0], generation);
          }
          if (host.hasZeroInstanceRun(id, generation, bareName)) {
            return makeEmptyInstanceManager();
          }
          // XFA-DATA-M3C: when the same-named child subform is absent from
          // the merged form tree (occur.initial=0, optional bind, or
          // never-instantiated schema option), Adobe still hands the
          // script an empty instanceManager so `parent._Foo.setInstances(N)`
          // is a chainable no-op. This sentinel is ONLY safe on container
          // handles (root, subform, area, subformSet, exclGroup) — XFA
          // 3.3 §6.4.3.2 limits the underscore-shorthand to those node
          // classes. Fields and draws stay `undefined` so existing
          // narrow-handle tests (m3b_phaseC_bindings::field_handle_is_frozen_and_narrow)
          // keep their property-isolation contract.
          if (host.nodeIsContainer(id, generation)) {
            return makeEmptyInstanceManager();
          }
        }
        // WP-3: choiceList is a listbox/combobox property not surfaced through
        // the FormTree. Return an empty frozen array.
        if (prop === "choiceList") {
          return Object.freeze([]);
        }
        // XFA-DATA-M3C: `<handle>.ui` exposes the widget-config sub-object.
        // We materialise a chainable stub (see makeUiStub) so scripts like
        // `field.ui.choiceList.commitOn = "exit"` complete without throwing.
        if (prop === "ui") {
          return makeUiStub();
        }
        // XFA-DATA-M3C: `<handle>.formattedValue` (Adobe SDK §JS A) reads
        // the field value formatted by its picture clause. Static flatten
        // has no live picture-clause formatter; return the raw value so
        // scripts can compare-and-branch without TypeError.
        if (prop === "formattedValue") {
          var fv = host.getRawValue(id, generation);
          return fv === undefined || fv === null ? "" : String(fv);
        }
        // XFA-DATA-M3C: `<handle>.execEvent("activity")` (Adobe SDK) fires
        // an event handler. Static flatten cannot dispatch new events
        // mid-script; absorb the call as a no-op returning undefined.
        if (prop === "execEvent") {
          return function() { return undefined; };
        }
        // XFA-DATA2-02: caption sub-element + resolveNode/resolveNodes
        // instance methods. Intercepted BEFORE shouldDeferHandleProperty +
        // makeChainHandle so the child-resolver host call (and its
        // resolve_failures bump) never happens. See captionSentinel /
        // handleResolveNode/Nodes definitions above for rationale.
        if (prop === "caption") {
          return captionSentinel;
        }
        if (prop === "resolveNode") {
          return handleResolveNode;
        }
        if (prop === "resolveNodes") {
          return handleResolveNodes;
        }
        // BE-1: `#items` — XFA 3.3 §7.7 / §8.1 choiceList item labels.
        // Scripts access `fieldHandle.#items` (e.g. `Wojewodztwo.#items`) to
        // read the display-label collection.  Returns an XFA-compatible
        // substitute (makeItemsSubstitute) so scripts can use both direct
        // array indexing and the `.nodes` / `.nodes.item(i)` access pattern.
        // `#` bypasses `shouldDeferHandleProperty` via `handlePropertyExclusions`.
        if (prop === "#items") {
          var displayItems = host.getDisplayItems(id, generation);
          if (displayItems.length > 0) {
            host.somItemsPathHit();
          }
          return makeItemsSubstitute(displayItems);
        }
        if (shouldDeferHandleProperty(prop)) {
          return undefined;
        }
        return makeChainHandle([id], prop, generation);
      },
      set: function(_target, prop, value) {
        // WP-3: `value` is an alias for rawValue on the set side.
        if (prop === "rawValue" || prop === "value") {
          host.setRawValue(id, generation, value);
        } else if (prop === "presence" && host.isInteractive()) {
          host.setPresence(id, generation, value);
        }
        return true;
      },
      has: function(target, prop) {
        if (typeof prop !== "string") {
          return Reflect.has(target, prop);
        }
        return prop === "rawValue" ||
          prop === "presence" ||
          prop === "somExpression" ||
          prop === "instanceManager" ||
          prop === "index" ||
          prop === "parent" ||
          prop === "ui" ||
          prop === "formattedValue" ||
          prop === "execEvent" ||
          prop === "setInstances" ||
          prop === "addInstance" ||
          prop === "removeInstance" ||
          prop === "isNull" ||
          prop === "clearItems" ||
          prop === "addItem" ||
          prop === "boundItem" ||
          prop === "caption" ||
          prop === "resolveNode" ||
          prop === "resolveNodes" ||
          prop === "#items" ||
          Reflect.has(target, prop);
      }
    });
  }

  // Phase C-α: viewer-stub that absorbs property writes silently.
  // Used as the return value of `event.target.getField()` so
  // AcroForm widget-tweak scripts (`field.doNotScroll = true`,
  // `field.required = false`, etc.) complete without error and
  // without mutating any flatten-relevant state.
  function makeViewerStub() {
    return new Proxy({}, {
      get: function(_t, _prop) { return undefined; },
      set: function(_t, _prop, _val) {
        
        return true;
      },
      has: function() { return true; }
    });
  }

  function toListIndex(value) {
    var n = Number(value);
    if (!isFinite(n) || n < 0) return -1;
    return Math.floor(n);
  }

  // XFA §8.5: a `$record` reference when there is no bound data node must return
  // an empty object that chains safely (`.value` → null, `.nodes.length` → 0)
  // rather than null, which would throw TypeError on any property access.
  function makeNullDataHandle() {
    var emptyNodes = [];
    // XFA null-safe: item() on an empty sentinel list returns a chainable null handle,
    // not native null, so callers can do nodes.item(0).value without TypeError.
    emptyNodes.item = function() { return makeNullDataHandle(); };
    Object.freeze(emptyNodes);
    var sentinel = nullProtoObject();
    // WP-3: configurable:true so the Proxy set-trap can return true without
    // triggering the ECMAScript "non-configurable accessor without setter" invariant.
    Object.defineProperty(sentinel, "value",
      { get: function() { return null; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "rawValue",
      { get: function() { return null; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "length",
      { get: function() { return 0; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "nodes",
      { get: function() { return emptyNodes; }, enumerable: true, configurable: true });
    // WP-3: instance.index on an unbound node → 0
    Object.defineProperty(sentinel, "index",
      { get: function() { return 0; }, enumerable: true, configurable: true });
    sentinel.item = function() { return makeNullDataHandle(); };
    return new Proxy(sentinel, {
      get: function(target, prop) {
        if (prop in target) return target[prop];
        if (typeof prop !== "string") return undefined;
        return makeNullDataHandle();
      },
      // WP-3: absorb all writes — null data handles are read-only sentinels.
      set: function(_target, _prop, _value) {
        return true;
      }
    });
  }

  // BE-1 tranche #1: benign "absent declared node" façade. Returned by the
  // implicit-globals `lookup` for a bare identifier that fails the scope
  // resolve but names a template-declared container (gated by the host
  // `isDeclaredAbsentNode`). Mirrors Adobe semantics: a reference to a
  // declared-but-absent node is an EMPTY node — `isNull === true`, `rawValue`/
  // `value` null, empty `nodes`, an empty `instanceManager`, and every further
  // SOM segment chains to another empty node. Writes are absorbed. This lets a
  // guarded script (`if (!Sub.Child.Field.isNull) {…} else {…}`) evaluate the
  // guard to `false` and run its else branch (e.g. `_X.setInstances(0)`,
  // `presence = "invisible"`) instead of throwing on `undefined`. Modelled on
  // `makeNullDataHandle`; the explicit boolean `isNull` is essential — without
  // it, `.isNull` would chain to a truthy façade object and invert the guard.
  function makeAbsentNodeHandle() {
    var sentinel = nullProtoObject();
    Object.defineProperty(sentinel, "isNull",
      { get: function() { return true; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "value",
      { get: function() { return null; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "rawValue",
      { get: function() { return null; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "length",
      { get: function() { return 0; }, enumerable: true, configurable: true });
    var emptyNodes = [];
    emptyNodes.item = function() { return makeAbsentNodeHandle(); };
    Object.freeze(emptyNodes);
    Object.defineProperty(sentinel, "nodes",
      { get: function() { return emptyNodes; }, enumerable: true, configurable: true });
    Object.defineProperty(sentinel, "instanceManager",
      { get: function() { return makeEmptyInstanceManager(); }, enumerable: true, configurable: true });
    sentinel.item = function() { return makeAbsentNodeHandle(); };
    return new Proxy(sentinel, {
      get: function(target, prop) {
        if (prop in target) return target[prop];
        if (typeof prop !== "string") return undefined;
        // `_<Name>` underscore-shorthand → an empty instanceManager, so chained
        // `Sub._Child.setInstances(n)` on an absent node is a safe no-op.
        if (prop.charAt(0) === "_" && prop.length > 1) return makeEmptyInstanceManager();
        // any further SOM segment chains to another empty node.
        return makeAbsentNodeHandle();
      },
      // absorb writes (presence, rawValue, mandatory, …) — empty nodes are inert.
      set: function(_target, _prop, _value) { return true; }
    });
  }

  // Phase D-γ: Data DOM handle — wraps a raw DataDom node index and exposes
  // `.value`, `.nodes`, `.length`, `.item(i)`, and named child access via Proxy.
  function makeDataHandle(rawId) {
    // WP-3: return null-safe sentinel so callers can chain .value / .nodes safely.
    if (rawId === undefined || rawId < 0) return makeNullDataHandle();
    var handle = nullProtoObject();
    Object.defineProperty(handle, "value", {
      get: function() {
        var v = host.dataValue(rawId);
        return (v === undefined || v === null) ? null : v;
      },
      enumerable: true, configurable: false
    });
    // rawValue is an alias for value — scripts use both forms on data handles.
    Object.defineProperty(handle, "rawValue", {
      get: function() {
        var v = host.dataValue(rawId);
        return (v === undefined || v === null) ? null : v;
      },
      enumerable: true, configurable: false
    });
    Object.defineProperty(handle, "length", {
      get: function() { return host.dataChildren(rawId).length; },
      enumerable: true, configurable: false
    });
    Object.defineProperty(handle, "nodes", {
      get: function() {
        var ids = host.dataChildren(rawId);
        var arr = [];
        for (var i = 0; i < ids.length; i++) arr.push(makeDataHandle(ids[i]));
        // Phase D-γ fix: XFA scripts call `nodeList.item(i)` on the array
        // returned by `.nodes`. Plain JS arrays have no `.item()` method —
        // add one that mirrors the W3C NodeList API. Out-of-bounds indices
        // return a null-safe sentinel so `.value` access never throws.
        var NULLNODE = Object.freeze({ value: null, rawValue: null });
        arr.item = function(idx) {
          var index = toListIndex(idx);
          if (index < 0 || index >= arr.length) return NULLNODE;
          return arr[index];
        };
        return Object.freeze(arr);
      },
      enumerable: true, configurable: false
    });
    handle.item = function(i) {
      var ids = host.dataChildren(rawId);
      var index = toListIndex(i);
      if (index < 0 || index >= ids.length) return null;
      return makeDataHandle(ids[index]);
    };
    return new Proxy(handle, {
      get: function(target, prop) {
        if (prop in target || typeof prop !== "string") return target[prop];
        if (prop === "rawValue" || prop === "value") return target.value;
        var childId = host.dataChildByName(rawId, prop);
        if (childId < 0) return makeNullDataHandle();
        return makeDataHandle(childId);
      }
    });
  }

  // Phase E (XFA-JS-HOST-STUBS): `xfa.host` is the most heavily used Adobe
  // Reader viewer namespace. The previous frozen stub only exposed
  // `numPages` + `messageBox`, so initializer scripts that touch
  // `xfa.host.title = "..."`, `xfa.host.openList(...)`, `xfa.host.beep()`,
  // etc. raised TypeError on the very first property access and inflated
  // `runtime_errors`. We expose a Proxy that:
  //   * resolves known read-only viewer properties to deterministic defaults
  //     (numPages, version, language, platform, name, title, validationsEnabled,
  //     calculationsEnabled, currentPage, pageCount);
  //   * absorbs every other write silently (viewer-only state has no flatten
  //     side-effects);
  //   * returns a null-safe sentinel for unknown reads so chains like
  //     `xfa.host.someVendorExt.message` don't TypeError;
  //   * exposes the interactive function family (messageBox, openList, beep,
  //     response, print, gotoURL, setFocus, exportData, importData,
  //     resetData) as safe-default thunks that ALSO bump the
  //     `unsupported_host_calls` counter so dispatch keeps observability
  //     without claiming a fake success (no "user clicked OK" lies).
  // No filesystem / network / process syscalls reach the host — every
  // interactive thunk is a pure JS no-op that delegates to host.unsupported
  // for accounting only. See benchmarks/JS_SANDBOX_SECURITY_AUDIT.md.
  var XFA_HOST_INTERACTIVE_CALLS = {
    "messageBox":   { kind: "ret", value: 0 },
    "openList":     { kind: "ret", value: -1 },
    "beep":         { kind: "ret", value: undefined },
    "response":     { kind: "ret", value: "" },
    "print":        { kind: "ret", value: undefined },
    "gotoURL":      { kind: "ret", value: undefined },
    "setFocus":     { kind: "ret", value: undefined },
    "exportData":   { kind: "ret", value: undefined },
    "importData":   { kind: "ret", value: undefined },
    "resetData":    { kind: "ret", value: undefined },
    "documentCountInBatch": { kind: "ret", value: 1 },
    "documentInBatch":      { kind: "ret", value: 0 },
    // JS2-01 (Sprint 2 Batch B): closeDoc is referenced by Canadian IMM
    // and Quebec dol4n templates as an interactive viewer entry point.
    // Static flatten cannot dismiss a document; safe-default undefined
    // with `unsupported_host_calls` accounting keeps observability without
    // a TypeError. Pure JS no-op — no filesystem / network reach the host.
    "closeDoc":     { kind: "ret", value: undefined }
  };

  // Read-side defaults for viewer-readable host properties. These are pure
  // accessors — no host call leaves the sandbox. The values mirror Adobe
  // Reader behaviour during static, non-interactive rendering.
  function makeXfaHostBase() {
    var base = nullProtoObject();
    Object.defineProperty(base, "numPages", {
      enumerable: true, configurable: false,
      get: function() { return host.numPages(); }
    });
    Object.defineProperty(base, "currentPage", {
      enumerable: true, configurable: true,
      get: function() { return 0; },
      set: function(_v) { /* viewer-only */ }
    });
    Object.defineProperty(base, "pageCount", {
      enumerable: true, configurable: false,
      get: function() { return host.numPages(); }
    });
    // Static deterministic identity strings. We deliberately avoid claiming
    // Acrobat compatibility — scripts that branch on `xfa.host.name` for
    // Adobe-specific behaviour should fall through to a non-Acrobat path.
    var SCALAR_DEFAULTS = {
      "version":    "PDFluent-XFA",
      "language":   "ENU",
      "platform":   "PDFluent",
      "name":       "PDFluent",
      "title":      "",
      "appType":    "Reader",
      "variation":  "Reader",
      "calculationsEnabled": true,
      "validationsEnabled":  true,
      "runtimeHighlight":    false,
      "runtimeHighlightColor": "",
      "viewerType":          "PDFluent",
      "fullScreen":          false
    };
    Object.keys(SCALAR_DEFAULTS).forEach(function(k) {
      var v = SCALAR_DEFAULTS[k];
      Object.defineProperty(base, k, {
        enumerable: true, configurable: true,
        get: function() { return v; },
        set: function(_v) { /* viewer-only, silently absorb */ }
      });
    });
    return base;
  }

  // Install interactive function thunks. Each thunk increments the
  // unsupported-host-call counter and returns a deterministic safe default.
  function installXfaHostInteractive(base) {
    Object.keys(XFA_HOST_INTERACTIVE_CALLS).forEach(function(name) {
      var spec = XFA_HOST_INTERACTIVE_CALLS[name];
      Object.defineProperty(base, name, {
        enumerable: true, configurable: false, writable: false,
        value: function() {
          host.unsupportedHostCall(name);
          return spec.value;
        }
      });
    });
  }

  var xfaHostBase = makeXfaHostBase();
  installXfaHostInteractive(xfaHostBase);
  // Wrap in a Proxy so unknown property reads return a null-safe sentinel
  // and unknown writes silently absorb. This is the "no TypeError" guarantee
  // for vendor-specific xfa.host extensions referenced by templated scripts.
  var xfaHost = new Proxy(xfaHostBase, {
    get: function(target, prop) {
      if (prop in target || typeof prop !== "string") return target[prop];
      // Unknown read — never throw, never claim a value. Sentinel only.
      return makeNullDataHandle();
    },
    set: function(_t, _p, _v) { return true; },
    has: function() { return true; }
  });

  var xfaLayout = nullProtoObject();
  Object.defineProperty(xfaLayout, "pageCount", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: function() {
      return host.numPages();
    }
  });
  // Phase D-γ: xfa.layout.page(node) — page number (1-based) of a form node.
  // During static flatten the layout is not yet run, so return a bounded
  // placeholder and mark the metadata as approximate.
  Object.defineProperty(xfaLayout, "page", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: function() {
      host.resolveFailure();
      return 1;
    }
  });
  // Phase D-γ: xfa.layout.pageSpan(node) — number of pages a node spans.
  // Always 1 during static flatten; metadata records the approximation.
  Object.defineProperty(xfaLayout, "pageSpan", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: function() {
      host.resolveFailure();
      return 1;
    }
  });
  Object.defineProperty(xfaLayout, "absPage", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: function() {
      host.bindingError();
      return null;
    }
  });

  var xfa = nullProtoObject();
  Object.defineProperty(xfa, "host", {
    enumerable: true,
    configurable: false,
    writable: false,
    // Note: deliberately NOT Object.freeze'd. `xfaHost` is already a Proxy
    // with sealed semantics (writes absorbed, unknown reads return sentinels).
    // Freezing would force every Set trap to throw under strict-mode scripts.
    value: xfaHost
  });
  Object.defineProperty(xfa, "layout", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: Object.freeze(xfaLayout)
  });

  // Phase E (XFA-JS-HOST-STUBS): viewer / interaction sub-namespaces. Each
  // is a Proxy that silently absorbs writes and returns chainable sentinels
  // on read so scripts can complete:
  //
  //   xfa.viewer        — Reader UI state (zoom, scrollbar, toolbar, ...)
  //   xfa.appState      — Reader-wide preference cache
  //   xfa.appearanceFilter — accessibility / high-contrast hints
  //   xfa.connection    — `<connection>` outbound data binding stubs
  //   xfa.signature     — interactive digital-signature panel
  //   xfa.aliasNode     — script-time DOM alias rebinding
  //   xfa.form          — top-level FormDOM root reference (we expose the
  //                       same resolveNode/resolveNodes pair so the script
  //                       feels uniform; legacy property reads sentinel)
  //
  // These never call out to the host other than for accounting; no
  // filesystem / network / process syscalls reach the host bindings. Reads
  // for known property names return spec-conforming defaults; everything
  // else falls back to the null-safe sentinel chain.
  function makeViewerStubNamespace(staticReads) {
    var base = nullProtoObject();
    if (staticReads) {
      Object.keys(staticReads).forEach(function(k) {
        var v = staticReads[k];
        Object.defineProperty(base, k, {
          enumerable: true, configurable: true,
          get: function() { return v; },
          set: function(_v) { /* viewer-only — silent absorb */ }
        });
      });
    }
    return new Proxy(base, {
      get: function(target, prop) {
        if (prop in target || typeof prop !== "string") return target[prop];
        return makeNullDataHandle();
      },
      set: function(_t, _p, _v) { return true; },
      has: function() { return true; }
    });
  }

  function makeInteractiveStubNamespace(funcs) {
    // funcs: { "sign": defaultRet, "verify": defaultRet, ... }
    var base = nullProtoObject();
    Object.keys(funcs).forEach(function(name) {
      var def = funcs[name];
      Object.defineProperty(base, name, {
        enumerable: true, configurable: false, writable: false,
        value: function() {
          host.unsupportedHostCall(name);
          return def;
        }
      });
    });
    return new Proxy(base, {
      get: function(target, prop) {
        if (prop in target || typeof prop !== "string") return target[prop];
        return makeNullDataHandle();
      },
      set: function(_t, _p, _v) { return true; },
      has: function() { return true; }
    });
  }

  Object.defineProperty(xfa, "viewer", {
    enumerable: true, configurable: false, writable: false,
    value: makeViewerStubNamespace({
      "zoomType":  "FitWidth",
      "zoom":      100,
      "scrollbar": "auto",
      "toolbar":   true,
      "menubar":   true,
      "statusbar": true
    })
  });
  Object.defineProperty(xfa, "appState", {
    enumerable: true, configurable: false, writable: false,
    value: makeViewerStubNamespace({
      "highlightRequiredFields": false,
      "fieldHighlightColor":     "",
      "ariaEnabled":             false
    })
  });
  Object.defineProperty(xfa, "appearanceFilter", {
    enumerable: true, configurable: false, writable: false,
    value: makeViewerStubNamespace(null)
  });
  Object.defineProperty(xfa, "aliasNode", {
    enumerable: true, configurable: false, writable: false,
    value: makeViewerStubNamespace(null)
  });
  Object.defineProperty(xfa, "connection", {
    enumerable: true, configurable: false, writable: false,
    // `<connection>` calls hit a real service endpoint in Adobe Reader.
    // Static flatten cannot honour that — every method is unsupported.
    value: makeInteractiveStubNamespace({
      "execute":   null,
      "open":      null,
      "close":     null,
      "send":      null
    })
  });
  Object.defineProperty(xfa, "signature", {
    enumerable: true, configurable: false, writable: false,
    // Digital signatures require an interactive certificate picker.
    value: makeInteractiveStubNamespace({
      "sign":     false,
      "verify":   "unknown",
      "enumerate": ""
    })
  });
  // WP-3 F3: `xfa.validate` is a viewer-only namespace controlling form-wide
  // validation behaviour (Reader UI prompts on field constraint violations).
  // Adobe initializers commonly do `xfa.validate.override = 0` /
  // `xfa.validate.max = N` to suppress modal dialogs that have no meaning
  // in a static flatten context. Expose a Proxy that silently absorbs every
  // property write (`override`, `max`, `messageMode`, etc.) and returns
  // empty defaults on read, so scripts complete without TypeError.
  Object.defineProperty(xfa, "validate", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: new Proxy(nullProtoObject(), {
      get: function(_t, prop) {
        if (prop === "override" || prop === "max") return 0;
        if (prop === "messageMode") return "";
        if (typeof prop !== "string") return undefined;
        // Unknown reads return a chainable null-safe sentinel so deeper
        // access like `xfa.validate.scriptTest.message` does not throw.
        return makeNullDataHandle();
      },
      set: function(_t, _prop, _value) { return true; },
      has: function() { return true; }
    })
  });
  Object.defineProperty(xfa, "resolveNode", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: function(path) {
      // Phase D-γ: data paths are routed to the DataDom, not the FormTree.
      if (typeof path === "string" &&
          (path.indexOf("data.") === 0 || path.indexOf("$data.") === 0 ||
           path.indexOf("xfa.datasets.data.") === 0)) {
        var rawId = host.dataResolveNode(path);
        if (rawId < 0) return null;
        return makeDataHandle(rawId);
      }
      // BE-1: intercept `FieldName.#items` — same logic as handleResolveNode.
      // Scripts call `xfa.resolveNode("Wojewodztwo.#items")` to get the items
      // collection for a choiceList; the form-tree SOM cannot resolve `#items`
      // as a node, so we resolve the field, fetch its display labels, and
      // return an XFA-compatible substitute (makeItemsSubstitute).
      // Guard: path.length > 7 prevents false-positive match when
      // lastIndexOf returns -1 and path.length-7 is also -1.
      if (typeof path === "string" && path.length > 7 &&
          path.lastIndexOf(".#items") === path.length - 7) {
        var fieldPath = path.substring(0, path.length - 7);
        var fid = host.resolveNodeId(fieldPath);
        if (fid >= 0) {
          var xrDisplayItems = host.getDisplayItems(fid, host.generation());
          if (xrDisplayItems.length > 0) {
            host.somItemsPathHit();
          }
          return makeItemsSubstitute(xrDisplayItems);
        }
        return null;
      }
      var id = host.resolveNodeId(path);
      if (id < 0) {
        return null;
      }
      return makeHandle(id, host.generation());
    }
  });
  // JS2-01 (Sprint 2 Batch B): `xfa.form` is the FormDOM root surface
  // Adobe Reader exposes (XFA 3.3 §6.1.4 — the result of merging template
  // + datasets). The previous build only commented that it should be
  // exposed (rquickjs_backend.rs:2477) but no actual binding existed —
  // scripts that did `xfa.form.resolveNode("Form1.Subform1")` or
  // `form.resolveNode(...)` ran into "cannot read property of undefined"
  // or "form is not defined". We expose a Proxy that:
  //   * forwards `resolveNode` / `resolveNodes` to the existing
  //     `xfa.resolveNode` / `xfa.resolveNodes` pair (cluster C contract
  //     preserved — missing paths still return `null`, not a sentinel);
  //   * absorbs unknown property writes (viewer-only flags) silently;
  //   * returns a chainable null-safe sentinel for unknown reads.
  // No new Rust closure is registered; the binding is pure JS routing.
  function makeFormNamespace() {
    var base = nullProtoObject();
    Object.defineProperty(base, "resolveNode", {
      enumerable: true, configurable: false, writable: false,
      value: function(path) { return xfa.resolveNode(path); }
    });
    Object.defineProperty(base, "resolveNodes", {
      enumerable: true, configurable: false, writable: false,
      value: function(path) { return xfa.resolveNodes(path); }
    });
    // Adobe's `form` exposes `recalculate(true/false)` as a no-op trigger
    // for the calculation cascade. Templates pass `1` (force) commonly.
    // Static flatten already ran calculate scripts — accept the call,
    // return undefined, no counter (it is not an interactive prompt).
    Object.defineProperty(base, "recalculate", {
      enumerable: true, configurable: false, writable: false,
      value: function() { return undefined; }
    });
    Object.defineProperty(base, "execValidate", {
      enumerable: true, configurable: false, writable: false,
      value: function() { return true; }
    });
    Object.defineProperty(base, "execInitialize", {
      enumerable: true, configurable: false, writable: false,
      value: function() { return undefined; }
    });
    Object.defineProperty(base, "execCalculate", {
      enumerable: true, configurable: false, writable: false,
      value: function() { return undefined; }
    });
    return new Proxy(base, {
      get: function(target, prop) {
        if (prop in target || typeof prop !== "string") return target[prop];
        return makeNullDataHandle();
      },
      set: function(_t, _p, _v) { return true; },
      has: function() { return true; }
    });
  }
  var formNamespace = makeFormNamespace();
  Object.defineProperty(xfa, "form", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: formNamespace
  });
  Object.defineProperty(xfa, "resolveNodes", {
    enumerable: true,
    configurable: false,
    writable: false,
    value: function(path) {
      // Phase D-γ: data paths are routed to the DataDom, not the FormTree.
      if (typeof path === "string" &&
          (path.indexOf("data.") === 0 || path.indexOf("$data.") === 0 ||
           path.indexOf("xfa.datasets.data.") === 0)) {
        var rawIds = host.dataResolveNodes(path);
        var out = [];
        for (var i = 0; i < rawIds.length; i++) out.push(makeDataHandle(rawIds[i]));
        return Object.freeze(out);
      }
      var generation = host.generation();
      var ids = host.resolveNodeIds(path);
      var out = [];
      for (var i = 0; i < ids.length; i++) {
        out.push(makeHandle(ids[i], generation));
      }
      return Object.freeze(out);
    }
  });
  // Phase D-δ.2: expose `xfa.event` as an alias for the per-script event
  // global. Real Adobe Reader populates this with the firing event;
  // during static flatten there is no dispatched UI event, so the
  // accessor returns the same defensive event-stub that the per-script
  // `event` parameter receives — newText/prevText/change default to
  // empty strings, target resolves to the firing field handle.
  Object.defineProperty(xfa, "event", {
    enumerable: true,
    configurable: false,
    get: function() {
      return makeEvent();
    }
  });

  // Phase E (XFA-JS-HOST-STUBS): Acrobat / Reader `app` global. Adobe
  // initializer scripts commonly do:
  //   app.calculate.override = true;       // viewer-only flag — silent absorb
  //   app.runtimeHighlight   = false;      // viewer-only flag — silent absorb
  //   app.alert("submitted"); app.launchURL("…")  // interactive — counted
  //
  // The previous frozen `app` only stubbed two functions; every other
  // property touch surfaced as TypeError. Wrap the whole namespace in a
  // Proxy with the same semantics as `xfa.host`:
  //   * known viewer properties resolve to deterministic defaults;
  //   * known interactive functions return a safe default + bump
  //     unsupported_host_calls (NOT runtime_errors);
  //   * unknown reads return a null-safe sentinel chain;
  //   * unknown writes are absorbed.
  //
  // `app.calculate` is itself an absorbing sub-Proxy — every assignment
  // (`app.calculate.override = true`, `app.calculate.suspend = false`, ...)
  // is viewer-only and has no flatten side-effect. We document this as an
  // explicit silent no-op (not UnsupportedHostCapability) because
  // suppressing the viewer's calculation cascade is the script author's
  // ASKING the viewer to stop, not a UI prompt to the user. See
  // benchmarks/JS_SANDBOX_SECURITY_AUDIT.md for the full classification.
  var APP_INTERACTIVE_CALLS = {
    "alert":       { kind: "ret", value: 0 },     // dialog OK pressed = 0
    "launchURL":   { kind: "ret", value: undefined },
    "execMenuItem":{ kind: "ret", value: undefined },
    "beep":        { kind: "ret", value: undefined },
    "openDoc":     { kind: "ret", value: null },
    "response":    { kind: "ret", value: "" },
    "mailMsg":     { kind: "ret", value: undefined },
    // JS2-01 (Sprint 2 Batch B): Adobe Acrobat SDK exposes `app.messageBox`
    // as a richer alias of `app.alert` (modal dialog, returns the pressed
    // button index — 0 = OK). Safe default mirrors `app.alert`. No new
    // capability surface; pure JS no-op with counter accounting.
    "messageBox":  { kind: "ret", value: 0 },
    // JS2-01: `app.closeDoc` is the Acrobat alias of `xfa.host.closeDoc`.
    // Templates targeting both Reader and Acrobat reference both spellings;
    // we counter-bump on each call and return undefined.
    "closeDoc":    { kind: "ret", value: undefined }
  };
  function makeAppBase() {
    var base = nullProtoObject();
    // Read-side static defaults — never call out, never lie about identity.
    var SCALAR_DEFAULTS = {
      "viewerType":     "PDFluent",
      "viewerVariation":"Reader",
      "viewerVersion":  0,
      "language":       "ENU",
      "platform":       "PDFluent",
      "fs":             null,  // file system gateway — explicitly null
      "media":          null,  // multimedia controller — explicitly null
      "fullscreen":     false,
      "runtimeHighlight": false,
      "runtimeHighlightColor": ""
    };
    Object.keys(SCALAR_DEFAULTS).forEach(function(k) {
      var v = SCALAR_DEFAULTS[k];
      Object.defineProperty(base, k, {
        enumerable: true, configurable: true,
        get: function() { return v; },
        set: function(_v) { /* viewer-only, silently absorb */ }
      });
    });
    // app.calculate sub-namespace: writes absorb, reads return defaults.
    Object.defineProperty(base, "calculate", {
      enumerable: true, configurable: false, writable: false,
      value: makeViewerStubNamespace({
        "override": true,
        "suspend":  false
      })
    });
    // Install interactive function thunks (same pattern as xfa.host).
    Object.keys(APP_INTERACTIVE_CALLS).forEach(function(name) {
      var spec = APP_INTERACTIVE_CALLS[name];
      Object.defineProperty(base, name, {
        enumerable: true, configurable: false, writable: false,
        value: function() {
          host.unsupportedHostCall(name);
          return spec.value;
        }
      });
    });
    return base;
  }
  var app = new Proxy(makeAppBase(), {
    get: function(target, prop) {
      if (prop in target || typeof prop !== "string") return target[prop];
      return makeNullDataHandle();
    },
    set: function(_t, _p, _v) { return true; },
    has: function() { return true; }
  });

  // Phase C-α: viewer-only `event` global. Real Adobe Reader populates
  // this with the firing event; during static flatten there is no
  // dispatched UI event, so the object is a defensive stub that:
  // - exposes `target` resolving to the firing field handle (≈ `this`),
  //   so scripts like `event.target.getField(somPath)` complete without
  //   ReferenceError;
  // - exposes `change` as an empty string (the spec default);
  // - returns viewer-stubs from `target.getField()` so AcroForm widget
  //   tweaks (`doNotScroll`, `required`, etc.) silently absorb.
  function makeEvent() {
    var id = host.currentNodeId();
    var fieldHandle = id < 0 ? null : makeHandle(id, host.generation());
    var target = nullProtoObject();
    Object.defineProperty(target, "getField", {
      enumerable: true, configurable: false, writable: false,
      value: function() {
        
        return makeViewerStub();
      }
    });
    Object.defineProperty(target, "name", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(target, "self", {
      enumerable: true, configurable: false,
      get: function() { return fieldHandle; }
    });
    var ev = nullProtoObject();
    Object.defineProperty(ev, "target", {
      enumerable: true, configurable: false,
      get: function() { return target; }
    });
    // Phase D-δ.2: stable empty-string defaults for the change-event property
    // family so scripts that read `xfa.event.newText` / `prevText` /
    // `change` on initialize/calculate (where no real change event occurred)
    // do not throw `cannot read property 'X' of undefined`. Adobe populates
    // these on actual `change`/`exit` events; we run those activities later
    // (or never) and surface deterministic empty defaults instead.
    Object.defineProperty(ev, "change", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "newText", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "prevText", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "fullText", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "selStart", {
      enumerable: true, configurable: false,
      get: function() { return 0; }
    });
    Object.defineProperty(ev, "selEnd", {
      enumerable: true, configurable: false,
      get: function() { return 0; }
    });
    // JS2-01 (Sprint 2 Batch B): the Phase E security audit §3.9 promised
    // that `event` exposes the full Adobe Acrobat SDK event surface
    // (`target`, `change`, `newText`, `prevText`, `fullText`, `selStart`,
    // `selEnd`, plus `name`, `type`, `shift`, `modifier`, `commitKey`,
    // `willCommit`, `rc`, `keyDown`, `value`, `reenter`). Only the first
    // seven were implemented; scripts that probe `event.name` for the
    // firing activity (`if (event.name === "calculate") {...}`) silently
    // saw `undefined`, and scripts that chained off `event.X` could trip
    // a "not a function" if `X` was expected to be callable.
    //
    // All values are deterministic spec defaults that match Adobe's
    // behaviour during a non-interactive flatten (no firing event):
    //   name       — current activity if known, else ""
    //   type       — event type label (Adobe ≈ "Field"), "" if unknown
    //   shift      — modifier-key state (false)
    //   modifier   — modifier-key state (false)
    //   commitKey  — 0 (no commit key pressed)
    //   willCommit — false (no commit pending)
    //   rc         — true (accept-by-default — same as Adobe's validate)
    //   keyDown    — false (no key pressed)
    //   value      — "" (current widget value, unknown during static flatten)
    //   reenter    — false (Acrobat re-entry flag)
    //
    // Read-only via getter, like the existing seven. The frozen ev object
    // means writes to these from scripts running in strict mode would throw
    // a TypeError — but no real script writes event scalars (the only
    // observed pattern is `event.value = ...` on a stale `event` reference
    // which is undefined, not the frozen object). If we ever observe
    // legitimate writes, swap getter for configurable getter+setter.
    Object.defineProperty(ev, "name", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "type", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "shift", {
      enumerable: true, configurable: false,
      get: function() { return false; }
    });
    Object.defineProperty(ev, "modifier", {
      enumerable: true, configurable: false,
      get: function() { return false; }
    });
    Object.defineProperty(ev, "commitKey", {
      enumerable: true, configurable: false,
      get: function() { return 0; }
    });
    Object.defineProperty(ev, "willCommit", {
      enumerable: true, configurable: false,
      get: function() { return false; }
    });
    Object.defineProperty(ev, "rc", {
      enumerable: true, configurable: false,
      get: function() { return true; }
    });
    Object.defineProperty(ev, "keyDown", {
      enumerable: true, configurable: false,
      get: function() { return false; }
    });
    Object.defineProperty(ev, "value", {
      enumerable: true, configurable: false,
      get: function() { return ""; }
    });
    Object.defineProperty(ev, "reenter", {
      enumerable: true, configurable: false,
      get: function() { return false; }
    });
    return Object.freeze(ev);
  }

  // Phase D-γ: XFA global `util` (Acrobat SDK §Util).  Provides date/number
  // formatting helpers used by many XFA templates. Only the subset required
  // by real-corpus scripts is implemented; unknown methods return "".
  //
  // util.printd(sFormat, dDate)  — format a Date per sFormat using UTC fields.
  //   Supported tokens: yyyy (year), yy (two-digit year), mm (month 01-12),
  //   m (1-12), dd (day 01-31), d (1-31), HH (hour 00-23),
  //   MM (minute 00-59), SS (second 00-59).
  // util.printx(cPicture, cValue) — picture format; returns cValue as-is.
  // util.scand(sFormat, cDate)   — deterministic numeric parser for the same
  //   token subset; unsupported or invalid input returns Invalid Date.
  var xfaUtil = (function() {
    var DateCtor = Date;
    var dateUtc = Date.UTC;
    function pad2(n) { return (n < 10 ? "0" : "") + n; }
    function invalidDate() { return new DateCtor(NaN); }
    function escapeRegex(text) {
      return String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function parseDate(fmt, input) {
      var fmtText, text;
      try {
        fmtText = String(fmt);
        text = String(input);
      } catch (_e) {
        return invalidDate();
      }

      var groups = [];
      var pattern = "^";
      for (var i = 0; i < fmtText.length;) {
        var rest = fmtText.substring(i);
        if (rest.indexOf("yyyy") === 0) {
          pattern += "(\\d{4})";
          groups.push("yyyy");
          i += 4;
        } else if (rest.indexOf("yy") === 0) {
          pattern += "(\\d{2})";
          groups.push("yy");
          i += 2;
        } else if (rest.indexOf("mm") === 0) {
          pattern += "(\\d{2})";
          groups.push("mm");
          i += 2;
        } else if (rest.indexOf("dd") === 0) {
          pattern += "(\\d{2})";
          groups.push("dd");
          i += 2;
        } else if (rest.indexOf("HH") === 0) {
          pattern += "(\\d{2})";
          groups.push("HH");
          i += 2;
        } else if (rest.indexOf("MM") === 0) {
          pattern += "(\\d{2})";
          groups.push("MM");
          i += 2;
        } else if (rest.indexOf("SS") === 0) {
          pattern += "(\\d{2})";
          groups.push("SS");
          i += 2;
        } else if (rest.indexOf("m") === 0) {
          pattern += "(\\d{1,2})";
          groups.push("m");
          i += 1;
        } else if (rest.indexOf("d") === 0) {
          pattern += "(\\d{1,2})";
          groups.push("d");
          i += 1;
        } else {
          pattern += escapeRegex(fmtText.charAt(i));
          i += 1;
        }
      }

      var match = new RegExp(pattern + "$").exec(text);
      if (!match) return invalidDate();

      var year = NaN, month = 1, day = 1, hour = 0, minute = 0, second = 0;
      for (var g = 0; g < groups.length; g++) {
        var value = parseInt(match[g + 1], 10);
        if (!isFinite(value)) return invalidDate();
        if (groups[g] === "yyyy") year = value;
        else if (groups[g] === "yy") year = 2000 + value;
        else if (groups[g] === "mm" || groups[g] === "m") month = value;
        else if (groups[g] === "dd" || groups[g] === "d") day = value;
        else if (groups[g] === "HH") hour = value;
        else if (groups[g] === "MM") minute = value;
        else if (groups[g] === "SS") second = value;
      }

      if (!isFinite(year) || month < 1 || month > 12 || day < 1 || day > 31 ||
          hour < 0 || hour > 23 || minute < 0 || minute > 59 ||
          second < 0 || second > 59) {
        return invalidDate();
      }
      var out = new DateCtor(dateUtc(year, month - 1, day, hour, minute, second));
      if (out.getUTCFullYear() !== year ||
          out.getUTCMonth() + 1 !== month ||
          out.getUTCDate() !== day ||
          out.getUTCHours() !== hour ||
          out.getUTCMinutes() !== minute ||
          out.getUTCSeconds() !== second) {
        return invalidDate();
      }
      return out;
    }
    var u = nullProtoObject();
    u.printd = function(fmt, date) {
      if (!(date instanceof DateCtor) || isNaN(date.getTime())) return "";
      var y = date.getUTCFullYear();
      var mo = date.getUTCMonth() + 1;
      var d  = date.getUTCDate();
      var h  = date.getUTCHours();
      var mi = date.getUTCMinutes();
      var s  = date.getUTCSeconds();
      var result = String(fmt);
      result = result.replace(/yyyy/g, y)
                     .replace(/yy/g,   String(y).slice(-2))
                     .replace(/mm/g,   pad2(mo))
                     .replace(/m/g,    mo)
                     .replace(/dd/g,   pad2(d))
                     .replace(/d/g,    d)
                     .replace(/HH/g,   pad2(h))
                     .replace(/MM/g,   pad2(mi))
                     .replace(/SS/g,   pad2(s));
      return result;
    };
    u.printx = function(_fmt, val) { return val === null || val === undefined ? "" : String(val); };
    u.scand  = function(fmt, str) { return parseDate(fmt, str); };
    return Object.freeze(u);
  }());

  // Phase C-α: minimal `console` no-op. Many forms guard with
  // `if (typeof console !== "undefined") console.log(...)` and proceed
  // when the symbol exists. Stub returns undefined; never writes
  // anywhere observable to the script.
  var consoleStub = nullProtoObject();
  ["log","warn","error","info","debug","trace"].forEach(function(name) {
    Object.defineProperty(consoleStub, name, {
      enumerable: true, configurable: false, writable: false,
      value: function() {  return undefined; }
    });
  });

  // Phase D-ι: form-level globals registered from `<variables>` `<script>`
  // blocks. Each entry is `name -> frozen object`. Populated by the host
  // once per document via `setVariablesScript`; cleared by
  // `clearVariablesScripts` at `reset_per_document`.
  var variablesScripts = lookupObject();
  // Phase D-ι.2: subform-scoped variables. Maps subform name -> namespace
  // object containing that subform's named scripts. Enables
  // `subformHandle.variables.ScriptName.method()` access paths.
  var subformVariables = lookupObject();
  // W3-D RETRY: form-level mutable string data items registered from
  // `<variables>` `<text name="X">value</text>` blocks (XFA 3.3 §5.5.2).
  // Each entry is `name -> { value: <string> }`. Adobe Reader exposes these
  // as global mutable string containers — the canonical IMM5709 pattern
  // is `<text name="globValidatePressed"/>` referenced from event scripts
  // as `globValidatePressed.value = "true";`. Populated by
  // `setVariablesDataItem`; cleared by `clearVariablesScripts` (shared
  // teardown — same per-document lifecycle).
  var variablesDataItems = lookupObject();
  // W3-D RETRY: subform-scoped variant of `variablesDataItems`, parallel to
  // `subformVariables` for scripts. Reserved for future subform-level data
  // items; currently populated only at root scope but the structure is
  // here so an upcoming pass can light it up without further refactor.
  var subformVariablesDataItems = lookupObject();
  // D4: flat first-wins exposure of subform-scoped named `<script>` objects to
  // bare-identifier lookup. The host only writes an entry here for names that
  // are unique across all subforms (ambiguous names are withheld — fail-closed
  // — and counted Rust-side). Consulted by the `with` proxy AFTER
  // `variablesScripts` / `variablesDataItems` (root scope wins) and BEFORE the
  // host SOM resolver, so a subform-scoped helper such as `countryScript`
  // resolves as a bare global instead of falling through to a SOM NoMatch.
  var subformScriptsByName = lookupObject();

  function makeImplicitGlobals(body) {
    var currentId = host.currentNodeId();
    var generation = host.generation();
    var localNames = collectLocalNames(String(body));
    var cachedHandles = lookupObject();
    var dynamicLocals = lookupObject();

    function lookup(name) {
      if (cachedHandles[name] !== undefined) {
        return cachedHandles[name];
      }
      var nodeIds = uniqueNodeIds(host.resolveImplicitNodeIds(currentId, name));
      if (nodeIds.length === 0) {
        // BE-1 tranche #1: a bare implicit identifier that fails the scope
        // resolve but names a template-declared container resolves to a benign
        // EMPTY node (Adobe semantics: isNull===true), not `undefined`. This
        // lets guarded scripts such as
        //   if (!Podmiot1.OsobaFizyczna.PESEL.isNull) {...} else {...}
        // take the empty (else) branch and run their setInstances(0)/presence
        // writes instead of throwing "cannot read property '…' of undefined"
        // and aborting. Undeclared names still return `undefined`, preserving
        // the D-θ.1 `A.B === undefined` byte-identity contract for genuine
        // misses. Gated host-side by `isDeclaredAbsentNode`; sandboxed-only.
        if (host.isDeclaredAbsentNode(name)) {
          var facade = makeAbsentNodeHandle();
          cachedHandles[name] = facade;
          return facade;
        }
        return undefined;
      }
      // Phase D-θ.2: wrap an implicit hit in the full-chain accumulator. The
      // resulting proxy accumulates SOM property names without contacting
      // the host until a terminal property is read; only then is the full
      // chain resolved with backtracking. This lets `A.B.C.D.rawValue`
      // disambiguate the same-name `A` whose subtree completes the chain,
      // rather than relying on a single-segment hint as in D-θ.1. Terminal
      // properties still resolve byte-for-byte identically to the
      // un-hinted walk so single-token reads keep their existing
      // semantics.
      var handle = makeChainProxy([], [name], nodeIds, generation, currentId);
      cachedHandles[name] = handle;
      return handle;
    }

    return new Proxy(Object.create(null), {
      has: function(_target, prop) {
        if (typeof prop !== "string") {
          return false;
        }
        // XFA-DATA-M3C: `_<Name>` and `parent` are XFA-defined globals that
        // must be visible to `with()` lookup even when the local-names
        // collector treats them as locals (they shadow no real var/let).
        if (prop === "parent") {
          return true;
        }
        if (prop.charAt(0) === "_" && prop.length > 1 &&
            localNames[prop] !== true) {
          // Probe — only claim presence when the bare-name resolves to a
          // real subform/container; otherwise fall through to the standard
          // defer rules so unrelated underscored locals stay undefined.
          // Quiet probe: a miss here is the schema-optional path and must
          // not count as a script-level resolve failure.
          var bare = prop.substring(1);
          if (uniqueNodeIds(host.resolveImplicitNodeIdsQuiet(currentId, bare)).length > 0 ||
              host.hasZeroInstanceRun(currentId, generation, bare)) {
            return true;
          }
        }
        if (shouldDeferGlobalName(prop, localNames)) {
          return false;
        }
        return true;
      },
      get: function(_target, prop) {
        if (typeof prop !== "string") {
          return undefined;
        }
        // XFA-DATA-M3C: bare `parent` resolves to the form-tree parent of
        // the current script node. Common in calculate/initialize scripts
        // for `parent.index`, `parent.rawValue`, and chain navigation that
        // mirrors Adobe's implicit-scope walk one step upward.
        if (prop === "parent") {
          var parentId = host.parentOfNode(currentId, generation);
          if (parentId < 0) return undefined;
          return makeHandle(parentId, generation);
        }
        // XFA 3.3 §6.4.3.2 underscore shorthand at the global scope:
        // `_<Name>` referenced as a bare identifier denotes the
        // instanceManager of a same-named subform reachable from the
        // current implicit scope. Adobe Reader exposes this both as a
        // child property (`parent._Foo`) and as a bare global. Without
        // this branch the `shouldDeferGlobalName` rule below returns
        // `undefined` for every underscored bare ident and the calling
        // script throws `ReferenceError: _Foo is not defined`.
        //
        // Only triggers when the target subform actually exists; otherwise
        // fall through so unrelated underscored locals keep their
        // existing deferred-undefined semantics.
        if (prop.charAt(0) === "_" && prop.length > 1 &&
            localNames[prop] !== true) {
          var bareName = prop.substring(1);
          // Quiet probe: schema-optional misses are NOT a script-level
          // resolve failure. We surface either a live manager, an empty
          // manager (zero-instance run or never-instantiated optional
          // subform), or fall through to the defer rules.
          var imIds = uniqueNodeIds(
            host.resolveImplicitNodeIdsQuiet(currentId, bareName)
          );
          if (imIds.length > 0) {
            return makeInstanceManager(imIds[0], generation);
          }
          if (host.hasZeroInstanceRun(currentId, generation, bareName)) {
            return makeEmptyInstanceManager();
          }
        }
        if (shouldDeferGlobalName(prop, localNames)) {
          return undefined;
        }
        // Phase D-γ: $record as a script-level global refers to the data
        // record bound to the current field's enclosing subform context.
        // Scripts write `var addr = $record.SECTION.nodes;` — we intercept
        // this here instead of letting resolveImplicitNodeId fail (-1).
        if (prop === "$record") {
          var recRaw = host.dataBoundRecord(currentId, generation);
          if (recRaw < 0) return makeNullDataHandle();
          return makeDataHandle(recRaw);
        }
        // BE-1: `$data` as a bare global refers to the data-DOM root node
        // (XFA 3.3 §3.3.2: `$data` == `xfa.datasets.data`).  Scripts write
        // e.g. `var root = $data; root.child.value` — we intercept here
        // before the SOM resolver so the data-dom root is returned directly.
        // `data_resolve_node("$data")` resolves to the root of the DataDom
        // (SomRoot::Data + zero segments -> start node) via resolve_data_som.
        if (prop === "$data") {
          var dataRootRaw = host.dataResolveNode("$data");
          if (dataRootRaw < 0) return makeNullDataHandle();
          host.somDataRootHit();
          return makeDataHandle(dataRootRaw);
        }
        // Phase D-γ: `util` is an XFA global (Acrobat SDK §Util) that provides
        // date/number formatting functions.  `util.printd(fmt, date)` is widely
        // used by XFA templates to format Date objects.  We intercept it here so
        // scripts can complete without a TypeError instead of throwing and
        // aborting all later mutations in the same script body.
        if (prop === "util") {
          return xfaUtil;
        }
        if (dynamicLocals[prop] !== undefined) {
          return dynamicLocals[prop];
        }
        // Phase D-ι: form-level named-script globals from <variables>
        // outrank the form-tree implicit lookup. Adobe XFA spec §5.5
        // exposes `<scriptName>.<topLevelDecl>` to all event/calculate
        // scripts in the same document.
        if (variablesScripts[prop] !== undefined) {
          return variablesScripts[prop];
        }
        // W3-D RETRY: form-level data items (XFA 3.3 §5.5.2) outrank the
        // form-tree implicit lookup, same as scripts. This lets templates
        // like Canadian IMM5709 reference `globValidatePressed.value`
        // without the bare ident falling through to the SOM resolver as a
        // `js_resolve_failure`. Scripts take precedence over data items in
        // the unlikely case both share a name (spec-undefined; we follow
        // declaration order, which is `setVariablesScript` first in the
        // host loop).
        if (variablesDataItems[prop] !== undefined) {
          return variablesDataItems[prop];
        }
        // D4: subform-scoped named script objects (unique-name only) resolve as
        // bare globals here, after root-scope scripts/data items and before the
        // host SOM resolver. This is the minimal SOM resolution for the
        // `countryScript` / `partNoScript` cluster (XFA 3.3 §5.5 subform
        // variables). Ambiguous names were never written here (fail-closed).
        if (subformScriptsByName[prop] !== undefined) {
          return subformScriptsByName[prop];
        }
        return lookup(prop);
      },
      set: function(_target, prop, value) {
        if (typeof prop !== "string") {
          return true;
        }
        if (shouldDeferGlobalName(prop, localNames)) {
          return false;
        }
        if (cachedHandles[prop] !== undefined) {
          return true;
        }
        dynamicLocals[prop] = value;
        return true;
      }
    });
  }

  return {
    // Phase E (XFA-JS-HOST-STUBS): `xfa` itself is still frozen because all
    // of its properties were installed with `configurable: false` and writes
    // go through inner-Proxy `set` traps that we control. `app` is a Proxy
    // whose underlying target is non-extensible after we install the
    // function thunks; freezing the Proxy itself would force the absorbing
    // `set` trap to throw a TypeError (proxy invariants: writes to
    // non-extensible targets must reject), defeating the whole point of the
    // silent-absorb design. We therefore expose `app` unfrozen — its safety
    // is enforced by the Proxy traps, not by Object.freeze.
    xfa: Object.freeze(xfa),
    app: app,
    // JS2-01 (Sprint 2 Batch B): top-level `form` global alias for
    // `xfa.form`. Adobe Reader exposes both spellings; templates such as
    // corpus forms reference bare `form.X`. The alias is identity-equal
    // to `xfa.form` (same Proxy), so cluster C contract preservation is
    // shared between the two surfaces. No new Rust closure introduced.
    form: formNamespace,
    consoleStub: Object.freeze(consoleStub),
    // Phase D-ι: register a `<variables>` `<script name="X">…` block as a
    // form-level global. Called by the host once per script body at
    // document load. `body` is the raw script source; `identNames` is a
    // pre-extracted array of top-level `var` / `function` identifiers
    // (Rust-side regex). The body is wrapped in an IIFE that returns a
    // frozen object whose properties are those identifiers. Variables
    // scripts share the same time/memory budget enforcement as event
    // scripts but emit no field mutations of their own. Errors during
    // evaluation are absorbed: the namespace remains undefined and
    // dependent event scripts will fail naturally at first use.
    // Phase D-ι / D-ι.2: register a named `<variables><script>` body.
    // `subformName` (4th param, optional) is non-empty for subform-scoped
    // scripts; omit or pass "" for root-level scripts.
    //
    // Root-level scripts (empty subformName) go into the flat
    // `variablesScripts` dict only — accessible as `ScriptName.X` from
    // any event script in the document.
    //
    // Subform-scoped scripts go into `subformVariables[subformName][name]`
    // ONLY — accessible as `subformHandle.variables.ScriptName.X`. They
    // are intentionally NOT written to the flat dict: two subforms may
    // define the same script name, and writing both to the flat map would
    // let the second registration silently shadow the first.
    setVariablesScript: function(name, body, identNames, subformName, exposeGlobal) {
      if (typeof name !== "string" || name.length === 0) return false;
      if (typeof body !== "string") return false;
      var idents = Array.isArray(identNames) ? identNames : [];
      var props = "";
      for (var i = 0; i < idents.length; i++) {
        var id = idents[i];
        if (typeof id !== "string" || id.length === 0) continue;
        if (i > 0) props += ",";
        props += JSON.stringify(id) + ": typeof " + id +
                 " !== \"undefined\" ? " + id + " : undefined";
      }
      // XFA-DATA2-02: inject `console` and `util` into the variables-script
      // closure so the form-level helper functions registered here can
      // reference them lexically and the dependent event scripts that call
      // those helpers do not blow up with `console is not defined` /
      // `util is not defined`. Both are the same sandbox-safe singletons
      // exposed to event scripts (silent no-op console, deterministic util).
      var wrapper = "(function(__console, __util){\n" +
                    "var console = __console; var util = __util;\n" +
                    body +
                    "\nreturn Object.freeze({" + props + "});\n})";
      try {
        var ns = (Function("return " + wrapper))()(consoleStub, xfaUtil);
        if (typeof subformName === "string" && subformName.length > 0) {
          if (subformVariables[subformName] === undefined) {
            subformVariables[subformName] = lookupObject();
          }
          subformVariables[subformName][name] = ns;
          // D4: also expose to bare-identifier lookup when the host marked this
          // name unique across subforms (ambiguous names are withheld).
          if (exposeGlobal === true && subformScriptsByName[name] === undefined) {
            subformScriptsByName[name] = ns;
          }
        } else {
          variablesScripts[name] = ns;
        }
        return true;
      } catch (_e) {
        return false;
      }
    },
    clearVariablesScripts: function() {
      var keys = Object.keys(variablesScripts);
      for (var i = 0; i < keys.length; i++) {
        delete variablesScripts[keys[i]];
      }
      var skeys = Object.keys(subformVariables);
      for (var j = 0; j < skeys.length; j++) {
        delete subformVariables[skeys[j]];
      }
      // D4: clear the flat subform-script exposure map on the same per-document
      // lifecycle as the scoped maps.
      var ssnkeys = Object.keys(subformScriptsByName);
      for (var n = 0; n < ssnkeys.length; n++) {
        delete subformScriptsByName[ssnkeys[n]];
      }
      // W3-D RETRY: data items share the same per-document lifecycle as
      // scripts. Dropping them here keeps a single bridge entry-point at
      // `reset_for_new_document` and prevents per-document drift.
      var dkeys = Object.keys(variablesDataItems);
      for (var k = 0; k < dkeys.length; k++) {
        delete variablesDataItems[dkeys[k]];
      }
      var sdkeys = Object.keys(subformVariablesDataItems);
      for (var m = 0; m < sdkeys.length; m++) {
        delete subformVariablesDataItems[sdkeys[m]];
      }
    },
    // W3-D RETRY: register a `<variables>` `<text name="X">value</text>`
    // data item (XFA 3.3 §5.5.2) as a form-level mutable string container.
    // Idempotent per (subformName?, name): a later registration overwrites
    // the earlier one, mirroring Adobe Reader's last-wins template merge.
    //
    // The returned shape is `{ value: <string> }` — minimal because real
    // templates only read/write `.value`. Writes coerce non-string inputs
    // to string (matching Adobe Reader's text-field semantics) so a
    // calculate script that does `globValidatePressed.value = true` does
    // not silently store a boolean.
    setVariablesDataItem: function(name, initial, subformName) {
      if (typeof name !== "string" || name.length === 0) return false;
      var initialStr = (typeof initial === "string") ? initial : "";
      // Use a closure-bound private slot so the `value` getter / setter
      // can coerce on write without exposing a plain-object property that
      // would let `delete item.value` succeed.
      var item = (function(initStr) {
        var current = initStr;
        var holder = Object.create(null);
        Object.defineProperty(holder, "value", {
          enumerable: true,
          configurable: false,
          get: function() { return current; },
          set: function(v) {
            current = (v === undefined || v === null) ? "" : String(v);
          }
        });
        // XFA 3.3 §5.5.2: data items also expose `.name`. Read-only.
        Object.defineProperty(holder, "name", {
          enumerable: true, configurable: false, writable: false,
          value: name
        });
        return holder;
      })(initialStr);
      if (typeof subformName === "string" && subformName.length > 0) {
        if (subformVariablesDataItems[subformName] === undefined) {
          subformVariablesDataItems[subformName] = lookupObject();
        }
        subformVariablesDataItems[subformName][name] = item;
      } else {
        variablesDataItems[name] = item;
      }
      return true;
    },
    evalScript: function(body) {
      var id = host.currentNodeId();
      var thisArg = id < 0 ? undefined : makeHandle(id, host.generation());
      // Phase C-α: install per-script `event` global in the function
      // closure so `event.target` resolves to the current field. Wrapping
      // body inside a function lets us pass `event` as a parameter
      // without leaking it to globalThis (where it would persist across
      // unrelated scripts).
      var ev = makeEvent();
      var consoleArg = consoleStub;
      var globals = makeImplicitGlobals(body);
      return (Function(
        "event",
        "console",
        "__globals",
        "with(__globals){\n" + String(body) + "\n}"
      )).call(thisArg, ev, consoleArg, globals);
    }
  };
})
"##;

impl XfaJsRuntime for SandboxedRuntime {
    fn init(&mut self) -> Result<(), SandboxError> {
        // Booting the engine (hardened globals, host functions, the binding
        // layer) is deferred to the first script; see `bindings_registered_check`.
        self.init_called.set(true);
        Ok(())
    }

    fn reset_for_new_document(&mut self) -> Result<(), SandboxError> {
        self.metadata = RuntimeMetadata::default();
        self.host.borrow_mut().reset_per_document();
        self.clear_deadline();
        // Memory limit is per-document; re-set to clear any prior accounting.
        self.engine
            .get_mut()
            .set_memory_limit(self.memory_budget_bytes);
        // Phase D-ι: drop all `<variables>` namespace globals from the
        // previous document so they do not leak into the next. Failure
        // here is non-fatal — it just means a slightly polluted global
        // namespace, never a correctness issue, but log via metadata.
        if let Err(e) = self.clear_variables_scripts_global() {
            log::debug!("D-ι clear failed: {e:?}");
        }
        Ok(())
    }

    // The `*mut FormTree` parameter is part of the existing
    // `XfaJsRuntime` trait — the caller in `flatten.rs` already enforces
    // that the pointer outlives this call. Clippy's
    // `not_unsafe_ptr_arg_deref` would require this signature to be
    // `unsafe fn`, which the trait does not allow.
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    fn set_form_handle(
        &mut self,
        form: *mut FormTree,
        root_id: FormNodeId,
    ) -> Result<(), SandboxError> {
        self.host.borrow_mut().set_form_handle(form, root_id);
        // Phase D-ι: register every `<variables>` `<script name="X">…` body
        // collected during merge as a form-level JS global. Done here
        // because by this point the form pointer is valid and the JS
        // runtime is initialised. Errors registering one script do not
        // block the others.
        if !form.is_null() {
            // SAFETY: caller guarantees `form` outlives this call.
            let scripts: Vec<(Option<String>, String, String)> =
                unsafe { (*form).variables_scripts.clone() };
            // D3 (trace-only): count collected vs registered vs failed and the
            // subform-scoped subset. Pure observability — no behaviour change.
            self.metadata.variables_scripts_collected = self
                .metadata
                .variables_scripts_collected
                .saturating_add(scripts.len());
            // D4: decide which subform-scoped script names are unique (and thus
            // eligible for bare-identifier exposure). A name declared by ≥2
            // subforms is ambiguous and withheld (fail-closed); count each such
            // ambiguous name once.
            let mut subform_name_counts: std::collections::HashMap<String, usize> =
                std::collections::HashMap::new();
            for (subform_scope, name, _) in &scripts {
                if subform_scope.is_some() {
                    *subform_name_counts.entry(name.clone()).or_insert(0) += 1;
                }
            }
            let ambiguous_subform_names = subform_name_counts.values().filter(|&&c| c > 1).count();
            self.metadata.som_lookup_ambiguous = self
                .metadata
                .som_lookup_ambiguous
                .saturating_add(ambiguous_subform_names);
            for (subform_scope, name, body) in scripts {
                if subform_scope.is_some() {
                    self.metadata.script_objects_subform_scoped = self
                        .metadata
                        .script_objects_subform_scoped
                        .saturating_add(1);
                }
                // D4: expose unique-name subform-scoped scripts as bare globals.
                let expose_global = subform_scope.is_some()
                    && subform_name_counts.get(&name).copied().unwrap_or(0) == 1;
                match self.register_variables_script(
                    &name,
                    &body,
                    subform_scope.as_deref(),
                    expose_global,
                ) {
                    Ok(true) => {
                        self.metadata.script_objects_registered =
                            self.metadata.script_objects_registered.saturating_add(1);
                        // Count only scripts that actually registered AND were
                        // exposed (JS bound the namespace into the flat map).
                        if expose_global {
                            self.metadata.som_subform_scripts_exposed =
                                self.metadata.som_subform_scripts_exposed.saturating_add(1);
                        }
                    }
                    Ok(false) => {
                        self.metadata.script_objects_register_failed = self
                            .metadata
                            .script_objects_register_failed
                            .saturating_add(1);
                        log::debug!("D-ι register `{name}` returned false (JS eval failed)");
                    }
                    Err(e) => {
                        self.metadata.script_objects_register_failed = self
                            .metadata
                            .script_objects_register_failed
                            .saturating_add(1);
                        log::debug!("D-ι register `{name}` failed: {e:?}");
                    }
                }
            }
            // W3-D RETRY: register `<variables><text name="X">…</text>`
            // data items after scripts so a same-named script (declaration
            // order) keeps precedence — matches the JS-side `get` trap
            // which consults `variablesScripts` before `variablesDataItems`.
            // SAFETY: same lifetime guarantee as above.
            let data_items: Vec<(Option<String>, String, String)> =
                unsafe { (*form).variables_data_items.clone() };
            // D3 (trace-only): count collected vs registered vs failed.
            self.metadata.variables_data_items_collected = self
                .metadata
                .variables_data_items_collected
                .saturating_add(data_items.len());
            for (subform_scope, name, initial) in data_items {
                match self.register_variables_data_item(&name, &initial, subform_scope.as_deref()) {
                    Ok(()) => {
                        self.metadata.script_objects_registered =
                            self.metadata.script_objects_registered.saturating_add(1);
                    }
                    Err(e) => {
                        self.metadata.script_objects_register_failed = self
                            .metadata
                            .script_objects_register_failed
                            .saturating_add(1);
                        log::debug!("W3-D register data item `{name}` failed: {e:?}");
                    }
                }
            }
        }
        Ok(())
    }

    fn set_data_handle(&mut self, dom: *const xfa_dom_resolver::data_dom::DataDom) {
        self.host.borrow_mut().set_data_handle(dom);
    }

    fn set_declared_subform_names(&mut self, names: std::collections::HashSet<String>) {
        self.host.borrow_mut().set_declared_subform_names(names);
    }

    fn reset_per_script(
        &mut self,
        current_id: FormNodeId,
        activity: Option<&str>,
    ) -> Result<(), SandboxError> {
        self.host
            .borrow_mut()
            .reset_per_script(current_id, activity);
        Ok(())
    }

    fn set_static_page_count(&mut self, page_count: u32) -> Result<(), SandboxError> {
        self.host.borrow_mut().set_static_page_count(page_count);
        Ok(())
    }

    fn set_presave_gate(&mut self, enabled: bool) {
        // D1.B: mirror the dispatch decision into the host-binding layer so
        // mutating host calls see the same gate.
        self.host.borrow_mut().set_presave_gate(enabled);
    }

    fn set_interactive(&mut self, enabled: bool) {
        // Phase 2: arm the host's interactive gate so `change`/`click`
        // dispatch and `setPresence` writes are accepted for this episode.
        self.host.borrow_mut().set_interactive(enabled);
    }

    fn execute_script(
        &mut self,
        activity: Option<&str>,
        body: &str,
    ) -> Result<RuntimeOutcome, SandboxError> {
        // D1.B: when the per-flatten gate is ON, the QuickJS backend's
        // defence-in-depth check accepts `preSave` exactly like the dispatch
        // gate. Without the gate, behaviour is byte-identical to v4 (W3-B
        // closure). Hard-stop: only `preSave` is unlocked; every other
        // denylist activity stays denied. The gate value is owned by the
        // host bindings (set via `set_presave_gate` from dispatch).
        let presave_gate = self.host.borrow().presave_gate();
        let interactive = self.host.borrow().interactive();
        let allowed = activity_allowed_for_sandbox_with_gate(activity, presave_gate)
            || (interactive && super::interactive_activity_allowed(activity));
        if !allowed {
            return Err(SandboxError::PhaseDenied(
                activity.unwrap_or("None").to_string(),
            ));
        }
        if body.len() > MAX_SCRIPT_BODY_BYTES {
            self.metadata.runtime_errors = self.metadata.runtime_errors.saturating_add(1);
            return Err(SandboxError::BodyTooLarge);
        }

        // W3-A — REDOS-01 mitigation. Reject script bodies containing
        // catastrophic-backtracking regex shapes BEFORE handing them to
        // QuickJS, because QuickJS's interrupt handler is polled at JS
        // opcode boundaries — not inside the regex C code — and cannot
        // bound a single pathological `test()` call.
        if let RegexScanVerdict::Reject { reason } = scan_script_for_redos(body) {
            self.metadata.runtime_errors = self.metadata.runtime_errors.saturating_add(1);
            return Err(SandboxError::RegexRejected(reason));
        }

        if self.bindings_registered_check().is_err() {
            self.metadata.runtime_errors = self.metadata.runtime_errors.saturating_add(1);
            return Err(SandboxError::ScriptError(
                "script engine not initialised".to_string(),
            ));
        }

        self.set_deadline();
        let result = catch_unwind(AssertUnwindSafe(|| {
            self.engine.borrow_mut().call_kept(
                "bridge",
                "evalScript",
                vec![In::Str(body.to_string())],
            )
        }));
        // Snapshot the deadline state BEFORE clearing so the classification
        // below can tell a timeout from a genuine ScriptError.
        let timed_out = self.deadline_elapsed();
        let classified = self.classify_timeout_or_walltime();
        self.clear_deadline();

        match result {
            Ok(Ok(_)) => {
                self.metadata.executed = self.metadata.executed.saturating_add(1);
                let host_metadata = self.host.borrow_mut().take_metadata();
                self.metadata.accumulate(host_metadata);
                Ok(RuntimeOutcome {
                    executed: true,
                    mutated_field_count: host_metadata.mutations,
                })
            }
            Ok(Err(fail)) => {
                let host_metadata = self.host.borrow_mut().take_metadata();
                self.metadata.accumulate(host_metadata);
                match fail {
                    // Stopped by the engine's time/step limit, or the
                    // deadline passed while the script ran. Both
                    // classifications bump the same `timeouts` counter.
                    Fail::Limit(_) => {
                        self.metadata.timeouts = self.metadata.timeouts.saturating_add(1);
                        Err(classified)
                    }
                    _ if timed_out => {
                        self.metadata.timeouts = self.metadata.timeouts.saturating_add(1);
                        Err(classified)
                    }
                    Fail::Memory(_) => {
                        self.metadata.oom = self.metadata.oom.saturating_add(1);
                        Err(SandboxError::OutOfMemory)
                    }
                    Fail::Threw(msg) => {
                        self.metadata.runtime_errors =
                            self.metadata.runtime_errors.saturating_add(1);
                        Err(SandboxError::ScriptError(msg))
                    }
                    // `Fail` is non-exhaustive: a failure kind this version does not know is a script error.
                    other => {
                        self.metadata.runtime_errors =
                            self.metadata.runtime_errors.saturating_add(1);
                        Err(SandboxError::ScriptError(format!("{other:?}")))
                    }
                }
            }
            Err(_) => {
                let host_metadata = self.host.borrow_mut().take_metadata();
                self.metadata.accumulate(host_metadata);
                self.metadata.runtime_errors = self.metadata.runtime_errors.saturating_add(1);
                Err(SandboxError::PanicCaptured(
                    "panic during sandboxed script execution".to_string(),
                ))
            }
        }
    }

    fn take_metadata(&mut self) -> RuntimeMetadata {
        std::mem::take(&mut self.metadata)
    }

    fn take_occur_mutations(&mut self) -> Vec<(usize, String, i64)> {
        self.host
            .borrow_mut()
            .take_occur_mutations()
            .into_iter()
            .map(|(id, prop, value)| (id.0, prop, value))
            .collect()
    }

    fn take_diag_logs(&mut self) -> crate::js_runtime::RuntimeDiagLogs {
        self.host.borrow_mut().take_diag_logs()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fresh_runtime() -> SandboxedRuntime {
        let mut rt = SandboxedRuntime::new().expect("js engine init");
        rt.init().expect("init");
        rt.reset_for_new_document().expect("reset");
        rt
    }

    #[test]
    fn harmless_calculate_script_executes() {
        let mut rt = fresh_runtime();
        let outcome = rt
            .execute_script(Some("calculate"), "var x = 1 + 1; x")
            .expect("ok");
        assert!(outcome.executed);
        let md = rt.take_metadata();
        assert_eq!(md.executed, 1);
        assert!(md.is_clean());
    }

    // BE-1 tranche #1: a bare implicit reference to a template-declared
    // container that has no live node resolves to a benign EMPTY node
    // (isNull===true, chainable, writes absorbed) — so the guarded
    // second-party pattern takes its else branch instead of throwing
    // "cannot read property '…' of undefined" and aborting the script.
    #[test]
    fn absent_declared_subform_resolves_to_empty_node() {
        let mut rt = fresh_runtime();
        let mut names = std::collections::HashSet::new();
        names.insert("Podmiot1".to_string());
        rt.set_declared_subform_names(names);
        // Mirrors the real NIP1/PESEL1 initialize script on 2ff85101.
        rt.execute_script(
            Some("calculate"),
            r#"
            if (Podmiot1.OsobaFizyczna.PESEL.isNull !== true)
                throw new Error('expected isNull === true on absent declared node');
            var tookElse = false;
            if (!Podmiot1.OsobaFizyczna.PESEL.isNull) { tookElse = false; }
            else { tookElse = true; }
            if (!tookElse) throw new Error('guard did not take the empty (else) branch');
            // Chained writes on the empty node must be inert (no throw).
            Podmiot1.OsobaFizyczna.presence = "invisible";
            Podmiot1.OsobaFizyczna.PESEL.rawValue = 2;
            if (Podmiot1.nodes.length !== 0) throw new Error('expected empty .nodes');
            "#,
        )
        .expect("absent declared subform must resolve to a benign empty node");
    }

    // BE-1 tranche #1: the discriminator is necessary — an UNDECLARED bare name
    // must still surface as `undefined`, preserving the D-θ.1 byte-identity
    // contract (`A.B === undefined` for genuine misses). Without the declared
    // set installed, the same identifier stays undefined.
    #[test]
    fn undeclared_bare_name_stays_undefined() {
        let mut rt = fresh_runtime();
        // No declared names installed at all.
        rt.execute_script(
            Some("calculate"),
            "if (typeof NemoNonexistent7 !== 'undefined') \
             throw new Error('D-theta.1 violated: undeclared name became defined');",
        )
        .expect("undeclared bare name must remain undefined");
        // Even with an UNRELATED declared name present, an undeclared ref stays undefined.
        let mut names = std::collections::HashSet::new();
        names.insert("SomeOtherSubform".to_string());
        rt.set_declared_subform_names(names);
        rt.execute_script(
            Some("calculate"),
            "if (typeof NemoNonexistent7 !== 'undefined') \
             throw new Error('D-theta.1 violated: undeclared name became defined (declared set present)');",
        )
        .expect("undeclared bare name must remain undefined even when other names are declared");
    }

    #[test]
    fn ui_activity_is_phase_denied() {
        let mut rt = fresh_runtime();
        let err = rt.execute_script(Some("click"), "1+1").unwrap_err();
        assert!(matches!(err, SandboxError::PhaseDenied(_)));
    }

    #[test]
    fn oversized_body_rejected_before_parse() {
        let mut rt = fresh_runtime();
        let body = "1;\n".repeat(MAX_SCRIPT_BODY_BYTES);
        let err = rt.execute_script(Some("calculate"), &body).unwrap_err();
        assert_eq!(err, SandboxError::BodyTooLarge);
    }

    #[test]
    fn fetch_is_undefined() {
        let mut rt = fresh_runtime();
        // Reading `typeof fetch` from a fresh context should return
        // "undefined" because we never register it. Surface as a thrown
        // error if it isn't, by using `if (typeof fetch !== 'undefined') throw 0`.
        rt.execute_script(
            Some("calculate"),
            "if (typeof fetch !== 'undefined') throw new Error('fetch leaked');",
        )
        .expect("must run cleanly with fetch undefined");
    }

    #[test]
    fn require_is_undefined() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("calculate"),
            "if (typeof require !== 'undefined') throw new Error('require leaked');",
        )
        .expect("must run cleanly with require undefined");
    }

    #[test]
    fn process_is_undefined() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("calculate"),
            "if (typeof process !== 'undefined') throw new Error('process leaked');",
        )
        .expect("must run cleanly with process undefined");
    }

    #[test]
    fn date_now_is_zero() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("calculate"),
            "if (Date.now() !== 0) throw new Error('Date.now not stubbed');",
        )
        .expect("Date.now must return 0");
    }

    #[test]
    fn math_random_is_undefined() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("calculate"),
            "if (typeof Math.random !== 'undefined') throw new Error('Math.random leaked');",
        )
        .expect("Math.random must be undefined");
    }

    #[test]
    fn infinite_loop_times_out() {
        let mut rt = SandboxedRuntime::new()
            .expect("init")
            .with_time_budget(Duration::from_millis(50));
        rt.init().unwrap();
        rt.reset_for_new_document().unwrap();
        let err = rt
            .execute_script(Some("calculate"), "while(true){}")
            .unwrap_err();
        assert_eq!(err, SandboxError::Timeout);
        let md = rt.take_metadata();
        assert_eq!(md.timeouts, 1);
        assert_eq!(md.executed, 0);
    }

    #[test]
    fn syntax_error_is_recoverable() {
        let mut rt = fresh_runtime();
        let err = rt
            .execute_script(Some("calculate"), "this is not javascript {{")
            .unwrap_err();
        assert!(matches!(err, SandboxError::ScriptError(_)));
        // Subsequent script should still run.
        rt.execute_script(Some("calculate"), "var ok = 1;")
            .expect("recovered");
    }

    #[test]
    fn null_receiver_silent_setter() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("calculate"),
            r#"
$record.NONEXISTENT_FIELD.rawValue = "hello";
$record.NONEXISTENT_FIELD.value = "world";
"#,
        )
        .expect("WP-3 null_receiver_silent_setter: set on null DataHandle must not throw");
    }

    #[test]
    fn null_record_returns_empty_nodelist() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("calculate"),
            r#"
var nodes = $record.FIELD.nodes;
if (nodes.length !== 0) {
  throw new Error("expected nodes.length == 0, got " + nodes.length);
}
// item() on an empty null-sentinel NodeList returns a chainable null handle (not
// native null) so callers can safely do .item(0).value without TypeError.
var itemVal = nodes.item(0).value;
if (itemVal !== null) {
  throw new Error("expected nodes.item(0).value == null, got " + itemVal);
}
"#,
        )
        .expect("WP-3 null_record_returns_empty_nodelist: $record.FIELD.nodes must be empty and chainable");
    }

    // WP-3 F3: xfa.validate is a no-op viewer stub absorbing writes silently.
    // Adobe-generated initialize scripts call `xfa.validate.override = 0`,
    // `xfa.validate.max = N`, `xfa.validate.scriptTest.message = "…"`; without
    // the stub these throw "Cannot set property X of undefined" because
    // `xfa.validate` was previously not defined on the host xfa object.
    #[test]
    fn xfa_validate_stub_absorbs_writes_silently() {
        let mut rt = fresh_runtime();
        rt.execute_script(
            Some("initialize"),
            r#"
xfa.validate.override = 0;
xfa.validate.max = 5;
xfa.validate.messageMode = "warning";
xfa.validate.scriptTest.message = "ignored";
xfa.validate.scriptTest.nested.deeper = true;
// Reads must return harmless defaults, never throw.
if (xfa.validate.override !== 0) throw new Error("override default");
if (xfa.validate.max !== 0) throw new Error("max default");
if (xfa.validate.messageMode !== "") throw new Error("messageMode default");
"#,
        )
        .expect("WP-3 F3 xfa_validate_stub: writes must absorb and reads must not throw");
    }

    // WP-3 F3: addInstance failure returns chainable sentinel so common
    // pattern `parent._Child.addInstance().rawValue = X` does not throw when
    // the instance manager refuses (occur/max bounds reached or unbound).
    // Note: this test exercises only the JS-side null-safety contract; full
    // end-to-end instance addition lives in m3b_phaseD_instance_manager.rs.
    #[test]
    fn add_instance_failure_returns_chainable_null_handle() {
        let mut rt = fresh_runtime();
        // No FormTree is installed, so any addInstance call must fail at the
        // host shim and surface a sentinel rather than native null.
        rt.execute_script(
            Some("initialize"),
            r#"
// Resolve a non-existent subform, addInstance() on an unbound instance
// manager must yield a chainable handle whose `.index` is a number and
// whose `.rawValue` setter is silent.
var im = xfa.resolveNode("NoSuchSubform");
if (im !== null) {
  // If a real handle was returned (shouldn't be), addInstance still must
  // either return a real handle or a null-safe sentinel — never throw.
  var added = im.addInstance();
  if (typeof added.index !== "number") {
    throw new Error("added.index must be a number, got " + typeof added.index);
  }
  added.rawValue = "chained";  // silent on sentinel
  added.value = "chained";     // silent on sentinel
}
"#,
        )
        .expect("WP-3 F3 add_instance_failure: chainable sentinel on failure path");
    }
}