//! `page.save` — a URL from the share sheet becomes a saved page.//!//! ## Why this is a METHOD and not a tool, in the tool surface's own words//!//! `cotton-tools/src/mcp/surface.rs` already refuses `create_page`,//! and the reason it gives names this caller://!//! > pages are saved from the share sheet — a URL from the owner's phone, not//! > an assistant write//!//! That is the strongest precedent in the tree for a phone method: the verb//! grid did not leave a gap, it wrote down whose write this is. So the share//! sheet's fifth branch — a URL becoming a `cotton_pages` row — is authored//! here, through [`crate::authoring::author_through_outbox`], with the same//! `Ctx::phone`, the same writer, the same outbox and the same `data` event//! every tool call from this device already takes.//!//! ## What lands//!//! One `cotton_pages` row. The URL is CANONICALISED and the host DERIVED — the//! TypeScript's `createPage` says "Host is derived, never passed in", and two//! spellings of one page is two rows in the reading pile.use serde_json::{json, Map, Value};use cotton_core::transforms::urls::{canonical_url, host_of, is_http_url};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::insert_row;usecrate::handle::CottonHandle;usecrate::methods::MethodError;/// What the share sheet sent.#[derive(Debug, Clone, PartialEq, Eq)]pubstructPageArgs {/// Canonical already — [`validate`] runs `canonical_url` so the id-minting/// path and the duplicate question below look at one spelling.pub url: String,pub host: String,/// What the sharing app called it, when it said. The page's REAL title/// arrives later, when the reader opens it and writes back what it learned.pub title: Option<String>,}pubfn validate(request: &Value) -> Result<PageArgs, MethodError> {let raw = request.get("url").and_then(Value::as_str).map(str::trim);if !is_http_url(raw) {returnErr(MethodError::new("bad_request", format!("`url` is one absolute http(s) URL, and {:?} is not one", raw.unwrap_or_default() ), )); }if request.get("excerpt").is_some() {// NOT SILENTLY IGNORED. A saved page keeps the article's own text,// and the serving Mac pulls it in from the address (`text`,// `text_state`); nothing a sharer sends is stored as that text.// Accepting the argument and dropping it would tell the share sheet// its summary was kept.returnErr(MethodError::new("bad_request","a saved page carries no excerpt — Cotton keeps the article's own text, pulled in \ from the address by the serving Mac", )); }let url = canonical_url(raw.unwrap_or_default());let host = host_of(&url);let title = request .get("title") .and_then(Value::as_str) .map(str::trim) .filter(|title| !title.is_empty()) .map(str::to_string);Ok(PageArgs { url, host, title })}/// A mailbox may contain one URL or prose with several URLs. Extraction is/// core's rule; the app never needs a second regex.pubfn validate_pages(request: &Value) -> Result<Vec<PageArgs>, MethodError> {ifletSome(text) = request.get("text") {if request.get("url").is_some() {returnErr(MethodError::new("bad_request","pass `url` or shared `text`, not both", )); }let text = text .as_str() .ok_or_else(|| MethodError::new("bad_request", "shared `text` must be a string"))?; cotton_core::transforms::urls::extract_urls(Some(text)) .into_iter() .map(|url| {letmut one = request.clone(); one["url"] = Value::from(url); validate(&one) }) .collect() } else {Ok(vec![validate(request)?]) }}/// Each extracted URL gets its own row, as useReaderIntake saved each URL.pubfn write_pages(ctx: &mutCtx<'_>, pages: &[PageArgs]) -> Result<Value, String> {let answers: Vec<Value> = pages .iter() .map(|page| write_page(ctx, page)) .collect::<Result<_, _>>()?;if answers.len() == 1 {returnOk(answers[0].clone()); }Ok(json!({"ids": answers.iter().map(|answer| answer["id"].clone()).collect::<Vec<_>>()}))}/// `page.save` — one page in the reading pile.pubfn save(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let args = validate_pages(request)?; handle .client() .write_rows("page.save", &mut |ctx| write_pages(ctx, &args)) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason))}/// The Plus door acts that run here (`create.doors[].act`): a pasted address/// is saved by this device (`page.save`), signed in or not; a shared one comes/// the same way through the share drain.pubfn door_method(act: &str) -> Option<&'static str> {match act {"page_from_link" => Some("page.save"), _ => None, }}/// The row itself, so a test can drive it over a `Ctx` without a handle.////// **A second save of the same URL writes a SECOND row**, and that is the/// TypeScript's behaviour rather than an omission: `cotton_pages` has no/// natural key and `createPage` mints a fresh id every time. Sharing the same/// link twice is a person saving it twice; the Reader is where a duplicate is/// archived. Refusing here would need a uniqueness rule the file does not/// declare, and inventing one in a port is exactly the new behaviour the lane/// may not add.pubfn write_page(ctx: &mutCtx<'_>, args: &PageArgs) -> Result<Value, String> {let id = ctx.new_uuid();letmut patch = Map::new(); patch.insert("url".to_string(), Value::from(args.url.clone())); patch.insert("host".to_string(), Value::from(args.host.clone())); patch.insert("title".to_string(), args.title.clone().map_or(Value::Null, Value::from), );// NULL: the page has not been read, and it did not come through the inbox —// the share sheet's URL branch writes the row directly, without a capture// for the router to file. patch.insert("read_at".to_string(), Value::Null); patch.insert("source_inbox_id".to_string(), Value::Null); patch.insert("archived_at".to_string(), Value::Null); insert_row(ctx, "cotton_pages", &id, patch).map_err(|failure| failure.to_string())?;Ok(json!({ "id": id }))}