Skip to main content

agent_first_data/document/format/
json.rs

1//! JSON format backend (via serde_json).
2
3use crate::document::{DocumentError, DocumentResult, Value};
4
5/// Lossless JSON source document. The parsed node tree stores byte spans for
6/// every value/member, so editors can replace only the requested span while
7/// retaining untouched ordering, whitespace, escapes, and number spelling.
8#[derive(Debug)]
9pub struct JsonDocument<'a> {
10    source: &'a str,
11    root: Node,
12}
13
14impl<'a> JsonDocument<'a> {
15    pub fn parse(source: &'a str) -> DocumentResult<Self> {
16        let mut parser = Parser::new(source);
17        let root = parser.parse_value(0)?;
18        if parser.skip_ws(root.end) != source.len() {
19            return Err(DocumentError::ParseError {
20                format: "JSON".to_string(),
21                detail: "trailing bytes after root value".to_string(),
22            });
23        }
24        Ok(Self { source, root })
25    }
26
27    #[must_use]
28    pub fn source(&self) -> &'a str {
29        self.source
30    }
31
32    #[must_use]
33    pub(crate) fn root(&self) -> &Node {
34        &self.root
35    }
36}
37
38/// Set a JSON value at `path` while retaining every byte outside the edited
39/// region. JSON has no comments, but this still preserves key order,
40/// whitespace, line endings, escapes, and untouched number spellings.
41///
42/// Matches the in-memory [`crate::document::set_path`] capability:
43/// - an existing value (scalar *or* collection) is replaced in place;
44/// - a missing leaf, and any missing intermediate parent objects, are created
45///   under the deepest existing ancestor object.
46pub fn set_preserving(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
47    let segments = crate::document::parse_path(path)?;
48    let document = JsonDocument::parse(content)?;
49    let root = document.root();
50    let mut output = content.to_string();
51    match resolve(root, &segments, 0) {
52        Some(target) => {
53            // Replace the whole existing node span — scalar or collection. A
54            // replaced collection is re-rendered compactly; everything outside
55            // its span (and key order) is untouched.
56            let replacement = compact_json(value)?;
57            output.replace_range(target.start..target.end, &replacement);
58        }
59        None => {
60            // The full path is absent. Find the deepest existing ancestor
61            // object, then splice one new member holding the remaining path
62            // chain wrapped around the leaf value — creating every missing
63            // intermediate object along the way.
64            let (insert_at, tail) = deepest_existing_object(root, &segments).ok_or_else(|| {
65                DocumentError::UnsupportedOperation {
66                    format: "JSON".to_string(),
67                    operation: "set".to_string(),
68                    detail: "cannot insert a new key into a non-object JSON value".to_string(),
69                }
70            })?;
71            let NodeKind::Object(entries) = &insert_at.kind else {
72                unreachable!("deepest_existing_object only returns object nodes");
73            };
74            let (member_key, rest) = tail.split_first().ok_or(DocumentError::EmptyPath)?;
75            let new_key =
76                serde_json::to_string(member_key).map_err(|error| DocumentError::ParseError {
77                    format: "JSON".to_string(),
78                    detail: error.to_string(),
79                })?;
80            let (position, fragment) = match entries.last() {
81                Some((_, last_node)) => {
82                    let anchor = last_node.member_start.unwrap_or(last_node.start);
83                    let (indent, multiline) = member_indent(content.as_bytes(), anchor);
84                    let member_value = nested_member_value(rest, value, multiline, &indent)?;
85                    let fragment = if multiline {
86                        format!(",\n{indent}{new_key}: {member_value}")
87                    } else {
88                        format!(", {new_key}: {member_value}")
89                    };
90                    (last_node.end, fragment)
91                }
92                None => {
93                    // Empty object: no sibling to mirror, so stay inline compact.
94                    let member_value = nested_member_value(rest, value, false, "")?;
95                    (insert_at.start + 1, format!("{new_key}: {member_value}"))
96                }
97            };
98            output.insert_str(position, &fragment);
99        }
100    }
101    serde_json::from_str::<serde_json::Value>(&output).map_err(|error| {
102        DocumentError::ParseError {
103            format: "JSON".to_string(),
104            detail: error.to_string(),
105        }
106    })?;
107    Ok(output)
108}
109
110/// Compact one-line JSON rendering of a document value.
111fn compact_json(value: &Value) -> DocumentResult<String> {
112    let json_value = serde_json::Value::try_from(value)?;
113    serde_json::to_string(&json_value).map_err(|error| DocumentError::UnsupportedOperation {
114        format: "JSON".to_string(),
115        operation: "set".to_string(),
116        detail: error.to_string(),
117    })
118}
119
120/// The deepest node reachable along `segments` that is an object, paired with
121/// the still-missing tail below it. Returns `None` if that deepest existing
122/// node is not an object (so a child key cannot be created under it).
123fn deepest_existing_object<'a>(
124    root: &'a Node,
125    segments: &'a [String],
126) -> Option<(&'a Node, &'a [String])> {
127    // `segments` itself does not resolve (checked by the caller), so start one
128    // level up and walk toward the root; the root (empty prefix) always exists.
129    for split in (0..segments.len()).rev() {
130        if let Some(node) = resolve(root, &segments[..split], 0) {
131            return match node.kind {
132                NodeKind::Object(_) => Some((node, &segments[split..])),
133                _ => None,
134            };
135        }
136    }
137    None
138}
139
140/// Render the value for a spliced member: the leaf `value` wrapped in an object
141/// for each remaining `tail` segment (`["a","b"] , v` → `{"a":{"b":v}}`).
142/// Multiline output is re-indented to sit at `base_indent`.
143fn nested_member_value(
144    tail: &[String],
145    value: &Value,
146    multiline: bool,
147    base_indent: &str,
148) -> DocumentResult<String> {
149    let mut nested = serde_json::Value::try_from(value)?;
150    for segment in tail.iter().rev() {
151        let mut object = serde_json::Map::new();
152        object.insert(segment.clone(), nested);
153        nested = serde_json::Value::Object(object);
154    }
155    if multiline {
156        let pretty =
157            serde_json::to_string_pretty(&nested).map_err(|error| DocumentError::ParseError {
158                format: "JSON".to_string(),
159                detail: error.to_string(),
160            })?;
161        Ok(pretty.replace('\n', &format!("\n{base_indent}")))
162    } else {
163        serde_json::to_string(&nested).map_err(|error| DocumentError::ParseError {
164            format: "JSON".to_string(),
165            detail: error.to_string(),
166        })
167    }
168}
169
170/// Indentation of the member whose key begins at `anchor`, and whether that
171/// member sits on its own line (so a spliced sibling should too).
172fn member_indent(bytes: &[u8], anchor: usize) -> (String, bool) {
173    match bytes[..anchor].iter().rposition(|byte| *byte == b'\n') {
174        Some(newline) => {
175            let indent = bytes[newline + 1..anchor]
176                .iter()
177                .take_while(|byte| matches!(byte, b' ' | b'\t'))
178                .map(|byte| *byte as char)
179                .collect();
180            (indent, true)
181        }
182        None => (String::new(), false),
183    }
184}
185
186/// Remove one existing JSON member or array item while preserving the rest of
187/// the source layout. Removing the root value is intentionally unsupported.
188pub fn unset_preserving(content: &str, path: &str) -> DocumentResult<String> {
189    let segments = crate::document::parse_path(path)?;
190    let document = JsonDocument::parse(content)?;
191    let root = document.root();
192    let target = resolve(root, &segments, 0).ok_or_else(|| DocumentError::PathNotFound {
193        path: path.to_string(),
194    })?;
195    if target.member_start.is_none()
196        && matches!(target.kind, NodeKind::Scalar)
197        && segments.is_empty()
198    {
199        return Err(DocumentError::UnsupportedOperation {
200            format: "JSON".to_string(),
201            operation: "unset".to_string(),
202            detail: "cannot remove the JSON root value".to_string(),
203        });
204    }
205    let mut start = target.member_start.unwrap_or(target.start);
206    if target.member_start.is_some()
207        && let Some(newline) = content.as_bytes()[..start]
208            .iter()
209            .rposition(|byte| *byte == b'\n')
210    {
211        let candidate = newline + 1;
212        if content.as_bytes()[candidate..start]
213            .iter()
214            .all(|byte| byte.is_ascii_whitespace())
215        {
216            start = candidate;
217        }
218    }
219    let end = target.end;
220    let after = skip_ws_bytes(content.as_bytes(), end);
221    // Removing a last/only member also removes the comma *before* it — but that
222    // search must stay inside the target's own parent container. A comma
223    // belonging to an enclosing object/array (e.g. a sibling earlier in the
224    // document) is not ours to take, or we splice across a container boundary.
225    let parent_body_start =
226        resolve(root, &segments[..segments.len() - 1], 0).map_or(0, |parent| parent.start + 1);
227    let (remove_start, mut remove_end, remove_following_line) =
228        if content.as_bytes().get(after) == Some(&b',') {
229            (start, after + 1, true)
230        } else if let Some(offset) = content.as_bytes()[parent_body_start..start]
231            .iter()
232            .rposition(|byte| *byte == b',')
233        {
234            (parent_body_start + offset, end, false)
235        } else {
236            (start, end, false)
237        };
238    if remove_following_line {
239        if content.as_bytes().get(remove_end) == Some(&b'\r') {
240            remove_end += 1;
241        }
242        if content.as_bytes().get(remove_end) == Some(&b'\n') {
243            remove_end += 1;
244        }
245    }
246    let mut output = content.to_string();
247    output.replace_range(remove_start..remove_end, "");
248    serde_json::from_str::<serde_json::Value>(&output).map_err(|error| {
249        DocumentError::ParseError {
250            format: "JSON".to_string(),
251            detail: error.to_string(),
252        }
253    })?;
254    Ok(output)
255}
256
257/// Append one JSON array item while retaining the existing array's trailing
258/// whitespace and all bytes outside the insertion point.
259pub fn append_array_item_preserving(
260    content: &str,
261    path: &str,
262    item: &Value,
263) -> DocumentResult<String> {
264    let segments = crate::document::parse_path(path)?;
265    let mut parser = Parser::new(content);
266    let root = parser.parse_value(0)?;
267    let target = resolve(&root, &segments, 0).ok_or_else(|| DocumentError::PathNotFound {
268        path: path.to_string(),
269    })?;
270    let NodeKind::Array(items) = &target.kind else {
271        return Err(DocumentError::UnsupportedOperation {
272            format: "JSON".to_string(),
273            operation: "add".to_string(),
274            detail: "target is not an array".to_string(),
275        });
276    };
277    let json_item = serde_json::Value::try_from(item)?;
278    let fragment =
279        serde_json::to_string(&json_item).map_err(|error| DocumentError::UnsupportedOperation {
280            format: "JSON".to_string(),
281            operation: "add".to_string(),
282            detail: error.to_string(),
283        })?;
284    let close = target
285        .end
286        .checked_sub(1)
287        .ok_or_else(|| DocumentError::ParseError {
288            format: "JSON".to_string(),
289            detail: "invalid array span".to_string(),
290        })?;
291    let whitespace_start = content.as_bytes()[target.start + 1..close]
292        .iter()
293        .rposition(|byte| !byte.is_ascii_whitespace())
294        .map(|index| target.start + 2 + index)
295        .unwrap_or(target.start + 1);
296    let insertion = if items.is_empty() {
297        fragment
298    } else {
299        format!(", {fragment}")
300    };
301    let mut output = content.to_string();
302    output.insert_str(whitespace_start, &insertion);
303    serde_json::from_str::<serde_json::Value>(&output).map_err(|error| {
304        DocumentError::ParseError {
305            format: "JSON".to_string(),
306            detail: error.to_string(),
307        }
308    })?;
309    Ok(output)
310}
311
312/// Remove a keyed object from a JSON array without rebuilding the document.
313pub fn remove_array_item_preserving(
314    content: &str,
315    path: &str,
316    slug: &str,
317    slug_field: &str,
318) -> DocumentResult<String> {
319    let segments = crate::document::parse_path(path)?;
320    let mut parser = Parser::new(content);
321    let root = parser.parse_value(0)?;
322    let target = resolve(&root, &segments, 0).ok_or_else(|| DocumentError::PathNotFound {
323        path: path.to_string(),
324    })?;
325    let NodeKind::Array(items) = &target.kind else {
326        return Err(DocumentError::UnsupportedOperation {
327            format: "JSON".to_string(),
328            operation: "remove".to_string(),
329            detail: "target is not an array".to_string(),
330        });
331    };
332    let item = items
333        .iter()
334        .find(|item| {
335            let Ok(value) =
336                serde_json::from_str::<serde_json::Value>(&content[item.start..item.end])
337            else {
338                return false;
339            };
340            value.get(slug_field).and_then(serde_json::Value::as_str) == Some(slug)
341        })
342        .ok_or_else(|| DocumentError::SlugNotFound {
343            prefix: path.to_string(),
344            slug: slug.to_string(),
345        })?;
346    let mut start = item.start;
347    if let Some(newline) = content.as_bytes()[..start]
348        .iter()
349        .rposition(|byte| *byte == b'\n')
350    {
351        let candidate = newline + 1;
352        if content.as_bytes()[candidate..start]
353            .iter()
354            .all(|byte| byte.is_ascii_whitespace())
355        {
356            start = candidate;
357        }
358    }
359    let after = skip_ws_bytes(content.as_bytes(), item.end);
360    let (mut remove_start, mut remove_end, remove_following_line) =
361        if content.as_bytes().get(after) == Some(&b',') {
362            (start, after + 1, true)
363        } else if let Some(comma) = content.as_bytes()[target.start..start]
364            .iter()
365            .rposition(|byte| *byte == b',')
366            .map(|offset| target.start + offset)
367        {
368            // Scoped to the array's own span (`target.start..start`), not
369            // the whole document: an unscoped backward search can walk past
370            // the array's opening `[` and land on an unrelated preceding
371            // sibling's comma (e.g. `{"a":1,"items":[{"id":"x"}]}` removing
372            // the sole item), corrupting the document instead of just
373            // collapsing the array to `[]`.
374            (comma, item.end, false)
375        } else {
376            (start, item.end, false)
377        };
378    if remove_following_line {
379        if content.as_bytes().get(remove_end) == Some(&b'\r') {
380            remove_end += 1;
381        }
382        if content.as_bytes().get(remove_end) == Some(&b'\n') {
383            remove_end += 1;
384        }
385    }
386    if remove_start > remove_end {
387        std::mem::swap(&mut remove_start, &mut remove_end);
388    }
389    let mut output = content.to_string();
390    output.replace_range(remove_start..remove_end, "");
391    serde_json::from_str::<serde_json::Value>(&output).map_err(|error| {
392        DocumentError::ParseError {
393            format: "JSON".to_string(),
394            detail: error.to_string(),
395        }
396    })?;
397    Ok(output)
398}
399
400fn skip_ws_bytes(source: &[u8], mut position: usize) -> usize {
401    while source
402        .get(position)
403        .is_some_and(|byte| matches!(byte, b' ' | b'\n' | b'\r' | b'\t'))
404    {
405        position += 1;
406    }
407    position
408}
409
410#[derive(Debug, Clone)]
411pub(crate) struct Node {
412    start: usize,
413    end: usize,
414    member_start: Option<usize>,
415    kind: NodeKind,
416}
417
418#[derive(Debug, Clone)]
419enum NodeKind {
420    Scalar,
421    Object(Vec<(String, Node)>),
422    Array(Vec<Node>),
423}
424
425fn resolve<'a>(node: &'a Node, segments: &[String], index: usize) -> Option<&'a Node> {
426    if index == segments.len() {
427        return Some(node);
428    }
429    match &node.kind {
430        NodeKind::Object(entries) => entries
431            .iter()
432            .rev()
433            .find(|(key, _)| key == &segments[index])
434            .and_then(|(_, child)| resolve(child, segments, index + 1)),
435        NodeKind::Array(items) => segments[index]
436            .parse::<usize>()
437            .ok()
438            .and_then(|item| items.get(item))
439            .and_then(|child| resolve(child, segments, index + 1)),
440        NodeKind::Scalar => None,
441    }
442}
443
444struct Parser<'a> {
445    source: &'a [u8],
446}
447
448impl<'a> Parser<'a> {
449    fn new(source: &'a str) -> Self {
450        Self {
451            source: source.as_bytes(),
452        }
453    }
454
455    fn parse_value(&mut self, mut position: usize) -> DocumentResult<Node> {
456        position = self.skip_ws(position);
457        let start = position;
458        let Some(byte) = self.source.get(position).copied() else {
459            return self.error(position, "expected JSON value");
460        };
461        let kind = match byte {
462            b'{' => self.parse_object(&mut position)?,
463            b'[' => self.parse_array(&mut position)?,
464            b'"' => {
465                position = self.parse_string(position)?;
466                NodeKind::Scalar
467            }
468            _ => {
469                position = self.parse_scalar(position)?;
470                NodeKind::Scalar
471            }
472        };
473        Ok(Node {
474            start,
475            end: position,
476            member_start: None,
477            kind,
478        })
479    }
480
481    fn parse_object(&mut self, position: &mut usize) -> DocumentResult<NodeKind> {
482        *position += 1;
483        let mut entries = Vec::new();
484        let mut keys = std::collections::HashSet::new();
485        loop {
486            *position = self.skip_ws(*position);
487            if self.source.get(*position) == Some(&b'}') {
488                *position += 1;
489                return Ok(NodeKind::Object(entries));
490            }
491            let key_start = *position;
492            let key_end = self.parse_string(*position)?;
493            let key = serde_json::from_slice::<String>(&self.source[key_start..key_end]).map_err(
494                |error| DocumentError::ParseError {
495                    format: "JSON".to_string(),
496                    detail: error.to_string(),
497                },
498            )?;
499            if !keys.insert(key.clone()) {
500                return self.error(key_start, "duplicate object key");
501            }
502            *position = self.skip_ws(key_end);
503            if self.source.get(*position) != Some(&b':') {
504                return self.error(*position, "expected `:` after object key");
505            }
506            *position += 1;
507            let child = self.parse_value(*position)?;
508            *position = child.end;
509            let mut child = child;
510            child.member_start = Some(key_start);
511            entries.push((key, child));
512            *position = self.skip_ws(*position);
513            match self.source.get(*position) {
514                Some(b',') => *position += 1,
515                Some(b'}') => {
516                    *position += 1;
517                    return Ok(NodeKind::Object(entries));
518                }
519                _ => return self.error(*position, "expected `,` or `}` in object"),
520            }
521        }
522    }
523
524    fn parse_array(&mut self, position: &mut usize) -> DocumentResult<NodeKind> {
525        *position += 1;
526        let mut items = Vec::new();
527        loop {
528            *position = self.skip_ws(*position);
529            if self.source.get(*position) == Some(&b']') {
530                *position += 1;
531                return Ok(NodeKind::Array(items));
532            }
533            let child = self.parse_value(*position)?;
534            *position = child.end;
535            items.push(child);
536            *position = self.skip_ws(*position);
537            match self.source.get(*position) {
538                Some(b',') => *position += 1,
539                Some(b']') => {
540                    *position += 1;
541                    return Ok(NodeKind::Array(items));
542                }
543                _ => return self.error(*position, "expected `,` or `]` in array"),
544            }
545        }
546    }
547
548    fn parse_string(&self, mut position: usize) -> DocumentResult<usize> {
549        if self.source.get(position) != Some(&b'"') {
550            return self.error(position, "expected JSON string");
551        }
552        position += 1;
553        let mut escaped = false;
554        while let Some(byte) = self.source.get(position).copied() {
555            position += 1;
556            if escaped {
557                escaped = false;
558            } else if byte == b'\\' {
559                escaped = true;
560            } else if byte == b'"' {
561                return Ok(position);
562            }
563        }
564        self.error(position, "unterminated JSON string")
565    }
566
567    fn parse_scalar(&self, mut position: usize) -> DocumentResult<usize> {
568        let start = position;
569        while let Some(byte) = self.source.get(position).copied() {
570            if matches!(byte, b',' | b']' | b'}' | b' ' | b'\n' | b'\r' | b'\t') {
571                break;
572            }
573            position += 1;
574        }
575        if position == start {
576            return self.error(position, "empty JSON scalar");
577        }
578        serde_json::from_slice::<serde_json::Value>(&self.source[start..position])
579            .map_err(|error| DocumentError::ParseError {
580                format: "JSON".to_string(),
581                detail: error.to_string(),
582            })
583            .map(|_| position)
584    }
585
586    fn skip_ws(&self, mut position: usize) -> usize {
587        while self
588            .source
589            .get(position)
590            .is_some_and(|byte| matches!(byte, b' ' | b'\n' | b'\r' | b'\t'))
591        {
592            position += 1;
593        }
594        position
595    }
596
597    fn error<T>(&self, position: usize, detail: &str) -> DocumentResult<T> {
598        Err(DocumentError::ParseError {
599            format: "JSON".to_string(),
600            detail: format!("at byte {position}: {detail}"),
601        })
602    }
603}
604
605pub fn load(content: &str) -> DocumentResult<Value> {
606    JsonDocument::parse(content)?;
607    serde_json::from_str::<serde_json::Value>(content)
608        .map(Value::from)
609        .map_err(|e| DocumentError::ParseError {
610            format: "JSON".to_string(),
611            detail: e.to_string(),
612        })
613}
614
615pub fn save(value: &Value) -> DocumentResult<String> {
616    let json_val = serde_json::Value::try_from(value)?;
617    serde_json::to_string_pretty(&json_val).map_err(|e| DocumentError::ParseError {
618        format: "JSON".to_string(),
619        detail: e.to_string(),
620    })
621}
622
623#[cfg(test)]
624mod tests {
625    use super::{JsonDocument, load, save};
626    use crate::document::Value;
627
628    #[test]
629    fn duplicate_keys_are_rejected_by_load_and_editor_parser() {
630        let source = r#"{"same":1,"same":2}"#;
631        assert!(load(source).is_err());
632        assert!(JsonDocument::parse(source).is_err());
633    }
634
635    #[test]
636    fn save_rejects_non_finite_float() {
637        let error = save(&Value::Float(f64::INFINITY)).expect_err("infinity must fail");
638        assert!(error.to_string().contains("non-finite"));
639    }
640}