Skip to main content

vibe/web_runtime/form_state/
mod.rs

1//! VibeScript Form State Lifecycle, Transactional Undo/Redo, Lamport LWW CRDT Merge,
2//! Four-Boundary Disclosure Filtering, Zero-Knowledge Field Proofs, and Semantic Serialization
3//! (`form.*` stdlib bindings).
4//!
5//! Directory-backed module structure (`AGENTS.md` §0-B):
6//! - `lifecycle`: `form.create`, `form.get_value`, `form.set_value`, `form.get_group_value`,
7//!   `form.reset`, `form.is_dirty`, `form.field_is_dirty`, `form.diff`, `form.commit_defaults`,
8//!   `form.request_submit`
9//! - `history_crdt`: `form.checkpoint`, `form.undo`, `form.redo`, `form.can_undo`,
10//!   `form.can_redo`, `form.rollback_to`, `form.crdt_merge`
11//! - `serialize_privacy`: `form.to_record`, `form.to_url_params`, `form.to_rdf_turtle`,
12//!   `form.to_quins`, `form.filter_disclosure`, `form.zk_prove_field`, `form.from_provider_json`
13
14pub mod history_crdt;
15pub mod lifecycle;
16pub mod serialize_privacy;
17
18use std::collections::BTreeMap;
19
20use crate::error::{DiagCode, Diagnostic};
21use crate::span::Span;
22use crate::value::Value;
23
24/// Maximum number of transactional undo/redo snapshots retained per form.
25pub(crate) const MAX_HISTORY_LEN: usize = 64;
26
27/// FNV-1a 64-bit offset basis (`AGENTS.md` §1).
28pub(crate) const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
29
30/// FNV-1a 64-bit prime (`AGENTS.md` §1).
31pub(crate) const FNV_PRIME: u64 = 0x100000001b3;
32
33/// Dispatch a `form.*` call in the VibeScript engine.
34pub fn call_form_state(
35    path: &str,
36    args: &[Value],
37    span: Span,
38) -> Result<Option<Value>, Diagnostic> {
39    if let Some(res) = lifecycle::call_lifecycle(path, args, span)? {
40        return Ok(Some(res));
41    }
42    if let Some(res) = history_crdt::call_history_crdt(path, args, span)? {
43        return Ok(Some(res));
44    }
45    if let Some(res) = serialize_privacy::call_serialize_privacy(path, args, span)? {
46        return Ok(Some(res));
47    }
48    Ok(None)
49}
50
51pub(crate) fn fnv1a_64(bytes: &[u8]) -> u64 {
52    let mut h = FNV_OFFSET_BASIS;
53    for &b in bytes {
54        h ^= b as u64;
55        h = h.wrapping_mul(FNV_PRIME);
56    }
57    h
58}
59
60pub(crate) fn push_bounded(list: &mut Vec<Value>, item: Value) {
61    if list.len() >= MAX_HISTORY_LEN {
62        list.remove(0);
63    }
64    list.push(item);
65}
66
67pub(crate) fn get_sub_record(rec: &BTreeMap<String, Value>, key: &str) -> BTreeMap<String, Value> {
68    match rec.get(key) {
69        Some(Value::Record(sub)) => sub.clone(),
70        _ => BTreeMap::new(),
71    }
72}
73
74pub(crate) fn get_sub_list(rec: &BTreeMap<String, Value>, key: &str) -> Vec<Value> {
75    match rec.get(key) {
76        Some(Value::List(items)) => items.clone(),
77        _ => Vec::new(),
78    }
79}
80
81pub(crate) fn extract_schema_base(form: &BTreeMap<String, Value>) -> String {
82    let base = match form.get("schema_iri") {
83        Some(Value::Iri(s)) | Some(Value::String(s)) => s.as_str(),
84        _ => "https://qualia.world/ontology/form#",
85    };
86    if base.ends_with('#') || base.ends_with('/') {
87        base.to_string()
88    } else {
89        format!("{base}#")
90    }
91}
92
93pub(crate) fn extract_str(
94    args: &[Value],
95    idx: usize,
96    ctx: &str,
97    span: Span,
98) -> Result<String, Diagnostic> {
99    match args.get(idx) {
100        Some(Value::String(s)) | Some(Value::Iri(s)) => Ok(s.clone()),
101        _ => Err(Diagnostic::new(
102            DiagCode::E100,
103            span,
104            format!("{ctx}: argument #{idx} must be a string"),
105        )),
106    }
107}
108
109pub(crate) fn extract_i64(
110    args: &[Value],
111    idx: usize,
112    ctx: &str,
113    span: Span,
114) -> Result<i64, Diagnostic> {
115    args.get(idx).and_then(Value::as_i64).ok_or_else(|| {
116        Diagnostic::new(
117            DiagCode::E100,
118            span,
119            format!("{ctx}: argument #{idx} must be an integer"),
120        )
121    })
122}
123
124pub(crate) fn extract_record(
125    args: &[Value],
126    idx: usize,
127    ctx: &str,
128    span: Span,
129) -> Result<BTreeMap<String, Value>, Diagnostic> {
130    match args.get(idx) {
131        Some(Value::Record(map)) => Ok(map.clone()),
132        _ => Err(Diagnostic::new(
133            DiagCode::E100,
134            span,
135            format!("{ctx}: argument #{idx} must be a record"),
136        )),
137    }
138}