//! `package.export`, `package.exportOpen` and `package.import`, against a //! seeded synthetic replica. use cotton_store::cottonpkg::Package; use serde_json::{json, Map, Value}; use crate::shell::client::phone_tests::attached; use cotton_store::fixtures::open_bundle::{ a_film_shelf, a_record_collection, books_missing, films_missing, music_missing, shelf_of_books, Shelf, BOOKS_TREE, FILMS_TREE, MUSIC_TREE, }; use cotton_store::Driver; use crate::fixture::WORKSPACE; use crate::shell::client::ClientController; use super::{export_on, export_open_on, import_on, package_file_name}; const NOW: &str = "2026-09-08T10:00:00.000Z"; fn args(value: Value) -> Map { value.as_object().expect("an object").clone() } /// RULE: `package.export` answers a path to a `.cottonpkg` in the exports folder and what it holds, never the bytes; `package.import` takes a path, and importing what this device already holds changes nothing while a record it lacks is made at its own id. #[test] fn a_package_goes_out_as_a_path_and_comes_back_in_through_the_writer() { let (dir, client) = attached(); let answer = export_on(&client, "Cotton", &args(json!({"tables": ["todo"], "now": NOW}))).expect("exports"); let path = answer["path"].as_str().expect("a path").to_string(); assert!(path.ends_with(".cottonpkg"), "{path}"); assert!(path.contains("exports"), "{path}"); assert_eq!(answer["fileName"], "cotton-2026-09-08.cottonpkg"); assert_eq!(answer["tables"][0]["table"], "cotton_todos"); // A record from elsewhere, written where it says its own database. let mut package = Package::from_bytes(&std::fs::read(&path).expect("reads")).expect("a package"); let source = package.manifest.source_database.clone(); package.records[0].1 = vec![args(json!({ "id": "todo-from-elsewhere", "workspace_id": source, "title": "A synthetic todo", "created_at": NOW, "updated_at": NOW, }))]; package.manifest.tables[0].rows = 1; let other = dir.path().join("other.cottonpkg"); std::fs::write(&other, package.to_bytes().expect("writes")).expect("written"); let request = args(json!({"path": other.to_string_lossy()})); let landed = import_on(&client, &request).expect("imports"); assert_eq!(landed["created"], json!({"cotton_todos": 1}), "{landed}"); let again = import_on(&client, &request).expect("imports again"); assert_eq!(again["created"], json!({}), "{again}"); assert_eq!(again["unchanged"], json!({"cotton_todos": 1}), "{again}"); } /// RULE: Every package method is offered on every build, by name. #[test] fn the_package_methods_are_offered_on_every_build() { for method in ["package.export", "package.exportOpen", "package.import"] { assert!(crate::methods::ALL_METHODS.contains(&method)); assert!(crate::methods::CLIENT_METHODS.contains(&method)); } } /// RULE: `package.import` takes a contacts `.vcf` (or a calendar `.ics`) the person was handed as a package, read by the core's readers, through the same writer. #[test] fn a_contacts_file_imports_through_the_same_method() { let (dir, client) = attached(); let file = dir.path().join("Family.vcf"); std::fs::write(&file, "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:card-asha\r\nFN:Asha Rao\r\nEMAIL:asha@example.com\r\nEND:VCARD\r\n") .expect("written"); let request = args(json!({"path": file.to_string_lossy()})); let landed = import_on(&client, &request).expect("imports"); assert_eq!(landed["created"], json!({"cotton_people": 1, "cotton_person_handles": 1}), "{landed}"); let again = import_on(&client, &request).expect("imports again"); assert_eq!(again["created"], json!({}), "{again}"); } // ── package.exportOpen ─────────────────────────────────────────────────── /// The open bundle's synthetic library in this phone's replica, every byte on /// its shelf kept here as a capture keeps it: the file in the media store and /// its ledger row. fn a_library(client: &ClientController) { let mut shelf = Shelf::default(); client .with_writer(|replica| { let db: &Driver = replica.driver; shelf_of_books(db, WORKSPACE, &mut shelf); a_record_collection(db, WORKSPACE, &mut shelf); a_film_shelf(db, WORKSPACE, &mut shelf); for (n, (key, bytes)) in shelf.0.iter().enumerate() { let path = client.layout().client_media_dir().join(WORKSPACE).join(format!("kept-{n}")); std::fs::create_dir_all(path.parent().expect("a folder")).expect("the media folder"); std::fs::write(&path, bytes).expect("the bytes"); cotton_store::media_ledger::enqueue_media( db, &cotton_store::media_ledger::MediaEnqueueInput { key: key.clone(), workspace_id: WORKSPACE.to_string(), sha256: format!("{n:064x}"), content_type: "application/octet-stream".to_string(), size_bytes: bytes.len() as i64, local_path: Some(path.to_string_lossy().to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, tier: None, captured_here: false, now: NOW.to_string(), }, ) .map_err(|error| error.to_string())?; } Ok(()) }) .expect("the library"); } /// Every file under `dir`, relative and `/`-separated, sorted. fn tree(dir: &std::path::Path) -> Vec { fn walk(base: &std::path::Path, at: &std::path::Path, out: &mut Vec) { for entry in std::fs::read_dir(at).expect("a folder").flatten() { let path = entry.path(); if path.is_dir() { walk(base, &path, out); } else { out.push(path.strip_prefix(base).expect("under the base").to_string_lossy().replace('\\', "/")); } } } let mut out = Vec::new(); walk(dir, dir, &mut out); out.sort(); out } /// RULE: `package.exportOpen` lays each kit's open bundle from this phone's replica and the bytes it keeps, into the folder it is given, the same tree `cotton_store::open_bundle` lays from the same library; it answers the folder, how many files and the keys this phone does not keep, never the bytes. #[test] fn the_open_bundle_lays_each_kit_from_what_this_phone_keeps() { let (dir, client) = attached(); a_library(&client); for (kit, expected, missing) in [ ("books", BOOKS_TREE, books_missing(WORKSPACE)), ("music", MUSIC_TREE, music_missing(WORKSPACE)), ("films", FILMS_TREE, films_missing(WORKSPACE)), ] { let out = dir.path().join(format!("open-{kit}")); let answer = export_open_on(&client, &args(json!({"kit": kit, "dir": out.to_string_lossy(), "now": NOW}))) .unwrap_or_else(|error| panic!("{kit}: {error:?}")); assert_eq!(tree(&out), expected, "{kit}"); assert_eq!( answer, json!({"dir": out.to_string_lossy(), "files": expected.len(), "missingMedia": missing, "kit": kit, "exportedAt": NOW}), "{kit}" ); } } /// RULE: `package.exportOpen` with `media: false` lays the metadata alone (a list names no file it does not lay) and lists nothing missing, since it asked for no bytes. #[test] fn the_open_bundle_without_media_lays_the_metadata_alone() { let (dir, client) = attached(); a_library(&client); let out = dir.path().join("open-music"); let answer = export_open_on(&client, &args(json!({"kit": "music", "dir": out.to_string_lossy(), "media": false, "now": NOW}))) .expect("lays"); assert_eq!(tree(&out), ["Music/listens.jsonl", "Music/playlists/Road Trip.m3u8"]); assert_eq!(std::fs::read_to_string(out.join("Music/playlists/Road Trip.m3u8")).expect("the list"), "#EXTM3U\n#PLAYLIST:Road Trip\n"); assert_eq!(answer["missingMedia"], json!([])); assert_eq!(answer["files"], 2); } /// RULE: `package.exportOpen` refuses a folder that already holds files and leaves them as they were; it refuses a kit it does not know, and a missing `dir`, in words. #[test] fn the_open_bundle_refuses_a_full_folder_and_an_unknown_kit() { let (dir, client) = attached(); let out = dir.path().join("full"); std::fs::create_dir_all(&out).expect("a folder"); std::fs::write(out.join("mine.txt"), b"keep me").expect("a file"); let refused = export_open_on(&client, &args(json!({"kit": "books", "dir": out.to_string_lossy()}))).expect_err("refused"); assert_eq!(refused.code, "export_refused"); assert!(refused.message.contains("empty folder"), "{refused:?}"); assert_eq!(tree(&out), ["mine.txt"]); let unknown = export_open_on(&client, &args(json!({"kit": "games", "dir": dir.path().join("games").to_string_lossy()}))) .expect_err("refused"); assert_eq!(unknown.code, "bad_request"); assert!(unknown.message.contains("books, music or films"), "{unknown:?}"); let nowhere = export_open_on(&client, &args(json!({"kit": "books"}))).expect_err("refused"); assert_eq!(nowhere.code, "bad_request"); } /// RULE (Rigby 11 walk, 8 Nov 2026): an exported package is named after the app that made it and the day on this phone's clock, never Cotton's name in another app. #[test] fn a_package_is_named_after_its_app_and_its_day() { assert_eq!(package_file_name("Rigby", "2026-11-07T20:00:00.000Z", Some("Asia/Kolkata")), "rigby-2026-11-08.cottonpkg"); assert_eq!(package_file_name("Rigby", "2026-11-07T20:00:00.000Z", None), "rigby-2026-11-07.cottonpkg"); assert_eq!(package_file_name("Cotton Books", NOW, Some("Asia/Kolkata")), "cotton-books-2026-09-08.cottonpkg"); assert_eq!(package_file_name("Nancy's Naga Kitchen", NOW, None), "nancys-naga-kitchen-2026-09-08.cottonpkg"); assert_eq!(package_file_name("", NOW, None), "cotton-2026-09-08.cottonpkg"); let (_dir, client) = attached(); let answer = export_on(&client, "Rigby", &args(json!({"tables": ["todo"], "now": NOW}))).expect("exports"); assert!(answer["fileName"].as_str().is_some_and(|name| name.starts_with("rigby-2026-09-0") && name.ends_with(".cottonpkg")), "{answer}"); assert!(answer["path"].as_str().is_some_and(|path| path.ends_with(answer["fileName"].as_str().unwrap())), "{answer}"); }