use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::{references, relationships};
use crate::assembly::{AssemblyError, ExecutedWorkspace, WorkspaceSources};
use crate::diagnostics::{
Diagnostic, DiagnosticCode, DiagnosticEntity, DiagnosticPath, DiagnosticSource, Severity,
};
use crate::execution::assets::{validate_authored_image_bytes, validate_image_bytes};
use crate::ir::*;
use crate::provenance::fingerprint_bytes;
mod repository_links;
mod walk;
pub(crate) use repository_links::repository_target_url;
pub(crate) use walk::{anchors as document_anchors, references as document_references};
pub(crate) fn external_url_allowed(kind: ReferenceKind, spelling: &str, generated: bool) -> bool {
let Ok(decoded) = percent_encoding::percent_decode_str(spelling).decode_utf8() else {
return false;
};
if spelling
.chars()
.chain(decoded.chars())
.any(|c| c.is_control() || c == '\\')
{
return false;
}
let Ok(url) = url::Url::parse(spelling) else {
return false;
};
if !url.username().is_empty() || url.password().is_some() {
return false;
}
match kind {
ReferenceKind::Link => matches!(url.scheme(), "https" | "http" | "mailto"),
ReferenceKind::Image => {
!generated && matches!(url.scheme(), "https" | "http") && url.host_str().is_some()
}
ReferenceKind::Semantic => false,
}
}
pub(crate) fn semantic_target<'a>(
document: &SourcedDocument,
kind: ReferenceKind,
spelling: &'a str,
) -> Option<&'a str> {
if kind == ReferenceKind::Semantic {
return Some(spelling);
}
if kind == ReferenceKind::Link
&& matches!(&document.source_format, DocumentFormat::Extracted { name } if matches!(name.as_str(), "julia-markdown" | "rd" | "numpy-docstring" | "python-docstring" | "rustdoc-markdown" | "doxygen-xml"))
{
return spelling.strip_prefix("@ref ");
}
None
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum DocumentIdentity {
Page {
page: String,
},
Item {
item: ItemReference,
},
Concept {
concept: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum ReferenceTarget {
Item {
item: ItemReference,
},
Page {
page: String,
fragment: Option<String>,
},
Anchor {
fragment: String,
},
Asset {
asset: AssetReference,
fragment: Option<String>,
},
Repository {
repository: String,
path: DiagnosticPath,
directory: bool,
fragment: Option<String>,
},
External {
url: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ReferenceKind {
Semantic,
Link,
Image,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolvedReference {
pub kind: ReferenceKind,
pub spelling: String,
pub target: ReferenceTarget,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResolvedDocument {
pub document: DocumentIdentity,
pub collection_path: Option<DiagnosticPath>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub source_ranges: Vec<IncludeSourceRange>,
pub anchors: BTreeSet<String>,
pub references: Vec<ResolvedReference>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentAsset {
pub fingerprint: Fingerprint,
pub media_type: String,
pub bytes: Vec<u8>,
}
#[derive(Debug)]
pub struct ResolvedWorkspace {
records: Vec<ResolvedDocument>,
pub(crate) components: BTreeMap<String, crate::components::ComponentBundle>,
pub(crate) public_assets: BTreeMap<String, String>,
logo: Option<AssetReference>,
open_graph: Option<AssetReference>,
assets: BTreeMap<String, ContentAsset>,
diagnostics: BTreeSet<Diagnostic>,
inputs: BTreeMap<PathBuf, AssetObservation>,
repository_targets: BTreeMap<PathBuf, RepositoryTargetObservation>,
}
#[derive(Debug)]
struct RepositoryTargetObservation {
path: PathBuf,
boundary: PathBuf,
directory: bool,
}
#[derive(Debug, PartialEq, Eq)]
struct AssetObservation {
path: PathBuf,
boundary: PathBuf,
fingerprint: Fingerprint,
}
impl ResolvedWorkspace {
pub fn records(&self) -> &[ResolvedDocument] {
&self.records
}
pub fn assets(&self) -> &BTreeMap<String, ContentAsset> {
&self.assets
}
pub fn logo(&self) -> Option<&AssetReference> {
self.logo.as_ref()
}
pub fn open_graph(&self) -> Option<&AssetReference> {
self.open_graph.as_ref()
}
pub fn diagnostics(&self) -> &BTreeSet<Diagnostic> {
&self.diagnostics
}
pub fn input_paths(&self) -> impl Iterator<Item = &Path> {
self.inputs
.keys()
.chain(self.repository_targets.keys())
.map(PathBuf::as_path)
}
pub fn revalidate(&self) -> Result<(), AssemblyError> {
for (selected, observation) in &self.inputs {
let AssetObservation {
path,
boundary,
fingerprint,
} = observation;
if fs::canonicalize(selected)? != *path {
return Err(AssemblyError::InputsChanged);
}
let resolved = crate::paths::resolve_input_file(
boundary,
"asset",
path.strip_prefix(boundary)
.map_err(|_| AssemblyError::InputsChanged)?,
boundary,
)?;
if resolved != *path || fingerprint_bytes(&fs::read(path)?) != *fingerprint {
return Err(AssemblyError::InputsChanged);
}
}
for (selected, observation) in &self.repository_targets {
let resolved = crate::paths::resolve_repository_target(
selected
.strip_prefix(&observation.boundary)
.map_err(|_| AssemblyError::InputsChanged)?,
&observation.boundary,
)?;
if resolved != observation.path || resolved.is_dir() != observation.directory {
return Err(AssemblyError::InputsChanged);
}
}
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
pub enum ResolutionError {
#[error(transparent)]
Inputs(#[from] AssemblyError),
#[error("workspace reference validation failed")]
Diagnostics(Vec<Diagnostic>),
}
impl ResolutionError {
pub fn diagnostics(&self) -> &[Diagnostic] {
match self {
Self::Diagnostics(diagnostics) => diagnostics,
_ => &[],
}
}
}
pub fn resolve_workspace(sources: &WorkspaceSources) -> Result<ResolvedWorkspace, ResolutionError> {
resolve(sources, sources.native_assets.clone(), false)
}
pub(crate) fn resolve_bundle(
sources: &WorkspaceSources,
) -> Result<ResolvedWorkspace, ResolutionError> {
resolve(sources, sources.native_assets.clone(), true)
}
pub fn resolve_executed_workspace(
executed: &ExecutedWorkspace,
) -> Result<ResolvedWorkspace, ResolutionError> {
let mut generated = executed.sources().native_assets.clone();
for result in executed.executed_pages().values() {
for staged in result.staged_assets() {
let asset = result
.validated()
.referenced_assets()
.find(|asset| asset.reference == staged.reference)
.ok_or(AssemblyError::InputsChanged)?;
let bytes = fs::read(&staged.path).map_err(AssemblyError::from)?;
if fingerprint_bytes(&bytes) != asset.reference.fingerprint
|| bytes.len() as u64 != asset.byte_size
|| validate_image_bytes(&asset.media_type, &bytes).is_err()
{
return Err(AssemblyError::InputsChanged.into());
}
generated.insert(
asset.reference.path.clone(),
ContentAsset {
fingerprint: asset.reference.fingerprint.clone(),
media_type: asset.media_type.clone(),
bytes,
},
);
}
}
resolve(executed.sources(), generated, false)
}
struct DocumentContext<'a> {
identity: DocumentIdentity,
owner: Option<&'a str>,
document: &'a SourcedDocument,
path: Option<PathBuf>,
entity: DiagnosticEntity,
}
fn resolve(
sources: &WorkspaceSources,
generated: BTreeMap<DiagnosticPath, ContentAsset>,
bundle_export: bool,
) -> Result<ResolvedWorkspace, ResolutionError> {
sources.revalidate()?;
let workspace = sources.workspace();
let mut documents = Vec::new();
let mut pages: BTreeMap<PathBuf, Vec<String>> = BTreeMap::new();
let path_for = |source: &SourceLocation| {
sources
.paths()
.repositories
.iter()
.find(|r| r.id == source.repository)
.map(|r| r.path.join(source.path.as_str()))
};
for (id, page) in &workspace.pages {
let path = page.document.source_location.as_ref().and_then(path_for);
if let Some(path) = &path {
pages.entry(path.clone()).or_default().push(id.clone());
}
for provenance in &page.document.provenance {
if !matches!(provenance.activity, ProvenanceActivity::Declaration) {
continue;
}
if let Some(DiagnosticSource::Repository {
repository,
path: source_path,
}) = &provenance.source
{
let source = SourceLocation {
repository: repository.clone(),
path: source_path.clone(),
span: None,
};
if let Some(alias) = path_for(&source) {
let aliases = pages.entry(alias).or_default();
if !aliases.contains(id) {
aliases.push(id.clone());
}
}
}
}
let prepared = sources.prepared_pages().get(id);
let entity =
if let (PageKind::Authored { collection }, Some(prepared)) = (&page.kind, prepared) {
DiagnosticEntity::Document {
collection: collection.clone(),
path: prepared.relative.clone(),
}
} else if let ContentOwner::Package { package } = &page.owner {
DiagnosticEntity::Package {
id: package.clone(),
}
} else {
DiagnosticEntity::Project
};
documents.push(DocumentContext {
identity: DocumentIdentity::Page { page: id.clone() },
owner: match &page.owner {
ContentOwner::Project => None,
ContentOwner::Package { package } => Some(package),
},
document: &page.document,
path,
entity,
});
}
for (package, record) in &workspace.packages {
for (item, record) in &record.items {
if let Some(document) = &record.documentation {
documents.push(DocumentContext {
identity: DocumentIdentity::Item {
item: ItemReference {
package: package.clone(),
item: item.clone(),
},
},
owner: Some(package),
document,
path: document.source_location.as_ref().and_then(path_for),
entity: DiagnosticEntity::Item {
package: package.clone(),
id: item.clone(),
},
});
}
}
}
for (concept, record) in &workspace.concepts {
if let Some(document) = &record.documentation {
documents.push(DocumentContext {
identity: DocumentIdentity::Concept {
concept: concept.clone(),
},
owner: None,
document,
path: document.source_location.as_ref().and_then(path_for),
entity: DiagnosticEntity::Concept {
id: concept.clone(),
},
});
}
}
documents.sort_by(|a, b| a.identity.cmp(&b.identity));
let anchors: BTreeMap<_, _> = documents
.iter()
.map(|d| {
(
d.identity.clone(),
walk::anchors(&d.document.document.blocks),
)
})
.collect();
let mut resolution = Resolver {
sources,
pages,
anchors,
generated,
result: ResolvedWorkspace {
records: vec![],
components: BTreeMap::new(),
public_assets: BTreeMap::new(),
logo: None,
open_graph: None,
assets: BTreeMap::new(),
diagnostics: workspace.diagnostics.clone(),
inputs: BTreeMap::new(),
repository_targets: BTreeMap::new(),
},
};
resolution
.result
.diagnostics
.extend(relationships::validate(workspace));
let presentation = &sources.configuration().presentation;
for (field, declaration, raster_only) in [
(
"presentation.logo.path",
presentation
.logo
.as_ref()
.map(|image| (&image.repository, &image.path)),
false,
),
(
"presentation.open-graph.path",
presentation
.open_graph
.as_ref()
.map(|image| (&image.repository, &image.path)),
true,
),
] {
let Some((repository, image_path)) = declaration else {
continue;
};
let root = &sources
.paths()
.repositories
.iter()
.find(|r| r.id == *repository)
.expect("validated presentation image repository")
.path;
let path =
crate::paths::resolve_input_file(root, field, Path::new(image_path.as_str()), root)
.map_err(AssemblyError::from)?;
let asset = resolution
.collect_asset(
root.join(image_path.as_str()),
path,
root,
ReferenceKind::Image,
)
.and_then(|asset| {
let media_type = &resolution.result.assets[&asset.fingerprint.value].media_type;
if raster_only && !matches!(media_type.as_str(), "image/png" | "image/jpeg") {
Err(DiagnosticCode::UnresolvedDocumentReference)
} else {
Ok(asset)
}
});
match asset {
Ok(asset) => {
if raster_only {
resolution.result.open_graph = Some(asset);
} else {
resolution.result.logo = Some(asset);
}
}
Err(code) => {
resolution.result.diagnostics.insert(
Diagnostic::new(
code,
Severity::Error,
if raster_only {
"presentation.open-graph.path must name a valid PNG or JPEG image."
} else {
"presentation.logo.path must name a valid SVG, PNG, or JPEG image."
},
)
.with_entity(DiagnosticEntity::ConfigurationField { path: field.into() }),
);
}
}
}
for declaration in &presentation.assets {
let root = &sources
.paths()
.repositories
.iter()
.find(|r| r.id == declaration.repository)
.expect("validated public asset repository")
.path;
let selected = root.join(declaration.path.as_str());
let path = crate::paths::resolve_input_file(
root,
"presentation.assets.path",
Path::new(declaration.path.as_str()),
root,
)
.map_err(AssemblyError::from)?;
let bytes = fs::read(&path).map_err(AssemblyError::from)?;
let fingerprint = fingerprint_bytes(&bytes);
resolution.result.public_assets.insert(
declaration.publish.as_str().into(),
fingerprint.value.clone(),
);
resolution
.result
.assets
.entry(fingerprint.value.clone())
.or_insert(ContentAsset {
fingerprint: fingerprint.clone(),
media_type: "application/octet-stream".into(),
bytes,
});
let observation = AssetObservation {
path,
boundary: root.clone(),
fingerprint,
};
if let Some(previous) = resolution.result.inputs.get_mut(&selected) {
if previous.path != observation.path || previous.fingerprint != observation.fingerprint
{
return Err(AssemblyError::InputsChanged.into());
}
if observation.boundary.starts_with(&previous.boundary) {
*previous = observation;
}
} else {
resolution.result.inputs.insert(selected, observation);
}
}
for asset in &sources.bundles.assets {
insert_asset(&mut resolution.result.assets, asset.clone())
.map_err(|_| AssemblyError::InputsChanged)?;
}
let component_names = sources
.configuration()
.components
.iter()
.map(|component| component.id.as_str())
.collect();
for context in documents {
if let Err(error) =
crate::components::validate_blocks(&context.document.document.blocks, &component_names)
{
let mut diagnostic = (*error).with_entity(context.entity.clone());
diagnostic.source = context.document.source_location.as_ref().map(|source| {
DiagnosticSource::Repository {
repository: source.repository.clone(),
path: source.path.clone(),
}
});
if let DocumentIdentity::Page { page } = &context.identity
&& let Some(prepared) = sources.prepared_pages().get(page)
{
crate::assembly::remap_include_diagnostic(&mut diagnostic, &prepared.source_ranges);
}
resolution.result.diagnostics.insert(diagnostic);
}
let mut imported = sources
.bundles
.documents
.get(&context.identity)
.map(|record| record.references.iter());
let mut references = Vec::new();
walk::references(
&context.document.document.blocks,
None,
&mut |kind, spelling, span, generated| {
if semantic_target(context.document, kind, spelling).is_none() {
if let Some(imported) = &mut imported {
references.push(
imported
.next()
.expect("validated bundle references")
.clone(),
);
return;
}
} else if bundle_export {
return;
}
match resolution.reference(&context, kind, spelling, generated) {
Ok(target) => references.push(ResolvedReference {
kind,
spelling: spelling.into(),
target,
}),
Err(code) => {
let mut diagnostic = Diagnostic::new(
code,
Severity::Error,
if code == DiagnosticCode::InvalidContentImage {
format!(
"Image asset `{spelling}` failed validation. PNG and JPEG must decode completely; SVG must satisfy the inert image policy, which excludes DTDs, styles, definitions, references, and clipping paths. Convert static Matplotlib SVGs to PNG before linking them; see the SVG conversion recipe in the authoring guide."
)
} else {
format!(
"Cannot resolve {kind:?} target `{spelling}` unambiguously and safely."
)
},
)
.with_entity(context.entity.clone());
diagnostic.span = context
.document
.provenance
.iter()
.find_map(|record| match record.activity {
ProvenanceActivity::DecodedDocumentation { decoded_span }
if decoded_span == span =>
{
record.span
}
_ => None,
})
.or(Some(span));
diagnostic.source = context.document.source_location.as_ref().map(|s| {
DiagnosticSource::Repository {
repository: s.repository.clone(),
path: s.path.clone(),
}
});
if !generated
&& let DocumentIdentity::Page { page } = &context.identity
&& let Some(prepared) = sources.prepared_pages().get(page)
{
crate::assembly::remap_include_diagnostic(
&mut diagnostic,
&prepared.source_ranges,
);
}
resolution.result.diagnostics.insert(diagnostic);
}
}
},
);
resolution.result.records.push(ResolvedDocument {
source_ranges: match &context.identity {
DocumentIdentity::Page { page } => sources
.prepared_pages()
.get(page)
.map(|p| p.source_ranges.clone())
.unwrap_or_default(),
_ => Vec::new(),
},
collection_path: match &context.identity {
DocumentIdentity::Page { page } => sources
.prepared_pages()
.get(page)
.map(|p| p.relative.clone()),
_ => None,
},
anchors: resolution
.anchors
.get(&context.identity)
.cloned()
.unwrap_or_default(),
document: context.identity,
references,
});
}
for asset in resolution.generated.values() {
insert_asset(&mut resolution.result.assets, asset.clone())
.map_err(|_| AssemblyError::InputsChanged)?;
}
if resolution
.result
.diagnostics
.iter()
.any(|d| d.severity == Severity::Error)
{
return Err(ResolutionError::Diagnostics(
resolution.result.diagnostics.into_iter().collect(),
));
}
let (components, assets, inputs) = crate::components::collect(sources)
.map_err(|diagnostic| ResolutionError::Diagnostics(vec![*diagnostic]))?;
resolution.result.components = components;
for (digest, asset) in assets {
resolution.result.assets.entry(digest).or_insert(asset);
}
for (path, boundary) in inputs {
let fingerprint = fingerprint_bytes(&fs::read(&path).map_err(AssemblyError::from)?);
resolution.result.inputs.insert(
path.clone(),
AssetObservation {
path,
boundary,
fingerprint,
},
);
}
sources.revalidate()?;
resolution.result.revalidate()?;
Ok(resolution.result)
}
struct Resolver<'a> {
sources: &'a WorkspaceSources,
pages: BTreeMap<PathBuf, Vec<String>>,
anchors: BTreeMap<DocumentIdentity, BTreeSet<String>>,
generated: BTreeMap<DiagnosticPath, ContentAsset>,
result: ResolvedWorkspace,
}
impl Resolver<'_> {
fn reference(
&mut self,
context: &DocumentContext<'_>,
kind: ReferenceKind,
spelling: &str,
generated: bool,
) -> Result<ReferenceTarget, DiagnosticCode> {
let invalid = DiagnosticCode::UnresolvedDocumentReference;
if kind == ReferenceKind::Link
&& let Some(target) = super::documenter_reference(
self.sources.workspace(),
context.document,
context.owner,
spelling,
)
{
return target;
}
if let Some(spelling) = semantic_target(context.document, kind, spelling) {
if matches!(&context.document.source_format, DocumentFormat::Extracted { name } if name == "rd")
&& kind == ReferenceKind::Link
{
return references::resolve_rd_help(
self.sources.workspace(),
context.owner,
spelling,
);
}
return references::resolve_item(self.sources.workspace(), context.owner, spelling)
.map(|item| ReferenceTarget::Item { item });
}
if spelling.is_empty() || spelling.chars().any(|c| c.is_control() || c == '\\') {
return Err(invalid);
}
let decoded = percent_encoding::percent_decode_str(spelling)
.decode_utf8()
.map_err(|_| invalid)?;
if decoded.chars().any(|c| c.is_control() || c == '\\') {
return Err(invalid);
}
if url::Url::parse(spelling).is_ok() {
if external_url_allowed(kind, spelling, generated) {
return Ok(ReferenceTarget::External {
url: spelling.into(),
});
}
return Err(invalid);
}
if decoded.starts_with('/') || spelling.contains('?') || url::Url::parse(&decoded).is_ok() {
return Err(invalid);
}
let (file, fragment) = spelling
.split_once('#')
.map_or((spelling, None), |(f, anchor)| (f, Some(anchor)));
let file = percent_encoding::percent_decode_str(file)
.decode_utf8()
.map_err(|_| invalid)?;
let fragment = fragment
.map(|f| {
percent_encoding::percent_decode_str(f)
.decode_utf8()
.map(|s| s.into_owned())
})
.transpose()
.map_err(|_| invalid)?;
if file.is_empty() {
let fragment = fragment.filter(|f| !f.is_empty()).ok_or(invalid)?;
if kind == ReferenceKind::Image
|| !self
.anchors
.get(&context.identity)
.is_some_and(|a| a.contains(&fragment))
{
return Err(invalid);
}
return Ok(ReferenceTarget::Anchor { fragment });
}
let rd_figure =
(spelling.starts_with("rd-example-assets/")
&& context.document.provenance.iter().any(|record| {
matches!(record.activity, ProvenanceActivity::RdExamples { .. })
}))
|| (spelling.starts_with("rmd-assets/sha256/")
&& context.document.provenance.iter().any(|record| {
matches!(record.activity, ProvenanceActivity::RMarkdown { .. })
}))
|| (spelling.starts_with("documenter-assets/sha256/")
&& context.document.provenance.iter().any(|record| {
matches!(
record.activity,
ProvenanceActivity::DocumenterExamples { .. }
)
}));
if (generated || rd_figure) && kind == ReferenceKind::Image {
let path = DiagnosticPath::try_from(file.as_ref()).map_err(|_| invalid)?;
let asset = self.generated.get(&path).ok_or(invalid)?;
if fragment.is_some() {
return Err(invalid);
}
return Ok(ReferenceTarget::Asset {
asset: AssetReference {
path: if rd_figure {
DiagnosticPath::try_from(format!(
"content-assets/sha256/{}",
asset.fingerprint.value
))
.map_err(|_| invalid)?
} else {
path
},
fingerprint: asset.fingerprint.clone(),
},
fragment: None,
});
}
let source = context.path.as_ref().ok_or(invalid)?;
let candidate = source.parent().ok_or(invalid)?.join(file.as_ref());
let included_repository = match &context.identity {
DocumentIdentity::Page { page } => self
.sources
.prepared_pages()
.get(page)
.filter(|prepared| prepared.included_resource_targets.contains(spelling))
.and_then(|prepared| {
self.sources
.paths()
.repositories
.iter()
.find(|repository| repository.id == prepared.location.repository)
}),
_ => None,
};
let canonical = if let Some(repository) = included_repository {
let path = crate::paths::resolve_repository_target(
candidate
.strip_prefix(&repository.path)
.map_err(|_| invalid)?,
&repository.path,
)
.map_err(|_| invalid)?;
if crate::generated_storage::is_reserved(&path) {
return Err(invalid);
}
path
} else {
fs::canonicalize(&candidate).map_err(|_| invalid)?
};
if kind != ReferenceKind::Image
&& let Some(ids) = self.pages.get(&canonical)
{
let [page] = ids.as_slice() else {
return Err(invalid);
};
if let Some(fragment) = &fragment
&& !fragment.is_empty()
&& !self
.anchors
.get(&DocumentIdentity::Page { page: page.clone() })
.is_some_and(|a| a.contains(fragment))
{
return Err(invalid);
}
return Ok(ReferenceTarget::Page {
page: page.clone(),
fragment,
});
}
let boundary = self
.sources
.paths()
.content
.iter()
.map(|c| &c.source_root)
.chain(self.sources.paths().packages.iter().map(|p| &p.path))
.chain(included_repository.map(|repository| &repository.path))
.filter(|root| canonical.starts_with(root))
.max_by_key(|root| root.components().count());
if canonical.is_dir()
|| matches!(
canonical.extension().and_then(|s| s.to_str()),
Some("md" | "qmd" | "rmd" | "Rmd")
)
|| boundary.is_none()
{
return self.repository_link(context, kind, candidate, fragment);
}
let boundary = boundary.ok_or(invalid)?;
let path = crate::paths::resolve_input_file(
boundary,
"asset",
canonical.strip_prefix(boundary).map_err(|_| invalid)?,
boundary,
)
.map_err(|_| invalid)?;
let asset = self.collect_asset(candidate, path, boundary, kind)?;
Ok(ReferenceTarget::Asset { asset, fragment })
}
fn collect_asset(
&mut self,
candidate: PathBuf,
path: PathBuf,
boundary: &Path,
kind: ReferenceKind,
) -> Result<AssetReference, DiagnosticCode> {
let invalid = DiagnosticCode::UnresolvedDocumentReference;
let bytes = fs::read(&path).map_err(|_| invalid)?;
let media_type = match path
.extension()
.and_then(|s| s.to_str())
.map(str::to_ascii_lowercase)
.as_deref()
{
Some("png") => "image/png",
Some("jpeg" | "jpg") => "image/jpeg",
Some("svg") => "image/svg+xml",
_ => "application/octet-stream",
};
if (kind == ReferenceKind::Image || media_type.starts_with("image/"))
&& validate_authored_image_bytes(media_type, &bytes).is_err()
{
return Err(DiagnosticCode::InvalidContentImage);
}
let fingerprint = fingerprint_bytes(&bytes);
let asset = AssetReference {
path: DiagnosticPath::try_from(format!("content-assets/sha256/{}", fingerprint.value))
.map_err(|_| invalid)?,
fingerprint: fingerprint.clone(),
};
insert_asset(
&mut self.result.assets,
ContentAsset {
fingerprint: fingerprint.clone(),
media_type: media_type.into(),
bytes,
},
)?;
let observation = AssetObservation {
path,
boundary: boundary.to_owned(),
fingerprint,
};
if let Some(old) = self.result.inputs.get_mut(&candidate) {
if old.path != observation.path || old.fingerprint != observation.fingerprint {
return Err(invalid);
}
if observation.boundary.starts_with(&old.boundary) {
*old = observation;
}
} else {
self.result.inputs.insert(candidate, observation);
}
Ok(asset)
}
}
fn insert_asset(
assets: &mut BTreeMap<String, ContentAsset>,
asset: ContentAsset,
) -> Result<(), DiagnosticCode> {
if let Some(previous) = assets.get_mut(&asset.fingerprint.value) {
if previous.bytes != asset.bytes {
return Err(DiagnosticCode::UnresolvedDocumentReference);
}
if previous.media_type == "application/octet-stream" {
previous.media_type = asset.media_type;
} else if asset.media_type != "application/octet-stream"
&& previous.media_type != asset.media_type
{
return Err(DiagnosticCode::UnresolvedDocumentReference);
}
} else {
assets.insert(asset.fingerprint.value.clone(), asset);
}
Ok(())
}