quillmark_core/document/mod.rs
1//! Parsing and typed in-memory model for Quillmark card-yaml documents.
2//!
3//! A [`Document`] holds a root [`Card`] plus ordered composable cards; each
4//! card carries a [`Payload`] — source-ordered items ([`PayloadItem`]:
5//! `$quill`/`$kind`/`$id` metadata, user fields, and comments, in the order
6//! they appear in the block's YAML content) — and a Markdown body.
7//! [`Document::parse`] returns errors for malformed YAML, unclosed
8//! fences, a missing root `$quill`, or unknown `$`-prefixed system keys.
9//!
10//! See [markdown-spec.md](https://github.com/borb-sh/quillmark/blob/main/prose/references/markdown-spec.md)
11//! for the card-yaml format specification.
12
13use serde::{Deserialize, Serialize};
14
15use quillmark_content::import::{from_markdown as import_markdown, ImportError};
16use quillmark_content::Content;
17
18use crate::error::ParseError;
19use crate::version::QuillReference;
20use crate::Diagnostic;
21
22/// The single markdown→content boundary for card bodies. Every construction path
23/// that starts from an authored markdown string ([`Document::parse`],
24/// wire/storage deserialization, seeding, blueprint) routes through it, so the
25/// markdown parser is reached from exactly one helper. An empty string yields
26/// the empty content without invoking the parser.
27pub(crate) fn import_body(md: &str) -> Result<Content, ImportError> {
28 if md.is_empty() {
29 Ok(Content::empty())
30 } else {
31 import_markdown(md)
32 }
33}
34
35/// Which encoding a `decode_richtext_value` failure came from, so a call site
36/// can prefix its diagnostic per encoding without re-deriving the dispatch.
37/// Surfaced publicly as the error of [`Card::field_richtext`].
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum RichtextDecodeError {
40 /// A JSON object that is not a valid canonical content.
41 NotContent(String),
42 /// A markdown string that failed to import.
43 BadMarkdown(String),
44}
45
46impl RichtextDecodeError {
47 /// The inner failure message, without an encoding-specific prefix.
48 pub fn into_message(self) -> String {
49 match self {
50 RichtextDecodeError::NotContent(m) | RichtextDecodeError::BadMarkdown(m) => m,
51 }
52 }
53}
54
55/// Decode a JSON value in either accepted richtext encoding: a canonical content
56/// **object** ([`from_canonical_value`](quillmark_content::serial::from_canonical_value))
57/// or an authored markdown **string** (via [`import_body`], the single markdown
58/// boundary). The one place the object-vs-string dispatch lives; a call site
59/// handles the shapes that are neither — `null`, array, scalar — and maps the
60/// error into its own type.
61///
62/// - `Some(Ok(rt))` — decoded.
63/// - `Some(Err(e))` — an object that is not a content, or a string that failed
64/// to import; `e` names the encoding so the caller can prefix its message.
65/// - `None` — the value is neither an object nor a string.
66pub(crate) fn decode_richtext_value(
67 value: &serde_json::Value,
68) -> Option<Result<Content, RichtextDecodeError>> {
69 match value {
70 serde_json::Value::Object(_) => Some(
71 quillmark_content::serial::from_canonical_value(value)
72 .map_err(|e| RichtextDecodeError::NotContent(e.to_string())),
73 ),
74 serde_json::Value::String(md) => {
75 Some(import_body(md).map_err(|e| RichtextDecodeError::BadMarkdown(e.to_string())))
76 }
77 _ => None,
78 }
79}
80
81/// Decode a JSON value for a `plaintext` field: a canonical content **object**
82/// (revalidated) or a literal **string** imported verbatim
83/// ([`from_plaintext`](quillmark_content::from_plaintext) — never markdown, so
84/// `*hi*` stays four plain characters). The plaintext twin of
85/// [`decode_richtext_value`]: the string branch is infallible (literal import
86/// can't fail), so only the object branch yields `Err` (`String` message). A
87/// call site handles the shapes that are neither — `null`, array, scalar. This
88/// is the single plaintext object-vs-string dispatch, shared by the coercion
89/// literal-import site and the validation shape check.
90///
91/// - `Some(Ok(rt))` — decoded.
92/// - `Some(Err(msg))` — an object that is not a valid content.
93/// - `None` — the value is neither an object nor a string.
94pub(crate) fn decode_plaintext_value(
95 value: &serde_json::Value,
96) -> Option<Result<Content, String>> {
97 match value {
98 serde_json::Value::Object(_) => {
99 Some(quillmark_content::serial::from_canonical_value(value).map_err(|e| e.to_string()))
100 }
101 serde_json::Value::String(s) => Some(Ok(quillmark_content::from_plaintext(s))),
102 _ => None,
103 }
104}
105
106pub mod assemble;
107pub mod dto;
108pub mod edit;
109pub mod emit;
110pub mod fences;
111pub mod limits;
112pub mod meta;
113pub mod payload;
114pub(crate) mod prescan;
115pub mod wire;
116pub(crate) mod yaml_hints;
117
118pub use dto::{peek_schema_version, StorageError, StoredDocument, SCHEMA_V0_93_0};
119pub use edit::EditError;
120pub use meta::{is_valid_kind_name, validate_composable_kind, CardKindError};
121pub use payload::{MetaKey, Payload, PayloadItem};
122// Reachable through `PayloadItem::nested_comments`, so nameable from here.
123pub use prescan::{CommentPathSegment, NestedComment};
124pub use wire::{CardWire, PayloadItemWire, WireError};
125
126/// Authoring-format rules for the `~~~` card-yaml markdown surface.
127///
128/// Surfaced verbatim to LLM/MCP consumers (and to CLI / Python bindings via
129/// the same text) so error parity holds — every consumer reads the same
130/// rules. This is the single source of truth; bindings should call into it
131/// rather than re-stating the rules in their own glue.
132pub const FORMAT_RULES: &str = "Document format rules:
133\u{2022} Block opener and closer are EXACTLY `~~~` (three tildes, no info string). The `~~~card-yaml` opener is also accepted as a non-canonical alias.
134\u{2022} A blank line must precede every `~~~` block opener (unless it is line 1), and the opener must be at column zero (no leading spaces). An indented `~~~` is an ordinary code block, not a card.
135\u{2022} The first block is the root and MUST contain `$quill: <name>@<version>`. Its `$kind` is `main` by position \u{2014} an explicit `$kind: main` is accepted but not required. Additional blocks declare composable cards via `$kind: <card_kind>`.
136\u{2022} Reserved `$`-keys: `$quill`, `$kind`, `$id`, `$ext`, `$seed`. User fields use lowercase snake_case.
137\u{2022} Prose body is the text after a block's closing `~~~`, up to the next opener or EOF. To include a literal fenced code block in prose, use a backtick fence (```); any column-zero `~~~` block is parsed as card metadata.
138\u{2022} A field that already shows a concrete value carries a default and is shippable as-is \u{2014} keep the line, override the value, or delete it to fall back to the default. A blank or null value (`field:`, `field: null`, `field: ~`) is treated the same as omitting the field: it falls back to the default, or to the type-empty zero value.
139\u{2022} `field: !must_fill <value>` marks a placeholder awaiting your input \u{2014} replace it with a real value and drop the `!must_fill` tag before shipping. A bare `field: !must_fill` is an empty placeholder. A leftover marker never blocks rendering, but it is reported as a warning until you replace it.
140\u{2022} Numbers and booleans MUST be unquoted (`year: 2025`, `pinned: true`); quoting turns them into strings and fails validation.
141\u{2022} Plain-scalar values cannot start with `*` or `&` (YAML alias/anchor markers) and cannot contain `: ` (colon-space). For markdown emphasis, embedded colons, or other special prefixes, quote the value: `field: '**bold**'` or `field: \"Name: subtitle\"`. Multi-line values use `|-`, not multi-line quoted scalars.";
142
143/// Authoring-ergonomics header that introduces a blueprint to an LLM/MCP
144/// consumer. The `{quill}` placeholder is substituted with the quill name.
145/// Designed to be shown above [`FORMAT_RULES`], which covers field-level
146/// semantics like the `!must_fill` marker — keep the wording tight here so the
147/// two strings do not duplicate guidance.
148const BLUEPRINT_INSTRUCTION_TEMPLATE: &str =
149 "Fill in the `{quill}` blueprint below: replace each `!must_fill` placeholder with a real \
150value and edit the body prose. Submit the filled markdown as `content` to `create_document`.";
151
152/// Render the blueprint-instruction header with `quill_name` substituted in.
153/// Single source of truth for the prose so every binding shows identical text.
154pub fn blueprint_instruction(quill_name: &str) -> String {
155 BLUEPRINT_INSTRUCTION_TEMPLATE.replace("{quill}", quill_name)
156}
157
158#[cfg(test)]
159mod tests;
160
161/// The record of one parse: the [`Document`] and any non-fatal warnings.
162/// Returned by [`Document::parse`], the single parse entry. Warnings live here
163/// and only here — `Document` is the value (equality, the storage DTO, and
164/// mutators all exclude warnings); `Parsed` is the parse *event*. A caller that
165/// wants only the document writes `Document::parse(md)?.document`.
166#[derive(Debug)]
167#[must_use = "carries parse warnings; read `.document`/`.warnings` or bind it"]
168pub struct Parsed {
169 pub document: Document,
170 pub warnings: Vec<Diagnostic>,
171}
172
173/// A single card-yaml block (root or composable). `body` is the content
174/// ([`Content`]) form of the prose after the closing fence — the empty content
175/// when none follows; check `card.body().is_blank()`. Markdown is a projection:
176/// [`Card::body_markdown`] re-emits it.
177#[derive(Debug, Clone, PartialEq)]
178pub struct Card {
179 payload: Payload,
180 body: Content,
181}
182
183impl Card {
184 /// Create a `Card` from its parts without validation. `body` is the content
185 /// form; to build from an authored markdown string, import it first via the
186 /// crate-internal `import_body` boundary. For user-facing construction of
187 /// composable cards use [`Card::new`].
188 pub fn from_parts(payload: Payload, body: Content) -> Self {
189 Self { payload, body }
190 }
191
192 pub fn quill(&self) -> Option<&QuillReference> {
193 self.payload.quill()
194 }
195
196 pub fn kind(&self) -> Option<&str> {
197 self.payload.kind()
198 }
199
200 pub fn id(&self) -> Option<&str> {
201 self.payload.id()
202 }
203
204 /// Opaque `$ext` map for out-of-band extension data (UI editor state,
205 /// agent annotations, …). Carried through Markdown and storage DTO
206 /// round-trips; never emitted into the plate JSON consumed by
207 /// backends.
208 pub fn ext(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
209 self.payload.ext()
210 }
211
212 pub fn payload(&self) -> &Payload {
213 &self.payload
214 }
215
216 pub fn payload_mut(&mut self) -> &mut Payload {
217 &mut self.payload
218 }
219
220 /// The card body as a [`Content`] content — the canonical content model.
221 /// For the markdown projection use [`Card::body_markdown`].
222 pub fn body(&self) -> &Content {
223 &self.body
224 }
225
226 /// The card body rendered back to its markdown projection. This is a
227 /// derived view (`export ∘ body`), not stored state; a `Document` round-trip
228 /// therefore canonicalizes the body (e.g. `__b__` → `**b**`).
229 pub fn body_markdown(&self) -> String {
230 quillmark_content::export::to_markdown(&self.body)
231 }
232
233 pub(crate) fn overwrite_body(&mut self, body: Content) {
234 self.body = body;
235 }
236
237 pub(crate) fn body_mut(&mut self) -> &mut Content {
238 &mut self.body
239 }
240
241 /// Read a richtext-valued user field back as a [`Content`] content — the
242 /// field-level twin of [`Card::body`]. Decodes the stored value through the
243 /// same object-or-markdown dispatch the writer
244 /// ([`commit_field`](Card::commit_field)) commits, so a field
245 /// stored as a canonical content reads back losslessly (identity marks
246 /// intact) and a still-authored markdown string imports.
247 ///
248 /// - `None` — the field is absent.
249 /// - `Some(Ok(rt))` — decoded content.
250 /// - `Some(Err(_))` — the field is present but neither a content object nor
251 /// an importable markdown string (e.g. a bare number a `store_field` wrote).
252 ///
253 /// A `Document` carries no schema, so this cannot itself tell a richtext
254 /// field from a plain string field; the caller names a field it knows is
255 /// richtext, exactly as it does when writing.
256 pub fn field_richtext(&self, name: &str) -> Option<Result<Content, RichtextDecodeError>> {
257 let value = self.payload.get(name)?.as_json();
258 Some(match crate::document::decode_richtext_value(value) {
259 Some(result) => result,
260 None => match value {
261 serde_json::Value::Null => Ok(Content::empty()),
262 _ => Err(RichtextDecodeError::NotContent(
263 "expected a richtext content object or a markdown string".to_string(),
264 )),
265 },
266 })
267 }
268
269 /// The markdown projection of a richtext-valued field (`export ∘ decode`) —
270 /// the field-level twin of [`Card::body_markdown`], and the projection an
271 /// emit or a markdown save writes for a content-valued field. The projection
272 /// twin of [`field_richtext`](Card::field_richtext), carrying its `Ok`/`Err`
273 /// decode outcome:
274 ///
275 /// - `None` — the field is absent.
276 /// - `Some(Ok(md))` — the projected markdown.
277 /// - `Some(Err(_))` — the field is present but does not decode as richtext
278 /// (a scalar/array/object a `store_field` wrote, or a non-content object).
279 ///
280 /// Absence returns `None`; a present non-richtext value returns `Some(Err)`,
281 /// so the projection surfaces the type mismatch instead of blanking on it.
282 pub fn field_markdown(&self, name: &str) -> Option<Result<String, RichtextDecodeError>> {
283 Some(self.field_richtext(name)?.map(|rt| quillmark_content::export::to_markdown(&rt)))
284 }
285
286 /// The plaintext projection of a content-valued field (`to_plaintext ∘
287 /// decode`) — the literal-codec twin of [`field_markdown`](Card::field_markdown),
288 /// for a `plaintext`-typed field: marks are never interpreted, so the text is
289 /// verbatim both ways. Carries [`field_richtext`](Card::field_richtext)'s
290 /// `Ok`/`Err` decode outcome:
291 ///
292 /// - `None` — the field is absent.
293 /// - `Some(Ok(text))` — the projected literal text.
294 /// - `Some(Err(_))` — the field is present but does not decode as content.
295 pub fn field_plaintext(&self, name: &str) -> Option<Result<String, RichtextDecodeError>> {
296 Some(self.field_richtext(name)?.map(|rt| quillmark_content::export::to_plaintext(&rt)))
297 }
298}
299
300/// A parsed, per-kind **seed overlay**: the sparse fields (and optional body)
301/// a newly-added card of a given kind starts with. Built from a `$seed[<kind>]`
302/// entry of the main card's [`Card::seed`] map via [`SeedOverlay::from_json`],
303/// and layered over the quill's schema-example seed by
304/// [`crate::Quill::seed_card`] (overlay › example › absent). The reserved inner
305/// key `$body` carries the body override; every other user field becomes an
306/// entry, while any other `$`-prefixed key is reserved and dropped.
307#[derive(Debug, Clone, PartialEq, Default)]
308pub struct SeedOverlay {
309 /// Field-value overrides, keyed by field name.
310 pub fields: indexmap::IndexMap<String, crate::value::QuillValue>,
311 /// Body override, when the overlay declares a `$body` string.
312 pub body: Option<String>,
313}
314
315impl SeedOverlay {
316 /// Parse an overlay from a `$seed[<kind>]` JSON value, or `None` when it is
317 /// not a mapping. Use this to turn the raw overlay object a consumer reads
318 /// from the main card's `$seed` map ([`Card::seed`]) into a typed overlay to
319 /// hand to [`crate::Quill::seed_card`] — e.g.
320 /// `doc.main().seed().and_then(|m| m.get(kind)).and_then(SeedOverlay::from_json)`.
321 pub fn from_json(value: &serde_json::Value) -> Option<Self> {
322 value.as_object().map(Self::from_json_map)
323 }
324
325 /// Build an overlay from a single `$seed[<kind>]` JSON map: the reserved
326 /// `$body` string becomes [`body`](Self::body); every other user-field entry
327 /// becomes a field. A non-string `$body` is ignored (no body override). Any
328 /// other `$`-prefixed key is reserved and dropped — never stored as a user
329 /// field — since an overlay only ever carries user fields plus `$body`.
330 fn from_json_map(map: &serde_json::Map<String, serde_json::Value>) -> Self {
331 let mut fields = indexmap::IndexMap::new();
332 let mut body = None;
333 for (key, value) in map {
334 if key == "$body" {
335 if let Some(s) = value.as_str() {
336 body = Some(s.to_string());
337 }
338 } else if key.starts_with('$') {
339 // Reserved key other than `$body`: not a user field. Drop it
340 // rather than smuggle a `$`-key into the field set.
341 continue;
342 } else {
343 fields.insert(
344 key.clone(),
345 crate::value::QuillValue::from_json(value.clone()),
346 );
347 }
348 }
349 SeedOverlay { fields, body }
350 }
351}
352
353/// A fully-parsed Quillmark document. Serde routes through [`StoredDocument`];
354/// for the plate wire shape see [`Document::to_plate_json`].
355///
356/// Parse-time warnings are *not* document state — they ride out-of-band on
357/// [`Parsed`] from [`Document::parse`], the single owner. Equality and the
358/// storage DTO therefore cover only structural content (`main` and `cards`).
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
360#[serde(into = "StoredDocument", try_from = "StoredDocument")]
361pub struct Document {
362 main: Card,
363 cards: Vec<Card>,
364}
365
366impl Document {
367 /// Create a blank document: a main card carrying only `$quill`, an empty
368 /// body, and no composable cards. The programmatic blank canvas — every
369 /// schema field is absent and resolves at render time (`default`, else
370 /// type-empty zero), so nothing the caller did not set reaches the
371 /// output. For an example-filled starter shaped like the blueprint, use
372 /// `Quill::seed_document`.
373 pub fn new(quill: QuillReference) -> Self {
374 let mut payload = Payload::new();
375 payload.set_quill(quill);
376 // Parsed main cards always carry `$kind: main` (the parser normalizes
377 // it in); match that shape so a blank document round-trips equal.
378 payload.set_kind("main");
379 Self {
380 main: Card::from_parts(payload, Content::empty()),
381 cards: Vec::new(),
382 }
383 }
384
385 /// Create a `Document` from a pre-built main card and composable cards.
386 /// `main` must carry `$quill`; composable cards must not.
387 pub fn from_main_and_cards(main: Card, cards: Vec<Card>) -> Self {
388 debug_assert!(main.quill().is_some(), "main card must carry `$quill`");
389 debug_assert!(
390 cards.iter().all(|c| c.quill().is_none()),
391 "composable cards must not carry `$quill`"
392 );
393 debug_assert!(
394 cards.iter().all(|c| c.seed().is_none()),
395 "composable cards must not carry `$seed`"
396 );
397 debug_assert!(
398 {
399 let mut seen = std::collections::HashSet::new();
400 cards
401 .iter()
402 .filter_map(|c| c.id())
403 .all(|id| !id.is_empty() && seen.insert(id))
404 },
405 "composable card `$id`s must be non-empty and unique per document"
406 );
407 Self { main, cards }
408 }
409
410 /// Parse card-yaml Markdown into a [`Parsed`] — the [`Document`] plus any
411 /// non-fatal warnings. The single parse entry; a caller that wants only the
412 /// document writes `Document::parse(md)?.document`. Errors on malformed
413 /// YAML, a missing root `$quill`, an over-size input, and the other
414 /// [`ParseError`] variants.
415 #[doc(alias = "from_markdown")]
416 pub fn parse(markdown: &str) -> Result<Parsed, ParseError> {
417 assemble::decompose_with_warnings(markdown)
418 .map(|(document, warnings)| Parsed { document, warnings })
419 }
420
421 pub fn main(&self) -> &Card {
422 &self.main
423 }
424
425 pub fn main_mut(&mut self) -> &mut Card {
426 &mut self.main
427 }
428
429 /// The `$quill` reference from the root block. Always present on parsed documents.
430 pub fn quill_reference(&self) -> QuillReference {
431 self.main
432 .quill()
433 .cloned()
434 .expect("root block's $quill is validated at parse time")
435 }
436
437 pub fn cards(&self) -> &[Card] {
438 &self.cards
439 }
440
441 pub fn cards_mut(&mut self) -> &mut [Card] {
442 &mut self.cards
443 }
444
445 /// A single composable card by index — the immutable twin of
446 /// [`card_mut`](Document::card_mut), so reading one card's payload does not
447 /// require materializing every card via [`cards`](Document::cards). `None`
448 /// when out of range.
449 pub fn card(&self, index: usize) -> Option<&Card> {
450 self.cards.get(index)
451 }
452
453 /// The composable card whose `$id` equals `id`, with its index —
454 /// resolving the durable card handle ([PROGRAMMATIC.md]) without a
455 /// hand-rolled scan over [`cards`](Document::cards). `$id` is unique per
456 /// document (parse repairs a duplicate, mutators and storage reject one),
457 /// so at most one card matches; `None` when none carries it.
458 ///
459 /// [PROGRAMMATIC.md]: https://github.com/borb-sh/quillmark/blob/main/prose/canon/PROGRAMMATIC.md
460 pub fn find_card(&self, id: &str) -> Option<(usize, &Card)> {
461 self.cards
462 .iter()
463 .enumerate()
464 .find(|(_, card)| card.id() == Some(id))
465 }
466
467 pub(crate) fn cards_vec_mut(&mut self) -> &mut Vec<Card> {
468 &mut self.cards
469 }
470
471 /// Serialize to the JSON wire shape consumed by backend plates. This is
472 /// the **only** place in `quillmark-core` that produces this shape:
473 ///
474 /// ```json
475 /// {
476 /// "$quill": "<ref>",
477 /// "$body": { "text": "…", "lines": [...], "marks": [...], "islands": [...] },
478 /// "$cards": [{ "$kind": "<tag>", "$body": <content>, "<field>": <value>, ... }],
479 /// "<field>": <value>, ...
480 /// }
481 /// ```
482 ///
483 /// `$body` (global and per-card) is canonical Content-JSON — the content as
484 /// a nested object, not a markdown string. Richtext payload fields likewise
485 /// cross as content objects (committed at coercion time).
486 ///
487 /// `$`-prefixed keys carry document-level metadata (quill ref, body
488 /// text, card list, card kind). User payload fields stay flat at the
489 /// root — they cannot collide with `$` keys because user field names are
490 /// never `$`-prefixed (they match `[A-Za-z_][A-Za-z0-9_]*`).
491 ///
492 /// `$kind` is document-defined and omitted for a kindless card (never a
493 /// fabricated `""`). This method is schema-free and emits `$body` for every
494 /// card and the root; the schema-gated render plate
495 /// (`QuillConfig::compile_data`) instead calls `to_plate_json_gated` with the
496 /// per-card body-presence it resolved, so a card whose kind enables no body
497 /// carries no `$body` — issue 1030's "absent on undefined".
498 pub fn to_plate_json(&self) -> serde_json::Value {
499 // Schema-free: the root and every card carry `$body`.
500 self.to_plate_json_gated(true, None)
501 }
502
503 /// [`to_plate_json`](Self::to_plate_json) with the body-presence decision
504 /// supplied by the caller: the root carries `$body` iff `main_body`, and card
505 /// *i* iff `card_bodies` is `None` (all present) or `card_bodies[i]` holds.
506 /// The schema-gated render plate (`QuillConfig::compile_data`) passes the
507 /// body-enabled bit it already resolved per card, so a body-disabled card
508 /// never carries `$body` (issue 1030, "absent on undefined") and the decision
509 /// is never re-derived from the serialized plate. `Document` stays schema-free
510 /// — it receives the decision, not a schema.
511 pub(crate) fn to_plate_json_gated(
512 &self,
513 main_body: bool,
514 card_bodies: Option<&[bool]>,
515 ) -> serde_json::Value {
516 let mut map = serde_json::Map::new();
517
518 map.insert(
519 "$quill".to_string(),
520 serde_json::Value::String(self.quill_reference().to_string()),
521 );
522
523 // The seam carries the body as canonical Content-JSON (Option A): a
524 // nested content object, byte-identical to `to_canonical_json`, never a lossy
525 // markdown string. Backends lower the content (typst → markup + source
526 // map; pdfform → `.text`); the markdown projection is `body_markdown`.
527 if main_body {
528 map.insert(
529 "$body".to_string(),
530 quillmark_content::serial::to_canonical_value(self.main.body()),
531 );
532 }
533
534 let cards_array: Vec<serde_json::Value> = self
535 .cards
536 .iter()
537 .enumerate()
538 .map(|(i, card)| {
539 let mut card_map = serde_json::Map::new();
540 // A kindless card carries no `$kind`, never a fabricated `""` —
541 // matching the resolved view's `kind: None`.
542 if let Some(kind) = card.kind() {
543 card_map.insert(
544 "$kind".to_string(),
545 serde_json::Value::String(kind.to_string()),
546 );
547 }
548 // `$body` iff the caller's schema defines a body for this card.
549 if card_bodies.map_or(true, |f| f.get(i).copied().unwrap_or(true)) {
550 card_map.insert(
551 "$body".to_string(),
552 quillmark_content::serial::to_canonical_value(card.body()),
553 );
554 }
555 for (key, value) in card.payload.iter() {
556 card_map.insert(key.clone(), value.as_json().clone());
557 }
558 serde_json::Value::Object(card_map)
559 })
560 .collect();
561
562 map.insert("$cards".to_string(), serde_json::Value::Array(cards_array));
563
564 for (key, value) in self.main.payload.iter() {
565 map.insert(key.clone(), value.as_json().clone());
566 }
567
568 serde_json::Value::Object(map)
569 }
570}