//! The six op kinds of a change (`packages/anatomy/src/curation/ops.ts`). Each one resolves //! its target, edits the working document in place and records what it changed; anything it //! cannot do exactly as written refuses (the applier adds the change id and op index). use serde_json::Value; use super::fields::{FieldKind, is_settable, read_field, write_field}; use super::records::{Recorder, js_deep_equal, js_string}; use super::rename::{Rename, propagate_rename}; use super::schema::{ AddOp, CiteOp, DocumentCollection, MoveOp, Op, Position, RemoveOp, RenameOp, Scope, SetOp, }; use super::targets::{ Located, Path, Step, TargetKind, at, child_list, child_prefix, fail, finding_scope, has_key, id_text, item_at_mut, list_at, list_at_mut, locate, top_collection_path, }; use crate::curation::PipelineError; fn collection_kind(field: DocumentCollection) -> TargetKind { match field { DocumentCollection::References => TargetKind::Reference, DocumentCollection::Categories => TargetKind::Category, DocumentCollection::Views => TargetKind::View, DocumentCollection::Annotations => TargetKind::Annotation, DocumentCollection::FindingZones => TargetKind::Zone, DocumentCollection::Regions => TargetKind::Region, } } fn collection_name(field: DocumentCollection) -> &'static str { match field { DocumentCollection::References => "references", DocumentCollection::Categories => "categories", DocumentCollection::Views => "views", DocumentCollection::Annotations => "annotations", DocumentCollection::FindingZones => "finding_zones", DocumentCollection::Regions => "regions", } } /// No sibling but `excluded` may already carry the id. fn assert_free( list: &[Value], key: &str, id: &str, excluded: Option, ) -> Result<(), PipelineError> { let taken = list .iter() .enumerate() .any(|(index, entry)| Some(index) != excluded && has_key(entry, key, id)); if taken { return Err(fail(format!("\"{id}\" already exists among its siblings"))); } Ok(()) } fn insertion_index( list: &[Value], key: &str, position: Option<&Position>, ) -> Result { let Some(position) = position else { return Ok(list.len()); }; let (anchor, after) = match position { Position::Index(index) => { let index = usize::try_from(*index).unwrap_or(usize::MAX); if index > list.len() { return Err(fail(format!("position {index} out of range"))); } return Ok(index); } Position::After { after } => (after, true), Position::Before { before } => (before, false), }; let index = list .iter() .position(|entry| has_key(entry, key, anchor)) .ok_or_else(|| fail(format!("unknown sibling \"{anchor}\"")))?; Ok(if after { index + 1 } else { index }) } fn unknown_field(op: &SetOp) -> PipelineError { fail(format!( "unknown field \"{}\" on \"{}\"", op.field, op.target )) } /// A B or C change leaves findings to the professional: no 'reviewed'. fn assert_not_reviewed(recorder: &Recorder<'_>, op: &SetOp) -> Result<(), PipelineError> { if op.field != "review_status" || op.value != "reviewed" { return Ok(()); } if recorder.change.level.needs_confirmation() { return Err(fail(format!( "level {:?} cannot set \"{}\" review_status to \"reviewed\"", recorder.change.level, op.target ))); } Ok(()) } fn set_self( doc: &mut Value, recorder: &mut Recorder<'_>, located: &Located, op: &SetOp, ) -> Result<(), PipelineError> { if !is_settable(FieldKind::of(&located.target, None), &op.field)? { return Err(unknown_field(op)); } let item = item_at_mut(doc, &located.item_path())?; recorder.touch(item); let before = read_field(item, &op.field)?; write_field(item, &op.field, &op.value)?; recorder.record(&op.target, Some(&op.field), before, Some(op.value.clone())); Ok(()) } /// Target and descendants that carry the field; unchanged items are skipped. fn set_subtree( doc: &mut Value, recorder: &mut Recorder<'_>, located: &Located, op: &SetOp, ) -> Result<(), PipelineError> { if located.target.kind != TargetKind::Finding { return Err(fail(format!( "scope subtree needs a finding target, got \"{}\"", op.target ))); } let mut entries = Vec::new(); for entry in finding_scope(doc, located, true)? { let kind = FieldKind::of(&located.target, Some(entry.is_category)); if is_settable(kind, &op.field)? { entries.push(entry); } } if entries.is_empty() { return Err(unknown_field(op)); } for entry in &entries { recorder.touch(item_at_mut(doc, &entry.path)?); } for entry in &entries { let item = item_at_mut(doc, &entry.path)?; let before = read_field(item, &op.field)?; if before .as_ref() .is_some_and(|value| js_deep_equal(value, &op.value)) { continue; } write_field(item, &op.field, &op.value)?; recorder.record( &entry.target, Some(&op.field), before, Some(op.value.clone()), ); } Ok(()) } fn apply_set( doc: &mut Value, recorder: &mut Recorder<'_>, op: &SetOp, ) -> Result<(), PipelineError> { assert_not_reviewed(recorder, op)?; let located = locate(doc, &op.target)?; match op.scope { None | Some(Scope::OwnItem) => set_self(doc, recorder, &located, op), Some(Scope::Subtree) => set_subtree(doc, recorder, &located, op), } } fn apply_rename( doc: &mut Value, recorder: &mut Recorder<'_>, op: &RenameOp, ) -> Result<(), PipelineError> { let located = locate(doc, &op.target)?; let Some(list) = &located.list else { return Err(fail("the document has no id to rename")); }; let key = located.target.kind.key_field(); assert_free(list_at(doc, list)?, key, &op.id, Some(located.index))?; let item = item_at_mut(doc, &located.item_path())?; let before = Value::Object(item.clone()); let from = js_string(item.get(key)); item.insert(key.to_owned(), Value::from(op.id.clone())); recorder.touch(item); let after = Value::Object(item.clone()); recorder.record(&op.target, None, Some(before), Some(after)); let rename = Rename { kind: located.target.kind, from, to: op.id.clone(), }; propagate_rename(doc, recorder, &rename) } struct Destination { list: Path, key: &'static str, prefix: String, } fn add_destination(doc: &mut Value, op: &AddOp) -> Result { let parent = locate(doc, &op.target)?; if parent.target.kind != TargetKind::Document { if let Some(field) = op.field { return Err(fail(format!( "field \"{}\" is only valid on document", collection_name(field) ))); } return Ok(Destination { list: child_list(doc, &parent)?, key: "id", prefix: child_prefix(&parent), }); } let Some(field) = op.field else { return Err(fail("add on document needs a field")); }; let kind = collection_kind(field); let list = top_collection_path(kind); list_at(doc, &list)?; Ok(Destination { list, key: kind.key_field(), prefix: format!("{}:", kind.name()), }) } /// A `children` or `categories` of an added value must be a list (a later add would otherwise /// replace the author's value by `[]`, as the TypeScript's `childrenOf` did), and each entry an /// object. The /// TypeScript met a null or a primitive there inconsistently (a TypeError when it walked it, /// silently skipped when a rename walked past it, refused by the gate when it stayed); the /// port refuses it at the add (RUST.md ยง11.12). Walked with an explicit stack. fn assert_object_children(value: &Value) -> Result<(), PipelineError> { let mut pending = vec![value]; while let Some(item) = pending.pop() { let Some(map) = item.as_object() else { continue; }; for key in ["children", "categories"] { let list = match map.get(key) { None => continue, Some(Value::Array(list)) => list, Some(_) => { return Err(fail(format!( "the added item holds a \"{key}\" that is not a list" ))); } }; if list.iter().any(|entry| !entry.is_object()) { return Err(fail(format!( "the added item holds a \"{key}\" entry that is not an object" ))); } pending.extend(list); } } Ok(()) } fn apply_add( doc: &mut Value, recorder: &mut Recorder<'_>, op: &AddOp, ) -> Result<(), PipelineError> { let Some(value) = op.value.as_object() else { return Err(fail("add needs an object value")); }; assert_object_children(&op.value)?; let dest = add_destination(doc, op)?; let Some(id) = value.get(dest.key).and_then(Value::as_str) else { return Err(fail(format!( "the added item needs a string \"{}\"", dest.key ))); }; let list = list_at(doc, &dest.list)?; assert_free(list, dest.key, id, None)?; let index = insertion_index(list, dest.key, op.position.as_ref())?; list_at_mut(doc, &dest.list)?.insert(index, op.value.clone()); let mut added = dest.list.clone(); added.push(Step::Index(index)); recorder.touch_tree(doc, &added)?; let target = format!("{}{id}", dest.prefix); recorder.record(&target, None, None, Some(op.value.clone())); Ok(()) } fn apply_remove( doc: &mut Value, recorder: &mut Recorder<'_>, op: &RemoveOp, ) -> Result<(), PipelineError> { let located = locate(doc, &op.target)?; let Some(list) = &located.list else { return Err(fail("the document cannot be removed")); }; let item = list_at_mut(doc, list)?.remove(located.index); recorder.record(&op.target, None, Some(item), None); Ok(()) } /// `after` of a move record is the new target path of the item. fn apply_move( doc: &mut Value, recorder: &mut Recorder<'_>, op: &MoveOp, ) -> Result<(), PipelineError> { let source = locate(doc, &op.target)?; if source.target.kind != TargetKind::Finding { return Err(fail(format!("only findings move, got \"{}\"", op.target))); } if op.to == op.target || op.to.starts_with(&format!("{}/", op.target)) { return Err(fail(format!("cannot move \"{}\" into itself", op.target))); } let parent = locate(doc, &op.to)?; let list = child_list(doc, &parent)?; let id = id_text(at(doc, &source.item_path())?); let excluded = (Some(&list) == source.list.as_ref()).then_some(source.index); assert_free(list_at(doc, &list)?, "id", &id, excluded)?; let source_list = source .list .as_ref() .ok_or_else(|| fail("a finding has siblings"))?; let item = list_at_mut(doc, source_list)?.remove(source.index); // The removal may have shifted the destination's indices: resolve it again. let parent = locate(doc, &op.to)?; let list = child_list(doc, &parent)?; let index = insertion_index(list_at(doc, &list)?, "id", op.position.as_ref())?; list_at_mut(doc, &list)?.insert(index, item); let mut moved = list; moved.push(Step::Index(index)); let item = item_at_mut(doc, &moved)?; recorder.touch(item); let before = Value::Object(item.clone()); let after = format!("{}{id}", child_prefix(&parent)); recorder.record(&op.target, None, Some(before), Some(Value::from(after))); Ok(()) } /// Every cited id must be declared in the document references. pub fn assert_declared(doc: &Value, ids: &[String]) -> Result<(), PipelineError> { let declared: Vec<&str> = list_at(doc, &top_collection_path(TargetKind::Reference))? .iter() .filter_map(|reference| reference.get("id").and_then(Value::as_str)) .collect(); let missing: Vec<&str> = ids .iter() .map(String::as_str) .filter(|id| !declared.contains(id)) .collect(); if !missing.is_empty() { return Err(fail(format!( "undeclared reference(s): {}", missing.join(", ") ))); } Ok(()) } /// `[...new Set(ids)]`: first occurrences, in order. fn distinct(ids: &[String]) -> Vec<&String> { let mut out: Vec<&String> = Vec::new(); for id in ids { if !out.contains(&id) { out.push(id); } } out } /// Appends citations in order, never twice on the same item. fn apply_cite( doc: &mut Value, recorder: &mut Recorder<'_>, op: &CiteOp, ) -> Result<(), PipelineError> { assert_declared(doc, &op.reference_ids)?; let located = locate(doc, &op.target)?; let scope = finding_scope(doc, &located, op.scope == Some(Scope::Subtree))?; for entry in &scope { recorder.touch(item_at_mut(doc, &entry.path)?); } for entry in &scope { let item = item_at_mut(doc, &entry.path)?; let before: Vec = item .get("reference_ids") .and_then(Value::as_array) .cloned() .unwrap_or_default(); let added: Vec = distinct(&op.reference_ids) .into_iter() .filter(|id| !before.contains(&Value::from(id.as_str()))) .map(|id| Value::from(id.clone())) .collect(); if added.is_empty() { continue; } let after: Vec = before.iter().cloned().chain(added).collect(); item.insert("reference_ids".to_owned(), Value::Array(after.clone())); recorder.record( &entry.target, Some("reference_ids"), Some(Value::Array(before)), Some(Value::Array(after)), ); } Ok(()) } pub fn apply_op(doc: &mut Value, recorder: &mut Recorder<'_>) -> Result<(), PipelineError> { match recorder.op { Op::Set(op) => apply_set(doc, recorder, op), Op::Rename(op) => apply_rename(doc, recorder, op), Op::Add(op) => apply_add(doc, recorder, op), Op::Remove(op) => apply_remove(doc, recorder, op), Op::Move(op) => apply_move(doc, recorder, op), Op::Cite(op) => apply_cite(doc, recorder, op), } }