Skip to main content

vibe/cbor_ast/cbor_ld/
mod.rs

1//! W3C CBOR-LD (`0xD9 0x0501` / `0xD9 0x0500`) Runtime Value Codec, Term Table,
2//! and Provider/TLD-Scoped JSON Namespace Uplift.
3
4pub mod json_uplift;
5pub mod terms;
6pub mod value_codec;
7
8use std::collections::BTreeMap;
9
10pub use json_uplift::{derive_provider_namespace, ingest_json_with_provider_ns};
11pub use terms::*;
12pub use value_codec::{decode_value_cbor_ld, encode_value_cbor_ld};
13
14use crate::error::{DiagCode, Diagnostic};
15use crate::span::Span;
16use crate::value::Value;
17
18/// Dispatches `cbor_ld.*` built-in calls for VibeScript (`vibe-0.1`).
19pub fn call_cbor_ld(path: &str, args: &[Value], span: Span) -> Result<Option<Value>, Diagnostic> {
20    match path {
21        "cbor_ld.encode" => {
22            let val = args.first().ok_or_else(|| {
23                Diagnostic::new(DiagCode::E600, span, "cbor_ld.encode requires a value")
24            })?;
25            let ctx = extract_opt_str(args.get(1)).unwrap_or(DEFAULT_CONTEXT_IRI);
26            let bytes = encode_value_cbor_ld(val, ctx);
27            let mut rec = BTreeMap::new();
28            rec.insert("__cbor_ld".to_string(), Value::Bool(true));
29            rec.insert("tag".to_string(), Value::I64(TAG_CBOR_LD_COMPRESSED as i64));
30            rec.insert("context".to_string(), Value::String(ctx.to_string()));
31            rec.insert("byte_len".to_string(), Value::I64(bytes.len() as i64));
32            rec.insert("hex".to_string(), Value::String(hex_encode(&bytes)));
33            rec.insert(
34                "bytes".to_string(),
35                Value::List(bytes.iter().map(|&b| Value::I64(b as i64)).collect()),
36            );
37            Ok(Some(Value::Record(rec)))
38        }
39        "cbor_ld.decode" => {
40            let arg = args.first().ok_or_else(|| {
41                Diagnostic::new(DiagCode::E600, span, "cbor_ld.decode requires 1 argument")
42            })?;
43            let raw = extract_cbor_bytes(arg, span)?;
44            let (_ctx, decoded) = decode_value_cbor_ld(&raw)
45                .map_err(|e| Diagnostic::new(DiagCode::E600, span, format!("CBOR-LD decode error: {e}")))?;
46            Ok(Some(decoded))
47        }
48        "cbor_ld.compress_iri" => {
49            let iri = args
50                .first()
51                .and_then(|v| extract_opt_str(Some(v)))
52                .ok_or_else(|| {
53                    Diagnostic::new(
54                        DiagCode::E600,
55                        span,
56                        "cbor_ld.compress_iri requires an IRI or string argument",
57                    )
58                })?;
59            let ctx = extract_opt_str(args.get(1)).unwrap_or(DEFAULT_CONTEXT_IRI);
60            Ok(Some(Value::U64(compress_iri(iri, ctx))))
61        }
62        "cbor_ld.expand_term" => {
63            let term_id = match args.first() {
64                Some(Value::U64(n)) => *n,
65                Some(Value::I64(n)) if *n >= 0 => *n as u64,
66                _ => {
67                    return Err(Diagnostic::new(
68                        DiagCode::E600,
69                        span,
70                        "cbor_ld.expand_term requires a non-negative integer term ID",
71                    ))
72                }
73            };
74            let ctx = extract_opt_str(args.get(1)).unwrap_or(DEFAULT_CONTEXT_IRI);
75            let expanded = expand_term(term_id, ctx).ok_or_else(|| {
76                Diagnostic::new(
77                    DiagCode::E600,
78                    span,
79                    format!("unknown CBOR-LD term ID {term_id}"),
80                )
81            })?;
82            Ok(Some(Value::Iri(expanded)))
83        }
84        "cbor_ld.verify_deterministic" => {
85            let arg = args.first().ok_or_else(|| {
86                Diagnostic::new(
87                    DiagCode::E600,
88                    span,
89                    "cbor_ld.verify_deterministic requires 1 argument",
90                )
91            })?;
92            let raw = match extract_cbor_bytes(arg, span) {
93                Ok(b) => b,
94                Err(_) => return Ok(Some(Value::Bool(false))),
95            };
96            let is_det = match decode_value_cbor_ld(&raw) {
97                Ok((ctx, val)) => encode_value_cbor_ld(&val, &ctx) == raw,
98                Err(_) => false,
99            };
100            Ok(Some(Value::Bool(is_det)))
101        }
102        "cbor_ld.ingest_json" => {
103            let json_src = extract_opt_str(args.first()).ok_or_else(|| {
104                Diagnostic::new(
105                    DiagCode::E600,
106                    span,
107                    "cbor_ld.ingest_json requires a JSON string as argument 0",
108                )
109            })?;
110            let provider = extract_opt_str(args.get(1)).ok_or_else(|| {
111                Diagnostic::new(
112                    DiagCode::E600,
113                    span,
114                    "cbor_ld.ingest_json requires a provider domain or TLD as argument 1",
115                )
116            })?;
117            let rec = ingest_json_with_provider_ns(json_src, provider)
118                .map_err(|e| Diagnostic::new(DiagCode::E600, span, e))?;
119            Ok(Some(rec))
120        }
121        "cbor_ld.provider_namespace" => {
122            let provider = extract_opt_str(args.first()).ok_or_else(|| {
123                Diagnostic::new(
124                    DiagCode::E600,
125                    span,
126                    "cbor_ld.provider_namespace requires a provider domain or TLD",
127                )
128            })?;
129            let (host, tld, ns_iri) = derive_provider_namespace(provider)
130                .map_err(|e| Diagnostic::new(DiagCode::E600, span, e))?;
131            let mut rec = BTreeMap::new();
132            rec.insert("provider_host".to_string(), Value::String(host));
133            rec.insert("provider_tld".to_string(), Value::String(tld));
134            rec.insert("namespace".to_string(), Value::Iri(ns_iri));
135            Ok(Some(Value::Record(rec)))
136        }
137        _ => Ok(None),
138    }
139}
140
141fn extract_opt_str(v: Option<&Value>) -> Option<&str> {
142    match v {
143        Some(Value::String(s)) | Some(Value::Iri(s)) => Some(s.as_str()),
144        _ => None,
145    }
146}
147
148fn extract_cbor_bytes(val: &Value, span: Span) -> Result<Vec<u8>, Diagnostic> {
149    match val {
150        Value::Record(map) => {
151            if let Some(Value::String(hex)) = map.get("hex") {
152                return hex_decode(hex, span);
153            }
154            if let Some(Value::List(list)) = map.get("bytes") {
155                return extract_byte_list(list, span);
156            }
157            Err(Diagnostic::new(
158                DiagCode::E600,
159                span,
160                "CBOR-LD record missing 'hex' or 'bytes' field",
161            ))
162        }
163        Value::String(hex) => hex_decode(hex, span),
164        Value::List(list) => extract_byte_list(list, span),
165        _ => Err(Diagnostic::new(
166            DiagCode::E600,
167            span,
168            "expected CBOR-LD record, hex string, or byte list",
169        )),
170    }
171}
172
173fn extract_byte_list(list: &[Value], span: Span) -> Result<Vec<u8>, Diagnostic> {
174    let mut out = Vec::with_capacity(list.len());
175    for item in list {
176        let n = match item {
177            Value::I64(v) if (0..=255).contains(v) => *v as u8,
178            Value::U64(v) if *v <= 255 => *v as u8,
179            _ => {
180                return Err(Diagnostic::new(
181                    DiagCode::E600,
182                    span,
183                    "byte list elements must be integers in 0..=255",
184                ))
185            }
186        };
187        out.push(n);
188    }
189    Ok(out)
190}
191
192pub(crate) fn hex_encode(bytes: &[u8]) -> String {
193    const HEX: &[u8; 16] = b"0123456789abcdef";
194    let mut out = String::with_capacity(bytes.len() * 2);
195    for &b in bytes {
196        out.push(HEX[(b >> 4) as usize] as char);
197        out.push(HEX[(b & 0x0F) as usize] as char);
198    }
199    out
200}
201
202fn hex_decode(hex: &str, span: Span) -> Result<Vec<u8>, Diagnostic> {
203    let clean = hex.trim().strip_prefix("0x").unwrap_or(hex.trim());
204    if clean.len() % 2 != 0 {
205        return Err(Diagnostic::new(
206            DiagCode::E600,
207            span,
208            "hex string must have even length",
209        ));
210    }
211    let mut out = Vec::with_capacity(clean.len() / 2);
212    let bytes = clean.as_bytes();
213    for i in (0..bytes.len()).step_by(2) {
214        let hi = (bytes[i] as char).to_digit(16);
215        let lo = (bytes[i + 1] as char).to_digit(16);
216        match (hi, lo) {
217            (Some(h), Some(l)) => out.push(((h << 4) | l) as u8),
218            _ => {
219                return Err(Diagnostic::new(
220                    DiagCode::E600,
221                    span,
222                    "invalid hex digit in CBOR-LD payload",
223                ))
224            }
225        }
226    }
227    Ok(out)
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use crate::value::{Duration, Instant, Quantity, QuinRef};
234
235    #[test]
236    fn static_and_dynamic_term_compression_round_trip() {
237        let static_id = compress_iri("qudt:KiloPascal", DEFAULT_CONTEXT_IRI);
238        assert_eq!(static_id, 40);
239        assert_eq!(
240            expand_term(static_id, DEFAULT_CONTEXT_IRI).as_deref(),
241            Some("qudt:KiloPascal")
242        );
243
244        let dyn_id = compress_iri("https://alice.org.au/ns#pressure", DEFAULT_CONTEXT_IRI);
245        assert_ne!(dyn_id & DYNAMIC_TERM_BIT, 0);
246        assert_eq!(dyn_id & !TOKEN_60BIT_MASK, 0);
247        let expanded = expand_term(dyn_id, DEFAULT_CONTEXT_IRI).unwrap();
248        assert!(expanded.starts_with("did:q42:term:"));
249        assert_eq!(compress_iri(&expanded, DEFAULT_CONTEXT_IRI), dyn_id);
250    }
251
252    #[test]
253    fn encode_decode_all_value_variants_deterministic() {
254        let mut rec = BTreeMap::new();
255        rec.insert("ui:target_id".to_string(), Value::String("btn_1".into()));
256        rec.insert(
257            "ui:value".to_string(),
258            Value::Quantity(Quantity::new(101.325, "qudt:KiloPascal")),
259        );
260        rec.insert("instant".to_string(), Value::Instant(Instant::unix(1700000000, 42)));
261        rec.insert("duration".to_string(), Value::Duration(Duration::from_nanos(5_000_000)));
262        rec.insert(
263            "quin".to_string(),
264            Value::QuinRef(QuinRef::from_quin(11, 22, 33, 44)),
265        );
266        rec.insert(
267            "denied".to_string(),
268            Value::DisclosureDenied {
269                capability: "clinical.read".into(),
270                reason: "consent required".into(),
271            },
272        );
273        rec.insert("iri".to_string(), Value::Iri("qudt:Meter".into()));
274        rec.insert("u64_val".to_string(), Value::U64(999));
275        let root = Value::Record(rec);
276
277        let bytes = encode_value_cbor_ld(&root, DEFAULT_CONTEXT_IRI);
278        // 0xD9 0x0501 = compressed CBOR-LD header
279        assert_eq!(&bytes[0..3], &[0xD9, 0x05, 0x01]);
280        let (ctx, decoded) = decode_value_cbor_ld(&bytes).unwrap();
281        assert_eq!(ctx, DEFAULT_CONTEXT_IRI);
282        assert_eq!(decoded, root);
283
284        let span = Span::new(0, 0);
285        let enc_val = call_cbor_ld("cbor_ld.encode", &[root.clone()], span)
286            .unwrap()
287            .unwrap();
288        let det = call_cbor_ld("cbor_ld.verify_deterministic", &[enc_val.clone()], span)
289            .unwrap()
290            .unwrap();
291        assert_eq!(det, Value::Bool(true));
292        let dec_val = call_cbor_ld("cbor_ld.decode", &[enc_val], span)
293            .unwrap()
294            .unwrap();
295        assert_eq!(dec_val, root);
296    }
297
298    #[test]
299    fn provider_tld_json_namespace_uplift_and_cbor_ld_encoding() {
300        let json = r#"{"patient_id": "p-42", "systolic_kpa": 16.0, "active": true}"#;
301        let res = ingest_json_with_provider_ns(json, "https://api.hospital.health/v1").unwrap();
302        let Value::Record(map) = &res else {
303            panic!("expected Record from ingest_json_with_provider_ns");
304        };
305        assert_eq!(
306            map.get("provider_host"),
307            Some(&Value::String("api.hospital.health".into()))
308        );
309        assert_eq!(
310            map.get("provider_tld"),
311            Some(&Value::String("health".into()))
312        );
313        assert_eq!(
314            map.get("context"),
315            Some(&Value::String("https://api.hospital.health/ns#".into()))
316        );
317
318        let span = Span::new(0, 0);
319        let decoded = call_cbor_ld("cbor_ld.decode", &[res], span).unwrap().unwrap();
320        let Value::Record(uplifted) = decoded else {
321            panic!("expected decoded Record");
322        };
323        assert_eq!(
324            uplifted.get("https://api.hospital.health/ns#patient_id"),
325            Some(&Value::String("p-42".into()))
326        );
327        assert_eq!(
328            uplifted.get("@provider_tld"),
329            Some(&Value::String("health".into()))
330        );
331
332        // Also test bare TLD input like ".gov.au"
333        let (host, tld, ns) = derive_provider_namespace(".gov.au").unwrap();
334        assert_eq!(host, "tld.gov.au");
335        assert_eq!(tld, "au");
336        assert_eq!(ns, "https://tld.gov.au/ns#");
337    }
338}