quilldown 1.5.0

Convert GitHub-Flavored Markdown into high-fidelity Word .docx documents.
Documentation
// <auto-generated by typra-emitter>
// Code generated by Typra emitter; DO NOT EDIT.

#![allow(
    unused_imports,
    dead_code,
    non_camel_case_types,
    unused_variables,
    unexpected_cfgs,
    clippy::all
)]

use super::context::{LoadContext, SaveContext};

use super::asset_reference::AssetReference;

use super::block::Block;

use super::document_metadata::DocumentMetadata;

use super::footnote_definition::FootnoteDefinition;

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Document {
    pub blocks: Vec<Block>,
    pub footnotes: Option<Vec<FootnoteDefinition>>,
    pub metadata: Option<DocumentMetadata>,
    pub assets: Option<Vec<AssetReference>>,
}

impl Document {
    /// Create a new Document with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load Document from a JSON string.
    pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
        let value: serde_json::Value = serde_json::from_str(json)?;
        Self::validate_input_at(&value, "")
            .map_err(|message| <serde_json::Error as serde::de::Error>::custom(message))?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load Document from a YAML string.
    pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
        let value: serde_json::Value = serde_yaml::from_str(yaml)?;
        Self::validate_input_at(&value, "")
            .map_err(|message| <serde_yaml::Error as serde::de::Error>::custom(message))?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load Document from an already-parsed JSON value, returning an error
    /// instead of panicking on invalid input. Fallible companion to
    /// `load_from_value` with the same validation policy as `from_json`.
    pub fn try_load_from_value(
        value: &serde_json::Value,
        ctx: &LoadContext,
    ) -> Result<Self, serde_json::Error> {
        Self::validate_input_at(value, "")
            .map_err(|message| <serde_json::Error as serde::de::Error>::custom(message))?;
        Ok(Self::load_from_value(value, ctx))
    }

    /// Load Document from a `serde_json::Value`.
    ///
    /// Calls `ctx.process_input` before field extraction.
    pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
        let value = ctx.process_input(value.clone());
        if let Err(message) = Self::validate_input_at(&value, "") {
            panic!("{}", message);
        }
        Self {
            blocks: value
                .get("blocks")
                .map(|v| Self::load_blocks(v, ctx))
                .unwrap_or_default(),
            footnotes: value.get("footnotes").map(|v| Self::load_footnotes(v, ctx)),
            metadata: value
                .get("metadata")
                .filter(|v| v.is_object() || v.is_array() || v.is_string())
                .map(|v| DocumentMetadata::load_from_value(v, ctx)),
            assets: value.get("assets").map(|v| Self::load_assets(v, ctx)),
        }
    }

    pub(crate) fn validate_input_at(value: &serde_json::Value, path: &str) -> Result<(), String> {
        if let Some(entries) = value
            .get("blocks")
            .and_then(|candidate| candidate.as_array())
        {
            let collection_path = if path.is_empty() {
                "blocks".to_string()
            } else {
                format!("{}.blocks", path)
            };
            for (index, entry) in entries.iter().enumerate() {
                let entry_path = format!("{}[{}]", collection_path, index);
                Block::validate_input_at(entry, &entry_path)?;
            }
        }
        if let Some(entries) = value
            .get("footnotes")
            .and_then(|candidate| candidate.as_array())
        {
            let collection_path = if path.is_empty() {
                "footnotes".to_string()
            } else {
                format!("{}.footnotes", path)
            };
            for (index, entry) in entries.iter().enumerate() {
                let entry_path = format!("{}[{}]", collection_path, index);
                FootnoteDefinition::validate_input_at(entry, &entry_path)?;
            }
        }
        let child_path = if path.is_empty() {
            "metadata".to_string()
        } else {
            format!("{}.metadata", path)
        };
        if let Some(child) = value.get("metadata") {
            DocumentMetadata::validate_input_at(child, &child_path)?;
        }
        if let Some(entries) = value
            .get("assets")
            .and_then(|candidate| candidate.as_array())
        {
            let collection_path = if path.is_empty() {
                "assets".to_string()
            } else {
                format!("{}.assets", path)
            };
            for (index, entry) in entries.iter().enumerate() {
                let entry_path = format!("{}[{}]", collection_path, index);
                AssetReference::validate_input_at(entry, &entry_path)?;
            }
        }
        Ok(())
    }

    /// Serialize Document to a `serde_json::Value`.
    ///
    /// Calls `ctx.process_dict` after serialization.
    pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
        let mut result = serde_json::Map::new();
        // Write base fields
        result.insert("blocks".to_string(), Self::save_blocks(&self.blocks, ctx));
        if let Some(items) = self.footnotes.as_ref() {
            result.insert("footnotes".to_string(), Self::save_footnotes(items, ctx));
        }
        if let Some(val) = self.metadata.as_ref() {
            let nested = val.to_value(ctx);
            if !nested.is_null() {
                result.insert("metadata".to_string(), nested);
            }
        }
        if let Some(items) = self.assets.as_ref() {
            result.insert("assets".to_string(), Self::save_assets(items, ctx));
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize Document to a JSON string.
    pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_value(ctx))
    }

    /// Serialize Document to a YAML string.
    pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(&self.to_value(ctx))
    }

    /// Load a collection of Block from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_blocks(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Block> {
        match data {
            serde_json::Value::Array(arr) => {
                arr.iter().map(|v| Block::load_from_value(v, ctx)).collect()
            }

            _ => Vec::new(),
        }
    }

    /// Save a collection of Block to a JSON value.
    fn save_blocks(items: &[Block], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of FootnoteDefinition from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_footnotes(data: &serde_json::Value, ctx: &LoadContext) -> Vec<FootnoteDefinition> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| FootnoteDefinition::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of FootnoteDefinition to a JSON value.
    fn save_footnotes(items: &[FootnoteDefinition], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }

    /// Load a collection of AssetReference from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_assets(data: &serde_json::Value, ctx: &LoadContext) -> Vec<AssetReference> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| AssetReference::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of AssetReference to a JSON value.
    fn save_assets(items: &[AssetReference], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }
}

// Serde for `Document` delegates to the canonical to_value/load_from_value
// logic so its serde wire form always equals the canonical to_value/load_from_value form. Uses a default (no-op) context — no ${env:}/${file:}
// resolution here — leaving the context-aware LoadContext/SaveContext API intact.
#[cfg(feature = "serde")]
impl serde::Serialize for Document {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serde::Serialize::serialize(&self.to_value(&SaveContext::default()), serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Document {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
        Self::validate_input_at(&value, "").map_err(serde::de::Error::custom)?;
        Ok(Self::load_from_value(&value, &LoadContext::default()))
    }
}