Skip to main content

quillmark_core/document/
edit.rs

1//! Typed mutators for [`Document`] and [`Card`].
2//!
3//! Every successful mutator leaves user field names matching
4//! `[A-Za-z_][A-Za-z0-9_]*`, composable `$kind`s valid, values inside the §8
5//! depth bound, and each card within the §8 field count
6//! ([`MAX_FIELD_COUNT`](crate::error::MAX_FIELD_COUNT)), so the result is safely
7//! serializable to the backend plate and re-readable by the parser. A write
8//! that would create a field past the count is [`EditError::InvalidPayload`].
9//! `$ext`/`$seed` are opaque mappings that carry no field-name invariant, but
10//! do carry the depth bound.
11
12use std::collections::BTreeMap;
13
14use quillmark_content::markdown::ImportError;
15use quillmark_content::model::Content;
16
17use crate::document::base::StaleBase;
18use crate::document::meta::{CardKindError, validate_composable_kind};
19use crate::document::payload::MetaKey;
20use crate::document::{Card, Codec, ContentDecodeError, Document, Payload, PayloadItem};
21use crate::error::Diagnostic;
22use crate::error::diag_args;
23use crate::path::DocPath;
24use crate::quill::{CoercionError, FieldSchema, FieldType, Leniency, QuillConfig};
25use crate::value::{PathSegment, QuillValue};
26use crate::version::QuillReference;
27
28/// A field plus its in-field path, rendered through
29/// [`DocPath`] (`recipients[0].name`), so a message names
30/// the address its anchor does.
31fn render_at(field: &str, at: &[PathSegment]) -> String {
32    at.iter()
33        .fold(crate::path::DocPath::new().field(field), |p, seg| {
34            p.segment(seg)
35        })
36        .to_string()
37}
38
39/// `true` if `name` matches `[A-Za-z_][A-Za-z0-9_]*`, tested on `name`'s own
40/// characters: the parser reads a key's raw bytes, so a name that merely
41/// normalises to ASCII (`U+212A KELVIN SIGN`) is not a top-level key.
42///
43/// Case is preserved verbatim; only `$`-prefixed keys are reserved, so a user
44/// field can never shadow system metadata.
45pub fn is_valid_field_name(name: &str) -> bool {
46    let mut chars = name.chars();
47    let Some(first) = chars.next() else {
48        return false;
49    };
50    if !first.is_ascii_alphabetic() && first != '_' {
51        return false;
52    }
53    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
54}
55
56/// The `richtext` codec name carried by [`EditError::FieldDecode`] and
57/// [`EditError::FieldNotSingleLine`]. Frozen with the diagnostic arg: it is the
58/// schema keyword, not a display string.
59pub const CODEC_RICHTEXT: &str = "richtext";
60
61/// The `text` codec. See [`CODEC_RICHTEXT`].
62pub const CODEC_TEXT: &str = "text";
63
64/// Errors returned by document and card mutators.
65#[derive(Debug, Clone, PartialEq, thiserror::Error)]
66#[non_exhaustive]
67pub enum EditError {
68    #[error("invalid field name '{0}': must match [A-Za-z_][A-Za-z0-9_]*")]
69    InvalidFieldName(String),
70
71    /// A typed write ([`TypedWriter::set`](crate::writer::TypedWriter::set) /
72    /// [`CardWriter::set`](crate::writer::CardWriter::set)) or a schema-bound
73    /// read addressed a well-formed name the bound schema does not declare (or
74    /// a card whose `$kind` carries no schema). A property an `object` field
75    /// does not declare is the same error one level down, `at` naming it. Use
76    /// [`Card::store_field`](Card::store_field) for opaque storage.
77    #[error("field '{}' is not declared in the schema", render_at(.field, .at))]
78    UnknownField {
79        field: String,
80        /// The steps from the field to the undeclared name, its last segment
81        /// being that name: empty when the field itself is the undeclared one,
82        /// `[Key("zip")]` for an `address` object that declares no `zip`. Rides
83        /// the [`doc_path`](Self::doc_path) anchor as its own segments, so
84        /// `field` stays the field's name.
85        at: Vec<PathSegment>,
86    },
87
88    #[error("invalid card kind '{0}': must match [a-z_][a-z0-9_]*")]
89    InvalidKindName(String),
90
91    #[error("card kind 'main' is reserved for the document root")]
92    ReservedKind,
93
94    /// A card placed as a composable card carries a `$` entry that binds the
95    /// document root (`$quill`, `$seed`).
96    #[error("'{key}' is carried by the document root only, not by a composable card")]
97    RootOnlyEntry { key: String },
98
99    #[error("index {index} is out of range (len = {len})")]
100    IndexOutOfRange { index: usize, len: usize },
101
102    /// A card placed with a `$id` outside the card-id grammar
103    /// ([`is_card_id`](super::card_id::is_card_id)).
104    #[error(
105        "invalid card id '{0}': must be 1 to 64 of [A-Za-z0-9_-], opening with a letter or digit"
106    )]
107    InvalidCardId(String),
108
109    /// A card placed with a `$id` another card of the document holds.
110    #[error("card id '{0}' is already held by another card")]
111    DuplicateCardId(String),
112
113    /// A write naming a card by a `$id` no composable card of the document
114    /// holds.
115    #[error("no card holds the id '{0}'")]
116    UnknownCardId(String),
117
118    /// A card placed in a document already holding
119    /// [`MAX_CARD_COUNT`](crate::error::MAX_CARD_COUNT) composable cards, past
120    /// which its markdown fails `parse::too_many_cards`.
121    #[error("the document already holds the maximum of {max} cards")]
122    TooManyCards { max: usize },
123
124    #[error("value nests deeper than the maximum of {max} levels")]
125    ValueTooDeep { max: usize },
126
127    /// Markdown import failed: the markdown codec rejected the input for a body
128    /// *or* a field path (e.g. container nesting past
129    /// [`MAX_NESTING_DEPTH`](quillmark_content::MAX_NESTING_DEPTH)). Returned
130    /// instead of silently degrading the target to empty on a rejected import.
131    #[error("markdown import failed: {0}")]
132    Import(ImportError),
133
134    /// A value could not become the field's content through `codec`: a JSON
135    /// object that is not a canonical content, a markdown string that failed to
136    /// import, a shape that is neither object nor string, or formatting under
137    /// the plain-only `text` codec. `message` names which.
138    ///
139    /// `codec` is the declared type's, not the stored shape's. Absence is not
140    /// this error: a missing field is `None`, and reads as the empty content.
141    #[error("{codec} field '{}': {message}", render_at(.field, .at))]
142    FieldDecode {
143        field: String,
144        /// The steps from the field to the value that failed, empty when the
145        /// field itself is the value. Rides the [`doc_path`](Self::doc_path)
146        /// anchor as its own segments, so `field` stays the field's name.
147        at: Vec<PathSegment>,
148        /// The codec that ran, named by the field's declared type:
149        /// [`CODEC_RICHTEXT`] or [`CODEC_TEXT`].
150        codec: String,
151        message: String,
152    },
153
154    /// A `Content` read
155    /// ([`TypedReader::get_content`](crate::reader::TypedReader::get_content))
156    /// addressed a field whose declared type is not a content *leaf*. The
157    /// schema answers before the payload is consulted, and the test is narrower
158    /// than the subtree walk: an `array<richtext>` carries content yet has no
159    /// single `Content`, so it lands here. Address one of its elements with
160    /// [`get_content_at`](crate::reader::TypedReader::get_content_at), which
161    /// raises this in turn for a path that resolves to no content leaf.
162    #[error("field '{}' is declared '{declared}', which is not a content field", render_at(.field, .at))]
163    FieldNotContent {
164        field: String,
165        /// The steps from the field to the addressed value, empty when the field
166        /// itself is addressed. `declared` names the type reached, so a
167        /// `string[]` element reports `string` rather than the field's `array`.
168        at: Vec<PathSegment>,
169        declared: String,
170    },
171
172    /// A content field written under a one-line schema (`shape: line`)
173    /// decoded to a multi-line content. Both text codecs carry the constraint,
174    /// so one code covers both and `codec` says which codec raised it.
175    #[error(
176        "{codec} field '{field}' is not a single line: {codec} requires a single line with \
177         no container or island; declare shape: lines to admit more"
178    )]
179    FieldNotSingleLine {
180        field: String,
181        /// The codec whose one-line constraint was violated: [`CODEC_RICHTEXT`]
182        /// or [`CODEC_TEXT`].
183        codec: String,
184    },
185
186    /// A typed write could not coerce the value to the field's schema type: the
187    /// general failure for scalar/array/object types (a `"x"` for an `integer`,
188    /// a non-object for an `object`, …). Content fields report through
189    /// [`FieldDecode`](Self::FieldDecode) / [`FieldNotSingleLine`](Self::FieldNotSingleLine)
190    /// instead.
191    #[error("field '{field}' could not be coerced to its schema type: {message}")]
192    FieldCoercionFailed {
193        field: String,
194        /// The schema type the write was coerced against; `message` alone is
195        /// English.
196        target: String,
197        message: String,
198    },
199
200    /// A content [`Change`](quillmark_content::change::Change) the value
201    /// refused; the value is as it was.
202    #[error("content change refused: {0}")]
203    Change(quillmark_content::change::ApplyError),
204
205    /// Markdown a write imports past
206    /// [`MAX_MARKDOWN_SIZE`](quillmark_content::MAX_MARKDOWN_SIZE) bytes, or a
207    /// content value a binding takes whose text, its slots' included, is.
208    #[error("an input of {size} bytes is past the limit of {max}")]
209    InputTooLarge { size: usize, max: usize },
210
211    /// A change a binding takes holding more than
212    /// [`MAX_CHANGE_STEPS`](crate::document::MAX_CHANGE_STEPS) steps, nested
213    /// ones counted.
214    #[error("a change of {count} steps is past the limit of {max}")]
215    TooManySteps { count: usize, max: usize },
216
217    /// A value whose text holds more marks than
218    /// [`max_marks`](quillmark_content::max_marks) of its length, or a change
219    /// that would leave one.
220    #[error("{count} marks over a text that holds at most {max}")]
221    TooManyMarks { count: usize, max: usize },
222
223    /// A value holding more than
224    /// [`MAX_ANCHORS`](quillmark_content::MAX_ANCHORS) anchors, or a change
225    /// that would leave one.
226    #[error("{count} anchors, past the limit of {max}")]
227    TooManyAnchors { count: usize, max: usize },
228
229    /// The card's item list violates an invariant of the list as a whole. An
230    /// input path taking a whole payload at once ([`Card::try_from`] a
231    /// [`CardWire`](crate::document::CardWire)) reaches every variant; a field
232    /// write reaches [`PayloadViolation::TooManyFields`], the one invariant a
233    /// caller holding a `(name, value)` pair cannot check for itself.
234    #[error("{0}")]
235    InvalidPayload(PayloadViolation),
236
237    /// A revise or replace whose change removes an `x-` island. Markdown
238    /// cannot spell one, and a host's own model may hold none, so the writer
239    /// may never have seen it; removing one takes a change of its own through
240    /// [`Card::apply`].
241    #[error(
242        "the write removes the {kind} island '{island}', which its writer may not have seen; remove it with apply"
243    )]
244    DropsExtIsland { island: String, kind: String },
245
246    /// A write's base no longer names the value: `edit::stale_base`.
247    #[error(transparent)]
248    StaleBase(StaleBase),
249}
250
251impl EditError {
252    /// A refused change, as [`TooManyMarks`](Self::TooManyMarks) or
253    /// [`TooManyAnchors`](Self::TooManyAnchors) where it passed a bound.
254    pub fn change(e: quillmark_content::change::ApplyError) -> Self {
255        match &e {
256            quillmark_content::change::ApplyError::Invalid(inv) => {
257                Self::bound(inv).unwrap_or(EditError::Change(e))
258            }
259            _ => EditError::Change(e),
260        }
261    }
262
263    /// A refused import, as [`InputTooLarge`](Self::InputTooLarge) where its
264    /// markdown passed the size bound.
265    pub fn import(e: ImportError) -> Self {
266        match e {
267            ImportError::TooLarge { size, max } => EditError::InputTooLarge { size, max },
268            e => EditError::Import(e),
269        }
270    }
271
272    /// The error a content bound `inv` names, `None` for an invariant that
273    /// is not one.
274    pub fn bound(inv: &quillmark_content::model::Invariant) -> Option<Self> {
275        use quillmark_content::model::Invariant;
276        match *inv {
277            Invariant::TooManyMarks { marks, max } => {
278                Some(EditError::TooManyMarks { count: marks, max })
279            }
280            Invariant::TooManyAnchors { anchors, max } => Some(EditError::TooManyAnchors {
281                count: anchors,
282                max,
283            }),
284            _ => None,
285        }
286    }
287
288    pub(crate) fn unknown_field(name: impl Into<String>) -> Self {
289        EditError::UnknownField {
290            field: name.into(),
291            at: Vec::new(),
292        }
293    }
294
295    /// The namespaced diagnostic `code` (e.g. `"edit::invalid_field_name"`),
296    /// one per variant and the variant's only stable discriminator. Consumers
297    /// route on this, not on message text. Every code: `docs/reference/diagnostic-codes.md`.
298    pub fn code(&self) -> &'static str {
299        match self {
300            EditError::InvalidFieldName(_) => "edit::invalid_field_name",
301            EditError::UnknownField { .. } => "edit::unknown_field",
302            EditError::InvalidKindName(_) => "edit::invalid_kind_name",
303            EditError::ReservedKind => "edit::reserved_kind",
304            EditError::RootOnlyEntry { .. } => "edit::root_only_entry",
305            EditError::IndexOutOfRange { .. } => "edit::index_out_of_range",
306            EditError::InvalidCardId(_) => "edit::invalid_card_id",
307            EditError::DuplicateCardId(_) => "edit::duplicate_card_id",
308            EditError::UnknownCardId(_) => "edit::unknown_card_id",
309            EditError::TooManyCards { .. } => "edit::too_many_cards",
310            EditError::ValueTooDeep { .. } => "edit::value_too_deep",
311            EditError::Import(_) => "edit::import",
312            EditError::FieldDecode { .. } => "edit::field_decode",
313            EditError::FieldNotContent { .. } => "edit::field_not_content",
314            EditError::FieldNotSingleLine { .. } => "edit::field_not_single_line",
315            EditError::FieldCoercionFailed { .. } => "edit::field_coercion_failed",
316            EditError::Change(_) => "edit::content_apply",
317            EditError::InputTooLarge { .. } => "edit::input_too_large",
318            EditError::TooManySteps { .. } => "edit::too_many_steps",
319            EditError::TooManyMarks { .. } => "edit::too_many_marks",
320            EditError::TooManyAnchors { .. } => "edit::too_many_anchors",
321            EditError::InvalidPayload(_) => "edit::invalid_payload",
322            EditError::DropsExtIsland { .. } => "edit::drops_ext_island",
323            EditError::StaleBase(e) => e.code(),
324        }
325    }
326
327    /// The facts this error's message interpolates. See
328    /// [`Diagnostic::args`](crate::error::Diagnostic::args).
329    ///
330    /// `field` and `kind` ride here as well as in the anchor, because
331    /// [`DocPath`] renders field segments unescaped and
332    /// parses on `.` and `[`: a malformed name cannot be recovered from the
333    /// rendered path. An `at` path is structural, so it rides the anchor alone.
334    pub fn args(&self) -> BTreeMap<String, serde_json::Value> {
335        match self {
336            EditError::InvalidFieldName(field) => diag_args! { "field" => field },
337            EditError::UnknownField { field, at: _ } => diag_args! { "field" => field },
338            EditError::InvalidKindName(kind) => diag_args! { "kind" => kind },
339            EditError::ReservedKind => diag_args! {},
340            EditError::RootOnlyEntry { key } => diag_args! { "key" => key },
341            EditError::IndexOutOfRange { index, len } => diag_args! {
342                "index" => index,
343                "len" => len,
344            },
345            EditError::InvalidCardId(id)
346            | EditError::DuplicateCardId(id)
347            | EditError::UnknownCardId(id) => {
348                diag_args! { "id" => id }
349            }
350            EditError::TooManyCards { max } => diag_args! { "max" => max },
351            EditError::ValueTooDeep { max } => diag_args! { "max" => max },
352            EditError::Import(_) => diag_args! {},
353            EditError::FieldDecode {
354                field,
355                at: _,
356                codec,
357                message: _,
358            } => diag_args! {
359                "field" => field,
360                "codec" => codec,
361            },
362            EditError::FieldNotContent {
363                field,
364                at: _,
365                declared,
366            } => diag_args! {
367                "field" => field,
368                "declared" => declared,
369            },
370            EditError::FieldNotSingleLine { field, codec } => diag_args! {
371                "field" => field,
372                "codec" => codec,
373            },
374            EditError::FieldCoercionFailed {
375                field,
376                target,
377                message: _,
378            } => diag_args! {
379                "field" => field,
380                "target" => target,
381            },
382            EditError::Change(e) => apply_args(e),
383            EditError::InputTooLarge { size, max } => diag_args! { "size" => size, "max" => max },
384            EditError::TooManySteps { count, max }
385            | EditError::TooManyMarks { count, max }
386            | EditError::TooManyAnchors { count, max } => {
387                diag_args! { "count" => count, "max" => max }
388            }
389            // One code, four sentences: the variant that spoke is not on the
390            // wire, so a consumer's template falls back to `message`.
391            EditError::InvalidPayload(_) => diag_args! {},
392            EditError::DropsExtIsland { island, kind } => diag_args! {
393                "island" => island,
394                "type" => kind,
395            },
396            EditError::StaleBase(e) => e.args(),
397        }
398    }
399
400    /// This error as a [`Diagnostic`] under its [`code`](Self::code) and
401    /// [`args`](Self::args), anchored at `path` when given.
402    pub fn to_diagnostic(&self, path: Option<DocPath>) -> Diagnostic {
403        let diagnostic = Diagnostic::new(crate::error::Severity::Error, self.to_string())
404            .with_code(self.code().to_string())
405            .with_args(self.args());
406        match path {
407            Some(path) => diagnostic.with_path(path.to_string()),
408            None => diagnostic,
409        }
410    }
411
412    /// The [`DocPath`] this error anchors to, relative to
413    /// `base`: the card root the mutator ran against, empty for a card built
414    /// before placement.
415    ///
416    /// - A field-named variant: its field under `base`, extended by the
417    ///   variant's `at` path, so an element read anchors at `main.<field>[<i>]`.
418    /// - [`IndexOutOfRange`](Self::IndexOutOfRange): the document-array slot
419    ///   `cards[index]`, base-independent — a structural op names a slot.
420    /// - The rest: `base` when it names a card, else no anchor.
421    pub fn doc_path(&self, base: &crate::path::DocPath) -> Option<crate::path::DocPath> {
422        use crate::path::DocPath;
423        match self {
424            EditError::FieldNotContent { field: f, at, .. }
425            | EditError::FieldDecode { field: f, at, .. }
426            | EditError::UnknownField { field: f, at } => {
427                Some(at.iter().fold(base.field(f), |p, seg| p.segment(seg)))
428            }
429            EditError::InvalidFieldName(f)
430            | EditError::FieldNotSingleLine { field: f, .. }
431            | EditError::FieldCoercionFailed { field: f, .. } => Some(base.field(f)),
432            EditError::IndexOutOfRange { index, .. } => Some(DocPath::card(None, *index)),
433            EditError::StaleBase(StaleBase { field: Some(f), .. }) => Some(base.field(f)),
434            _ => (!base.segs().is_empty()).then(|| base.clone()),
435        }
436    }
437}
438
439/// A field-level invariant violation, shared by every payload ingestion path.
440///
441/// Each boundary maps it to its own error type (`ParseError`, `StorageError`,
442/// [`EditError`]), so the invariant is enforced once, here. Its
443/// [`Display`](std::fmt::Display) is the reason alone, for a boundary carrying the
444/// offending key itself; [`message`](Self::message) names the key inline for the
445/// boundaries whose error type does not.
446#[derive(Debug, Clone, Copy, PartialEq, Eq)]
447pub enum FieldViolation {
448    /// The field name does not match `[A-Za-z_][A-Za-z0-9_]*` (spec §3.4 / §10).
449    InvalidName,
450    /// The value nests deeper than [`MAX_JSON_DEPTH`](quillmark_content::MAX_JSON_DEPTH)
451    /// (spec §8).
452    TooDeep,
453}
454
455impl FieldViolation {
456    /// The reason with `key` named inline, for `ParseError::InvalidStructure`
457    /// and `StorageError::Malformed`, whose error types carry no key of their
458    /// own.
459    pub fn message(&self, key: &str) -> String {
460        format!("invalid field {key:?}: {self}")
461    }
462}
463
464impl std::fmt::Display for FieldViolation {
465    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466        match self {
467            FieldViolation::InvalidName => {
468                f.write_str("field names must match [A-Za-z_][A-Za-z0-9_]*")
469            }
470            FieldViolation::TooDeep => write!(
471                f,
472                "nests deeper than the maximum of {} levels",
473                quillmark_content::MAX_JSON_DEPTH
474            ),
475        }
476    }
477}
478
479/// A payload-level invariant violation: [`FieldViolation`]'s seam one level up,
480/// reading the item list rather than one item's contents. Shared by every
481/// payload ingestion path, each mapping it to its own error type.
482///
483/// Every variant names something YAML cannot express, so a payload carrying one
484/// emits markdown the parser rejects — except
485/// [`MultiLineComment`](Self::MultiLineComment), which re-reads cleanly as a
486/// different document.
487#[derive(Debug, Clone, PartialEq, Eq)]
488pub enum PayloadViolation {
489    /// Two user fields share a key; a YAML mapping admits each key once.
490    DuplicateField { key: String },
491    /// More user fields than [`MAX_FIELD_COUNT`](crate::error::MAX_FIELD_COUNT)
492    /// (spec §8). Comments and `$` entries are not charged, matching the bound
493    /// the parser applies after `$`-key extraction.
494    TooManyFields { count: usize, max: usize },
495    /// A `$` system entry appears more than once; emit writes its line for each.
496    DuplicateMeta { key: &'static str },
497    /// Comment text spans lines. A `#` opens one line, so every line after the
498    /// first emits as bare YAML: the payload re-reads as fields no one wrote.
499    MultiLineComment,
500}
501
502impl std::fmt::Display for PayloadViolation {
503    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504        match self {
505            PayloadViolation::DuplicateField { key } => {
506                write!(f, "duplicate user-field key {key:?}")
507            }
508            PayloadViolation::TooManyFields { count, max } => write!(
509                f,
510                "card has {count} user fields, exceeding the maximum of {max}"
511            ),
512            PayloadViolation::DuplicateMeta { key } => {
513                write!(f, "duplicate `{key}` entry")
514            }
515            PayloadViolation::MultiLineComment => {
516                f.write_str("comment text spans multiple lines; a comment occupies one line")
517            }
518        }
519    }
520}
521
522pub(crate) fn edit_error_from_violation(name: &str, v: FieldViolation) -> EditError {
523    match v {
524        FieldViolation::InvalidName => EditError::InvalidFieldName(name.to_string()),
525        FieldViolation::TooDeep => EditError::ValueTooDeep {
526            max: quillmark_content::MAX_JSON_DEPTH,
527        },
528    }
529}
530
531fn check_field_name(name: &str) -> Result<(), EditError> {
532    if is_valid_field_name(name) {
533        Ok(())
534    } else {
535        Err(EditError::InvalidFieldName(name.to_string()))
536    }
537}
538
539fn check_field(name: &str, value: &serde_json::Value) -> Result<(), EditError> {
540    validate_field(name, value).map_err(|v| edit_error_from_violation(name, v))
541}
542
543/// `value` with each content value it holds, at any depth, decoded as a body
544/// write decodes one and held in its canonical form: a field's content
545/// validates, stores, compares and hashes as a body's does.
546/// [`EditError::FieldDecode`] at the first content value that does not
547/// decode.
548pub(crate) fn canonical_field(
549    name: &str,
550    mut value: serde_json::Value,
551) -> Result<serde_json::Value, EditError> {
552    let mut at = Vec::new();
553    canonicalize_contents(&mut value, &mut at)
554        .map_err(|(codec, e)| field_decode(name, &at, codec, ContentDecodeError::NotContent(e)))?;
555    Ok(value)
556}
557
558fn canonicalize_contents(
559    value: &mut serde_json::Value,
560    at: &mut Vec<PathSegment>,
561) -> Result<(), (Codec, String)> {
562    if quillmark_content::units::is_content_value(value) {
563        let content = quillmark_content::model::Content::from_value(value)
564            .map_err(|e| (Codec::of_object(value), e.to_string()))?;
565        *value = content.to_value();
566        return Ok(());
567    }
568    match value {
569        serde_json::Value::Object(map) => {
570            for (key, v) in map.iter_mut() {
571                at.push(PathSegment::Key(key.clone()));
572                canonicalize_contents(v, at)?;
573                at.pop();
574            }
575        }
576        serde_json::Value::Array(items) => {
577            for (index, v) in items.iter_mut().enumerate() {
578                at.push(PathSegment::Index(index));
579                canonicalize_contents(v, at)?;
580                at.pop();
581            }
582        }
583        _ => {}
584    }
585    Ok(())
586}
587
588/// The composable-kind rule mapped onto the mutator error surface.
589fn check_kind(kind: &str) -> Result<(), EditError> {
590    validate_composable_kind(kind).map_err(|e| match e {
591        CardKindError::InvalidName => EditError::InvalidKindName(kind.to_string()),
592        CardKindError::Reserved => EditError::ReservedKind,
593    })
594}
595
596/// A decode failure at an address, under the codec that ran. The one
597/// [`EditError::FieldDecode`] constructor for a codec outcome, shared with the
598/// schema-bound reads in [`reader`](crate::reader).
599pub(crate) fn field_decode(
600    name: &str,
601    at: &[PathSegment],
602    codec: Codec,
603    e: ContentDecodeError,
604) -> EditError {
605    EditError::FieldDecode {
606        field: name.to_string(),
607        at: at.to_vec(),
608        codec: codec.name().to_string(),
609        message: e.into_message(),
610    }
611}
612
613/// Depth-bound the values of an `$ext` / `$seed` map: the map itself is level
614/// 1, so its values carry the rest of the budget. The iterator form of
615/// [`crate::value::depth_check_meta_map`], for the merge that must clear the
616/// bound before it owns a map.
617fn check_meta_depth<'v>(
618    values: impl IntoIterator<Item = &'v serde_json::Value>,
619) -> Result<(), EditError> {
620    let max = quillmark_content::MAX_JSON_DEPTH;
621    if values
622        .into_iter()
623        .any(|v| crate::value::json_depth_exceeds(v, max - 1))
624    {
625        return Err(EditError::ValueTooDeep { max });
626    }
627    Ok(())
628}
629
630/// Validate a user field: name conformance and value-depth bound.
631pub fn validate_field(key: &str, value: &serde_json::Value) -> Result<(), FieldViolation> {
632    if !is_valid_field_name(key) {
633        return Err(FieldViolation::InvalidName);
634    }
635    if crate::value::json_depth_exceeds(value, quillmark_content::MAX_JSON_DEPTH) {
636        return Err(FieldViolation::TooDeep);
637    }
638    Ok(())
639}
640
641/// Validate a payload against every [`PayloadViolation`]. The per-item twin is
642/// [`validate_field`].
643pub fn validate_payload(payload: &Payload) -> Result<(), PayloadViolation> {
644    let max = crate::error::MAX_FIELD_COUNT;
645    let count = payload.len();
646    if count > max {
647        return Err(PayloadViolation::TooManyFields { count, max });
648    }
649
650    let mut fields: std::collections::HashSet<&str> = std::collections::HashSet::new();
651    let mut seen_quill = false;
652    let mut seen_kind = false;
653    let mut seen_id = false;
654    let mut metas: std::collections::HashSet<MetaKey> = std::collections::HashSet::new();
655    for item in payload.items() {
656        let dup = |key| Err(PayloadViolation::DuplicateMeta { key });
657        match item {
658            PayloadItem::Field { key, .. } => {
659                if !fields.insert(key.as_str()) {
660                    return Err(PayloadViolation::DuplicateField { key: key.clone() });
661                }
662            }
663            PayloadItem::Quill { .. } => {
664                if std::mem::replace(&mut seen_quill, true) {
665                    return dup("$quill");
666                }
667            }
668            PayloadItem::Kind { .. } => {
669                if std::mem::replace(&mut seen_kind, true) {
670                    return dup("$kind");
671                }
672            }
673            PayloadItem::Id { .. } => {
674                if std::mem::replace(&mut seen_id, true) {
675                    return dup("$id");
676                }
677            }
678            PayloadItem::Meta { key, .. } => {
679                if !metas.insert(*key) {
680                    return dup(key.as_str());
681                }
682            }
683            PayloadItem::Comment { text, .. } => {
684                if text.contains(['\n', '\r']) {
685                    return Err(PayloadViolation::MultiLineComment);
686                }
687            }
688        }
689    }
690    if payload
691        .nested_comments()
692        .iter()
693        .any(|nc| nc.text.contains(['\n', '\r']))
694    {
695        return Err(PayloadViolation::MultiLineComment);
696    }
697    Ok(())
698}
699
700/// Map a strict-write [`CoercionError`] to the field-write [`EditError`] surface.
701///
702/// Keys on the coercion `target`, not the field's own type, because the
703/// constraint can be nested: an `array` of one-line `richtext` items fails with
704/// `target == RICHTEXT_SINGLE_LINE_TARGET` while the field's type is `Array`.
705fn conform_error_to_edit(name: &str, err: CoercionError) -> EditError {
706    let CoercionError::Uncoercible {
707        path: _,
708        value: _,
709        target,
710        reason,
711    } = err;
712    let field = name.to_string();
713    match target.as_str() {
714        t if t == crate::quill::RICHTEXT_SINGLE_LINE_TARGET => EditError::FieldNotSingleLine {
715            field,
716            codec: CODEC_RICHTEXT.to_string(),
717        },
718        t if t == crate::quill::TEXT_SINGLE_LINE_TARGET => EditError::FieldNotSingleLine {
719            field,
720            codec: CODEC_TEXT.to_string(),
721        },
722        CODEC_RICHTEXT | CODEC_TEXT => EditError::FieldDecode {
723            field,
724            at: Vec::new(),
725            codec: target,
726            message: reason,
727        },
728        _ => EditError::FieldCoercionFailed {
729            field,
730            target,
731            message: reason,
732        },
733    }
734}
735
736/// The `(name, error)` pairs for the batch names that would land past the §8
737/// field count, `None` when the batch fits. The count belongs to the payload, so
738/// a batch asks it once, before it applies any of itself: what comes back is the
739/// overflowing tail, one diagnostic per offending field as every other batch
740/// refusal reports.
741pub(crate) fn overflow_errors<'n>(
742    payload: &Payload,
743    names: impl IntoIterator<Item = &'n str>,
744) -> Option<Vec<(String, EditError)>> {
745    let (count, past) = payload.overflow(names)?;
746    Some(
747        past.into_iter()
748            .map(|name| {
749                (
750                    name.to_string(),
751                    EditError::InvalidPayload(PayloadViolation::TooManyFields {
752                        count,
753                        max: crate::error::MAX_FIELD_COUNT,
754                    }),
755                )
756            })
757            .collect(),
758    )
759}
760
761/// The canonical stored form of a typed field write, **without applying it**:
762/// the dry-run that lets a batch collect every violation before mutating. Beside
763/// it, one `parse::dropped_construct` per construct a markdown string in the
764/// value dropped on its import, at its path under `base`, the card's root.
765pub(crate) fn resolve_field_write(
766    name: &str,
767    value: &QuillValue,
768    schema: &FieldSchema,
769    base: &crate::path::DocPath,
770) -> Result<(QuillValue, Vec<Diagnostic>), EditError> {
771    check_field_name(name)?;
772    let mut drops = Vec::new();
773    let stored = QuillConfig::conform_value(
774        value,
775        schema,
776        &base.field(name),
777        Leniency::Write,
778        &mut drops,
779    )
780    .map_err(|e| conform_error_to_edit(name, e))?;
781    check_field(name, stored.as_json())?;
782    Ok((stored, drops))
783}
784
785/// The literal text a `text` field's strict write commits for `body`: the
786/// codec's boundary cleanup, so what a revise carries anchors onto is what
787/// lands.
788pub(crate) fn committed_text(
789    name: &str,
790    body: String,
791    schema: &FieldSchema,
792) -> Result<String, EditError> {
793    let (committed, _) =
794        resolve_field_write(name, &QuillValue::from(body), schema, &DocPath::new())?;
795    Codec::Text
796        .decode_field(committed.as_json())
797        .map(|c| Codec::Text.project(&c))
798        .map_err(|e| field_decode(name, &[], Codec::Text, e))
799}
800
801/// The mutable handle on a card already placed in a [`Document`]: every
802/// `&mut self` verb [`Card`] carries, forwarded, and no way to replace the card
803/// itself. Reads arrive through [`Deref`](std::ops::Deref).
804///
805/// Placement is positional — the main card carries `$quill` and `$seed`, a
806/// composable card carries neither — and the gates that police it
807/// ([`Unchecked::insert_card`],
808/// [`Card::store_seed_overlay`]) run when a card is placed or edited, not when
809/// one is assigned over another. Handing out a `&mut Card` would make
810/// `*doc.card_mut(0).unwrap() = doc.main().clone()` a legal write past all of
811/// them, and [`Document::quill_reference`] reads the root's `$quill` without
812/// re-checking. A card built before placement is an ordinary `Card`, so the
813/// verbs stay there and this only withholds the assignment.
814pub struct CardMut<'a>(&'a mut Card);
815
816impl<'a> CardMut<'a> {
817    pub(crate) fn new(card: &'a mut Card) -> Self {
818        Self(card)
819    }
820
821    #[cfg(test)]
822    pub(crate) fn payload_mut(&mut self) -> &mut Payload {
823        self.0.payload_mut()
824    }
825
826    /// [`Card::remove_field`].
827    pub fn remove_field(&mut self, name: &str) -> Result<Option<QuillValue>, EditError> {
828        self.0.remove_field(name)
829    }
830
831    /// [`Card::store_ext`].
832    pub fn store_ext(
833        &mut self,
834        value: serde_json::Map<String, serde_json::Value>,
835    ) -> Result<(), EditError> {
836        self.0.store_ext(value)
837    }
838
839    /// [`Card::remove_ext`].
840    pub fn remove_ext(&mut self) -> Option<serde_json::Map<String, serde_json::Value>> {
841        self.0.remove_ext()
842    }
843
844    /// [`Card::store_seed_overlay`].
845    pub fn store_seed_overlay(
846        &mut self,
847        card_kind: impl Into<String>,
848        value: serde_json::Value,
849    ) -> Result<(), EditError> {
850        self.0.store_seed_overlay(card_kind, value)
851    }
852
853    /// [`Card::remove_seed_overlay`].
854    pub fn remove_seed_overlay(&mut self, card_kind: &str) -> Option<serde_json::Value> {
855        self.0.remove_seed_overlay(card_kind)
856    }
857
858    /// [`Card::overwrite_body`].
859    #[cfg(test)]
860    pub(crate) fn overwrite_body(&mut self, content: Content) {
861        self.0.overwrite_body(content)
862    }
863
864    /// [`Card::apply`].
865    pub fn apply<'o>(
866        &mut self,
867        target: super::Target<'_>,
868        change: &quillmark_content::change::Change,
869        opts: impl Into<super::WriteOptions<'o>>,
870    ) -> Result<super::Receipt, EditError> {
871        self.0.apply(target, change, opts)
872    }
873
874    /// [`Card::revise`].
875    pub fn revise<'o>(
876        &mut self,
877        target: super::Target<'_>,
878        markdown: &str,
879        opts: impl Into<super::WriteOptions<'o>>,
880    ) -> Result<super::Receipt, EditError> {
881        self.0.revise(target, markdown, opts)
882    }
883
884    /// [`Card::replace`].
885    pub fn replace<'o>(
886        &mut self,
887        target: super::Target<'_>,
888        content: &quillmark_content::model::Content,
889        opts: impl Into<super::WriteOptions<'o>>,
890    ) -> Result<super::Receipt, EditError> {
891        self.0.replace(target, content, opts)
892    }
893
894    /// [`Card::split_block`].
895    pub fn split_block<'o>(
896        &mut self,
897        target: super::Target<'_>,
898        at: usize,
899        id: Option<&str>,
900        opts: impl Into<super::WriteOptions<'o>>,
901    ) -> Result<super::Receipt, EditError> {
902        self.0.split_block(target, at, id, opts)
903    }
904
905    /// [`Card::join_blocks`].
906    pub fn join_blocks<'o>(
907        &mut self,
908        target: super::Target<'_>,
909        id: &str,
910        opts: impl Into<super::WriteOptions<'o>>,
911    ) -> Result<super::Receipt, EditError> {
912        self.0.join_blocks(target, id, opts)
913    }
914
915    /// [`Card::delete_range`].
916    pub fn delete_range<'o>(
917        &mut self,
918        target: super::Target<'_>,
919        start: usize,
920        end: usize,
921        opts: impl Into<super::WriteOptions<'o>>,
922    ) -> Result<super::Receipt, EditError> {
923        self.0.delete_range(target, start, end, opts)
924    }
925
926    /// [`Card::indent`].
927    pub fn indent<'o>(
928        &mut self,
929        target: super::Target<'_>,
930        first: &str,
931        last: &str,
932        opts: impl Into<super::WriteOptions<'o>>,
933    ) -> Result<super::Receipt, EditError> {
934        self.0.indent(target, first, last, opts)
935    }
936
937    /// [`Card::outdent`].
938    pub fn outdent<'o>(
939        &mut self,
940        target: super::Target<'_>,
941        first: &str,
942        last: &str,
943        opts: impl Into<super::WriteOptions<'o>>,
944    ) -> Result<super::Receipt, EditError> {
945        self.0.outdent(target, first, last, opts)
946    }
947
948    /// [`Card::wrap`].
949    pub fn wrap<'o>(
950        &mut self,
951        target: super::Target<'_>,
952        first: &str,
953        last: &str,
954        with: quillmark_content::structural::Wrap,
955        opts: impl Into<super::WriteOptions<'o>>,
956    ) -> Result<super::Receipt, EditError> {
957        self.0.wrap(target, first, last, with, opts)
958    }
959
960    /// [`Card::write`].
961    pub fn write<'o>(
962        &mut self,
963        target: super::Target<'_>,
964        edit: super::Edit<'_>,
965        opts: impl Into<super::WriteOptions<'o>>,
966    ) -> Result<super::Receipt, EditError> {
967        self.0.write(target, edit, opts)
968    }
969
970    /// [`Card::write_in`].
971    pub fn write_in<'o>(
972        &mut self,
973        target: super::Target<'_>,
974        edit: super::Edit<'_>,
975        opts: impl Into<super::WriteOptions<'o>>,
976        u: impl quillmark_content::units::Units,
977    ) -> Result<super::Receipt, EditError> {
978        self.0.write_in(target, edit, opts, u)
979    }
980
981    /// [`Card::overwrite_field`].
982    #[cfg(test)]
983    pub(crate) fn overwrite_field(
984        &mut self,
985        name: &str,
986        content: Content,
987    ) -> Result<(), EditError> {
988        self.0.overwrite_field(name, content)
989    }
990
991    #[doc(hidden)]
992    pub fn commit_field(
993        &mut self,
994        name: &str,
995        value: impl Into<QuillValue>,
996        schema: &FieldSchema,
997    ) -> Result<(), EditError> {
998        self.0.commit_field(name, value, schema)
999    }
1000
1001    #[doc(hidden)]
1002    pub fn revise_field_checked(
1003        &mut self,
1004        name: &str,
1005        body: impl Into<String>,
1006        schema: &FieldSchema,
1007    ) -> Result<super::Receipt, EditError> {
1008        self.0.revise_field_checked(name, body, schema)
1009    }
1010}
1011
1012impl std::ops::Deref for CardMut<'_> {
1013    type Target = Card;
1014
1015    fn deref(&self) -> &Card {
1016        self.0
1017    }
1018}
1019
1020impl Document {
1021    pub fn set_quill_ref(&mut self, reference: QuillReference) {
1022        self.main_card_mut().payload_mut().set_quill(reference);
1023    }
1024
1025    pub fn card_mut(&mut self, index: usize) -> Option<CardMut<'_>> {
1026        self.cards_vec_mut().get_mut(index).map(CardMut::new)
1027    }
1028
1029    /// The writes no quill schema checks: [`Unchecked`].
1030    pub fn unchecked(&mut self) -> Unchecked<'_> {
1031        Unchecked(self)
1032    }
1033
1034    /// Place `card` at `at` (`None` appends), its `$id` as
1035    /// [`Unchecked::insert_card`] takes it, answering that id.
1036    pub(crate) fn place_card(
1037        &mut self,
1038        at: Option<usize>,
1039        mut card: Card,
1040    ) -> Result<String, EditError> {
1041        let len = self.cards().len();
1042        let index = at.unwrap_or(len);
1043        if index > len {
1044            return Err(EditError::IndexOutOfRange { index, len });
1045        }
1046        Self::check_composable_placement(&card)?;
1047        self.check_card_room()?;
1048        let held: std::collections::HashSet<String> = self
1049            .cards()
1050            .iter()
1051            .filter_map(Card::id)
1052            .map(str::to_string)
1053            .collect();
1054        let id = match card.id() {
1055            Some(id) if !super::card_id::is_card_id(id) => {
1056                return Err(EditError::InvalidCardId(id.to_string()));
1057            }
1058            Some(id) if held.contains(id) => {
1059                return Err(EditError::DuplicateCardId(id.to_string()));
1060            }
1061            Some(id) => id.to_string(),
1062            None => {
1063                let id = super::card_id::Mint::new(held).mint();
1064                card.payload_mut().set_id(id.clone());
1065                id
1066            }
1067        };
1068        self.cards_vec_mut().insert(index, card);
1069        Ok(id)
1070    }
1071
1072    fn check_card_room(&self) -> Result<(), EditError> {
1073        let max = crate::error::MAX_CARD_COUNT;
1074        if self.cards().len() >= max {
1075            return Err(EditError::TooManyCards { max });
1076        }
1077        Ok(())
1078    }
1079
1080    /// The `$` entries a card may carry once placed as a composable card. A
1081    /// card with no `$kind` is rejected as an invalid (empty) name.
1082    ///
1083    /// Positional, so it lives here rather than in `TryFrom<CardWire>`: a
1084    /// [`CardWire`](crate::document::CardWire) is equally how the *main* card
1085    /// is read back and rewritten, and carries no signal of which it is.
1086    fn check_composable_placement(card: &Card) -> Result<(), EditError> {
1087        check_kind(card.kind().unwrap_or(""))?;
1088        if card.quill().is_some() {
1089            return Err(EditError::RootOnlyEntry {
1090                key: "$quill".to_string(),
1091            });
1092        }
1093        if card.seed().is_some() {
1094            return Err(EditError::RootOnlyEntry {
1095                key: MetaKey::Seed.as_str().to_string(),
1096            });
1097        }
1098        Ok(())
1099    }
1100
1101    pub fn remove_card(&mut self, index: usize) -> Option<Card> {
1102        if index >= self.cards().len() {
1103            return None;
1104        }
1105        Some(self.cards_vec_mut().remove(index))
1106    }
1107
1108    /// Move card at `from` to position `to`. No-op when `from == to`.
1109    /// Either index out of range → [`EditError::IndexOutOfRange`].
1110    pub fn move_card(&mut self, from: usize, to: usize) -> Result<(), EditError> {
1111        let len = self.cards().len();
1112        if from >= len {
1113            return Err(EditError::IndexOutOfRange { index: from, len });
1114        }
1115        if to >= len {
1116            return Err(EditError::IndexOutOfRange { index: to, len });
1117        }
1118        if from == to {
1119            return Ok(());
1120        }
1121        let card = self.cards_vec_mut().remove(from);
1122        self.cards_vec_mut().insert(to, card);
1123        Ok(())
1124    }
1125}
1126
1127/// The writes on a [`Document`] that no quill schema checks, from
1128/// [`Document::unchecked`]: a field stored with no type coercion, and a card
1129/// placed whole. Each still holds every invariant the document does: names,
1130/// the §8 bounds, card ids, and each content value decoded as a body write
1131/// decodes one and stored in its canonical form, so `==`, the stored bytes
1132/// and the markdown export agree for a field as they do for a body. The
1133/// schema-checked writes are [`Quill::writer`](crate::quill::Quill::writer)'s.
1134pub struct Unchecked<'a>(&'a mut Document);
1135
1136impl Unchecked<'_> {
1137    /// [`Card::store_field`] on the main card (`card: None`) or the composable
1138    /// card at `card`, [`EditError::IndexOutOfRange`] where none is.
1139    pub fn store_field(
1140        &mut self,
1141        card: Option<usize>,
1142        name: &str,
1143        value: impl Into<QuillValue>,
1144    ) -> Result<(), EditError> {
1145        let len = self.0.cards().len();
1146        let card = match card {
1147            None => self.0.main_card_mut(),
1148            Some(index) => self
1149                .0
1150                .cards_vec_mut()
1151                .get_mut(index)
1152                .ok_or(EditError::IndexOutOfRange { index, len })?,
1153        };
1154        card.store_field(name, value)
1155    }
1156
1157    /// Place a composable card at `at` (`None` appends; past the last card
1158    /// [`EditError::IndexOutOfRange`]), answering its `$id`. Its `$kind` must
1159    /// be a valid, non-reserved composable kind ([`EditError::InvalidKindName`]
1160    /// / [`EditError::ReservedKind`]), and the document must hold fewer than
1161    /// [`MAX_CARD_COUNT`](crate::error::MAX_CARD_COUNT) cards
1162    /// ([`EditError::TooManyCards`]). A card spelling an id keeps it, refused
1163    /// where it is no card id ([`EditError::InvalidCardId`]) or another card
1164    /// holds it ([`EditError::DuplicateCardId`]). A card spelling none mints
1165    /// one positionally.
1166    pub fn insert_card(&mut self, at: Option<usize>, card: Card) -> Result<String, EditError> {
1167        self.0.place_card(at, card)
1168    }
1169}
1170
1171impl Card {
1172    /// Create a composable card with the given kind, no fields, and an empty body.
1173    pub fn new(kind: impl Into<String>) -> Result<Self, EditError> {
1174        let kind = kind.into();
1175        check_kind(&kind)?;
1176        let mut payload = Payload::new();
1177        payload.set_kind(kind);
1178        Ok(Card::from_parts(payload, Content::empty()))
1179    }
1180
1181    /// Store a payload field with no schema in play: schema coercion is
1182    /// deferred to render; contrast the typed
1183    /// [`TypedWriter::set`](crate::writer::TypedWriter::set). Scalars convert
1184    /// in place (`store_field("qty", 3)`) via the `From` impls on
1185    /// [`QuillValue`]. Each content value in `value`, at any depth, decodes as
1186    /// a body write's does and stores in its canonical form.
1187    ///
1188    /// Returns [`EditError::InvalidFieldName`] when `name` does not match
1189    /// `[A-Za-z_][A-Za-z0-9_]*`, [`EditError::FieldDecode`] for a content
1190    /// value that does not decode, and [`EditError::InvalidPayload`] when
1191    /// `name` is absent and the card already carries
1192    /// [`MAX_FIELD_COUNT`](crate::error::MAX_FIELD_COUNT) fields; overwriting a
1193    /// field a full card already carries is not a growth and lands.
1194    pub fn store_field(
1195        &mut self,
1196        name: &str,
1197        value: impl Into<QuillValue>,
1198    ) -> Result<(), EditError> {
1199        let value = value.into();
1200        check_field(name, value.as_json())?;
1201        let value = QuillValue::from_json(canonical_field(name, value.into_json())?);
1202        self.payload_mut()
1203            .insert(name.to_string(), value)
1204            .map_err(EditError::InvalidPayload)?;
1205        Ok(())
1206    }
1207
1208    /// Remove a payload field; `Ok(None)` when the name is absent. Same name
1209    /// validation as [`Card::store_field`].
1210    pub fn remove_field(&mut self, name: &str) -> Result<Option<QuillValue>, EditError> {
1211        check_field_name(name)?;
1212        Ok(self.payload_mut().remove(name))
1213    }
1214
1215    /// Replace the card's opaque `$ext` map wholesale, inserting it at the
1216    /// canonical position (after `$quill`/`$kind`, before user fields)
1217    /// when none existed. Passing an empty map records an explicit `$ext: {}`.
1218    ///
1219    /// The whole map is the write, so a consumer holding one namespace merges
1220    /// the rest of [`ext`](Card::ext) into what it stores; nested comments
1221    /// attached to the replaced map are dropped. [`EditError::ValueTooDeep`]
1222    /// when the map nests past the §8 depth limit.
1223    pub fn store_ext(
1224        &mut self,
1225        value: serde_json::Map<String, serde_json::Value>,
1226    ) -> Result<(), EditError> {
1227        let value =
1228            crate::value::depth_check_meta_map(value, |max| EditError::ValueTooDeep { max })?;
1229        self.payload_mut().set_ext(value);
1230        Ok(())
1231    }
1232
1233    /// Remove the card's `$ext` map *entirely*, returning the previous map.
1234    /// Discards every namespace at once.
1235    pub fn remove_ext(&mut self) -> Option<serde_json::Map<String, serde_json::Value>> {
1236        self.payload_mut().take_ext()
1237    }
1238
1239    /// The map is written back only after the depth check passes, so the card is
1240    /// unchanged on error.
1241    fn merge_meta_namespace(
1242        &mut self,
1243        key: MetaKey,
1244        namespace: String,
1245        value: serde_json::Value,
1246    ) -> Result<(), EditError> {
1247        let surviving = self
1248            .payload()
1249            .meta(key)
1250            .into_iter()
1251            .flatten()
1252            .filter(|(k, _)| **k != namespace)
1253            .map(|(_, v)| v);
1254        check_meta_depth(surviving.chain(std::iter::once(&value)))?;
1255        let mut map = self.payload().meta(key).cloned().unwrap_or_default();
1256        map.insert(namespace, value);
1257        self.payload_mut().set_meta(key, map);
1258        Ok(())
1259    }
1260
1261    /// Emptying the map drops the entry rather than leaving `$<key>: {}`.
1262    fn remove_meta_namespace(
1263        &mut self,
1264        key: MetaKey,
1265        namespace: &str,
1266    ) -> Option<serde_json::Value> {
1267        let mut map = self.payload().meta(key)?.clone();
1268        let removed = map.shift_remove(namespace)?;
1269        if map.is_empty() {
1270            self.payload_mut().take_meta(key);
1271        } else {
1272            self.payload_mut().set_meta(key, map);
1273        }
1274        Some(removed)
1275    }
1276
1277    /// The raw `$seed` map (keyed by card-kind), or `None`. For a parsed,
1278    /// per-kind overlay, index this map by kind and pass the entry to
1279    /// [`crate::document::SeedOverlay::from_json`]. Only the main card carries
1280    /// `$seed`.
1281    pub fn seed(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
1282        self.payload().seed()
1283    }
1284
1285    /// Merge a card-kind's seed overlay `value` into the card's `$seed` map
1286    /// under `card_kind`, creating the map when absent and replacing any
1287    /// existing overlay for that kind; sibling kinds are preserved. Unlike the
1288    /// free-form namespaces of `$ext`, `card_kind` must be a valid, non-reserved
1289    /// composable kind ([`EditError::InvalidKindName`] /
1290    /// [`EditError::ReservedKind`] otherwise). `$seed` binds the document root,
1291    /// so a card that is not the root is [`EditError::RootOnlyEntry`]. Returns
1292    /// [`EditError::ValueTooDeep`] when the merged map nests past the §8 depth
1293    /// limit; the card is unchanged on error.
1294    pub fn store_seed_overlay(
1295        &mut self,
1296        card_kind: impl Into<String>,
1297        value: serde_json::Value,
1298    ) -> Result<(), EditError> {
1299        let card_kind = card_kind.into();
1300        check_kind(&card_kind)?;
1301        self.check_carries_root_only(MetaKey::Seed)?;
1302        self.merge_meta_namespace(MetaKey::Seed, card_kind, value)
1303    }
1304
1305    /// Refuse a root-only write on a card that is not the root. `$kind: main`
1306    /// is the root's own marker: the parser normalizes it in, the DTO
1307    /// synthesizes it, and placement refuses it as reserved, so a card answers
1308    /// this about itself.
1309    fn check_carries_root_only(&self, key: MetaKey) -> Result<(), EditError> {
1310        if self.kind() == Some("main") {
1311            return Ok(());
1312        }
1313        Err(EditError::RootOnlyEntry {
1314            key: key.as_str().to_string(),
1315        })
1316    }
1317
1318    /// Remove `card_kind` from the card's `$seed` map, returning the overlay
1319    /// stored there. Emptying the map drops the `$seed` entry entirely.
1320    pub fn remove_seed_overlay(&mut self, card_kind: &str) -> Option<serde_json::Value> {
1321        self.remove_meta_namespace(MetaKey::Seed, card_kind)
1322    }
1323
1324    /// Overwrite the body, keeping the ids of what it kept: no diff, no schema check,
1325    /// infallible, the stored body's anchors gone. The public whole-value
1326    /// write is [`replace`](Self::replace).
1327    #[cfg(test)]
1328    pub(crate) fn overwrite_body(&mut self, content: Content) {
1329        self.set_body(quillmark_content::diff::align(self.body(), content));
1330    }
1331
1332    /// Overwrite a content field's value: the
1333    /// field-level twin of [`overwrite_body`](Self::overwrite_body). Stores the
1334    /// canonical content JSON (identity and content-only marks intact), no diff,
1335    /// no schema check. The previous value's anchors are gone. Returns
1336    /// [`EditError::InvalidFieldName`] for a malformed name, and
1337    /// [`EditError::InvalidPayload`] when an absent `name` would take the card
1338    /// past the §8 field count.
1339    ///
1340    /// A field stored under `codec: "plain"` keeps it and refuses a `content`
1341    /// that is not plain with [`EditError::FieldDecode`]; one still stored as
1342    /// an authored string lands under the codec its next bound load
1343    /// ([`Quill::conform`](crate::quill::Quill::conform)) gives it.
1344    #[cfg(test)]
1345    pub(crate) fn overwrite_field(
1346        &mut self,
1347        name: &str,
1348        content: Content,
1349    ) -> Result<(), EditError> {
1350        check_field_name(name)?;
1351        self.store_field_content(name, &content)
1352    }
1353
1354    /// Assumes `name` is already validated: every caller checks it or resolves an
1355    /// existing field first. The §8 field count is the payload's, so an absent
1356    /// `name` on a full card is [`EditError::InvalidPayload`].
1357    #[cfg(test)]
1358    fn store_field_content(&mut self, name: &str, content: &Content) -> Result<(), EditError> {
1359        let stored = self
1360            .payload
1361            .get(name)
1362            .map(QuillValue::as_json)
1363            .filter(|v| v.is_object());
1364        if stored.map_or(Codec::Richtext, Codec::of_object) == Codec::Text && !content.is_plain() {
1365            return Err(field_decode(
1366                name,
1367                &[],
1368                Codec::Text,
1369                super::ContentDecodeError::NotContent(
1370                    quillmark_content::model::Invariant::NotPlain.to_string(),
1371                ),
1372            ));
1373        }
1374        let canonical =
1375            super::stored_over(self.payload.get(name).map(QuillValue::as_json), content);
1376        self.payload_mut()
1377            .insert(name.to_string(), QuillValue::from_json(canonical))
1378            .map(|_| ())
1379            .map_err(EditError::InvalidPayload)
1380    }
1381
1382    /// Write-time commit: validate and normalize `value` per the field's schema
1383    /// `type` and store the canonical form. The typed sibling of the opaque
1384    /// [`store_field`](Self::store_field), which defers coercion to render.
1385    ///
1386    /// Each content field commits the canonical content object, a `text`
1387    /// field's spelling `codec: "plain"`. Stricter than
1388    /// the render floor: a cross-type value the floor would coerce (`1` → `true`)
1389    /// fails here. `null` passes through unchanged, under the null ≡ absent rule.
1390    ///
1391    /// The caller supplies `schema` because a [`Document`] holds only a `$quill`
1392    /// *reference*; [`crate::writer::TypedWriter`] resolves it per field and
1393    /// commits as this does, returning the `parse::dropped_construct` warnings
1394    /// this discards.
1395    ///
1396    /// Returns [`EditError::InvalidFieldName`] for a malformed name,
1397    /// [`EditError::FieldDecode`] / [`EditError::FieldNotSingleLine`]
1398    /// for a content field, [`EditError::FieldCoercionFailed`] for any other type
1399    /// mismatch, [`EditError::ValueTooDeep`] when the stored value nests
1400    /// past the §8 depth limit, and [`EditError::InvalidPayload`] when `name` is
1401    /// absent and the card is at the §8 field count.
1402    ///
1403    /// **Hidden**: the typed primitive, whose door is
1404    /// [`Quill::writer`](crate::quill::Quill::writer).
1405    #[doc(hidden)]
1406    pub fn commit_field(
1407        &mut self,
1408        name: &str,
1409        value: impl Into<QuillValue>,
1410        schema: &FieldSchema,
1411    ) -> Result<(), EditError> {
1412        self.commit_field_at(name, &value.into(), schema, &DocPath::new())?;
1413        Ok(())
1414    }
1415
1416    /// [`commit_field`](Self::commit_field), returning one
1417    /// `parse::dropped_construct` per construct a markdown string in `value`
1418    /// dropped, at its path under `base`, the card's root.
1419    pub(crate) fn commit_field_at(
1420        &mut self,
1421        name: &str,
1422        value: &QuillValue,
1423        schema: &FieldSchema,
1424        base: &DocPath,
1425    ) -> Result<Vec<Diagnostic>, EditError> {
1426        let (stored, drops) = resolve_field_write(name, value, schema, base)?;
1427        self.payload_mut()
1428            .insert(name.to_string(), stored)
1429            .map_err(EditError::InvalidPayload)?;
1430        Ok(drops)
1431    }
1432
1433    /// [`revise`](Self::revise) of the body with no base: the one revise at
1434    /// [`Target::Body`](super::Target::Body), its receipt's `applied` counted
1435    /// in scalars on the body it read, which
1436    /// [`Receipt::in_units`](super::Receipt::in_units) converts.
1437    pub(crate) fn revise_body(
1438        &mut self,
1439        body: impl Into<String>,
1440    ) -> Result<super::Receipt, EditError> {
1441        self.revise_counted(super::Target::Body, &body.into())
1442    }
1443
1444    /// The field's current content value: a markdown string imports, an
1445    /// absent field is empty, and an object reads under the codec it names.
1446    pub(crate) fn richtext_value(
1447        &self,
1448        name: &str,
1449    ) -> Result<quillmark_content::model::Content, EditError> {
1450        check_field_name(name)?;
1451        match self.payload.get(name) {
1452            None => Ok(Content::empty()),
1453            Some(v) => Codec::Richtext
1454                .read_content(v.as_json())
1455                .map_err(|e| field_decode(name, &[], Codec::Richtext, e)),
1456        }
1457    }
1458
1459    /// The revise of `before`, the value at `target`, by `markdown`, as
1460    /// [`revise`](Self::revise) builds it, landed nowhere.
1461    fn revision(
1462        &self,
1463        before: &quillmark_content::model::Content,
1464        markdown: &str,
1465    ) -> Result<quillmark_content::diff::Revision, EditError> {
1466        quillmark_content::diff::revise(before, markdown).map_err(|e| match e {
1467            quillmark_content::diff::ReviseError::Import(e) => EditError::import(e),
1468            quillmark_content::diff::ReviseError::Refused(e) => EditError::change(e),
1469        })
1470    }
1471
1472    /// Revise a content field from authored text **with schema enforcement**:
1473    /// [`revise`](Self::revise) of the field, read under the
1474    /// codec `schema` declares, then the conform
1475    /// [`commit_field`](Self::commit_field) runs. Returns the
1476    /// [`Receipt`](super::Receipt), and leaves the field unchanged on any error. A
1477    /// `text` field imports no markdown, so its receipt holds no warning.
1478    ///
1479    /// **Hidden** on the same terms as [`commit_field`](Self::commit_field): its
1480    /// door is
1481    /// [`TypedWriter::revise`](crate::writer::TypedWriter::revise).
1482    #[doc(hidden)]
1483    pub fn revise_field_checked(
1484        &mut self,
1485        name: &str,
1486        body: impl Into<String>,
1487        schema: &FieldSchema,
1488    ) -> Result<super::Receipt, EditError> {
1489        check_field_name(name)?;
1490        let target = super::Target::Field(name);
1491        if matches!(schema.r#type, FieldType::Text { .. }) {
1492            let text = committed_text(name, body.into(), schema)?;
1493            let mut before = match self.payload.get(name) {
1494                None => Content::empty(),
1495                Some(v) => Codec::Text
1496                    .read_content(v.as_json())
1497                    .map_err(|e| field_decode(name, &[], Codec::Text, e))?,
1498            };
1499            before.codec = Codec::Text.content();
1500            let revised = self.revision(&before, &text)?;
1501            let stored = QuillValue::from_json(revised.content.to_value());
1502            return self.revising(target, before, Vec::new(), |card| {
1503                card.payload_mut()
1504                    .insert(name.to_string(), stored)
1505                    .map(|_| ())
1506                    .map_err(EditError::InvalidPayload)
1507            });
1508        }
1509        let before = self.richtext_value(name)?;
1510        let body = body.into();
1511        let body = match schema.r#type {
1512            FieldType::RichText { shape } => {
1513                quillmark_content::markdown::admitting(&body, shape.admit())
1514            }
1515            _ => std::borrow::Cow::Borrowed(body.as_str()),
1516        };
1517        let revised = self.revision(&before, &body)?;
1518        super::write::keeps_ext_islands(&before, &revised.content)?;
1519        let (stored, _) = resolve_field_write(
1520            name,
1521            &QuillValue::from_json(revised.content.to_value()),
1522            schema,
1523            &DocPath::new(),
1524        )?;
1525        self.revising(target, before, revised.warnings, |card| {
1526            card.payload_mut()
1527                .insert(name.to_string(), stored)
1528                .map(|_| ())
1529                .map_err(EditError::InvalidPayload)
1530        })
1531    }
1532}
1533
1534fn apply_args(e: &quillmark_content::change::ApplyError) -> BTreeMap<String, serde_json::Value> {
1535    use quillmark_content::change::ApplyError as A;
1536    let reason = match e {
1537        A::Stale { .. } => "stale",
1538        A::UnknownBlock { .. } => "unknown_block",
1539        A::UnknownContainer { .. } => "unknown_container",
1540        A::ContainerKind { .. } => "container_kind",
1541        A::ContainerInUse { .. } => "container_in_use",
1542        A::UnknownAnchor { .. } => "unknown_anchor",
1543        A::AnchorHeld { .. } => "anchor_held",
1544        A::UnknownIsland { .. } => "unknown_island",
1545        A::UnknownSlot { .. } => "unknown_slot",
1546        A::BadStep { .. } => "bad_step",
1547        A::Invalid(_) => "invalid",
1548        _ => return diag_args! {},
1549    };
1550    let mut args = diag_args! { "reason" => reason };
1551    if let A::Stale { step } | A::BadStep { step, .. } = e {
1552        args.insert("step".into(), (*step).into());
1553    }
1554    args
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559    use super::*;
1560    use crate::path::DocPath;
1561
1562    #[test]
1563    fn field_error_anchors_under_the_card_base() {
1564        let main = DocPath::main();
1565        assert_eq!(
1566            EditError::FieldCoercionFailed {
1567                field: "font_size".into(),
1568                target: "integer".into(),
1569                message: "x".into(),
1570            }
1571            .doc_path(&main)
1572            .unwrap()
1573            .to_string(),
1574            "main.font_size"
1575        );
1576        let card = DocPath::card(Some("indorsement"), 1);
1577        assert_eq!(
1578            EditError::unknown_field("signature_block")
1579                .doc_path(&card)
1580                .unwrap()
1581                .to_string(),
1582            "cards.indorsement[1].signature_block"
1583        );
1584    }
1585
1586    #[test]
1587    fn index_out_of_range_anchors_at_the_array_slot() {
1588        for base in [DocPath::main(), DocPath::card(Some("note"), 0)] {
1589            assert_eq!(
1590                EditError::IndexOutOfRange { index: 4, len: 2 }
1591                    .doc_path(&base)
1592                    .unwrap()
1593                    .to_string(),
1594                "cards[4]"
1595            );
1596        }
1597    }
1598
1599    #[test]
1600    fn kind_and_depth_errors_anchor_at_base_or_nowhere() {
1601        assert_eq!(
1602            EditError::ReservedKind
1603                .doc_path(&DocPath::card(None, 2))
1604                .unwrap()
1605                .to_string(),
1606            "cards[2]"
1607        );
1608        assert_eq!(
1609            EditError::ValueTooDeep { max: 8 }.doc_path(&DocPath::new()),
1610            None
1611        );
1612        assert_eq!(
1613            EditError::ValueTooDeep { max: 8 }
1614                .doc_path(&DocPath::main())
1615                .unwrap()
1616                .to_string(),
1617            "main"
1618        );
1619    }
1620}