Skip to main content

pdf_xfa/
dynamic.rs

1// Copyright (c) 2026 Innovation Trigger B.V.
2//
3// PDFluent is available under two licences, at your option: the GNU AGPLv3, or
4// the PDFluent Commercial Licence. See the LICENSE file in this repository --
5// that file travels with the copy you received, which a URL does not.
6
7use std::collections::HashMap;
8
9use crate::error::{Result, XfaError};
10use crate::javascript_policy::{self, JavaScriptEntryPoint};
11use crate::js_runtime::{
12    activity_allowed_for_sandbox_with_gate, presave_during_flatten_enabled, NullRuntime,
13    RuntimeMetadata, SandboxError, XfaJsRuntime,
14};
15use formcalc_interpreter::{
16    interpreter::Interpreter, lexer::tokenize, parser, som_bridge::SomResolver,
17    value::Value as FormCalcValue,
18};
19use xfa_dom_resolver::som::{parse_som, SomExpression, SomIndex, SomRoot, SomSelector};
20use xfa_layout_engine::form::{
21    EventScript, FormNodeId, FormNodeType, FormTree, GroupKind, Presence, ScriptLanguage,
22};
23
24// XFA Spec 3.3 §9.3 — Dynamic Forms Re-Layout: after script execution the
25// layout processor must re-run layout.  The spec does not prescribe a fixed
26// pass limit; Adobe typically converges in 2-3 passes.  Our limit of 3 is a
27// pragmatic cap that matches observed Adobe behavior.
28const MAX_SCRIPT_PASSES: usize = 3;
29
30/// Controls only the pre-flight handling of parsed JavaScript-bearing XFA
31/// event hooks. JavaScript execution remains denied by `javascript_policy`.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub enum JsExecutionMode {
34    /// Abort before script execution when any JavaScript or unsupported script
35    /// language is present. This preserves the original policy-gate behavior.
36    Strict,
37    /// Skip JavaScript and unsupported-language scripts, then continue running
38    /// FormCalc and the layout pipeline. Skipped scripts are reported in the
39    /// returned outcome.
40    #[default]
41    BestEffortStatic,
42    /// **M3-B Phase B opt-in.** Route JavaScript scripts through the sandboxed
43    /// runtime adapter (`crate::js_runtime`). Requires the Cargo feature
44    /// `xfa-js-sandboxed` to be compiled in for any script to actually
45    /// execute; without the feature the runtime returns
46    /// [`SandboxError::NotCompiledIn`] and the dispatch path falls back to
47    /// the same skip behaviour as [`Self::BestEffortStatic`] while incrementing
48    /// `js_runtime_errors` so callers can observe the dead-code state.
49    /// Phase B registers no host bindings; see
50    /// `benchmarks/runs/M3B_HOST_BINDINGS_MINIMUM_SET.md` for the Phase C
51    /// roadmap.
52    SandboxedRuntime,
53}
54/// Fidelity level of the flattened output relative to the source XFA data.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum OutputQuality {
57    /// All data was bound and rendered without skipping any scripts or content.
58    #[default]
59    Exact,
60    /// Some scripts were skipped (e.g. JavaScript with `BestEffortStatic` mode);
61    /// output may differ from a full Adobe Reader render.
62    BestEffort,
63    /// All JavaScript scripts on the document executed inside the sandbox
64    /// without runtime / timeout / OOM errors (requires `xfa-js-sandboxed` feature).
65    Sandboxed,
66}
67
68impl OutputQuality {
69    /// Return a short lowercase string label suitable for logging and metrics.
70    pub fn as_str(self) -> &'static str {
71        match self {
72            Self::Exact => "exact",
73            Self::BestEffort => "best_effort",
74            Self::Sandboxed => "sandboxed",
75        }
76    }
77}
78/// Aggregate outcome of the dynamic script processing pass.
79///
80/// Returned by [`flatten_xfa_to_pdf_with_metadata`](crate::flatten_xfa_to_pdf_with_metadata)
81/// and embedded in [`FlattenMetadata`](crate::FlattenMetadata).
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct DynamicScriptOutcome {
84    /// Number of form field values that were mutated by scripts.
85    pub changes: usize,
86    /// True when the document contains at least one JavaScript event hook.
87    pub js_present: bool,
88    /// Number of JavaScript scripts that were skipped (not executed).
89    pub js_skipped: usize,
90    /// Number of scripts in unsupported languages (not FormCalc, not JavaScript) skipped.
91    pub other_skipped: usize,
92    /// Number of FormCalc scripts that ran successfully.
93    pub formcalc_run: usize,
94    /// Number of FormCalc scripts that produced an error.
95    pub formcalc_errors: usize,
96    /// Overall output quality after script processing.
97    pub output_quality: OutputQuality,
98    /// **M3-B Phase B.** Scripts that ran to completion in the sandboxed
99    /// runtime. Always 0 when mode != [`JsExecutionMode::SandboxedRuntime`]
100    /// or when the `xfa-js-sandboxed` feature is not compiled in.
101    pub js_executed: usize,
102    /// **M3-B Phase B.** Sandbox errors that did not fall under timeout / OOM
103    /// (parse error, throw, missing host binding in Phase B, FFI panic). The
104    /// dispatch path treats these as a script skip; the parent flatten never
105    /// aborts because of them (S-17 fail-open).
106    pub js_runtime_errors: usize,
107    /// **M3-B Phase B.** Per-script time-budget exhaustions.
108    pub js_timeouts: usize,
109    /// **M3-B Phase B.** Per-document memory-budget exhaustions.
110    pub js_oom: usize,
111    /// **M3-B Phase C.** Host-binding invocations.
112    pub js_host_calls: usize,
113    /// **M3-B Phase C.** Successful host-side `field.rawValue` writes.
114    pub js_mutations: usize,
115    /// **M3-B Phase D.** Successful host-side instanceManager writes.
116    pub js_instance_writes: usize,
117    /// **M3-B Phase D-β.** Successful host-side listbox clearItems / addItem writes.
118    pub js_list_writes: usize,
119    /// **M3-B Phase C.** Binding-level failures.
120    pub js_binding_errors: usize,
121    /// **M3-B Phase C.** SOM resolution misses / failures.
122    pub js_resolve_failures: usize,
123    /// **M3-B Phase D-γ.** Successful DataDom reads (children / value / child-by-name).
124    pub js_data_reads: usize,
125    /// **M3-B Phase E (XFA-JS-HOST-STUBS).** Scripts touched a host capability
126    /// that requires real viewer / user interaction (UI dialogs, signature,
127    /// submit, openList, beep, ...). The stub returned a deterministic safe
128    /// default so the script kept running; this counter records how often
129    /// such a touch happened so callers can distinguish "would-have-been
130    /// interactive" from genuine runtime errors.
131    pub js_unsupported_host_calls: usize,
132    /// **M3-B Phase D-θ.2.** Strict probe calls skipped because
133    /// `parentIds.length == 1 && chain.length == 1` (no same-name
134    /// sibling ambiguity possible). Each skipped call saves one
135    /// `resolveWithFullChainStrict` host round-trip.
136    pub js_probe_skips: usize,
137    /// **D3 (trace-only).** `<variables>` `<script>` objects collected.
138    pub variables_scripts_collected: usize,
139    /// **D3 (trace-only).** `<variables>` `<text>` data items collected.
140    pub variables_data_items_collected: usize,
141    /// **D3 (trace-only).** Script objects / data items whose registration
142    /// bound a namespace (JS-side `setVariables*` returned success).
143    pub script_objects_registered: usize,
144    /// **D3 (trace-only).** Script objects / data items that did NOT register
145    /// (Rust skip or JS-side eval failure). Observability only.
146    pub script_objects_register_failed: usize,
147    /// **D3 (trace-only).** Script objects collected under a nested subform
148    /// scope (registered to `subformVariables` only — not bare-ident visible).
149    pub script_objects_subform_scoped: usize,
150    /// **D4.** Total SOM lookups at the host resolve boundary.
151    pub som_lookups_total: usize,
152    /// **D4.** SOM lookups that resolved.
153    pub som_lookup_successes: usize,
154    /// **D4.** SOM lookups that returned NoMatch.
155    pub som_lookup_failures: usize,
156    /// **D4.** Subform-script names withheld for ambiguity (fail-closed).
157    pub som_lookup_ambiguous: usize,
158    /// **D4.** Subform-scoped script objects exposed to bare-identifier lookup.
159    pub som_subform_scripts_exposed: usize,
160    /// **D4 (trace-only).** `occur`-path SOM references (classified, not resolved).
161    pub som_occur_path_refs: usize,
162    /// **D5.** `node.occur` handle accesses (successes + failures).
163    pub occur_lookups_total: usize,
164    /// **D5.** `node.occur` accesses where the node handle was live.
165    pub occur_lookup_successes: usize,
166    /// **D5.** `node.occur` accesses where the node handle was not live.
167    pub occur_lookup_failures: usize,
168    /// **D5.** Reads of an occur property (`min`/`max`/`initial`).
169    pub occur_property_reads: usize,
170    /// **D5.** Writes to an occur property (captured, not applied).
171    pub occur_property_writes: usize,
172    /// **D5.** Writes specifically to `occur.min`.
173    pub occur_min_writes: usize,
174    /// **D5.** Writes specifically to `occur.max`.
175    pub occur_max_writes: usize,
176    /// **D5.** Occur mutations captured as intent (no layout effect).
177    pub occur_mutations_captured: usize,
178    /// **D5/D6.** Occur mutations APPLIED to layout (D5: 0; D6: >0 under `XFA_OCCUR_APPLY`).
179    pub occur_mutations_applied: usize,
180    /// **D6.** Captured occur mutations not applied (gate off / rollback / unsupported).
181    pub occur_mutations_skipped: usize,
182    /// **D6.** Captured occur mutations skipped because the target is not a
183    /// repeatable container (fail-closed).
184    pub occur_application_ambiguous: usize,
185    /// **D6.** Distinct nodes whose occur was applied.
186    pub occur_application_targets: usize,
187    /// **D7.** Presence retry was active (sandboxed + both flags + no rollback).
188    pub presence_retry_enabled: bool,
189    /// **D7.** Hidden/invisible/inactive nodes considered under occur targets.
190    pub presence_retry_candidates: usize,
191    /// **D7.** Nodes admitted (Hidden/Invisible -> Visible).
192    pub presence_retry_admitted: usize,
193    /// **D7.** Candidates skipped (e.g. Inactive, fail-closed).
194    pub presence_retry_skipped: usize,
195    /// **D7.** Total nodes under admitted subtrees (recovery breadth).
196    pub presence_retry_nodes_under_admitted: usize,
197    /// **D7.** Field/draw nodes under admitted subtrees.
198    pub presence_retry_text_nodes_admitted: usize,
199
200    // ---- Epic A: runtime observability enrichment (XFA_FLATTEN_TRACE / XFA_RUNTIME_DIAG) ----
201    /// **E-1 (XFA_FLATTEN_TRACE).** Per-script lifecycle entries (capped at 500).
202    /// Each entry records the script index, host node id/name, activity, language,
203    /// and outcome (executed|skipped_activity|skipped_mode|error|timeout).
204    pub script_lifecycle: Vec<ScriptLifecycleEntry>,
205
206    /// **E-6 (XFA_FLATTEN_TRACE).** Per-activity tally of JS scripts that were
207    /// skipped (not routed through the sandbox).
208    pub skipped_activities: SkippedActivities,
209
210    /// **E-2 (XFA_RUNTIME_DIAG).** SOM resolution misses logged at the host-binding
211    /// boundary. Capped at 200 entries.
212    pub som_fail_log: Vec<SomFailEntry>,
213
214    /// **E-3 (XFA_RUNTIME_DIAG).** Per-write instanceManager mutation log (capped at 200).
215    pub instance_write_log: Vec<InstanceWriteEntry>,
216
217    /// **E-4 (XFA_RUNTIME_DIAG).** Presence mutations observed during FormCalc
218    /// script execution (capped at 200). JS-side presence writes go through the
219    /// host binding; FormCalc goes through `set_presence` in dynamic.rs — this
220    /// captures the FormCalc path.
221    pub presence_mutation_log: Vec<PresenceMutationEntry>,
222
223    /// **E-5 (XFA_FLATTEN_TRACE).** Number of named subforms hidden by
224    /// `apply_form_dom_presence` because they had no matching form-DOM entry.
225    pub form_dom_match_failures: usize,
226
227    /// **E-5 (XFA_RUNTIME_DIAG).** Per-suppression entries from
228    /// `apply_form_dom_presence` (capped at 200).
229    pub form_dom_match_log: Vec<FormDomMatchEntry>,
230}
231
232// ---- Epic A support types ----
233
234/// E-1: one entry in `script.lifecycle[]`.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct ScriptLifecycleEntry {
237    /// Zero-based index of this script in document execution order.
238    pub script_idx: usize,
239    /// FormNodeId that owns the script.
240    pub node_id: usize,
241    /// `name` attribute of the owning node (may be empty).
242    pub node_name: String,
243    /// `activity` attribute of the event element (e.g. `"initialize"`), or empty.
244    pub activity: String,
245    /// Script language.
246    pub lang: &'static str,
247    /// Execution outcome.
248    pub outcome: &'static str,
249}
250
251/// E-6: per-activity skip tallies for JavaScript scripts.
252#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
253pub struct SkippedActivities {
254    /// Scripts with `activity="initialize"` skipped.
255    pub initialize: usize,
256    /// Scripts with `activity="calculate"` skipped.
257    pub calculate: usize,
258    /// Scripts with `activity="click"` skipped.
259    pub click: usize,
260    /// Scripts with `activity="docReady"` skipped.
261    pub doc_ready: usize,
262    /// Scripts with `activity="layoutReady"` skipped.
263    pub layout_ready: usize,
264    /// Scripts with any other (or absent) activity attribute skipped.
265    pub other: usize,
266}
267
268impl SkippedActivities {
269    fn bump(&mut self, activity: Option<&str>) {
270        match activity {
271            Some("initialize") => self.initialize += 1,
272            Some("calculate") => self.calculate += 1,
273            Some("click") => self.click += 1,
274            Some("docReady") => self.doc_ready += 1,
275            Some("layoutReady") => self.layout_ready += 1,
276            _ => self.other += 1,
277        }
278    }
279}
280
281/// E-2: one SOM-miss entry.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct SomFailEntry {
284    /// The SOM path that failed to resolve.
285    pub path: String,
286    /// Miss category (e.g. `"resolve_miss"`, `"formcalc_miss"`).
287    pub kind: String,
288    /// Script index (matches `ScriptLifecycleEntry::script_idx`).
289    pub script_idx: usize,
290    /// Activity at the time of the miss.
291    pub activity: String,
292}
293
294/// E-3: one instanceManager write entry.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct InstanceWriteEntry {
297    /// Script index.
298    pub script_idx: usize,
299    /// Activity.
300    pub activity: String,
301    /// Parent container node id.
302    pub parent_node_id: usize,
303    /// Parent container node name.
304    pub parent_node_name: String,
305    /// Prototype node name (the repeated child template).
306    pub prototype_node_name: String,
307    /// Instance count before the write.
308    pub old_count: usize,
309    /// Instance count after the write.
310    pub new_count: usize,
311}
312
313/// E-4: one presence-mutation observation.
314#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct PresenceMutationEntry {
316    /// Script index at mutation time (best-effort; may be 0 for FormCalc).
317    pub script_idx: usize,
318    /// Activity at mutation time.
319    pub activity: String,
320    /// Node id.
321    pub node_id: usize,
322    /// Node name.
323    pub node_name: String,
324    /// Presence before the change.
325    pub old_presence: String,
326    /// Presence after the change.
327    pub new_presence: String,
328}
329
330/// E-5: one form-DOM match-failure / suppression entry.
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub struct FormDomMatchEntry {
333    /// Template FormNodeId of the hidden subform.
334    pub template_node_id: usize,
335    /// Name of the suppressed subform.
336    pub template_node_name: String,
337    /// Short reason string.
338    pub reason: String,
339}
340
341impl Default for DynamicScriptOutcome {
342    fn default() -> Self {
343        Self {
344            changes: 0,
345            js_present: false,
346            js_skipped: 0,
347            other_skipped: 0,
348            formcalc_run: 0,
349            formcalc_errors: 0,
350            output_quality: OutputQuality::Exact,
351            js_executed: 0,
352            js_runtime_errors: 0,
353            js_timeouts: 0,
354            js_oom: 0,
355            js_host_calls: 0,
356            js_mutations: 0,
357            js_instance_writes: 0,
358            js_list_writes: 0,
359            js_binding_errors: 0,
360            js_resolve_failures: 0,
361            js_data_reads: 0,
362            js_unsupported_host_calls: 0,
363            js_probe_skips: 0,
364            variables_scripts_collected: 0,
365            variables_data_items_collected: 0,
366            script_objects_registered: 0,
367            script_objects_register_failed: 0,
368            script_objects_subform_scoped: 0,
369            som_lookups_total: 0,
370            som_lookup_successes: 0,
371            som_lookup_failures: 0,
372            som_lookup_ambiguous: 0,
373            som_subform_scripts_exposed: 0,
374            som_occur_path_refs: 0,
375            occur_lookups_total: 0,
376            occur_lookup_successes: 0,
377            occur_lookup_failures: 0,
378            occur_property_reads: 0,
379            occur_property_writes: 0,
380            occur_min_writes: 0,
381            occur_max_writes: 0,
382            occur_mutations_captured: 0,
383            occur_mutations_applied: 0,
384            occur_mutations_skipped: 0,
385            occur_application_ambiguous: 0,
386            occur_application_targets: 0,
387            presence_retry_enabled: false,
388            presence_retry_candidates: 0,
389            presence_retry_admitted: 0,
390            presence_retry_skipped: 0,
391            presence_retry_nodes_under_admitted: 0,
392            presence_retry_text_nodes_admitted: 0,
393            script_lifecycle: Vec::new(),
394            skipped_activities: SkippedActivities::default(),
395            som_fail_log: Vec::new(),
396            instance_write_log: Vec::new(),
397            presence_mutation_log: Vec::new(),
398            form_dom_match_failures: 0,
399            form_dom_match_log: Vec::new(),
400        }
401    }
402}
403
404/// Snapshot of field values, presence states, and structural shape used for
405/// rollback after a failed script pass.
406///
407/// XFA-INST-MGR (2026-05-17): the snapshot now also captures every node's
408/// children list plus the total node count. When `restore_snapshot` runs it
409/// truncates any clones added by `instanceManager.addInstance` /
410/// `setInstances` and restores the original child ordering, so a rollback is
411/// structurally consistent end-to-end — not just at the field-value layer.
412/// This keeps the layout pass from seeing half-applied script mutations when
413/// scripts produced enough errors to invalidate the pass.
414///
415/// NOTE: The rollback policy itself is our own heuristic — the XFA spec does
416/// not define one. It protects against scripts that blank out all fields
417/// (broken SOM resolution, etc.) or that add structural clones we cannot
418/// safely keep after rejecting the pass.
419struct FormSnapshot {
420    field_values: Vec<(usize, String)>,
421    presences: Vec<(usize, Presence)>,
422    /// Per-node children list at snapshot time.  Indexed by `form.nodes`
423    /// position; `children[i]` is the saved `children` vec for node `i`.
424    children: Vec<Vec<FormNodeId>>,
425    /// Total node count at snapshot time.  On rollback `form.nodes` and
426    /// `form.metadata` are truncated back to this length, evicting any
427    /// runtime-created clones from the form tree.
428    node_count: usize,
429    populated_count: usize,
430}
431
432fn snapshot_form(form: &FormTree) -> FormSnapshot {
433    let mut field_values = Vec::new();
434    let mut presences = Vec::new();
435    let mut children = Vec::with_capacity(form.nodes.len());
436    let mut populated_count = 0usize;
437    for (idx, node) in form.nodes.iter().enumerate() {
438        if let FormNodeType::Field { value } = &node.node_type {
439            field_values.push((idx, value.clone()));
440            if !value.trim().is_empty() {
441                populated_count += 1;
442            }
443        }
444        presences.push((idx, form.metadata[idx].presence));
445        children.push(node.children.clone());
446    }
447    FormSnapshot {
448        field_values,
449        presences,
450        children,
451        node_count: form.nodes.len(),
452        populated_count,
453    }
454}
455
456fn restore_snapshot(form: &mut FormTree, snapshot: &FormSnapshot) {
457    for (idx, value) in &snapshot.field_values {
458        if let FormNodeType::Field { value: fv } = &mut form.nodes[*idx].node_type {
459            *fv = value.clone();
460        }
461    }
462    for (idx, presence) in &snapshot.presences {
463        form.metadata[*idx].presence = *presence;
464    }
465    // XFA-INST-MGR: drop any runtime-created clones first, THEN restore the
466    // original children lists.  Truncating must happen before assignment
467    // because the saved children vec may reference indices that the snapshot
468    // already covers (clones never receive an `xfa_id`, so `node_ids` does
469    // not need pruning — see `host::clone_subtree`).
470    if form.nodes.len() > snapshot.node_count {
471        form.nodes.truncate(snapshot.node_count);
472        form.metadata.truncate(snapshot.node_count);
473    }
474    for (idx, saved_children) in snapshot.children.iter().enumerate() {
475        if let Some(node) = form.nodes.get_mut(idx) {
476            node.children = saved_children.clone();
477        }
478    }
479}
480
481fn should_rollback(
482    form: &FormTree,
483    snapshot: &FormSnapshot,
484    errors: usize,
485    successes: usize,
486) -> bool {
487    if errors > 0 && errors > successes {
488        return true;
489    }
490    if snapshot.populated_count >= 2 {
491        let mut now_empty = 0usize;
492        for (idx, old_value) in &snapshot.field_values {
493            if old_value.trim().is_empty() {
494                continue;
495            }
496            if let FormNodeType::Field { value } = &form.nodes[*idx].node_type {
497                if value.trim().is_empty() {
498                    now_empty += 1;
499                }
500            }
501        }
502        if now_empty * 2 > snapshot.populated_count {
503            return true;
504        }
505    }
506    false
507}
508// XFA Spec 3.3 §9.3 — Dynamic Forms: after data binding, scripts run in
509// two phases: (1) initialize events fire once, (2) calculate events may
510// iterate until stable (convergence) or MAX_SCRIPT_PASSES is reached.
511// The spec (§14.3.2) defines the event model; our implementation runs
512// initialize then calculate, matching Adobe's processing order.
513//
514// NOTE: §10.6 Rule 3 states the merge-completion order as:
515//   value calcs → property calcs → validations → initialize events.
516// Our order (initialize first) differs from the spec but matches Adobe's
517// observed behavior on our 20K test corpus (97%+ SSIM). §28.2 (p1231)
518// documents Adobe's event execution insert-at-position-2 algorithm.
519//
520// The default JavaScript handling is best-effort static flattening: parsed
521// JavaScript and unsupported-language scripts are skipped and reported, while
522// FormCalc continues to run. Use `apply_dynamic_scripts_with_mode(..., Strict)`
523// when callers need the legacy whole-form JavaScript policy gate.
524
525/// Convenience entry point: runs the script pipeline with the default
526/// [`JsExecutionMode`] (currently [`JsExecutionMode::BestEffortStatic`]).
527///
528/// Prefer [`apply_dynamic_scripts_with_runtime`] when you need explicit
529/// runtime injection (e.g. in tests or when using the sandboxed runtime).
530#[doc(hidden)]
531pub fn apply_dynamic_scripts(
532    form: &mut FormTree,
533    root_id: FormNodeId,
534) -> Result<DynamicScriptOutcome> {
535    apply_dynamic_scripts_with_mode(form, root_id, JsExecutionMode::default())
536}
537
538/// Runs the script pipeline with an explicit [`JsExecutionMode`], using the
539/// internal [`NullRuntime`] (or the compiled-in QuickJS runtime for
540/// [`JsExecutionMode::SandboxedRuntime`]).
541///
542/// This is an intermediate convenience wrapper. The canonical low-level entry
543/// point is [`apply_dynamic_scripts_with_runtime`], which accepts any
544/// [`XfaJsRuntime`] implementation.
545#[doc(hidden)]
546pub fn apply_dynamic_scripts_with_mode(
547    form: &mut FormTree,
548    root_id: FormNodeId,
549    mode: JsExecutionMode,
550) -> Result<DynamicScriptOutcome> {
551    // M3-B Phase C-α (2026-05-03): when the caller asks for SandboxedRuntime
552    // and the `xfa-js-sandboxed` feature is compiled in, instantiate the
553    // real QuickJS-backed adapter. Without the feature, fall back to
554    // NullRuntime which surfaces `SandboxError::NotCompiledIn` per script
555    // (existing Phase B fallback semantics).
556    #[cfg(feature = "xfa-js-sandboxed")]
557    {
558        if mode == JsExecutionMode::SandboxedRuntime {
559            match crate::js_runtime::QuickJsRuntime::new() {
560                Ok(mut rt) => {
561                    return apply_dynamic_scripts_with_runtime(form, root_id, mode, &mut rt);
562                }
563                Err(_e) => {
564                    // QuickJS init failure is rare; fall through to NullRuntime
565                    // so the dispatch path can still record per-script errors
566                    // and the flatten succeeds in best-effort mode.
567                }
568            }
569        }
570    }
571    apply_dynamic_scripts_with_runtime(form, root_id, mode, &mut NullRuntime::new())
572}
573
574/// D6: opt-in gate for applying captured `occur.min` mutations to layout.
575/// Default OFF. Even in sandboxed mode, occur application only happens when
576/// `XFA_OCCUR_APPLY=1`, so the committed default (and default sandboxed
577/// capture-only) behaviour is unchanged.
578fn occur_apply_enabled() -> bool {
579    std::env::var("XFA_OCCUR_APPLY").ok().as_deref() == Some("1")
580}
581
582/// D7: opt-in gate for presence/visibility retry. Default OFF. Requires
583/// `XFA_PRESENCE_RETRY=1`; the dispatch path additionally requires
584/// `XFA_OCCUR_APPLY=1` (occur application is the prerequisite for the retry).
585fn presence_retry_enabled() -> bool {
586    std::env::var("XFA_PRESENCE_RETRY").ok().as_deref() == Some("1")
587}
588
589/// Epic A: true when `XFA_RUNTIME_DIAG` is set to `"1"`.  Gates the verbose
590/// per-entry log arrays (E-2, E-3, E-4, E-5-log).  Default OFF so normal
591/// flattens are byte-identical and zero-cost.
592pub(crate) fn runtime_diag_enabled() -> bool {
593    std::env::var("XFA_RUNTIME_DIAG").ok().as_deref() == Some("1")
594}
595
596// Epic A E-4: thread-local accumulator for FormCalc presence mutations.
597// Active only during `apply_dynamic_scripts_with_runtime` when
598// `XFA_RUNTIME_DIAG=1`.  Using thread-local avoids threading an extra Vec
599// through `run_script_phase` / `write_formcalc_value` / `set_presence`.
600std::thread_local! {
601    static PRESENCE_MUT_LOG: std::cell::RefCell<Option<Vec<PresenceMutationEntry>>> =
602        const { std::cell::RefCell::new(None) };
603}
604
605/// Push a presence mutation entry into the thread-local log.
606/// Called from `set_presence_inner` when an entry was created.
607fn push_presence_mutation(
608    node_id: usize,
609    node_name: &str,
610    old_presence: &'static str,
611    new_presence: &'static str,
612) {
613    PRESENCE_MUT_LOG.with(|cell| {
614        if let Some(ref mut log) = *cell.borrow_mut() {
615            if log.len() < 200 {
616                log.push(PresenceMutationEntry {
617                    // script_idx/activity are not readily available at this call
618                    // depth — report 0/"" (best-effort per Epic A spec note).
619                    script_idx: 0,
620                    activity: String::new(),
621                    node_id,
622                    node_name: node_name.to_string(),
623                    old_presence: old_presence.to_string(),
624                    new_presence: new_presence.to_string(),
625                });
626            }
627        }
628    });
629}
630
631/// Phase B entry point that lets the caller inject a sandboxed runtime
632/// adapter. When `mode == JsExecutionMode::SandboxedRuntime` the supplied
633/// `runtime` is consulted for every JavaScript script whose `<event activity>`
634/// is in [`crate::js_runtime::SANDBOX_ACTIVITY_ALLOWLIST`]. UI / submission
635/// activities skip the runtime entirely and are recorded as `js_skipped`,
636/// matching `BestEffortStatic` behaviour for those scripts.
637///
638/// Other modes ignore `runtime` entirely; callers that just need the
639/// existing strict / best-effort behaviour should use
640/// [`apply_dynamic_scripts_with_mode`] (which routes through
641/// [`crate::js_runtime::NullRuntime`]).
642pub fn apply_dynamic_scripts_with_runtime(
643    form: &mut FormTree,
644    root_id: FormNodeId,
645    mode: JsExecutionMode,
646    runtime: &mut dyn XfaJsRuntime,
647) -> Result<DynamicScriptOutcome> {
648    let parents = build_parent_map(form, root_id);
649    let all_scripts: Vec<(FormNodeId, Vec<EventScript>)> = form
650        .nodes
651        .iter()
652        .enumerate()
653        .filter_map(|(idx, _)| {
654            let node_id = FormNodeId(idx);
655            let scripts = form.meta(node_id).event_scripts.clone();
656            (!scripts.is_empty()).then_some((node_id, scripts))
657        })
658        .collect();
659
660    let has_unsupported_script = all_scripts.iter().any(|(_, node_scripts)| {
661        node_scripts
662            .iter()
663            .any(|script| script.language != ScriptLanguage::FormCalc)
664    });
665
666    if mode == JsExecutionMode::Strict && has_unsupported_script {
667        return Err(javascript_policy::reject_execution(
668            JavaScriptEntryPoint::XfaEventHook,
669        ));
670    }
671
672    let mut js_skipped = 0usize;
673    let mut other_skipped = 0usize;
674    let mut sandbox_metadata = RuntimeMetadata::default();
675    let mut scripts = Vec::new();
676    let sandbox_active = mode == JsExecutionMode::SandboxedRuntime;
677    let snapshot = snapshot_form(form);
678
679    // D1.B (XFA Product Quality Wave 3 — preSave gated allow). The env-var
680    // gate is read ONCE per flatten so all scripts in this document see the
681    // same decision. Default OFF; flipping requires
682    // `XFA_PRESAVE_DURING_FLATTEN=1`. The host-binding layer is informed via
683    // `set_presave_gate` so dispatch and host stay in lock-step (defence-
684    // in-depth §2 of the policy doc).
685    let presave_gate = sandbox_active && presave_during_flatten_enabled();
686
687    // Epic A E-1/E-6: read gates once; zero cost unless env is set.
688    let trace_enabled = crate::flatten_trace::enabled();
689    let diag_enabled = runtime_diag_enabled();
690
691    // E-1: lifecycle log (cap 500).
692    let mut script_lifecycle: Vec<ScriptLifecycleEntry> = Vec::new();
693    // E-6: per-activity skip tally.
694    let mut skipped_activities = SkippedActivities::default();
695    // Running script index (mirrors host.rs next_script_idx for JS; for
696    // FormCalc scripts we share the same monotonic counter).
697    let mut dispatch_script_idx: usize = 0;
698
699    if sandbox_active {
700        // Best-effort init / reset; init failures are non-fatal — the
701        // dispatch path will record them as runtime_errors per script.
702        let _ = runtime.init();
703        let _ = runtime.reset_for_new_document();
704        let _ = runtime.set_form_handle(form as *mut FormTree, root_id);
705        runtime.set_presave_gate(presave_gate);
706    }
707
708    for (node_id, node_scripts) in all_scripts {
709        let node = form.get(node_id);
710        let node_name = if trace_enabled || diag_enabled {
711            node.name.clone()
712        } else {
713            String::new()
714        };
715        let mut formcalc_scripts = Vec::new();
716        for script in node_scripts {
717            match script.language {
718                ScriptLanguage::FormCalc => formcalc_scripts.push(script),
719                ScriptLanguage::JavaScript => {
720                    let activity_str = script.activity.as_deref().unwrap_or("");
721                    if sandbox_active
722                        && activity_allowed_for_sandbox_with_gate(
723                            script.activity.as_deref(),
724                            presave_gate,
725                        )
726                    {
727                        let this_idx = dispatch_script_idx;
728                        dispatch_script_idx += 1;
729                        let _ = runtime.reset_per_script(node_id, script.activity.as_deref());
730                        let outcome_str = match runtime
731                            .execute_script(script.activity.as_deref(), &script.script)
732                        {
733                            Ok(_) => {
734                                // Counter increment lives on `take_metadata()`.
735                                "executed"
736                            }
737                            Err(SandboxError::Timeout) => {
738                                js_skipped += 1;
739                                "timeout"
740                            }
741                            Err(SandboxError::OutOfMemory) => {
742                                js_skipped += 1;
743                                "error"
744                            }
745                            Err(e) => {
746                                // M3-B Phase C-α: surface the per-script error
747                                // class via `log::debug!` for normal builds and
748                                // also via stderr when `XFA_JS_DEBUG=1` is set
749                                // (operator triage aid; xfa-cli does not init
750                                // a logger that respects RUST_LOG).
751                                log::debug!(
752                                    "sandbox script error on activity={:?}: {}",
753                                    script.activity.as_deref(),
754                                    e
755                                );
756                                if std::env::var("XFA_JS_DEBUG").ok().as_deref() == Some("1") {
757                                    eprintln!(
758                                        "XFA_JS_DEBUG sandbox script error on activity={:?}: {}",
759                                        script.activity.as_deref(),
760                                        e
761                                    );
762                                }
763                                js_skipped += 1;
764                                "error"
765                            }
766                        };
767                        // E-1: record lifecycle entry when tracing is on.
768                        if trace_enabled && script_lifecycle.len() < 500 {
769                            script_lifecycle.push(ScriptLifecycleEntry {
770                                script_idx: this_idx,
771                                node_id: node_id.0,
772                                node_name: node_name.clone(),
773                                activity: activity_str.to_string(),
774                                lang: "javascript",
775                                outcome: outcome_str,
776                            });
777                        }
778                    } else {
779                        js_skipped += 1;
780                        // E-1: record skipped lifecycle entry.
781                        if trace_enabled && script_lifecycle.len() < 500 {
782                            let skip_reason = if sandbox_active {
783                                "skipped_activity"
784                            } else {
785                                "skipped_mode"
786                            };
787                            script_lifecycle.push(ScriptLifecycleEntry {
788                                script_idx: dispatch_script_idx,
789                                node_id: node_id.0,
790                                node_name: node_name.clone(),
791                                activity: activity_str.to_string(),
792                                lang: "javascript",
793                                outcome: skip_reason,
794                            });
795                        }
796                        // E-6: tally per-activity skips.
797                        if trace_enabled {
798                            skipped_activities.bump(script.activity.as_deref());
799                        }
800                        dispatch_script_idx += 1;
801                    }
802                }
803                ScriptLanguage::Other => {
804                    other_skipped += 1;
805                    // E-1: log other-language skips.
806                    if trace_enabled && script_lifecycle.len() < 500 {
807                        script_lifecycle.push(ScriptLifecycleEntry {
808                            script_idx: dispatch_script_idx,
809                            node_id: node_id.0,
810                            node_name: node_name.clone(),
811                            activity: script.activity.as_deref().unwrap_or("").to_string(),
812                            lang: "other",
813                            outcome: "skipped_mode",
814                        });
815                    }
816                    dispatch_script_idx += 1;
817                }
818            }
819        }
820        if !formcalc_scripts.is_empty() {
821            scripts.push((node_id, formcalc_scripts));
822        }
823    }
824
825    let mut captured_occur: Vec<(usize, String, i64)> = Vec::new();
826    // Epic A E-2/E-3: logs drained from host bindings.
827    let mut sandbox_diag = crate::js_runtime::RuntimeDiagLogs::default();
828    if sandbox_active {
829        let _ = runtime.set_form_handle(std::ptr::null_mut(), root_id);
830        sandbox_metadata = runtime.take_metadata();
831        captured_occur = runtime.take_occur_mutations();
832        if diag_enabled {
833            sandbox_diag = runtime.take_diag_logs();
834        }
835    }
836
837    let mut stats = ScriptStats::default();
838
839    // Epic A E-4: arm the thread-local presence mutation log.
840    if diag_enabled {
841        PRESENCE_MUT_LOG.with(|cell| {
842            *cell.borrow_mut() = Some(Vec::new());
843        });
844    }
845
846    let mut changes = sandbox_metadata
847        .mutations
848        .saturating_add(sandbox_metadata.instance_writes)
849        + run_script_phase(
850            form,
851            root_id,
852            &parents,
853            &scripts,
854            ScriptPhase::Initialize,
855            1,
856            &mut stats,
857        )?
858        + run_script_phase(
859            form,
860            root_id,
861            &parents,
862            &scripts,
863            ScriptPhase::Calculate,
864            MAX_SCRIPT_PASSES,
865            &mut stats,
866        )?;
867
868    // E-4: drain and disarm.
869    let presence_mutation_log = if diag_enabled {
870        PRESENCE_MUT_LOG.with(|cell| cell.borrow_mut().take().unwrap_or_default())
871    } else {
872        Vec::new()
873    };
874
875    let sandbox_rollback_errors = sandbox_metadata
876        .runtime_errors
877        .saturating_add(sandbox_metadata.timeouts)
878        .saturating_add(sandbox_metadata.oom)
879        .saturating_add(sandbox_metadata.binding_errors);
880    let rollback_errors = stats.errors.saturating_add(sandbox_rollback_errors);
881    let rollback_successes = stats.successes.saturating_add(sandbox_metadata.executed);
882
883    let rolled_back = should_rollback(form, &snapshot, rollback_errors, rollback_successes);
884    if rolled_back {
885        restore_snapshot(form, &snapshot);
886        changes = 0;
887    }
888
889    // D6: apply captured `occur.min` mutations to the form before layout.
890    // Strictly gated: sandboxed mode + the opt-in `XFA_OCCUR_APPLY=1` flag +
891    // the script pass did NOT roll back. Default flatten and the default
892    // sandboxed (capture-only) behaviour are unchanged. Each captured write is
893    // applied only to a live, repeatable container node (Subform/Area/ExclGroup);
894    // everything else fails closed (counted, not applied). `occur.max` writes
895    // are captured but not applied in D6 (min-only scope).
896    let mut occur_applied_targets: std::collections::HashSet<usize> =
897        std::collections::HashSet::new();
898    if sandbox_active && !rolled_back && occur_apply_enabled() && !captured_occur.is_empty() {
899        for (idx, prop, value) in &captured_occur {
900            if prop != "min" {
901                // occur.max captured but not applied in D6.
902                sandbox_metadata.occur_mutations_skipped =
903                    sandbox_metadata.occur_mutations_skipped.saturating_add(1);
904                continue;
905            }
906            if *value < 0 || *idx >= form.nodes.len() {
907                sandbox_metadata.occur_mutations_skipped =
908                    sandbox_metadata.occur_mutations_skipped.saturating_add(1);
909                continue;
910            }
911            let nid = FormNodeId(*idx);
912            let is_repeatable = matches!(
913                form.get(nid).node_type,
914                FormNodeType::Subform | FormNodeType::Area | FormNodeType::ExclGroup
915            );
916            if !is_repeatable {
917                // Fail closed: only repeatable containers may have occur applied.
918                sandbox_metadata.occur_application_ambiguous = sandbox_metadata
919                    .occur_application_ambiguous
920                    .saturating_add(1);
921                sandbox_metadata.occur_mutations_skipped =
922                    sandbox_metadata.occur_mutations_skipped.saturating_add(1);
923                continue;
924            }
925            let v = *value as u32;
926            let node = form.get_mut(nid);
927            node.occur.min = v;
928            if node.occur.initial < v {
929                node.occur.initial = v;
930            }
931            if let Some(m) = node.occur.max {
932                if m < v {
933                    node.occur.max = Some(v);
934                }
935            }
936            sandbox_metadata.occur_mutations_applied =
937                sandbox_metadata.occur_mutations_applied.saturating_add(1);
938            occur_applied_targets.insert(*idx);
939        }
940        sandbox_metadata.occur_application_targets = sandbox_metadata
941            .occur_application_targets
942            .saturating_add(occur_applied_targets.len());
943    } else if !captured_occur.is_empty() {
944        // Captured but the apply gate is closed (default capture-only path):
945        // count them as skipped for observability without touching layout.
946        sandbox_metadata.occur_mutations_skipped = sandbox_metadata
947            .occur_mutations_skipped
948            .saturating_add(captured_occur.len());
949    }
950
951    // D7: opt-in presence/visibility retry. Strictly gated: sandboxed +
952    // `XFA_PRESENCE_RETRY=1` + `XFA_OCCUR_APPLY=1` (occur application is the
953    // prerequisite) + no rollback. Admits (`Hidden`/`Invisible` -> `Visible`)
954    // ONLY nodes that are an occur-applied target or a descendant of one
955    // (occur-related, unambiguous). `Inactive` is skipped (fail-closed). Default
956    // and default-sandboxed behaviour are unchanged.
957    let mut pr_candidates = 0usize;
958    let mut pr_admitted = 0usize;
959    let mut pr_skipped = 0usize;
960    let mut pr_nodes_under_admitted = 0usize;
961    let mut pr_text_nodes_admitted = 0usize;
962    let presence_retry_active = sandbox_active
963        && !rolled_back
964        && occur_apply_enabled()
965        && presence_retry_enabled()
966        && !occur_applied_targets.is_empty();
967    if presence_retry_active {
968        let mut visited: std::collections::HashSet<usize> = std::collections::HashSet::new();
969        let mut stack: Vec<FormNodeId> = occur_applied_targets
970            .iter()
971            .map(|&i| FormNodeId(i))
972            .collect();
973        let mut admitted_ids: std::collections::HashSet<usize> = std::collections::HashSet::new();
974        while let Some(nid) = stack.pop() {
975            if nid.0 >= form.nodes.len() || !visited.insert(nid.0) {
976                continue;
977            }
978            let presence = form.meta(nid).presence;
979            if presence == Presence::Hidden || presence == Presence::Invisible {
980                pr_candidates += 1;
981                // Fail-closed safety: never un-hide `Inactive` (intentionally
982                // removed); only `Hidden`/`Invisible` are admitted here.
983                form.meta_mut(nid).presence = Presence::Visible;
984                pr_admitted += 1;
985                admitted_ids.insert(nid.0);
986            } else if presence == Presence::Inactive {
987                pr_candidates += 1;
988                pr_skipped += 1;
989            }
990            for &c in &form.get(nid).children {
991                stack.push(c);
992            }
993        }
994        // Count content under admitted subtrees (observability of recovery).
995        for &aid in &admitted_ids {
996            let mut s = vec![FormNodeId(aid)];
997            let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
998            while let Some(n) = s.pop() {
999                if n.0 >= form.nodes.len() || !seen.insert(n.0) {
1000                    continue;
1001                }
1002                pr_nodes_under_admitted += 1;
1003                if let FormNodeType::Draw(_) | FormNodeType::Field { .. } = form.get(n).node_type {
1004                    pr_text_nodes_admitted += 1;
1005                }
1006                for &c in &form.get(n).children {
1007                    s.push(c);
1008                }
1009            }
1010        }
1011    }
1012
1013    let js_seen_count = js_skipped + sandbox_metadata.executed;
1014    let js_present = js_seen_count > 0;
1015    let output_quality = if sandbox_active && js_present && sandbox_metadata.is_clean() {
1016        OutputQuality::Sandboxed
1017    } else if (sandbox_active && js_present) || js_skipped > 0 || other_skipped > 0 {
1018        OutputQuality::BestEffort
1019    } else {
1020        OutputQuality::Exact
1021    };
1022
1023    Ok(DynamicScriptOutcome {
1024        changes,
1025        js_present,
1026        js_skipped,
1027        other_skipped,
1028        formcalc_run: stats.formcalc_run,
1029        formcalc_errors: stats.formcalc_errors,
1030        output_quality,
1031        js_executed: sandbox_metadata.executed,
1032        js_runtime_errors: sandbox_metadata.runtime_errors,
1033        js_timeouts: sandbox_metadata.timeouts,
1034        js_oom: sandbox_metadata.oom,
1035        js_host_calls: sandbox_metadata.host_calls,
1036        js_mutations: sandbox_metadata.mutations,
1037        js_instance_writes: sandbox_metadata.instance_writes,
1038        js_list_writes: sandbox_metadata.list_writes,
1039        js_binding_errors: sandbox_metadata.binding_errors,
1040        js_resolve_failures: sandbox_metadata.resolve_failures,
1041        js_data_reads: sandbox_metadata.data_reads,
1042        js_unsupported_host_calls: sandbox_metadata.unsupported_host_calls,
1043        js_probe_skips: sandbox_metadata.probe_skips,
1044        variables_scripts_collected: sandbox_metadata.variables_scripts_collected,
1045        variables_data_items_collected: sandbox_metadata.variables_data_items_collected,
1046        script_objects_registered: sandbox_metadata.script_objects_registered,
1047        script_objects_register_failed: sandbox_metadata.script_objects_register_failed,
1048        script_objects_subform_scoped: sandbox_metadata.script_objects_subform_scoped,
1049        som_lookups_total: sandbox_metadata.som_lookups_total,
1050        som_lookup_successes: sandbox_metadata.som_lookup_successes,
1051        som_lookup_failures: sandbox_metadata.som_lookup_failures,
1052        som_lookup_ambiguous: sandbox_metadata.som_lookup_ambiguous,
1053        som_subform_scripts_exposed: sandbox_metadata.som_subform_scripts_exposed,
1054        som_occur_path_refs: sandbox_metadata.som_occur_path_refs,
1055        occur_lookups_total: sandbox_metadata.occur_lookups_total,
1056        occur_lookup_successes: sandbox_metadata.occur_lookup_successes,
1057        occur_lookup_failures: sandbox_metadata.occur_lookup_failures,
1058        occur_property_reads: sandbox_metadata.occur_property_reads,
1059        occur_property_writes: sandbox_metadata.occur_property_writes,
1060        occur_min_writes: sandbox_metadata.occur_min_writes,
1061        occur_max_writes: sandbox_metadata.occur_max_writes,
1062        occur_mutations_captured: sandbox_metadata.occur_mutations_captured,
1063        occur_mutations_applied: sandbox_metadata.occur_mutations_applied,
1064        occur_mutations_skipped: sandbox_metadata.occur_mutations_skipped,
1065        occur_application_ambiguous: sandbox_metadata.occur_application_ambiguous,
1066        occur_application_targets: sandbox_metadata.occur_application_targets,
1067        presence_retry_enabled: presence_retry_active,
1068        presence_retry_candidates: pr_candidates,
1069        presence_retry_admitted: pr_admitted,
1070        presence_retry_skipped: pr_skipped,
1071        presence_retry_nodes_under_admitted: pr_nodes_under_admitted,
1072        presence_retry_text_nodes_admitted: pr_text_nodes_admitted,
1073        // Epic A fields.
1074        script_lifecycle,
1075        skipped_activities,
1076        som_fail_log: sandbox_diag.som_fail_log,
1077        instance_write_log: sandbox_diag.instance_write_log,
1078        presence_mutation_log,
1079        form_dom_match_failures: 0,
1080        form_dom_match_log: Vec::new(),
1081    })
1082}
1083
1084fn has_hidden_ancestor(
1085    form: &FormTree,
1086    parents: &HashMap<FormNodeId, FormNodeId>,
1087    node_id: FormNodeId,
1088) -> bool {
1089    let mut cursor = parents.get(&node_id).copied();
1090    while let Some(ancestor) = cursor {
1091        if form.meta(ancestor).presence.is_not_visible() {
1092            return true;
1093        }
1094        cursor = parents.get(&ancestor).copied();
1095    }
1096    false
1097}
1098
1099#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1100enum ScriptPhase {
1101    Initialize,
1102    Calculate,
1103}
1104
1105#[derive(Default)]
1106struct ScriptStats {
1107    errors: usize,
1108    successes: usize,
1109    formcalc_run: usize,
1110    formcalc_errors: usize,
1111}
1112
1113#[derive(Debug)]
1114struct ScriptResult {
1115    changes: usize,
1116    error: bool,
1117}
1118
1119fn run_script_phase(
1120    form: &mut FormTree,
1121    root_id: FormNodeId,
1122    parents: &HashMap<FormNodeId, FormNodeId>,
1123    scripts: &[(FormNodeId, Vec<EventScript>)],
1124    phase: ScriptPhase,
1125    max_passes: usize,
1126    stats: &mut ScriptStats,
1127) -> Result<usize> {
1128    let mut total_changes = 0;
1129
1130    for _ in 0..max_passes {
1131        let mut pass_changes = 0;
1132
1133        for (node_id, node_scripts) in scripts {
1134            if has_hidden_ancestor(form, parents, *node_id) {
1135                continue;
1136            }
1137
1138            for script in node_scripts
1139                .iter()
1140                .filter(|script| should_run_script(script, phase))
1141            {
1142                let result = execute_event_script(form, root_id, parents, *node_id, script, phase)?;
1143                stats.formcalc_run += 1;
1144                if result.error {
1145                    stats.errors += 1;
1146                    stats.formcalc_errors += 1;
1147                } else {
1148                    stats.successes += 1;
1149                }
1150                pass_changes += result.changes;
1151            }
1152        }
1153
1154        total_changes += pass_changes;
1155        if pass_changes == 0 {
1156            break;
1157        }
1158    }
1159
1160    Ok(total_changes)
1161}
1162
1163fn should_run_script(script: &EventScript, phase: ScriptPhase) -> bool {
1164    match phase {
1165        ScriptPhase::Initialize => script.activity.as_deref() == Some("initialize"),
1166        ScriptPhase::Calculate => script.activity.as_deref() == Some("calculate"),
1167    }
1168}
1169
1170fn execute_event_script(
1171    form: &mut FormTree,
1172    root_id: FormNodeId,
1173    parents: &HashMap<FormNodeId, FormNodeId>,
1174    current_id: FormNodeId,
1175    script: &EventScript,
1176    phase: ScriptPhase,
1177) -> Result<ScriptResult> {
1178    match script.language {
1179        ScriptLanguage::FormCalc => Ok(execute_formcalc_script(
1180            form, root_id, parents, current_id, script, phase,
1181        )),
1182        ScriptLanguage::JavaScript => Err(javascript_policy::reject_execution(
1183            JavaScriptEntryPoint::XfaEventHook,
1184        )),
1185        ScriptLanguage::Other => Err(XfaError::UnsupportedFeature("script language".to_string())),
1186    }
1187}
1188
1189/// Emit a stderr line when `XFA_FORMCALC_DEBUG=1` is set so that residual-scan
1190/// tooling can aggregate FormCalc failures by stage (`lexer` / `parser` /
1191/// `interpreter`) and message. Off by default; emits nothing otherwise.
1192///
1193/// Mirrors the `XFA_JS_DEBUG` opt-in pattern used by the sandbox JS runtime.
1194fn formcalc_debug_emit(stage: &str, message: &str, script: &EventScript) {
1195    if std::env::var("XFA_FORMCALC_DEBUG").ok().as_deref() != Some("1") {
1196        return;
1197    }
1198    let activity = script.activity.as_deref().unwrap_or("?");
1199    // Single-line, double-quoted message so the scan script's regex can parse
1200    // it like `XFA_JS_DEBUG resolve_*` lines. Newlines collapsed defensively.
1201    let one_line = message.replace(['\n', '\r'], " ");
1202    eprintln!("XFA_FORMCALC_DEBUG stage={stage} activity=\"{activity}\" message=\"{one_line}\"");
1203}
1204
1205fn execute_formcalc_script(
1206    form: &mut FormTree,
1207    root_id: FormNodeId,
1208    parents: &HashMap<FormNodeId, FormNodeId>,
1209    current_id: FormNodeId,
1210    script: &EventScript,
1211    phase: ScriptPhase,
1212) -> ScriptResult {
1213    let tokens = match tokenize(&script.script) {
1214        Ok(t) => t,
1215        Err(err) => {
1216            formcalc_debug_emit("lexer", &format!("{err}"), script);
1217            return ScriptResult {
1218                changes: 0,
1219                error: true,
1220            };
1221        }
1222    };
1223    let ast = match parser::parse(tokens) {
1224        Ok(a) => a,
1225        Err(err) => {
1226            formcalc_debug_emit("parser", &format!("{err}"), script);
1227            return ScriptResult {
1228                changes: 0,
1229                error: true,
1230            };
1231        }
1232    };
1233
1234    let mut interpreter = Interpreter::new();
1235    let mut resolver = FormTreeSomResolver::new(form, root_id, parents, current_id);
1236    let result = match interpreter.exec_with_resolver(&ast, &mut resolver) {
1237        Ok(r) => r,
1238        Err(err) => {
1239            formcalc_debug_emit("interpreter", &format!("{err}"), script);
1240            return ScriptResult {
1241                changes: resolver.changes,
1242                error: true,
1243            };
1244        }
1245    };
1246
1247    if matches!(phase, ScriptPhase::Calculate) {
1248        resolver.changes += write_formcalc_value(
1249            resolver.form,
1250            current_id,
1251            ResolvedProperty::RawValue,
1252            result,
1253        );
1254    }
1255
1256    ScriptResult {
1257        changes: resolver.changes,
1258        error: false,
1259    }
1260}
1261
1262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1263enum ResolvedProperty {
1264    RawValue,
1265    Presence,
1266    SomExpression,
1267}
1268
1269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1270struct ResolvedTarget {
1271    node_id: FormNodeId,
1272    property: ResolvedProperty,
1273}
1274
1275struct FormTreeSomResolver<'a> {
1276    form: &'a mut FormTree,
1277    root_id: FormNodeId,
1278    parents: &'a HashMap<FormNodeId, FormNodeId>,
1279    current_id: FormNodeId,
1280    changes: usize,
1281}
1282
1283impl<'a> FormTreeSomResolver<'a> {
1284    fn new(
1285        form: &'a mut FormTree,
1286        root_id: FormNodeId,
1287        parents: &'a HashMap<FormNodeId, FormNodeId>,
1288        current_id: FormNodeId,
1289    ) -> Self {
1290        Self {
1291            form,
1292            root_id,
1293            parents,
1294            current_id,
1295            changes: 0,
1296        }
1297    }
1298
1299    fn resolve_target(&self, path: &str) -> Option<ResolvedTarget> {
1300        let trimmed = path.trim();
1301        if trimmed.is_empty() {
1302            return None;
1303        }
1304
1305        if matches!(trimmed, "rawValue" | "presence" | "somExpression") {
1306            return Some(ResolvedTarget {
1307                node_id: self.current_id,
1308                property: parse_property_name(trimmed)?,
1309            });
1310        }
1311
1312        let (expr, property) = split_property_path(trimmed)?;
1313        let node_id = self.resolve_expression(&expr)?.into_iter().next()?;
1314        Some(ResolvedTarget { node_id, property })
1315    }
1316
1317    fn count_targets(&self, path: &str) -> usize {
1318        let trimmed = path.trim();
1319        if trimmed.is_empty() {
1320            return 0;
1321        }
1322        if matches!(trimmed, "rawValue" | "presence" | "somExpression") {
1323            return 1;
1324        }
1325        let Some((expr, _property)) = split_property_path(trimmed) else {
1326            return 0;
1327        };
1328        self.resolve_expression(&expr)
1329            .map_or(0, |nodes| nodes.len())
1330    }
1331
1332    fn resolve_expression(&self, expr: &SomExpression) -> Option<Vec<FormNodeId>> {
1333        match expr.root {
1334            SomRoot::Data | SomRoot::Record | SomRoot::Template => None,
1335            SomRoot::CurrentContainer => {
1336                if expr.segments.is_empty() {
1337                    Some(vec![self.current_id])
1338                } else {
1339                    Some(self.follow_absolute(vec![self.current_id], &expr.segments))
1340                }
1341            }
1342            SomRoot::Form => {
1343                if expr.segments.is_empty() {
1344                    Some(vec![self.root_id])
1345                } else {
1346                    Some(self.follow_absolute(vec![self.root_id], &expr.segments))
1347                }
1348            }
1349            SomRoot::Xfa => {
1350                let segments = strip_xfa_form_prefix(&expr.segments);
1351                if segments.is_empty() {
1352                    Some(vec![self.root_id])
1353                } else {
1354                    Some(self.follow_absolute(vec![self.root_id], segments))
1355                }
1356            }
1357            SomRoot::Unqualified => {
1358                if expr.segments.is_empty() {
1359                    Some(vec![self.current_id])
1360                } else {
1361                    Some(self.follow_unqualified(&expr.segments))
1362                }
1363            }
1364        }
1365    }
1366
1367    fn follow_absolute(
1368        &self,
1369        mut current: Vec<FormNodeId>,
1370        segments: &[xfa_dom_resolver::som::SomSegment],
1371    ) -> Vec<FormNodeId> {
1372        for (idx, segment) in segments.iter().enumerate() {
1373            let allow_self = idx == 0;
1374            current = current
1375                .into_iter()
1376                .flat_map(|node_id| self.step_from_node(node_id, segment, allow_self))
1377                .collect();
1378            if current.is_empty() {
1379                break;
1380            }
1381        }
1382        current
1383    }
1384
1385    fn follow_unqualified(
1386        &self,
1387        segments: &[xfa_dom_resolver::som::SomSegment],
1388    ) -> Vec<FormNodeId> {
1389        let Some((first, rest)) = segments.split_first() else {
1390            return vec![self.current_id];
1391        };
1392
1393        let mut scope = Some(self.current_id);
1394        while let Some(scope_id) = scope {
1395            let anchors: Vec<_> = descendants_inclusive(self.form, scope_id)
1396                .into_iter()
1397                .filter(|node_id| self.node_matches_segment(*node_id, first))
1398                .collect();
1399            let matched = self.follow_remaining(anchors, rest);
1400            if !matched.is_empty() {
1401                return matched;
1402            }
1403            scope = self.parents.get(&scope_id).copied();
1404        }
1405
1406        let anchors: Vec<_> = descendants_inclusive(self.form, self.root_id)
1407            .into_iter()
1408            .filter(|node_id| self.node_matches_segment(*node_id, first))
1409            .collect();
1410        self.follow_remaining(anchors, rest)
1411    }
1412
1413    fn follow_remaining(
1414        &self,
1415        mut current: Vec<FormNodeId>,
1416        segments: &[xfa_dom_resolver::som::SomSegment],
1417    ) -> Vec<FormNodeId> {
1418        for segment in segments {
1419            current = current
1420                .into_iter()
1421                .flat_map(|node_id| self.step_from_node(node_id, segment, false))
1422                .collect();
1423            if current.is_empty() {
1424                break;
1425            }
1426        }
1427        current
1428    }
1429
1430    fn step_from_node(
1431        &self,
1432        node_id: FormNodeId,
1433        segment: &xfa_dom_resolver::som::SomSegment,
1434        allow_self: bool,
1435    ) -> Vec<FormNodeId> {
1436        // XFA-F3-06: `..` (parent) navigation — a segment whose name is an
1437        // empty string (produced by the `.` separator after `..` in the raw path)
1438        // or literally ".." navigates to the parent node.
1439        if let SomSelector::Name(name) = &segment.selector {
1440            if name == ".." {
1441                // Navigate to parent
1442                if let Some(&parent_id) = self.parents.get(&node_id) {
1443                    return apply_index_to_single(parent_id, segment.index);
1444                }
1445                return Vec::new();
1446            }
1447        }
1448
1449        if allow_self && self.node_matches_selector(node_id, &segment.selector) {
1450            return apply_index_to_single(node_id, segment.index);
1451        }
1452
1453        let matches: Vec<_> = self
1454            .form
1455            .get(node_id)
1456            .children
1457            .iter()
1458            .copied()
1459            .filter(|child_id| self.node_matches_selector(*child_id, &segment.selector))
1460            .collect();
1461
1462        apply_index(matches, segment.index)
1463    }
1464
1465    fn node_matches_segment(
1466        &self,
1467        node_id: FormNodeId,
1468        segment: &xfa_dom_resolver::som::SomSegment,
1469    ) -> bool {
1470        if !self.node_matches_selector(node_id, &segment.selector) {
1471            return false;
1472        }
1473
1474        match segment.index {
1475            SomIndex::All => true,
1476            SomIndex::None => self.sibling_position(node_id, &segment.selector) == Some(0),
1477            SomIndex::Specific(idx) => {
1478                self.sibling_position(node_id, &segment.selector) == Some(idx)
1479            }
1480        }
1481    }
1482
1483    fn sibling_position(&self, node_id: FormNodeId, selector: &SomSelector) -> Option<usize> {
1484        let Some(parent_id) = self.parents.get(&node_id).copied() else {
1485            return self.node_matches_selector(node_id, selector).then_some(0);
1486        };
1487
1488        self.form
1489            .get(parent_id)
1490            .children
1491            .iter()
1492            .copied()
1493            .filter(|candidate| self.node_matches_selector(*candidate, selector))
1494            .position(|candidate| candidate == node_id)
1495    }
1496
1497    fn node_matches_selector(&self, node_id: FormNodeId, selector: &SomSelector) -> bool {
1498        match selector {
1499            SomSelector::Name(name) => self.form.get(node_id).name == *name,
1500            SomSelector::Class(class_name) => self.node_matches_class(node_id, class_name),
1501            SomSelector::AllChildren => true,
1502        }
1503    }
1504
1505    fn node_matches_class(&self, node_id: FormNodeId, class_name: &str) -> bool {
1506        let class_name = class_name.to_ascii_lowercase();
1507        match class_name.as_str() {
1508            "subform" => matches!(
1509                self.form.get(node_id).node_type,
1510                FormNodeType::Root | FormNodeType::Subform
1511            ),
1512            "pageset" => {
1513                matches!(self.form.get(node_id).node_type, FormNodeType::PageSet)
1514            }
1515            "pagearea" => matches!(
1516                self.form.get(node_id).node_type,
1517                FormNodeType::PageArea { .. }
1518            ),
1519            "field" => matches!(self.form.get(node_id).node_type, FormNodeType::Field { .. }),
1520            "draw" => matches!(
1521                self.form.get(node_id).node_type,
1522                FormNodeType::Draw(_) | FormNodeType::Image { .. }
1523            ),
1524            "exclgroup" => self.form.meta(node_id).group_kind == GroupKind::ExclusiveChoice,
1525            _ => false,
1526        }
1527    }
1528}
1529
1530impl SomResolver for FormTreeSomResolver<'_> {
1531    fn resolve_path(
1532        &mut self,
1533        path: &str,
1534    ) -> formcalc_interpreter::error::Result<Option<FormCalcValue>> {
1535        let Some(target) = self.resolve_target(path) else {
1536            // XFA-F3-06: log a warning instead of silently returning None so
1537            // that SOM path failures are diagnosable.
1538            if !path.trim().is_empty() {
1539                log::warn!("SOM bridge: path not resolved: {:?}", path.trim());
1540            }
1541            return Ok(None);
1542        };
1543        Ok(Some(read_formcalc_value(
1544            self.form,
1545            self.root_id,
1546            self.parents,
1547            target,
1548        )))
1549    }
1550
1551    fn assign_path(
1552        &mut self,
1553        path: &str,
1554        value: FormCalcValue,
1555    ) -> formcalc_interpreter::error::Result<bool> {
1556        let Some(target) = self.resolve_target(path) else {
1557            // XFA-F3-06: descriptive warning on assignment failure.
1558            if !path.trim().is_empty() {
1559                log::warn!("SOM bridge: assignment target not found: {:?}", path.trim());
1560            }
1561            return Ok(false);
1562        };
1563        self.changes += write_formcalc_value(self.form, target.node_id, target.property, value);
1564        Ok(true)
1565    }
1566
1567    fn count_path_matches(&mut self, path: &str) -> formcalc_interpreter::error::Result<usize> {
1568        Ok(self.count_targets(path))
1569    }
1570}
1571
1572fn split_property_path(path: &str) -> Option<(SomExpression, ResolvedProperty)> {
1573    let normalized = if let Some(rest) = path.strip_prefix("this.") {
1574        format!("$.{rest}")
1575    } else if path == "this" {
1576        "$".to_string()
1577    } else {
1578        path.to_string()
1579    };
1580
1581    let mut expr = parse_som(&normalized).ok()?;
1582    let property = if let Some(last) = expr.segments.last() {
1583        match &last.selector {
1584            SomSelector::Name(name) => {
1585                parse_property_name(name).unwrap_or(ResolvedProperty::RawValue)
1586            }
1587            _ => ResolvedProperty::RawValue,
1588        }
1589    } else {
1590        ResolvedProperty::RawValue
1591    };
1592
1593    if matches!(
1594        expr.segments.last().map(|segment| &segment.selector),
1595        Some(SomSelector::Name(name)) if parse_property_name(name).is_some()
1596    ) {
1597        expr.segments.pop();
1598    }
1599
1600    Some((expr, property))
1601}
1602
1603fn parse_property_name(name: &str) -> Option<ResolvedProperty> {
1604    match name {
1605        "rawValue" => Some(ResolvedProperty::RawValue),
1606        "presence" => Some(ResolvedProperty::Presence),
1607        "somExpression" => Some(ResolvedProperty::SomExpression),
1608        _ => None,
1609    }
1610}
1611
1612fn strip_xfa_form_prefix(
1613    segments: &[xfa_dom_resolver::som::SomSegment],
1614) -> &[xfa_dom_resolver::som::SomSegment] {
1615    match segments.first() {
1616        Some(segment)
1617            if matches!(&segment.selector, SomSelector::Name(name) if name == "form")
1618                && matches!(segment.index, SomIndex::None) =>
1619        {
1620            &segments[1..]
1621        }
1622        _ => segments,
1623    }
1624}
1625
1626fn apply_index(matches: Vec<FormNodeId>, index: SomIndex) -> Vec<FormNodeId> {
1627    match index {
1628        SomIndex::None => matches.into_iter().take(1).collect(),
1629        SomIndex::Specific(idx) => matches.get(idx).copied().into_iter().collect(),
1630        SomIndex::All => matches,
1631    }
1632}
1633
1634fn apply_index_to_single(node_id: FormNodeId, index: SomIndex) -> Vec<FormNodeId> {
1635    match index {
1636        SomIndex::None | SomIndex::Specific(0) | SomIndex::All => vec![node_id],
1637        SomIndex::Specific(_) => Vec::new(),
1638    }
1639}
1640
1641fn read_formcalc_value(
1642    form: &FormTree,
1643    root_id: FormNodeId,
1644    parents: &HashMap<FormNodeId, FormNodeId>,
1645    target: ResolvedTarget,
1646) -> FormCalcValue {
1647    match target.property {
1648        ResolvedProperty::RawValue => get_formcalc_raw_value(form, target.node_id),
1649        ResolvedProperty::Presence => FormCalcValue::String(
1650            match form.meta(target.node_id).presence {
1651                Presence::Visible => "visible",
1652                Presence::Hidden => "hidden",
1653                Presence::Invisible => "invisible",
1654                Presence::Inactive => "inactive",
1655            }
1656            .to_string(),
1657        ),
1658        ResolvedProperty::SomExpression => {
1659            FormCalcValue::String(build_som_expression(form, root_id, parents, target.node_id))
1660        }
1661    }
1662}
1663
1664fn get_formcalc_raw_value(form: &FormTree, node_id: FormNodeId) -> FormCalcValue {
1665    match &form.get(node_id).node_type {
1666        FormNodeType::Field { value } => string_to_formcalc_value(value),
1667        _ if form.meta(node_id).group_kind == GroupKind::ExclusiveChoice => {
1668            for &child_id in &form.get(node_id).children {
1669                if let FormNodeType::Field { value } = &form.get(child_id).node_type {
1670                    if !value.is_empty() {
1671                        let selected = form.meta(child_id).item_value.as_deref().unwrap_or(value);
1672                        return string_to_formcalc_value(selected);
1673                    }
1674                }
1675            }
1676            FormCalcValue::Null
1677        }
1678        _ => FormCalcValue::Null,
1679    }
1680}
1681
1682fn write_formcalc_value(
1683    form: &mut FormTree,
1684    node_id: FormNodeId,
1685    property: ResolvedProperty,
1686    value: FormCalcValue,
1687) -> usize {
1688    match property {
1689        ResolvedProperty::RawValue => set_raw_value(form, node_id, formcalc_to_script_value(value)),
1690        ResolvedProperty::Presence => {
1691            set_presence(form, node_id, ScriptValue::String(value.to_string_val()))
1692        }
1693        ResolvedProperty::SomExpression => 0,
1694    }
1695}
1696
1697fn string_to_formcalc_value(value: &str) -> FormCalcValue {
1698    let trimmed = value.trim();
1699    if trimmed.is_empty() {
1700        FormCalcValue::Null
1701    } else if let Ok(number) = trimmed.parse::<f64>() {
1702        FormCalcValue::Number(number)
1703    } else {
1704        FormCalcValue::String(value.to_string())
1705    }
1706}
1707
1708fn formcalc_to_script_value(value: FormCalcValue) -> ScriptValue {
1709    match value {
1710        FormCalcValue::Null => ScriptValue::Null,
1711        FormCalcValue::Number(number) => ScriptValue::String(normalize_number(number)),
1712        FormCalcValue::String(value) => ScriptValue::String(value),
1713    }
1714}
1715
1716fn build_som_expression(
1717    form: &FormTree,
1718    root_id: FormNodeId,
1719    parents: &HashMap<FormNodeId, FormNodeId>,
1720    node_id: FormNodeId,
1721) -> String {
1722    let mut parts = Vec::new();
1723    let mut cursor = Some(node_id);
1724    while let Some(current) = cursor {
1725        let node = form.get(current);
1726        if !node.name.is_empty() {
1727            let index = if let Some(parent_id) = parents.get(&current).copied() {
1728                form.get(parent_id)
1729                    .children
1730                    .iter()
1731                    .copied()
1732                    .filter(|sibling_id| form.get(*sibling_id).name == node.name)
1733                    .position(|sibling_id| sibling_id == current)
1734                    .unwrap_or(0)
1735            } else {
1736                0
1737            };
1738            parts.push(format!("{}[{index}]", node.name));
1739        }
1740        if current == root_id {
1741            break;
1742        }
1743        cursor = parents.get(&current).copied();
1744    }
1745    parts.reverse();
1746
1747    if parts.is_empty() {
1748        "$form".to_string()
1749    } else {
1750        format!("$form.{}", parts.join("."))
1751    }
1752}
1753
1754fn descendants_inclusive(form: &FormTree, root_id: FormNodeId) -> Vec<FormNodeId> {
1755    let mut out = Vec::new();
1756    collect_descendants(form, root_id, &mut out);
1757    out
1758}
1759
1760fn collect_descendants(form: &FormTree, node_id: FormNodeId, out: &mut Vec<FormNodeId>) {
1761    out.push(node_id);
1762    for &child_id in &form.get(node_id).children {
1763        collect_descendants(form, child_id, out);
1764    }
1765}
1766
1767fn build_parent_map(form: &FormTree, root_id: FormNodeId) -> HashMap<FormNodeId, FormNodeId> {
1768    let mut parents = HashMap::new();
1769    populate_parent_map(form, root_id, &mut parents);
1770    parents
1771}
1772
1773fn populate_parent_map(
1774    form: &FormTree,
1775    node_id: FormNodeId,
1776    parents: &mut HashMap<FormNodeId, FormNodeId>,
1777) {
1778    for &child_id in &form.get(node_id).children {
1779        parents.insert(child_id, node_id);
1780        populate_parent_map(form, child_id, parents);
1781    }
1782}
1783
1784fn set_raw_value(form: &mut FormTree, node_id: FormNodeId, value: ScriptValue) -> usize {
1785    let value = match value {
1786        ScriptValue::Null => String::new(),
1787        ScriptValue::String(value) => value,
1788    };
1789
1790    if form.meta(node_id).group_kind == GroupKind::ExclusiveChoice {
1791        let mut changes = 0;
1792        for &child_id in &form.get(node_id).children.clone() {
1793            let item_value = form.meta(child_id).item_value.clone();
1794            let next = if item_value.as_deref() == Some(value.as_str()) {
1795                value.clone()
1796            } else {
1797                String::new()
1798            };
1799            if let FormNodeType::Field { value: field_value } =
1800                &mut form.get_mut(child_id).node_type
1801            {
1802                if *field_value != next {
1803                    *field_value = next;
1804                    changes += 1;
1805                }
1806            }
1807        }
1808        return changes;
1809    }
1810
1811    if let FormNodeType::Field { value: field_value } = &mut form.get_mut(node_id).node_type {
1812        if *field_value != value {
1813            *field_value = value;
1814            return 1;
1815        }
1816    }
1817
1818    0
1819}
1820
1821fn set_presence(form: &mut FormTree, node_id: FormNodeId, value: ScriptValue) -> usize {
1822    set_presence_inner(form, node_id, value).0
1823}
1824
1825/// Returns `(change_count, Option<(old_str, new_str)>)` for E-4 observability.
1826fn set_presence_inner(
1827    form: &mut FormTree,
1828    node_id: FormNodeId,
1829    value: ScriptValue,
1830) -> (usize, Option<(&'static str, &'static str)>) {
1831    let value = match value {
1832        ScriptValue::Null => return (0, None),
1833        ScriptValue::String(value) => value,
1834    };
1835    let normalized = value.trim().to_ascii_lowercase();
1836    let new_presence = match normalized.as_str() {
1837        "visible" | "open" => Presence::Visible,
1838        "hidden" => Presence::Hidden,
1839        "invisible" => Presence::Invisible,
1840        "inactive" => Presence::Inactive,
1841        _ => return (0, None),
1842    };
1843
1844    let meta = form.meta_mut(node_id);
1845    let old_presence = meta.presence;
1846    if old_presence == new_presence {
1847        return (0, None);
1848    }
1849    meta.presence = new_presence;
1850
1851    fn pres_str(p: Presence) -> &'static str {
1852        match p {
1853            Presence::Visible => "visible",
1854            Presence::Hidden => "hidden",
1855            Presence::Invisible => "invisible",
1856            Presence::Inactive => "inactive",
1857        }
1858    }
1859    let mutation = (pres_str(old_presence), pres_str(new_presence));
1860    if runtime_diag_enabled() {
1861        let node_name = form.get(node_id).name.clone();
1862        push_presence_mutation(node_id.0, &node_name, mutation.0, mutation.1);
1863    }
1864    (1, Some(mutation))
1865}
1866
1867fn normalize_number(number: f64) -> String {
1868    if number.fract().abs() < f64::EPSILON {
1869        (number as i64).to_string()
1870    } else {
1871        number.to_string()
1872    }
1873}
1874
1875#[derive(Debug, Clone, PartialEq, Eq)]
1876enum ScriptValue {
1877    Null,
1878    String(String),
1879}
1880
1881#[cfg(test)]
1882mod tests {
1883    use super::*;
1884    use xfa_layout_engine::form::{
1885        FieldKind, FormNode, FormNodeMeta, FormNodeStyle, GroupKind, Occur,
1886    };
1887    use xfa_layout_engine::text::FontMetrics;
1888    use xfa_layout_engine::types::{BoxModel, LayoutStrategy};
1889
1890    fn add_node(tree: &mut FormTree, name: &str, node_type: FormNodeType) -> FormNodeId {
1891        tree.add_node(FormNode {
1892            name: name.to_string(),
1893            node_type,
1894            box_model: BoxModel::default(),
1895            layout: LayoutStrategy::TopToBottom,
1896            children: Vec::new(),
1897            occur: Occur::once(),
1898            font: FontMetrics::default(),
1899            calculate: None,
1900            validate: None,
1901            column_widths: Vec::new(),
1902            col_span: 1,
1903        })
1904    }
1905
1906    fn empty_meta() -> FormNodeMeta {
1907        FormNodeMeta {
1908            field_kind: FieldKind::Text,
1909            group_kind: GroupKind::None,
1910            style: FormNodeStyle::default(),
1911            ..Default::default()
1912        }
1913    }
1914
1915    fn formcalc_script(script: &str, activity: &str) -> EventScript {
1916        EventScript::formcalc(script, Some(activity))
1917    }
1918
1919    fn javascript_script(script: &str, activity: &str) -> EventScript {
1920        EventScript::javascript(script, Some(activity))
1921    }
1922
1923    fn other_script(script: &str, activity: &str) -> EventScript {
1924        EventScript::new(
1925            script.to_string(),
1926            ScriptLanguage::Other,
1927            Some(activity.to_string()),
1928            None,
1929            None,
1930        )
1931    }
1932
1933    fn script_policy_fixture(include_js: bool) -> (FormTree, FormNodeId, FormNodeId) {
1934        let mut tree = FormTree::new();
1935        let root = add_node(&mut tree, "root", FormNodeType::Root);
1936        let js_hook = add_node(
1937            &mut tree,
1938            "JsHook",
1939            FormNodeType::Field {
1940                value: String::new(),
1941            },
1942        );
1943        let runner = add_node(
1944            &mut tree,
1945            "Runner",
1946            FormNodeType::Field {
1947                value: String::new(),
1948            },
1949        );
1950        let target = add_node(
1951            &mut tree,
1952            "Target",
1953            FormNodeType::Field {
1954                value: String::new(),
1955            },
1956        );
1957
1958        tree.get_mut(root).children = vec![js_hook, runner, target];
1959        if include_js {
1960            tree.meta_mut(js_hook).event_scripts = vec![javascript_script(
1961                "xfa.host.messageBox('skip');",
1962                "initialize",
1963            )];
1964        }
1965        tree.meta_mut(runner).event_scripts =
1966            vec![formcalc_script(r#"Target.rawValue = "ran""#, "initialize")];
1967
1968        (tree, root, target)
1969    }
1970
1971    fn other_language_policy_fixture() -> (FormTree, FormNodeId, FormNodeId) {
1972        let mut tree = FormTree::new();
1973        let root = add_node(&mut tree, "root", FormNodeType::Root);
1974        let other = add_node(&mut tree, "OtherHook", FormNodeType::Subform);
1975        let runner = add_node(&mut tree, "Runner", FormNodeType::Subform);
1976        let target = add_node(
1977            &mut tree,
1978            "Target",
1979            FormNodeType::Field {
1980                value: String::new(),
1981            },
1982        );
1983
1984        tree.get_mut(root).children = vec![other, runner, target];
1985        tree.meta_mut(other).event_scripts = vec![other_script("MsgBox \"skip\"", "initialize")];
1986        tree.meta_mut(runner).event_scripts =
1987            vec![formcalc_script(r#"Target.rawValue = "ran""#, "initialize")];
1988
1989        (tree, root, target)
1990    }
1991
1992    fn field_value(tree: &FormTree, node_id: FormNodeId) -> &str {
1993        match &tree.get(node_id).node_type {
1994            FormNodeType::Field { value } => value,
1995            _ => panic!("expected field"),
1996        }
1997    }
1998
1999    #[test]
2000    fn change_event_toggles_relative_hidden_subform() {
2001        let mut tree = FormTree::new();
2002        let root = add_node(&mut tree, "root", FormNodeType::Root);
2003        let section = add_node(&mut tree, "Section", FormNodeType::Subform);
2004        let group = add_node(&mut tree, "Choice", FormNodeType::Subform);
2005        let option1 = add_node(
2006            &mut tree,
2007            "Option1",
2008            FormNodeType::Field {
2009                value: "1".to_string(),
2010            },
2011        );
2012        let option2 = add_node(
2013            &mut tree,
2014            "Option2",
2015            FormNodeType::Field {
2016                value: String::new(),
2017            },
2018        );
2019        let details = add_node(&mut tree, "Details", FormNodeType::Subform);
2020
2021        tree.get_mut(root).children = vec![section];
2022        tree.get_mut(section).children = vec![group, details];
2023        tree.get_mut(group).children = vec![option1, option2];
2024
2025        tree.meta_mut(group).group_kind = GroupKind::ExclusiveChoice;
2026        tree.meta_mut(group).event_scripts = vec![formcalc_script(
2027            r#"
2028Details.presence = "hidden"
2029if (this.rawValue == 1) then
2030  Details.presence = "visible"
2031endif
2032"#,
2033            "initialize",
2034        )];
2035        tree.meta_mut(option1).item_value = Some("1".into());
2036        tree.meta_mut(option2).item_value = Some("2".into());
2037        tree.meta_mut(details).presence = Presence::Hidden;
2038
2039        apply_dynamic_scripts(&mut tree, root).unwrap();
2040
2041        assert_eq!(tree.meta(details).presence, Presence::Visible);
2042    }
2043
2044    #[test]
2045    fn calculate_script_on_hidden_block_uses_sibling_values() {
2046        let mut tree = FormTree::new();
2047        let root = add_node(&mut tree, "root", FormNodeType::Root);
2048        let section = add_node(&mut tree, "Section", FormNodeType::Subform);
2049        let option1 = add_node(
2050            &mut tree,
2051            "Opt1",
2052            FormNodeType::Field {
2053                value: "1".to_string(),
2054            },
2055        );
2056        let option2 = add_node(
2057            &mut tree,
2058            "Opt2",
2059            FormNodeType::Field {
2060                value: String::new(),
2061            },
2062        );
2063        let details = add_node(&mut tree, "Details", FormNodeType::Subform);
2064
2065        tree.get_mut(root).children = vec![section];
2066        tree.get_mut(section).children = vec![option1, option2, details];
2067        tree.meta_mut(details).presence = Presence::Hidden;
2068        tree.meta_mut(details).event_scripts = vec![formcalc_script(
2069            r#"
2070this.presence = "hidden"
2071if ((Opt1.rawValue == 1) or (Opt2.rawValue == 1)) then
2072  this.presence = "visible"
2073endif
2074"#,
2075            "calculate",
2076        )];
2077
2078        apply_dynamic_scripts(&mut tree, root).unwrap();
2079
2080        assert_eq!(tree.meta(details).presence, Presence::Visible);
2081    }
2082
2083    #[test]
2084    fn multi_pass_scripts_propagate_raw_values() {
2085        let mut tree = FormTree::new();
2086        let root = add_node(&mut tree, "root", FormNodeType::Root);
2087        let section = add_node(&mut tree, "Section", FormNodeType::Subform);
2088        let controller = add_node(
2089            &mut tree,
2090            "Controller",
2091            FormNodeType::Field {
2092                value: "1".to_string(),
2093            },
2094        );
2095        let target = add_node(
2096            &mut tree,
2097            "Target",
2098            FormNodeType::Field {
2099                value: String::new(),
2100            },
2101        );
2102        let details = add_node(&mut tree, "Details", FormNodeType::Subform);
2103
2104        tree.get_mut(root).children = vec![section];
2105        tree.get_mut(section).children = vec![controller, target, details];
2106
2107        tree.meta_mut(controller).event_scripts = vec![formcalc_script(
2108            r#"
2109if (this.rawValue == 1) then
2110  Target.rawValue = 1
2111endif
2112"#,
2113            "calculate",
2114        )];
2115        tree.meta_mut(details).presence = Presence::Hidden;
2116        tree.meta_mut(details).event_scripts = vec![formcalc_script(
2117            r#"
2118this.presence = "hidden"
2119if (Target.rawValue == 1) then
2120  this.presence = "visible"
2121endif
2122"#,
2123            "calculate",
2124        )];
2125
2126        apply_dynamic_scripts(&mut tree, root).unwrap();
2127
2128        if let FormNodeType::Field { value } = &tree.get(target).node_type {
2129            assert_eq!(value, "1");
2130        } else {
2131            panic!("expected field");
2132        }
2133        assert_eq!(tree.meta(details).presence, Presence::Visible);
2134    }
2135
2136    // ─── #1097: FormCalc SOM bridge hardening ────────────────────────────────
2137
2138    /// SOM path `form1.#subform[0].field1.rawValue` resolves correctly on a
2139    /// simple form tree.
2140    #[test]
2141    fn som_path_resolves_on_simple_form_tree() {
2142        let mut tree = FormTree::new();
2143        let root = add_node(&mut tree, "root", FormNodeType::Root);
2144        let form1 = add_node(&mut tree, "form1", FormNodeType::Subform);
2145        let subform = add_node(&mut tree, "subform1", FormNodeType::Subform);
2146        let field1 = add_node(
2147            &mut tree,
2148            "field1",
2149            FormNodeType::Field {
2150                value: "hello".to_string(),
2151            },
2152        );
2153
2154        tree.get_mut(root).children = vec![form1];
2155        tree.get_mut(form1).children = vec![subform];
2156        tree.get_mut(subform).children = vec![field1];
2157
2158        // Use a calculate script to read the value via absolute SOM path
2159        tree.meta_mut(root).event_scripts = vec![formcalc_script(
2160            "form1.subform1.field1.rawValue",
2161            "calculate",
2162        )];
2163
2164        let parents = super::build_parent_map(&tree, root);
2165        let resolver = FormTreeSomResolver::new(&mut tree, root, &parents, root);
2166        let target = resolver.resolve_target("form1.subform1.field1.rawValue");
2167        assert!(target.is_some(), "SOM path must resolve to a node");
2168        let target = target.unwrap();
2169        let val = super::read_formcalc_value(&tree, root, &parents, target);
2170        match val {
2171            formcalc_interpreter::value::Value::String(s) => assert_eq!(s, "hello"),
2172            formcalc_interpreter::value::Value::Number(n) => {
2173                // number coercion: not expected here
2174                panic!("expected string, got number {n}")
2175            }
2176            _ => panic!("expected string value"),
2177        }
2178    }
2179
2180    /// An invalid SOM path returns `None` (descriptive non-panic failure).
2181    #[test]
2182    fn invalid_som_path_returns_none_not_panic() {
2183        let mut tree = FormTree::new();
2184        let root = add_node(&mut tree, "root", FormNodeType::Root);
2185        let parents = super::build_parent_map(&tree, root);
2186        let resolver = FormTreeSomResolver::new(&mut tree, root, &parents, root);
2187
2188        // This should not panic — it should return None
2189        let result = resolver.resolve_target("nonexistent.deep.path.rawValue");
2190        assert!(
2191            result.is_none(),
2192            "invalid SOM path must return None, not panic"
2193        );
2194    }
2195
2196    #[test]
2197    fn best_effort_skips_javascript_and_runs_formcalc() {
2198        let (mut tree, root, target) = script_policy_fixture(true);
2199
2200        let outcome = apply_dynamic_scripts(&mut tree, root).unwrap();
2201
2202        assert_eq!(field_value(&tree, target), "ran");
2203        assert!(outcome.js_present);
2204        assert_eq!(outcome.js_skipped, 1);
2205        assert_eq!(outcome.other_skipped, 0);
2206        assert_eq!(outcome.formcalc_run, 1);
2207        assert_eq!(outcome.formcalc_errors, 0);
2208        assert_eq!(outcome.output_quality, OutputQuality::BestEffort);
2209    }
2210
2211    #[test]
2212    fn strict_mode_preserves_javascript_reject() {
2213        let (mut tree, root, target) = script_policy_fixture(true);
2214
2215        let err =
2216            apply_dynamic_scripts_with_mode(&mut tree, root, JsExecutionMode::Strict).unwrap_err();
2217
2218        assert!(matches!(err, XfaError::UnsupportedFeature(feature) if feature == "javascript"));
2219        assert_eq!(field_value(&tree, target), "");
2220    }
2221
2222    #[test]
2223    fn formcalc_only_reports_exact_quality() {
2224        let (mut tree, root, target) = script_policy_fixture(false);
2225
2226        let outcome = apply_dynamic_scripts(&mut tree, root).unwrap();
2227
2228        assert_eq!(field_value(&tree, target), "ran");
2229        assert!(!outcome.js_present);
2230        assert_eq!(outcome.js_skipped, 0);
2231        assert_eq!(outcome.other_skipped, 0);
2232        assert_eq!(outcome.formcalc_run, 1);
2233        assert_eq!(outcome.formcalc_errors, 0);
2234        assert_eq!(outcome.output_quality, OutputQuality::Exact);
2235    }
2236
2237    #[test]
2238    fn other_language_scripts_skip_in_best_effort_and_reject_in_strict() {
2239        let (mut tree, root, target) = other_language_policy_fixture();
2240        let (mut strict_tree, strict_root, _) = other_language_policy_fixture();
2241
2242        let outcome = apply_dynamic_scripts(&mut tree, root).unwrap();
2243        assert_eq!(field_value(&tree, target), "ran");
2244        assert_eq!(outcome.js_skipped, 0);
2245        assert_eq!(outcome.other_skipped, 1);
2246        assert_eq!(outcome.formcalc_run, 1);
2247        assert_eq!(outcome.output_quality, OutputQuality::BestEffort);
2248
2249        let err =
2250            apply_dynamic_scripts_with_mode(&mut strict_tree, strict_root, JsExecutionMode::Strict)
2251                .unwrap_err();
2252        assert!(matches!(err, XfaError::UnsupportedFeature(feature) if feature == "javascript"));
2253    }
2254
2255    #[test]
2256    fn javascript_direct_executor_call_is_still_denied() {
2257        let mut tree = FormTree::new();
2258        let root = add_node(&mut tree, "root", FormNodeType::Root);
2259        let trigger = add_node(
2260            &mut tree,
2261            "Trigger",
2262            FormNodeType::Field {
2263                value: String::new(),
2264            },
2265        );
2266        tree.get_mut(root).children = vec![trigger];
2267
2268        let parents = build_parent_map(&tree, root);
2269        let script = javascript_script("xfa.host.messageBox('deny');", "initialize");
2270        let err = execute_event_script(
2271            &mut tree,
2272            root,
2273            &parents,
2274            trigger,
2275            &script,
2276            ScriptPhase::Initialize,
2277        )
2278        .unwrap_err();
2279
2280        assert!(matches!(err, XfaError::UnsupportedFeature(feature) if feature == "javascript"));
2281    }
2282
2283    #[test]
2284    fn javascript_resolve_node_call_is_explicitly_denied() {
2285        let mut tree = FormTree::new();
2286        let root = add_node(&mut tree, "root", FormNodeType::Root);
2287        let form = add_node(&mut tree, "formulier1", FormNodeType::Subform);
2288        let admin = add_node(&mut tree, "ADMIN", FormNodeType::Subform);
2289        let lock = add_node(
2290            &mut tree,
2291            "LockForm_AD",
2292            FormNodeType::Field {
2293                value: "1".to_string(),
2294            },
2295        );
2296        let reset = add_node(
2297            &mut tree,
2298            "Reset",
2299            FormNodeType::Field {
2300                value: "1".to_string(),
2301            },
2302        );
2303
2304        tree.get_mut(root).children = vec![form];
2305        tree.get_mut(form).children = vec![admin, reset];
2306        tree.get_mut(admin).children = vec![lock];
2307        tree.meta_mut(reset).event_scripts = vec![javascript_script(
2308            r#"xfa.resolveNode("formulier1.ADMIN.LockForm_AD").rawValue = 0;"#,
2309            "initialize",
2310        )];
2311
2312        let err =
2313            apply_dynamic_scripts_with_mode(&mut tree, root, JsExecutionMode::Strict).unwrap_err();
2314        assert!(matches!(err, XfaError::UnsupportedFeature(feature) if feature == "javascript"));
2315
2316        if let FormNodeType::Field { value } = &tree.get(lock).node_type {
2317            assert_eq!(value, "1");
2318        } else {
2319            panic!("expected field");
2320        }
2321    }
2322
2323    #[test]
2324    fn javascript_utils_hide_if_empty_is_explicitly_denied() {
2325        let mut tree = FormTree::new();
2326        let root = add_node(&mut tree, "root", FormNodeType::Root);
2327        let empty = add_node(
2328            &mut tree,
2329            "EmptyField",
2330            FormNodeType::Field {
2331                value: String::new(),
2332            },
2333        );
2334        tree.get_mut(root).children = vec![empty];
2335        tree.meta_mut(empty).event_scripts =
2336            vec![javascript_script("Utils.hideIfEmpty(this);", "initialize")];
2337
2338        let err =
2339            apply_dynamic_scripts_with_mode(&mut tree, root, JsExecutionMode::Strict).unwrap_err();
2340        assert!(matches!(err, XfaError::UnsupportedFeature(feature) if feature == "javascript"));
2341
2342        assert!(!tree.meta(empty).presence.is_not_visible());
2343    }
2344
2345    #[test]
2346    fn malformed_javascript_payload_is_explicitly_denied_without_panic() {
2347        let mut tree = FormTree::new();
2348        let root = add_node(&mut tree, "root", FormNodeType::Root);
2349        let container = add_node(&mut tree, "Container", FormNodeType::Subform);
2350        let empty = add_node(
2351            &mut tree,
2352            "EmptyField",
2353            FormNodeType::Field {
2354                value: String::new(),
2355            },
2356        );
2357
2358        tree.get_mut(root).children = vec![container];
2359        tree.get_mut(container).children = vec![empty];
2360        tree.meta_mut(empty).event_scripts = vec![javascript_script(
2361            "\0}{{not.valid.javascript(",
2362            "initialize",
2363        )];
2364
2365        let err =
2366            apply_dynamic_scripts_with_mode(&mut tree, root, JsExecutionMode::Strict).unwrap_err();
2367        assert!(matches!(err, XfaError::UnsupportedFeature(feature) if feature == "javascript"));
2368
2369        assert!(!tree.meta(container).presence.is_not_visible());
2370    }
2371
2372    #[test]
2373    fn default_meta_helper_is_constructible() {
2374        let meta = empty_meta();
2375        assert_eq!(meta.group_kind, GroupKind::None);
2376    }
2377
2378    #[test]
2379    fn calculate_event_applies_formcalc_return_value() {
2380        let mut tree = FormTree::new();
2381        let root = add_node(&mut tree, "root", FormNodeType::Root);
2382        let total = add_node(
2383            &mut tree,
2384            "Total",
2385            FormNodeType::Field {
2386                value: String::new(),
2387            },
2388        );
2389
2390        tree.get_mut(root).children = vec![total];
2391        tree.meta_mut(total).event_scripts = vec![formcalc_script("40 + 2", "calculate")];
2392
2393        apply_dynamic_scripts(&mut tree, root).unwrap();
2394
2395        match &tree.get(total).node_type {
2396            FormNodeType::Field { value } => assert_eq!(value, "42"),
2397            _ => panic!("expected field"),
2398        }
2399    }
2400
2401    #[test]
2402    fn calculate_event_resolves_bare_field_names_as_raw_values() {
2403        let mut tree = FormTree::new();
2404        let root = add_node(&mut tree, "root", FormNodeType::Root);
2405        let section = add_node(&mut tree, "Section", FormNodeType::Subform);
2406        let number1 = add_node(
2407            &mut tree,
2408            "Number1",
2409            FormNodeType::Field {
2410                value: "40".to_string(),
2411            },
2412        );
2413        let number2 = add_node(
2414            &mut tree,
2415            "Number2",
2416            FormNodeType::Field {
2417                value: "2".to_string(),
2418            },
2419        );
2420        let total = add_node(
2421            &mut tree,
2422            "Total",
2423            FormNodeType::Field {
2424                value: String::new(),
2425            },
2426        );
2427
2428        tree.get_mut(root).children = vec![section];
2429        tree.get_mut(section).children = vec![number1, number2, total];
2430        tree.meta_mut(total).event_scripts =
2431            vec![formcalc_script("Number1 + Number2", "calculate")];
2432
2433        apply_dynamic_scripts(&mut tree, root).unwrap();
2434
2435        match &tree.get(total).node_type {
2436            FormNodeType::Field { value } => assert_eq!(value, "42"),
2437            _ => panic!("expected field"),
2438        }
2439    }
2440
2441    #[test]
2442    fn click_events_are_skipped_during_flatten() {
2443        let mut tree = FormTree::new();
2444        let root = add_node(&mut tree, "root", FormNodeType::Root);
2445        let trigger = add_node(
2446            &mut tree,
2447            "Trigger",
2448            FormNodeType::Field {
2449                value: "1".to_string(),
2450            },
2451        );
2452        let details = add_node(&mut tree, "Details", FormNodeType::Subform);
2453
2454        tree.get_mut(root).children = vec![trigger, details];
2455        tree.meta_mut(details).presence = Presence::Hidden;
2456        tree.meta_mut(trigger).event_scripts = vec![formcalc_script(
2457            r#"
2458Details.presence = "visible"
2459"#,
2460            "click",
2461        )];
2462
2463        apply_dynamic_scripts(&mut tree, root).unwrap();
2464
2465        assert_eq!(tree.meta(details).presence, Presence::Hidden);
2466    }
2467
2468    #[test]
2469    fn rollback_when_scripts_mostly_error() {
2470        // Set up a form with fields that have values.  Attach scripts that
2471        // will fail to parse so that errors > successes.  After
2472        // apply_dynamic_scripts the field values must be unchanged.
2473        let mut tree = FormTree::new();
2474        let root = add_node(&mut tree, "root", FormNodeType::Root);
2475        let field_a = add_node(
2476            &mut tree,
2477            "FieldA",
2478            FormNodeType::Field {
2479                value: "hello".to_string(),
2480            },
2481        );
2482        let field_b = add_node(
2483            &mut tree,
2484            "FieldB",
2485            FormNodeType::Field {
2486                value: "world".to_string(),
2487            },
2488        );
2489
2490        tree.get_mut(root).children = vec![field_a, field_b];
2491
2492        // Two scripts that fail parsing (invalid FormCalc), zero successes.
2493        tree.meta_mut(field_a).event_scripts = vec![formcalc_script("@@INVALID@@", "initialize")];
2494        tree.meta_mut(field_b).event_scripts =
2495            vec![formcalc_script("@@ALSO_BROKEN@@", "initialize")];
2496
2497        apply_dynamic_scripts(&mut tree, root).unwrap();
2498
2499        // Fields should retain their original values (rollback).
2500        match &tree.get(field_a).node_type {
2501            FormNodeType::Field { value } => assert_eq!(value, "hello"),
2502            _ => panic!("expected field"),
2503        }
2504        match &tree.get(field_b).node_type {
2505            FormNodeType::Field { value } => assert_eq!(value, "world"),
2506            _ => panic!("expected field"),
2507        }
2508    }
2509
2510    #[test]
2511    fn rollback_when_populated_fields_go_empty() {
2512        // Calculate scripts returning Null clear field values. When >50%
2513        // of populated fields go empty, the rollback heuristic fires.
2514        let mut tree = FormTree::new();
2515        let root = add_node(&mut tree, "root", FormNodeType::Root);
2516        let field_a = add_node(
2517            &mut tree,
2518            "FieldA",
2519            FormNodeType::Field {
2520                value: "keep".to_string(),
2521            },
2522        );
2523        let field_b = add_node(
2524            &mut tree,
2525            "FieldB",
2526            FormNodeType::Field {
2527                value: "also_keep".to_string(),
2528            },
2529        );
2530
2531        tree.get_mut(root).children = vec![field_a, field_b];
2532
2533        // Calculate scripts whose return value (Null) is written to the field,
2534        // blanking it.  The expression `Null()` is not a real FormCalc builtin,
2535        // but `0` would set the field to "0" (not empty).  Instead we use the
2536        // snapshot/rollback logic directly.
2537        // We test the heuristic by manually setting up the condition.
2538        let snapshot = super::snapshot_form(&tree);
2539
2540        // Simulate scripts clearing both fields.
2541        if let FormNodeType::Field { value } = &mut tree.get_mut(field_a).node_type {
2542            *value = String::new();
2543        }
2544        if let FormNodeType::Field { value } = &mut tree.get_mut(field_b).node_type {
2545            *value = String::new();
2546        }
2547
2548        assert!(super::should_rollback(&tree, &snapshot, 0, 2));
2549
2550        super::restore_snapshot(&mut tree, &snapshot);
2551
2552        match &tree.get(field_a).node_type {
2553            FormNodeType::Field { value } => assert_eq!(value, "keep"),
2554            _ => panic!("expected field"),
2555        }
2556        match &tree.get(field_b).node_type {
2557            FormNodeType::Field { value } => assert_eq!(value, "also_keep"),
2558            _ => panic!("expected field"),
2559        }
2560    }
2561
2562    #[test]
2563    fn no_rollback_when_scripts_succeed() {
2564        // A single working script with no errors → no rollback, change persists.
2565        let mut tree = FormTree::new();
2566        let root = add_node(&mut tree, "root", FormNodeType::Root);
2567        let total = add_node(
2568            &mut tree,
2569            "Total",
2570            FormNodeType::Field {
2571                value: String::new(),
2572            },
2573        );
2574
2575        tree.get_mut(root).children = vec![total];
2576        tree.meta_mut(total).event_scripts = vec![formcalc_script("40 + 2", "calculate")];
2577
2578        apply_dynamic_scripts(&mut tree, root).unwrap();
2579
2580        match &tree.get(total).node_type {
2581            FormNodeType::Field { value } => assert_eq!(value, "42"),
2582            _ => panic!("expected field"),
2583        }
2584    }
2585
2586    /// QF1-C regression: `formcalc_errors` counter MUST tick when a FormCalc
2587    /// script invokes an unknown function. This is the canonical signal the
2588    /// QF1-C residual scan (`scripts/xfa_formcalc_residual_scan.py`) aggregates
2589    /// off the `XFA script metadata:` stderr line.
2590    #[test]
2591    fn formcalc_unknown_function_increments_error_counter() {
2592        let mut tree = FormTree::new();
2593        let root = add_node(&mut tree, "root", FormNodeType::Root);
2594        let total = add_node(
2595            &mut tree,
2596            "Total",
2597            FormNodeType::Field {
2598                value: String::new(),
2599            },
2600        );
2601
2602        tree.get_mut(root).children = vec![total];
2603        // `definitelyNotAFormCalcBuiltin(1)` triggers `FormCalcError::UnknownFunction`
2604        // in `crates/formcalc-interpreter/src/interpreter.rs`.
2605        tree.meta_mut(total).event_scripts = vec![formcalc_script(
2606            "definitelyNotAFormCalcBuiltin(1)",
2607            "calculate",
2608        )];
2609
2610        let outcome = apply_dynamic_scripts(&mut tree, root).unwrap();
2611        assert_eq!(outcome.formcalc_run, 1, "the script must be attempted");
2612        assert_eq!(
2613            outcome.formcalc_errors, 1,
2614            "unknown-function failure must increment formcalc_errors"
2615        );
2616    }
2617
2618    // ─── Epic A enrichment tests ──────────────────────────────────────────────
2619    //
2620    // Environment variable writes are not `std::sync::atomic` — we serialise all
2621    // three tests with a process-wide `Mutex` so they cannot race on the env.
2622    static ENV_LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
2623
2624    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
2625        ENV_LOCK
2626            .get_or_init(|| std::sync::Mutex::new(()))
2627            .lock()
2628            .unwrap_or_else(|e| e.into_inner())
2629    }
2630
2631    /// E-1: `script_lifecycle` is populated when `XFA_FLATTEN_TRACE=1`.
2632    ///
2633    /// Builds a FormTree with a single JavaScript `initialize` event on a field.
2634    /// In `BestEffortStatic` mode the script is skipped but still recorded in
2635    /// the lifecycle vec with outcome `"skipped_mode"`.
2636    #[test]
2637    fn script_lifecycle_populated_when_trace_enabled() {
2638        let _guard = env_lock();
2639        std::env::set_var("XFA_FLATTEN_TRACE", "1");
2640
2641        let mut tree = FormTree::new();
2642        let root = add_node(&mut tree, "root", FormNodeType::Root);
2643        let field = add_node(
2644            &mut tree,
2645            "TraceField",
2646            FormNodeType::Field {
2647                value: String::new(),
2648            },
2649        );
2650        tree.get_mut(root).children = vec![field];
2651        tree.meta_mut(field).event_scripts = vec![javascript_script(
2652            "xfa.host.messageBox('trace');",
2653            "initialize",
2654        )];
2655
2656        let outcome =
2657            apply_dynamic_scripts_with_mode(&mut tree, root, JsExecutionMode::BestEffortStatic)
2658                .unwrap();
2659
2660        std::env::remove_var("XFA_FLATTEN_TRACE");
2661
2662        assert!(
2663            !outcome.script_lifecycle.is_empty(),
2664            "script_lifecycle must have at least one entry when XFA_FLATTEN_TRACE=1"
2665        );
2666        let entry = &outcome.script_lifecycle[0];
2667        assert_eq!(entry.node_name, "TraceField");
2668        assert_eq!(entry.activity, "initialize");
2669        assert_eq!(entry.lang, "javascript");
2670        // BestEffortStatic skips JS entirely — outcome must reflect that.
2671        assert_eq!(
2672            entry.outcome, "skipped_mode",
2673            "BestEffortStatic JS must appear as skipped_mode in lifecycle"
2674        );
2675    }
2676
2677    /// E-6: `skipped_activities` tallies correctly for a `click` script.
2678    ///
2679    /// A JavaScript script with `activity="click"` cannot be executed during
2680    /// flatten (not in the sandbox allowlist and skipped by BestEffortStatic).
2681    /// When `XFA_FLATTEN_TRACE=1` the `skipped_activities.click` counter must
2682    /// increment by exactly 1.
2683    #[test]
2684    fn skipped_activities_tallies_click_correctly() {
2685        let _guard = env_lock();
2686        std::env::set_var("XFA_FLATTEN_TRACE", "1");
2687
2688        let mut tree = FormTree::new();
2689        let root = add_node(&mut tree, "root", FormNodeType::Root);
2690        let btn = add_node(
2691            &mut tree,
2692            "ClickBtn",
2693            FormNodeType::Field {
2694                value: String::new(),
2695            },
2696        );
2697        tree.get_mut(root).children = vec![btn];
2698        // `click` activity — never executed during flatten regardless of mode.
2699        tree.meta_mut(btn).event_scripts = vec![javascript_script(
2700            "xfa.host.messageBox('clicked');",
2701            "click",
2702        )];
2703
2704        let outcome =
2705            apply_dynamic_scripts_with_mode(&mut tree, root, JsExecutionMode::BestEffortStatic)
2706                .unwrap();
2707
2708        std::env::remove_var("XFA_FLATTEN_TRACE");
2709
2710        assert_eq!(
2711            outcome.skipped_activities.click, 1,
2712            "exactly one click-activity JS script must be tallied in skipped_activities.click"
2713        );
2714        // Other buckets must stay at zero.
2715        assert_eq!(outcome.skipped_activities.initialize, 0);
2716        assert_eq!(outcome.skipped_activities.calculate, 0);
2717        assert_eq!(outcome.skipped_activities.other, 0);
2718    }
2719
2720    /// E-5: `form_dom_match_failures` increments when `apply_form_dom_presence`
2721    /// suppresses a named subform absent from the form DOM.
2722    ///
2723    /// The FormTree contains a named `Subform` child ("Ghost") that does NOT
2724    /// appear in the form XML packet.  The form XML contains a sibling child
2725    /// ("Present") so that the "has_subform_children" guard inside
2726    /// `apply_form_dom_presence` fires and suppression logic runs.
2727    #[test]
2728    fn form_dom_match_failures_increments_for_unmatched_subform() {
2729        use crate::flatten::{apply_form_dom_presence, XfaRenderingPolicy};
2730
2731        let _guard = env_lock();
2732        // E-5 diag log is armed when XFA_FLATTEN_TRACE or XFA_RUNTIME_DIAG is set.
2733        std::env::set_var("XFA_FLATTEN_TRACE", "1");
2734
2735        let mut tree = FormTree::new();
2736        let root = add_node(&mut tree, "root", FormNodeType::Root);
2737        // "form1" is the top-level subform that the form XML root-subform matches.
2738        let form1 = add_node(&mut tree, "form1", FormNodeType::Subform);
2739        // "Present" appears in the form DOM — will be matched.
2740        let present = add_node(&mut tree, "Present", FormNodeType::Subform);
2741        // "Ghost" is NOT in the form DOM — will be suppressed.
2742        let ghost = add_node(&mut tree, "Ghost", FormNodeType::Subform);
2743
2744        tree.get_mut(root).children = vec![form1];
2745        tree.get_mut(form1).children = vec![present, ghost];
2746
2747        // Minimal form XML: root subform "form1" contains one child "Present"
2748        // but no "Ghost" child.  Because "Present" is listed, the
2749        // `has_subform_children` guard fires and "Ghost" is suppressed.
2750        let form_xml = r#"<form>
2751  <subform name="form1">
2752    <subform name="Present"/>
2753  </subform>
2754</form>"#;
2755
2756        let (_admitted, match_failures, match_log) = apply_form_dom_presence(
2757            &mut tree,
2758            root,
2759            form_xml,
2760            XfaRenderingPolicy::SavedStateFaithful,
2761            false,
2762        );
2763
2764        std::env::remove_var("XFA_FLATTEN_TRACE");
2765
2766        assert_eq!(
2767            match_failures, 1,
2768            "exactly one unmatched named subform (Ghost) must be counted"
2769        );
2770        assert_eq!(match_log.len(), 1, "match_log must contain the Ghost entry");
2771        assert_eq!(match_log[0].template_node_name, "Ghost");
2772        assert_eq!(match_log[0].reason, "formdom_unmatched_suppressed");
2773        // Verify presence was actually suppressed on the FormTree node.
2774        assert!(
2775            tree.meta(ghost).presence.is_not_visible(),
2776            "Ghost subform must have been hidden by apply_form_dom_presence"
2777        );
2778    }
2779}