From 289037235cded8b863c035a8c42783c69eef2071 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sun, 19 Jul 2026 11:02:57 +0200 Subject: [PATCH 01/12] feat(tags): revamp tags tab (#29) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat(tags): revamp tags tab — tooltips, entry counts, Create/Move flows, Esc handling (#29) --- crates/archivr-core/src/archive.rs | 434 ++++- crates/archivr-core/src/database.rs | 924 +++++++--- crates/archivr-server/src/routes.rs | 1613 ++++++++++++----- .../static/assets/index-BpGwC-YY.js | 47 + ...{index-C0COQCCD.css => index-DLdY9nrw.css} | 2 +- .../static/assets/index-Db35_tmT.js | 47 - crates/archivr-server/static/index.html | 4 +- frontend/src/api.js | 20 + frontend/src/components/TagsView.jsx | 402 +++- frontend/src/components/TagsView.stories.jsx | 167 ++ frontend/src/styles.css | 129 ++ 11 files changed, 2942 insertions(+), 847 deletions(-) create mode 100644 crates/archivr-server/static/assets/index-BpGwC-YY.js rename crates/archivr-server/static/assets/{index-C0COQCCD.css => index-DLdY9nrw.css} (50%) delete mode 100644 crates/archivr-server/static/assets/index-Db35_tmT.js create mode 100644 frontend/src/components/TagsView.stories.jsx diff --git a/crates/archivr-core/src/archive.rs b/crates/archivr-core/src/archive.rs index 9eafb4b..dd16e66 100644 --- a/crates/archivr-core/src/archive.rs +++ b/crates/archivr-core/src/archive.rs @@ -85,6 +85,8 @@ pub struct Tag { #[derive(Debug, Clone, serde::Serialize)] pub struct TagNode { pub tag: Tag, + pub entry_count: i64, + pub subtree_count: i64, pub children: Vec, } @@ -196,7 +198,10 @@ pub fn initialize_store_directories(store_path: &Path) -> Result<()> { Ok(()) } -pub fn list_root_entries(conn: &rusqlite::Connection, caller_bits: u32) -> Result> { +pub fn list_root_entries( + conn: &rusqlite::Connection, + caller_bits: u32, +) -> Result> { let mut stmt = conn.prepare( "SELECT e.entry_uid, @@ -336,16 +341,18 @@ pub fn get_capture_job( conn: &rusqlite::Connection, job_uid: &str, ) -> Result> { - Ok(database::get_capture_job(conn, job_uid)?.map(|r| CaptureJobSummary { - job_uid: r.job_uid, - archive_id: r.archive_id, - run_uid: r.run_uid, - status: r.status, - error_text: r.error_text, - notes_json: r.notes_json, - created_at: r.created_at, - updated_at: r.updated_at, - })) + Ok( + database::get_capture_job(conn, job_uid)?.map(|r| CaptureJobSummary { + job_uid: r.job_uid, + archive_id: r.archive_id, + run_uid: r.run_uid, + status: r.status, + error_text: r.error_text, + notes_json: r.notes_json, + created_at: r.created_at, + updated_at: r.updated_at, + }), + ) } /// Lists all collections in the archive. @@ -413,8 +420,7 @@ pub fn list_entries_for_collection( OR (ce.visibility_bits & CAST(?2 AS INTEGER)) != 0) \ GROUP BY e.id \ ORDER BY e.archived_at DESC, e.id DESC", - ENTRY_SELECT_COLS, - ENTRY_FROM_JOINS, + ENTRY_SELECT_COLS, ENTRY_FROM_JOINS, ); let mut stmt = conn.prepare(&sql)?; let entries = stmt @@ -448,9 +454,12 @@ pub fn resolve_artifact_path( artifact: &EntryArtifactSummary, ) -> Result { let joined = store_path.join(&artifact.relpath); - let canonical_store = store_path - .canonicalize() - .with_context(|| format!("failed to canonicalize store path: {}", store_path.display()))?; + let canonical_store = store_path.canonicalize().with_context(|| { + format!( + "failed to canonicalize store path: {}", + store_path.display() + ) + })?; let canonical_artifact = joined .canonicalize() .with_context(|| format!("artifact path does not exist: {}", joined.display()))?; @@ -522,13 +531,13 @@ pub fn parse_search_query(raw: &str) -> Result { match prefix { "source" => query.source_kind = Some(value), - "type" => query.entity_kind = Some(value), - "url" => query.url = Some(value), - "title" => query.title = Some(value), - "after" => query.after = Some(value), + "type" => query.entity_kind = Some(value), + "url" => query.url = Some(value), + "title" => query.title = Some(value), + "after" => query.after = Some(value), "before" => query.before = Some(value), - "tag" => query.tag = Some(value), - other => return Err(other.to_string()), + "tag" => query.tag = Some(value), + other => return Err(other.to_string()), } } else { free_text_tokens.push(token); @@ -541,16 +550,14 @@ pub fn parse_search_query(raw: &str) -> Result { Ok(query) } -const ENTRY_SELECT_COLS: &str = - "SELECT e.entry_uid, e.archived_at, e.source_kind, e.entity_kind, e.title, \ +const ENTRY_SELECT_COLS: &str = "SELECT e.entry_uid, e.archived_at, e.source_kind, e.entity_kind, e.title, \ e.visibility, si.canonical_url, COUNT(ea.id) AS artifact_count, \ COALESCE(SUM(b.byte_size), 0) AS total_artifact_bytes, \ parent.entry_uid AS parent_entry_uid, \ EXISTS(SELECT 1 FROM entry_artifacts fav WHERE fav.entry_id = e.id AND fav.artifact_role = 'favicon') AS has_favicon, \ e.cached_bytes"; -const ENTRY_FROM_JOINS: &str = - "FROM archived_entries e \ +const ENTRY_FROM_JOINS: &str = "FROM archived_entries e \ JOIN source_identities si ON si.id = e.source_identity_id \ LEFT JOIN entry_artifacts ea ON ea.entry_id = e.id \ LEFT JOIN blobs b ON b.id = ea.blob_id \ @@ -579,14 +586,12 @@ pub fn search_entries( JOIN entry_tag_assignments eta ON eta.entry_id = e.id \ JOIN descendants d ON eta.tag_id = d.id \ WHERE 1=1", - ENTRY_SELECT_COLS, - ENTRY_FROM_JOINS, + ENTRY_SELECT_COLS, ENTRY_FROM_JOINS, ); } else { sql = format!( "{} {} WHERE e.parent_entry_id IS NULL", - ENTRY_SELECT_COLS, - ENTRY_FROM_JOINS, + ENTRY_SELECT_COLS, ENTRY_FROM_JOINS, ); } @@ -687,19 +692,65 @@ pub fn create_tag(conn: &rusqlite::Connection, full_path: &str) -> Result { } /// Returns the full tag tree with root nodes at the top level and children nested. +/// Each node includes a direct entry count and a subtree count (unique entries +/// assigned to the tag itself or any descendant). pub fn list_tag_tree(conn: &rusqlite::Connection) -> Result> { use std::collections::HashMap; let records = database::list_all_tags(conn)?; + // Fetch direct entry counts for all tags in a single query. + let mut counts: HashMap = HashMap::new(); + { + let mut stmt = conn.prepare( + "SELECT t.tag_uid, COUNT(eta.entry_id) \ + FROM tags t \ + LEFT JOIN entry_tag_assignments eta ON eta.tag_id = t.id \ + GROUP BY t.id", + )?; + for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + let (uid, cnt) = row?; + counts.insert(uid, cnt); + } + } + + // Fetch subtree entry counts: for each tag, count distinct entries assigned + // to it or any descendant. COUNT(DISTINCT) ensures an entry tagged at both + // a parent and a child is counted only once. + let mut subtree_counts: HashMap = HashMap::new(); + { + let mut stmt = conn.prepare( + "WITH RECURSIVE descendants(ancestor_id, descendant_id) AS ( \ + SELECT id, id FROM tags \ + UNION ALL \ + SELECT d.ancestor_id, t.id \ + FROM tags t JOIN descendants d ON t.parent_tag_id = d.descendant_id \ + ) \ + SELECT t.tag_uid, COUNT(DISTINCT eta.entry_id) \ + FROM tags t \ + JOIN descendants d ON d.ancestor_id = t.id \ + LEFT JOIN entry_tag_assignments eta ON eta.tag_id = d.descendant_id \ + GROUP BY t.id", + )?; + for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))? { + let (uid, cnt) = row?; + subtree_counts.insert(uid, cnt); + } + } + let mut by_parent: HashMap, Vec> = HashMap::new(); for record in records { - by_parent.entry(record.parent_tag_id).or_default().push(record); + by_parent + .entry(record.parent_tag_id) + .or_default() + .push(record); } fn build_nodes( parent_id: Option, by_parent: &HashMap, Vec>, + counts: &HashMap, + subtree_counts: &HashMap, ) -> Vec { let Some(children) = by_parent.get(&parent_id) else { return Vec::new(); @@ -713,22 +764,21 @@ pub fn list_tag_tree(conn: &rusqlite::Connection) -> Result> { slug: r.slug.clone(), full_path: r.full_path.clone(), }, - children: build_nodes(Some(r.id), by_parent), + entry_count: counts.get(&r.tag_uid).copied().unwrap_or(0), + subtree_count: subtree_counts.get(&r.tag_uid).copied().unwrap_or(0), + children: build_nodes(Some(r.id), by_parent, counts, subtree_counts), }) .collect() } - Ok(build_nodes(None, &by_parent)) + Ok(build_nodes(None, &by_parent, &counts, &subtree_counts)) } /// Returns the tags assigned to an entry. /// /// Returns `Ok(None)` if the entry_uid does not exist (caller maps to 404). /// Returns `Ok(Some([]))` if the entry exists but has no tags. -pub fn get_entry_tags( - conn: &rusqlite::Connection, - entry_uid: &str, -) -> Result>> { +pub fn get_entry_tags(conn: &rusqlite::Connection, entry_uid: &str) -> Result>> { let Some(entry_id) = conn .query_row( "SELECT id FROM archived_entries WHERE entry_uid = ?1", @@ -1111,10 +1161,14 @@ mod tests { // Entry 1: tweet by source x let si1 = database::upsert_source_identity( - &conn, "x", "tweet", Some("t-1"), + &conn, + "x", + "tweet", + Some("t-1"), Some("https://x.com/user/status/1"), "https://x.com/user/status/1", - ).unwrap(); + ) + .unwrap(); database::create_archived_entry( &conn, &database::NewEntry { @@ -1132,14 +1186,19 @@ mod tests { source_metadata_json: "{}".to_string(), display_metadata_json: None, }, - ).unwrap(); + ) + .unwrap(); // Entry 2: web page let si2 = database::upsert_source_identity( - &conn, "web", "page", Some("page-1"), + &conn, + "web", + "page", + Some("page-1"), Some("https://medium.com/article"), "https://medium.com/article", - ).unwrap(); + ) + .unwrap(); database::create_archived_entry( &conn, &database::NewEntry { @@ -1157,7 +1216,8 @@ mod tests { source_metadata_json: "{}".to_string(), display_metadata_json: None, }, - ).unwrap(); + ) + .unwrap(); conn } @@ -1173,10 +1233,14 @@ mod tests { #[test] fn search_q_filters_on_title() { let conn = make_test_db_with_entries(); - let results = search_entries(&conn, &SearchEntriesQuery { - q: Some("polymarket".to_string()), - ..Default::default() - }).unwrap(); + let results = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("polymarket".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert_eq!(results.len(), 1); assert_eq!(results[0].entity_kind, "tweet"); } @@ -1184,10 +1248,14 @@ mod tests { #[test] fn search_entity_kind_exact_match() { let conn = make_test_db_with_entries(); - let results = search_entries(&conn, &SearchEntriesQuery { - entity_kind: Some("page".to_string()), - ..Default::default() - }).unwrap(); + let results = search_entries( + &conn, + &SearchEntriesQuery { + entity_kind: Some("page".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert_eq!(results.len(), 1); assert_eq!(results[0].source_kind, "web"); } @@ -1195,10 +1263,14 @@ mod tests { #[test] fn search_url_like_filter() { let conn = make_test_db_with_entries(); - let results = search_entries(&conn, &SearchEntriesQuery { - url: Some("medium.com".to_string()), - ..Default::default() - }).unwrap(); + let results = search_entries( + &conn, + &SearchEntriesQuery { + url: Some("medium.com".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert_eq!(results.len(), 1); assert_eq!(results[0].title.as_deref(), Some("Resume Templates")); } @@ -1206,21 +1278,29 @@ mod tests { #[test] fn search_no_match_returns_empty() { let conn = make_test_db_with_entries(); - let results = search_entries(&conn, &SearchEntriesQuery { - q: Some("zzznonexistent".to_string()), - ..Default::default() - }).unwrap(); + let results = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("zzznonexistent".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert!(results.is_empty()); } #[test] fn search_multiple_filters_compound() { let conn = make_test_db_with_entries(); - let results = search_entries(&conn, &SearchEntriesQuery { - source_kind: Some("x".to_string()), - entity_kind: Some("tweet".to_string()), - ..Default::default() - }).unwrap(); + let results = search_entries( + &conn, + &SearchEntriesQuery { + source_kind: Some("x".to_string()), + entity_kind: Some("tweet".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert_eq!(results.len(), 1); } @@ -1243,9 +1323,8 @@ mod tests { title: &str, url: &str, ) -> database::ArchivedEntry { - let si = database::upsert_source_identity( - conn, "web", "page", None, Some(url), url, - ).unwrap(); + let si = + database::upsert_source_identity(conn, "web", "page", None, Some(url), url).unwrap(); database::create_archived_entry( conn, &database::NewEntry { @@ -1263,7 +1342,8 @@ mod tests { source_metadata_json: "{}".to_string(), display_metadata_json: None, }, - ).unwrap() + ) + .unwrap() } #[test] @@ -1275,32 +1355,143 @@ mod tests { let tree = list_tag_tree(&conn).unwrap(); assert_eq!(tree.len(), 2, "expected two root nodes"); - let science = tree.iter().find(|n| n.tag.slug == "science").expect("science root missing"); + let science = tree + .iter() + .find(|n| n.tag.slug == "science") + .expect("science root missing"); assert_eq!(science.children.len(), 1, "science should have one child"); assert_eq!(science.children[0].tag.slug, "cs"); - let art = tree.iter().find(|n| n.tag.slug == "art").expect("art root missing"); + let art = tree + .iter() + .find(|n| n.tag.slug == "art") + .expect("art root missing"); assert!(art.children.is_empty(), "art should have no children"); } + #[test] + fn tag_tree_entry_counts_direct_and_subtree() { + let (conn, user_id, run_id) = make_tag_test_db(); + // Tree: /science -> /science/cs -> /science/cs/algorithms + create_tag(&conn, "/science/cs/algorithms").unwrap(); + + let e1 = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "E1", + "https://example.com/e1", + ); + let e2 = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "E2", + "https://example.com/e2", + ); + + // e1 → /science/cs/algorithms (leaf), e2 → /science (root) + assign_entry_tag(&conn, &e1.entry_uid, "/science/cs/algorithms").unwrap(); + assign_entry_tag(&conn, &e2.entry_uid, "/science").unwrap(); + + let tree = list_tag_tree(&conn).unwrap(); + let science = tree.iter().find(|n| n.tag.slug == "science").unwrap(); + let cs = science + .children + .iter() + .find(|n| n.tag.slug == "cs") + .unwrap(); + let algo = cs + .children + .iter() + .find(|n| n.tag.slug == "algorithms") + .unwrap(); + + assert_eq!(science.entry_count, 1, "science direct = 1"); + assert_eq!( + science.subtree_count, 2, + "science subtree = 2 (e1 via algo, e2 direct)" + ); + assert_eq!(cs.entry_count, 0, "cs direct = 0"); + assert_eq!(cs.subtree_count, 1, "cs subtree = 1 (e1 via algo)"); + assert_eq!(algo.entry_count, 1, "algo direct = 1"); + assert_eq!(algo.subtree_count, 1, "algo subtree = 1"); + } + + #[test] + fn tag_tree_subtree_count_deduplicates_shared_entry() { + // Regression: an entry assigned to both a parent and a child must count + // as 1 in the parent's subtree_count, not 2. + let (conn, user_id, run_id) = make_tag_test_db(); + create_tag(&conn, "/science/cs").unwrap(); + + let e = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "E", + "https://example.com/ded", + ); + assign_entry_tag(&conn, &e.entry_uid, "/science").unwrap(); + assign_entry_tag(&conn, &e.entry_uid, "/science/cs").unwrap(); + + let tree = list_tag_tree(&conn).unwrap(); + let science = tree.iter().find(|n| n.tag.slug == "science").unwrap(); + + assert_eq!( + science.subtree_count, 1, + "entry assigned to both parent and child must not be double-counted" + ); + assert_eq!(science.entry_count, 1, "science direct = 1"); + assert_eq!(science.children[0].subtree_count, 1, "cs subtree = 1"); + } + #[test] fn assign_entry_tag_is_idempotent() { let (conn, user_id, run_id) = make_tag_test_db(); - let entry = make_entry_in_db(&conn, user_id, run_id, None, None, "Test", "https://example.com/t1"); + let entry = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "Test", + "https://example.com/t1", + ); assign_entry_tag(&conn, &entry.entry_uid, "/science").unwrap(); assign_entry_tag(&conn, &entry.entry_uid, "/science").unwrap(); let tags = get_entry_tags(&conn, &entry.entry_uid).unwrap().unwrap(); - assert_eq!(tags.len(), 1, "idempotent assign should yield exactly one tag"); + assert_eq!( + tags.len(), + 1, + "idempotent assign should yield exactly one tag" + ); } #[test] fn remove_entry_tag_clears_assignment() { let (conn, user_id, run_id) = make_tag_test_db(); - let entry = make_entry_in_db(&conn, user_id, run_id, None, None, "Test", "https://example.com/t2"); + let entry = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "Test", + "https://example.com/t2", + ); - let tag = assign_entry_tag(&conn, &entry.entry_uid, "/science").unwrap().unwrap(); + let tag = assign_entry_tag(&conn, &entry.entry_uid, "/science") + .unwrap() + .unwrap(); remove_entry_tag(&conn, &entry.entry_uid, &tag.tag_uid).unwrap(); let tags = get_entry_tags(&conn, &entry.entry_uid).unwrap().unwrap(); @@ -1310,7 +1501,15 @@ mod tests { #[test] fn entries_for_tag_includes_descendants() { let (conn, user_id, run_id) = make_tag_test_db(); - let entry = make_entry_in_db(&conn, user_id, run_id, None, None, "Compilers Paper", "https://example.com/c1"); + let entry = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "Compilers Paper", + "https://example.com/c1", + ); assign_entry_tag(&conn, &entry.entry_uid, "/science/cs/compilers").unwrap(); @@ -1322,11 +1521,23 @@ mod tests { #[test] fn entries_for_tag_includes_child_entries() { let (conn, user_id, run_id) = make_tag_test_db(); - let parent = make_entry_in_db(&conn, user_id, run_id, None, None, "Playlist", "https://example.com/pl"); + let parent = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "Playlist", + "https://example.com/pl", + ); let child = make_entry_in_db( - &conn, user_id, run_id, - Some(parent.id), Some(parent.id), - "Video 1", "https://example.com/pl/v1", + &conn, + user_id, + run_id, + Some(parent.id), + Some(parent.id), + "Video 1", + "https://example.com/pl/v1", ); assign_entry_tag(&conn, &child.entry_uid, "/science").unwrap(); @@ -1334,42 +1545,77 @@ mod tests { let results = entries_for_tag(&conn, "/science").unwrap(); assert_eq!(results.len(), 1, "only the tagged child should appear"); assert_eq!(results[0].entry_uid, child.entry_uid); - assert_eq!(results[0].parent_entry_uid.as_deref(), Some(parent.entry_uid.as_str())); + assert_eq!( + results[0].parent_entry_uid.as_deref(), + Some(parent.entry_uid.as_str()) + ); } #[test] fn search_with_tag_filter_works() { let (conn, user_id, run_id) = make_tag_test_db(); - let entry = make_entry_in_db(&conn, user_id, run_id, None, None, "Science Article", "https://example.com/s1"); + let entry = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "Science Article", + "https://example.com/s1", + ); assign_entry_tag(&conn, &entry.entry_uid, "/science").unwrap(); - let results = search_entries(&conn, &SearchEntriesQuery { - tag: Some("/science".to_string()), - ..Default::default() - }).unwrap(); + let results = search_entries( + &conn, + &SearchEntriesQuery { + tag: Some("/science".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert_eq!(results.len(), 1); assert_eq!(results[0].entry_uid, entry.entry_uid); - let empty = search_entries(&conn, &SearchEntriesQuery { - tag: Some("/art".to_string()), - ..Default::default() - }).unwrap(); + let empty = search_entries( + &conn, + &SearchEntriesQuery { + tag: Some("/art".to_string()), + ..Default::default() + }, + ) + .unwrap(); assert!(empty.is_empty(), "no entries under /art"); } #[test] fn search_without_tag_returns_roots_only() { let (conn, user_id, run_id) = make_tag_test_db(); - let parent = make_entry_in_db(&conn, user_id, run_id, None, None, "Parent", "https://example.com/par"); + let parent = make_entry_in_db( + &conn, + user_id, + run_id, + None, + None, + "Parent", + "https://example.com/par", + ); let _child = make_entry_in_db( - &conn, user_id, run_id, - Some(parent.id), Some(parent.id), - "Child", "https://example.com/par/c", + &conn, + user_id, + run_id, + Some(parent.id), + Some(parent.id), + "Child", + "https://example.com/par/c", ); let results = search_entries(&conn, &SearchEntriesQuery::default()).unwrap(); - assert_eq!(results.len(), 1, "plain search should return root entries only"); + assert_eq!( + results.len(), + 1, + "plain search should return root entries only" + ); assert_eq!(results[0].entry_uid, parent.entry_uid); } } diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 159972f..e158734 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -135,7 +135,7 @@ pub struct RoleRecord { pub struct InstanceSettings { pub public_index_enabled: bool, pub public_entry_content_enabled: bool, - pub open_registration_enabled: bool, // maps to public_archive_submission_enabled column + pub open_registration_enabled: bool, // maps to public_archive_submission_enabled column pub default_entry_visibility: u32, /// Global default for ad-blocking via uBlock Origin Lite during WebPage captures. /// Per-capture requests can override this. @@ -532,13 +532,11 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> { pub fn open_auth_db(auth_db_path: &Path) -> Result { if let Some(parent) = auth_db_path.parent() { - std::fs::create_dir_all(parent).with_context(|| { - format!("failed to create auth DB directory {}", parent.display()) - })?; + std::fs::create_dir_all(parent) + .with_context(|| format!("failed to create auth DB directory {}", parent.display()))?; } - let conn = Connection::open(auth_db_path).with_context(|| { - format!("failed to open auth database at {}", auth_db_path.display()) - })?; + let conn = Connection::open(auth_db_path) + .with_context(|| format!("failed to open auth database at {}", auth_db_path.display()))?; initialize_auth_schema(&conn)?; Ok(conn) } @@ -566,11 +564,10 @@ pub fn create_owner(conn: &Connection, username: &str, password_hash: &str) -> R )?; let user_id = conn.last_insert_rowid(); for slug in &["user", "admin", "owner"] { - let role_id: i64 = conn.query_row( - "SELECT id FROM roles WHERE slug = ?1", - [slug], - |row| row.get(0), - )?; + let role_id: i64 = + conn.query_row("SELECT id FROM roles WHERE slug = ?1", [slug], |row| { + row.get(0) + })?; conn.execute( "INSERT OR IGNORE INTO user_roles (user_id, role_id, assigned_at) VALUES (?1, ?2, ?3)", @@ -804,12 +801,12 @@ pub fn list_cookie_rules(conn: &Connection) -> Result> { let records = stmt .query_map([], |row| { Ok(CookieRule { - rule_uid: row.get(0)?, - url_pattern: row.get(1)?, + rule_uid: row.get(0)?, + url_pattern: row.get(1)?, pattern_kind: row.get(2)?, cookies_json: row.get(3)?, - ordinal: row.get(4)?, - created_at: row.get(5)?, + ordinal: row.get(4)?, + created_at: row.get(5)?, }) })? .collect::, _>>()?; @@ -865,10 +862,7 @@ pub fn update_cookie_rule( } pub fn delete_cookie_rule(conn: &Connection, rule_uid: &str) -> Result<()> { - let rows = conn.execute( - "DELETE FROM cookie_rules WHERE rule_uid = ?1", - [rule_uid], - )?; + let rows = conn.execute("DELETE FROM cookie_rules WHERE rule_uid = ?1", [rule_uid])?; if rows == 0 { anyhow::bail!("cookie rule not found: {rule_uid}"); } @@ -893,7 +887,11 @@ pub fn update_user_password(conn: &Connection, user_id: i64, new_hash: &str) -> Ok(()) } -pub fn update_user_display_name(conn: &Connection, user_id: i64, display_name: Option<&str>) -> Result<()> { +pub fn update_user_display_name( + conn: &Connection, + user_id: i64, + display_name: Option<&str>, +) -> Result<()> { conn.execute( "UPDATE users SET display_name = ?1 WHERE id = ?2", params![display_name, user_id], @@ -937,9 +935,13 @@ pub fn invalidate_user_sessions(conn: &Connection, user_id: i64) -> Result Result> { - conn.query_row("SELECT id FROM users WHERE user_uid = ?1", [user_uid], |r| r.get(0)) - .optional() - .map_err(Into::into) + conn.query_row( + "SELECT id FROM users WHERE user_uid = ?1", + [user_uid], + |r| r.get(0), + ) + .optional() + .map_err(Into::into) } /// Lists all users with their assigned roles and computed role_bits. @@ -948,7 +950,16 @@ pub fn list_users(conn: &Connection) -> Result> { "SELECT id, user_uid, username, email, status, created_at FROM users ORDER BY created_at ASC", )?; let rows: Vec<(i64, String, String, Option, String, String)> = stmt - .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))? + .query_map([], |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + )) + })? .collect::>()?; rows.into_iter() @@ -958,9 +969,18 @@ pub fn list_users(conn: &Connection) -> Result> { "SELECT r.slug FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = ?1 ORDER BY r.level, r.bit_position", )?; - let role_slugs: Vec = - rs.query_map([id], |r| r.get(0))?.collect::>()?; - Ok(UserSummary { user_uid, username, email, status, created_at, role_slugs, role_bits }) + let role_slugs: Vec = rs + .query_map([id], |r| r.get(0))? + .collect::>()?; + Ok(UserSummary { + user_uid, + username, + email, + status, + created_at, + role_slugs, + role_bits, + }) }) .collect() } @@ -982,9 +1002,18 @@ pub fn get_user_by_uid(conn: &Connection, user_uid: &str) -> Result = - rs.query_map([id], |r| r.get(0))?.collect::>()?; - Ok(Some(UserSummary { user_uid, username, email, status, created_at, role_slugs, role_bits })) + let role_slugs: Vec = rs + .query_map([id], |r| r.get(0))? + .collect::>()?; + Ok(Some(UserSummary { + user_uid, + username, + email, + status, + created_at, + role_slugs, + role_bits, + })) } } } @@ -1005,11 +1034,8 @@ pub fn create_user( params![user_uid, username, email, password_hash, now_timestamp()], )?; let user_id = conn.last_insert_rowid(); - let role_id: i64 = conn.query_row( - "SELECT id FROM roles WHERE slug = 'user'", - [], - |r| r.get(0), - )?; + let role_id: i64 = + conn.query_row("SELECT id FROM roles WHERE slug = 'user'", [], |r| r.get(0))?; conn.execute( "INSERT OR IGNORE INTO user_roles (user_id, role_id, assigned_at, assigned_by_user_id) VALUES (?1, ?2, ?3, ?4)", @@ -1023,7 +1049,11 @@ pub fn create_user( pub fn set_user_status(conn: &Connection, user_uid: &str, status: &str) -> Result { if status == "disabled" { let id: Option = conn - .query_row("SELECT id FROM users WHERE user_uid = ?1", [user_uid], |r| r.get(0)) + .query_row( + "SELECT id FROM users WHERE user_uid = ?1", + [user_uid], + |r| r.get(0), + ) .optional()?; if let Some(id) = id { invalidate_user_sessions(conn, id)?; @@ -1045,16 +1075,24 @@ pub fn assign_role( assigned_by_user_id: i64, ) -> Result<()> { let role_id: i64 = conn - .query_row("SELECT id FROM roles WHERE slug = ?1", [role_slug], |r| r.get(0)) + .query_row("SELECT id FROM roles WHERE slug = ?1", [role_slug], |r| { + r.get(0) + }) .map_err(|_| anyhow::anyhow!("role '{}' not found", role_slug))?; conn.execute( "INSERT OR IGNORE INTO user_roles (user_id, role_id, assigned_at, assigned_by_user_id) VALUES (?1, ?2, ?3, ?4)", - params![target_user_id, role_id, now_timestamp(), assigned_by_user_id], + params![ + target_user_id, + role_id, + now_timestamp(), + assigned_by_user_id + ], )?; // Cumulative: ensure 'user' whenever any non-guest role is assigned if role_slug != "user" && role_slug != "guest" { - let uid: i64 = conn.query_row("SELECT id FROM roles WHERE slug = 'user'", [], |r| r.get(0))?; + let uid: i64 = + conn.query_row("SELECT id FROM roles WHERE slug = 'user'", [], |r| r.get(0))?; conn.execute( "INSERT OR IGNORE INTO user_roles (user_id, role_id, assigned_at, assigned_by_user_id) VALUES (?1, ?2, ?3, ?4)", @@ -1063,7 +1101,9 @@ pub fn assign_role( } // Also ensure 'admin' when assigning 'owner' if role_slug == "owner" { - let aid: i64 = conn.query_row("SELECT id FROM roles WHERE slug = 'admin'", [], |r| r.get(0))?; + let aid: i64 = conn.query_row("SELECT id FROM roles WHERE slug = 'admin'", [], |r| { + r.get(0) + })?; conn.execute( "INSERT OR IGNORE INTO user_roles (user_id, role_id, assigned_at, assigned_by_user_id) VALUES (?1, ?2, ?3, ?4)", @@ -1088,7 +1128,9 @@ pub fn remove_role(conn: &Connection, target_user_id: i64, role_slug: &str) -> R } } let role_id: i64 = conn - .query_row("SELECT id FROM roles WHERE slug = ?1", [role_slug], |r| r.get(0)) + .query_row("SELECT id FROM roles WHERE slug = ?1", [role_slug], |r| { + r.get(0) + }) .map_err(|_| anyhow::anyhow!("role '{}' not found", role_slug))?; conn.execute( "DELETE FROM user_roles WHERE user_id = ?1 AND role_id = ?2", @@ -1122,7 +1164,9 @@ pub fn list_roles(conn: &Connection) -> Result> { /// Returns the created RoleRecord. pub fn create_custom_role(conn: &Connection, slug: &str, name: &str) -> Result { if slug.is_empty() || !slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { - anyhow::bail!("role slug must be non-empty and contain only ASCII letters, digits, or hyphens"); + anyhow::bail!( + "role slug must be non-empty and contain only ASCII letters, digits, or hyphens" + ); } let next_bit: i64 = conn.query_row( "SELECT COALESCE(MAX(bit_position) + 1, 4) FROM roles WHERE bit_position >= 4", @@ -1509,10 +1553,7 @@ pub fn cascade_cached_bytes_after_delete(conn: &Connection, entry_id: i64) -> Re /// "still there" during the recalculation. /// /// Must be called before any subtree rows are deleted so the `entry_artifacts` JOIN resolves. -fn cascade_cached_bytes_after_subtree_delete( - conn: &Connection, - subtree_ids: &[i64], -) -> Result<()> { +fn cascade_cached_bytes_after_subtree_delete(conn: &Connection, subtree_ids: &[i64]) -> Result<()> { if subtree_ids.is_empty() { return Ok(()); } @@ -1588,9 +1629,7 @@ pub fn delete_entry(conn: &Connection, entry_uid: &str) -> Result { // Collect the full subtree while rows still exist. let subtree_ids: Vec = { - let mut stmt = conn.prepare( - "SELECT id FROM archived_entries WHERE root_entry_id = ?1", - )?; + let mut stmt = conn.prepare("SELECT id FROM archived_entries WHERE root_entry_id = ?1")?; stmt.query_map([entry_id], |row| row.get(0))? .collect::>()? }; @@ -1615,10 +1654,7 @@ pub fn delete_entry(conn: &Connection, entry_uid: &str) -> Result { )?; // Root entry: CASCADE handles entry_artifacts, entry_tag_assignments, collection_entries. - conn.execute( - "DELETE FROM archived_entries WHERE id = ?1", - [entry_id], - )?; + conn.execute("DELETE FROM archived_entries WHERE id = ?1", [entry_id])?; Ok(true) } @@ -1703,7 +1739,9 @@ pub fn list_orphaned_blob_rows(conn: &Connection) -> Result Result> { +pub fn all_referenced_file_relpaths( + conn: &Connection, +) -> Result> { let mut set = std::collections::HashSet::new(); { let mut stmt = conn.prepare("SELECT DISTINCT relpath FROM entry_artifacts")?; @@ -1809,11 +1847,7 @@ pub fn add_entry_artifact(conn: &Connection, artifact: &NewArtifact) -> Result Result<()> { +pub fn remove_entry_tag_assignment(conn: &Connection, entry_id: i64, tag_id: i64) -> Result<()> { conn.execute( "DELETE FROM entry_tag_assignments WHERE entry_id = ?1 AND tag_id = ?2", params![entry_id, tag_id], @@ -1955,12 +1989,18 @@ pub fn main_archive_entry_count(conn: &Connection) -> Result { } pub fn create_tag_path(conn: &Connection, full_path: &str) -> Result { - let segments = normalized_tag_segments(full_path)?; - let mut parent_tag_id = None; - let mut current_path = String::new(); - let mut current_id = 0; + let raw_segments = normalized_tag_segments(full_path)?; + // Slugify each segment consistently with rename_tag. + let segments: Vec = raw_segments + .into_iter() + .map(slugify_segment) + .collect::>>()?; - for segment in segments { + let mut parent_tag_id: Option = None; + let mut current_path = String::new(); + let mut current_id: i64 = 0; + + for segment in &segments { current_path.push('/'); current_path.push_str(segment); @@ -1984,7 +2024,7 @@ pub fn create_tag_path(conn: &Connection, full_path: &str) -> Result { public_id("tag"), parent_tag_id, humanize_slug(segment), - segment, + segment.as_str(), current_path ], )?; @@ -2027,30 +2067,7 @@ pub fn rename_tag( tag_uid: &str, new_segment: &str, ) -> Result> { - // Slugify: spaces→hyphens, keep alphanumeric and hyphens (case preserved), collapse runs, strip edges. - let trimmed = new_segment.trim(); - let hyphenated: String = trimmed.chars().map(|c| if c == ' ' { '-' } else { c }).collect(); - let filtered: String = hyphenated - .chars() - .filter(|c| c.is_alphanumeric() || *c == '-') - .collect(); - let mut new_slug = String::new(); - let mut prev_hyphen = false; - for c in filtered.chars() { - if c == '-' { - if !prev_hyphen { - new_slug.push(c); - } - prev_hyphen = true; - } else { - new_slug.push(c); - prev_hyphen = false; - } - } - let new_slug = new_slug.trim_matches('-').to_string(); - if new_slug.is_empty() { - bail!("new segment slugifies to empty string"); - } + let new_slug = slugify_segment(new_segment)?; // Fetch existing tag. let tag = match get_tag_by_uid(conn, tag_uid)? { @@ -2084,15 +2101,18 @@ pub fn rename_tag( )?; let old_prefix_slash = format!("{}/", old_prefix); let new_prefix_slash = format!("{}/", new_full_path); - // Use hierarchy (recursive CTE over parent_tag_id) instead of LIKE to avoid - // treating '_'/'%' in historical slugs as wildcards. + // Replace the leading old_prefix_slash with new_prefix_slash across all + // descendants. REPLACE(full_path, old, new) would corrupt paths where the + // old prefix string appears again deeper in the tree (e.g. /foo/other/foo/bar). + // Use prefix-anchored substitution instead: keep everything after the prefix + // and prepend the new prefix. conn.execute( "WITH RECURSIVE descendants(id) AS (\ SELECT id FROM tags WHERE parent_tag_id = ?1 \ UNION ALL \ SELECT t.id FROM tags t JOIN descendants d ON t.parent_tag_id = d.id \ ) \ - UPDATE tags SET full_path = REPLACE(full_path, ?2, ?3) \ + UPDATE tags SET full_path = ?3 || substr(full_path, length(?2) + 1) \ WHERE id IN (SELECT id FROM descendants)", params![tag.id, old_prefix_slash, new_prefix_slash], )?; @@ -2129,6 +2149,97 @@ pub fn delete_tag(conn: &Connection, tag_uid: &str) -> Result { Ok(deleted > 0) } +/// Moves a tag and its entire subtree to a new parent. +/// +/// `new_parent_uid = None` promotes the tag to root level. +/// Returns `Ok(None)` if `tag_uid` is not found. +/// Returns an error if: +/// - `new_parent_uid` refers to the tag itself or a descendant of it +/// - the resulting path would collide with an existing tag +/// - `new_parent_uid` is provided but not found +pub fn move_tag( + conn: &Connection, + tag_uid: &str, + new_parent_uid: Option<&str>, +) -> Result> { + let tag = match get_tag_by_uid(conn, tag_uid)? { + Some(t) => t, + None => return Ok(None), + }; + + let new_parent: Option = match new_parent_uid { + Some(uid) => { + let parent = match get_tag_by_uid(conn, uid)? { + Some(p) => p, + None => bail!("parent tag not found"), + }; + if parent.tag_uid == tag.tag_uid { + bail!("cannot move a tag under itself"); + } + // Reject if the proposed parent is a descendant of the tag being moved. + if parent.full_path.starts_with(&format!("{}/", tag.full_path)) { + bail!("cannot move a tag under one of its own descendants"); + } + Some(parent) + } + None => None, + }; + + let new_full_path = match &new_parent { + Some(p) => format!("{}/{}", p.full_path, tag.slug), + None => format!("/{}", tag.slug), + }; + + // No-op when the path would not change. + if new_full_path == tag.full_path { + return Ok(Some(tag)); + } + + // Collision check. + if let Some(existing) = get_tag_by_path(conn, &new_full_path)? { + if existing.tag_uid != tag_uid { + bail!("a tag already exists at path: {new_full_path}"); + } + } + + let new_parent_id: Option = new_parent.as_ref().map(|p| p.id); + let tag_id = tag.id; + let old_prefix_slash = format!("{}/", tag.full_path); + let new_prefix_slash = format!("{}/", new_full_path); + + let result = (|| -> Result<()> { + conn.execute_batch("BEGIN")?; + // Update the moved tag itself: new parent and new full_path. + conn.execute( + "UPDATE tags SET parent_tag_id = ?1, full_path = ?2 WHERE tag_uid = ?3", + params![new_parent_id, new_full_path, tag_uid], + )?; + // Cascade the full_path prefix change to every descendant. + // Use prefix-anchored substitution: ?3 || substr(full_path, length(?2) + 1) + // rather than REPLACE, which would corrupt paths where the old prefix slug + // appears again at a non-overlapping position deeper in the tree. + conn.execute( + "WITH RECURSIVE descendants(id) AS (\ + SELECT id FROM tags WHERE parent_tag_id = ?1 \ + UNION ALL \ + SELECT t.id FROM tags t JOIN descendants d ON t.parent_tag_id = d.id \ + ) \ + UPDATE tags SET full_path = ?3 || substr(full_path, length(?2) + 1) \ + WHERE id IN (SELECT id FROM descendants)", + params![tag_id, old_prefix_slash, new_prefix_slash], + )?; + conn.execute_batch("COMMIT")?; + Ok(()) + })(); + + if let Err(e) = result { + let _ = conn.execute_batch("ROLLBACK"); + return Err(e); + } + + get_tag_by_uid(conn, tag_uid) +} + fn refresh_run_counters(conn: &Connection, run_id: i64) -> Result<()> { conn.execute( "UPDATE archive_runs @@ -2182,7 +2293,13 @@ pub fn create_collection( conn.execute( "INSERT INTO collections (collection_uid, name, slug, default_visibility_bits, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5)", - params![collection_uid, name, slug, default_visibility_bits as i64, now], + params![ + collection_uid, + name, + slug, + default_visibility_bits as i64, + now + ], )?; let id = conn.last_insert_rowid(); Ok(CollectionRecord { @@ -2216,10 +2333,7 @@ pub fn list_collections(conn: &Connection) -> Result> { } /// Returns a collection by its uid, or None if not found. -pub fn get_collection_by_uid( - conn: &Connection, - uid: &str, -) -> Result> { +pub fn get_collection_by_uid(conn: &Connection, uid: &str) -> Result> { conn.query_row( "SELECT id, collection_uid, name, slug, default_visibility_bits, created_at \ FROM collections WHERE collection_uid = ?1", @@ -2327,10 +2441,7 @@ pub fn update_collection( /// Deletes a collection and cascades to collection_entries. /// Returns true if deleted, false if not found. /// Refuses to delete the '_default_' collection. -pub fn delete_collection( - conn: &Connection, - collection_uid: &str, -) -> Result { +pub fn delete_collection(conn: &Connection, collection_uid: &str) -> Result { let coll = get_collection_by_uid(conn, collection_uid)?; let Some(coll) = coll else { return Ok(false) }; if coll.slug == "_default_" { @@ -2403,6 +2514,39 @@ fn humanize_slug(slug: &str) -> String { .join(" ") } +/// Converts a raw input string into a valid tag slug: +/// spaces → hyphens, strip non-(alphanumeric|hyphen), collapse runs, trim edge hyphens. +/// Returns an error if the result is empty. +fn slugify_segment(input: &str) -> Result { + let hyphenated: String = input + .trim() + .chars() + .map(|c| if c == ' ' { '-' } else { c }) + .collect(); + let filtered: String = hyphenated + .chars() + .filter(|c| c.is_alphanumeric() || *c == '-') + .collect(); + let mut slug = String::new(); + let mut prev_hyphen = false; + for c in filtered.chars() { + if c == '-' { + if !prev_hyphen { + slug.push(c); + } + prev_hyphen = true; + } else { + slug.push(c); + prev_hyphen = false; + } + } + let slug = slug.trim_matches('-').to_string(); + if slug.is_empty() { + bail!("segment slugifies to empty string"); + } + Ok(slug) +} + /// A minimal view of an archived entry needed for re-archiving. pub struct EntryForRearchive { pub id: i64, @@ -2779,7 +2923,11 @@ mod tests { #[test] fn get_blob_by_sha256_returns_none_for_unknown() { let conn = conn(); - let result = get_blob_by_sha256(&conn, "0000000000000000000000000000000000000000000000000000000000000000").unwrap(); + let result = get_blob_by_sha256( + &conn, + "0000000000000000000000000000000000000000000000000000000000000000", + ) + .unwrap(); assert!(result.is_none()); } @@ -2788,11 +2936,17 @@ mod tests { let conn = Connection::open_in_memory().unwrap(); initialize_auth_schema(&conn).unwrap(); let count: i64 = conn - .query_row("SELECT COUNT(*) FROM roles WHERE is_builtin = 1", [], |r| r.get(0)) + .query_row("SELECT COUNT(*) FROM roles WHERE is_builtin = 1", [], |r| { + r.get(0) + }) .unwrap(); assert_eq!(count, 4); let owner_bits: i64 = conn - .query_row("SELECT bit_position FROM roles WHERE slug = 'owner'", [], |r| r.get(0)) + .query_row( + "SELECT bit_position FROM roles WHERE slug = 'owner'", + [], + |r| r.get(0), + ) .unwrap(); assert_eq!(owner_bits, 3); } @@ -2892,7 +3046,8 @@ mod tests { let conn = conn(); let job_uid = create_capture_job(&conn, "test").unwrap(); update_capture_job_status(&conn, &job_uid, "running", None, None, None).unwrap(); - update_capture_job_status(&conn, &job_uid, "completed", Some("run_abc"), None, None).unwrap(); + update_capture_job_status(&conn, &job_uid, "completed", Some("run_abc"), None, None) + .unwrap(); let job = get_capture_job(&conn, &job_uid).unwrap().unwrap(); assert_eq!(job.status, "completed"); assert_eq!(job.run_uid.as_deref(), Some("run_abc")); @@ -2910,7 +3065,17 @@ mod tests { // (covers the case where run_uid was never written back before the crash). let user_id = ensure_default_user(&conn).unwrap(); let run = create_archive_run(&conn, user_id, 1).unwrap(); - create_archive_run_item(&conn, run.id, None, 0, "https://example.com", None, "web", "file").unwrap(); + create_archive_run_item( + &conn, + run.id, + None, + 0, + "https://example.com", + None, + "web", + "file", + ) + .unwrap(); let n = fail_stalled_capture_jobs(&conn).unwrap(); assert_eq!(n, 1); // one capture_job updated @@ -2921,19 +3086,23 @@ mod tests { assert!(job.error_text.as_deref().unwrap().contains("interrupted")); // archive_run is failed - let updated_run: String = conn.query_row( - "SELECT status FROM archive_runs WHERE id = ?1", - [run.id], - |r| r.get(0), - ).unwrap(); + let updated_run: String = conn + .query_row( + "SELECT status FROM archive_runs WHERE id = ?1", + [run.id], + |r| r.get(0), + ) + .unwrap(); assert_eq!(updated_run, "failed"); // archive_run_item is failed - let item_status: String = conn.query_row( - "SELECT status FROM archive_run_items WHERE run_id = ?1", - [run.id], - |r| r.get(0), - ).unwrap(); + let item_status: String = conn + .query_row( + "SELECT status FROM archive_run_items WHERE run_id = ?1", + [run.id], + |r| r.get(0), + ) + .unwrap(); assert_eq!(item_status, "failed"); } @@ -2947,7 +3116,8 @@ mod tests { fn user_create_and_list() { let conn = make_auth_conn_for_mgmt(); let owner_id = create_owner(&conn, "owner", "hash").unwrap(); - let uid = create_user(&conn, "alice", Some("alice@example.com"), "hash2", owner_id).unwrap(); + let uid = + create_user(&conn, "alice", Some("alice@example.com"), "hash2", owner_id).unwrap(); let users = list_users(&conn).unwrap(); assert_eq!(users.len(), 2); let alice = users.iter().find(|u| u.username == "alice").unwrap(); @@ -2961,10 +3131,20 @@ mod tests { let conn = make_auth_conn_for_mgmt(); let owner_id = create_owner(&conn, "owner", "hash").unwrap(); let uid = create_user(&conn, "bob", None, "hash", owner_id).unwrap(); - let bob_id: i64 = conn.query_row("SELECT id FROM users WHERE user_uid = ?1", [&uid], |r| r.get(0)).unwrap(); + let bob_id: i64 = conn + .query_row("SELECT id FROM users WHERE user_uid = ?1", [&uid], |r| { + r.get(0) + }) + .unwrap(); create_session(&conn, bob_id, 3, None).unwrap(); set_user_status(&conn, &uid, "disabled").unwrap(); - let sess_count: i64 = conn.query_row("SELECT COUNT(*) FROM sessions WHERE user_id = ?1", [bob_id], |r| r.get(0)).unwrap(); + let sess_count: i64 = conn + .query_row( + "SELECT COUNT(*) FROM sessions WHERE user_id = ?1", + [bob_id], + |r| r.get(0), + ) + .unwrap(); assert_eq!(sess_count, 0, "sessions should be cleared on disable"); let u = get_user_by_uid(&conn, &uid).unwrap().unwrap(); assert_eq!(u.status, "disabled"); @@ -3011,16 +3191,18 @@ mod tests { let _ = create_tag_path(&conn, "science/cs/algorithms").unwrap(); let science = get_tag_by_path(&conn, "/science").unwrap().unwrap(); - let cs = get_tag_by_path(&conn, "/science/cs").unwrap().unwrap(); - let algo = get_tag_by_path(&conn, "/science/cs/algorithms").unwrap().unwrap(); + let cs = get_tag_by_path(&conn, "/science/cs").unwrap().unwrap(); + let algo = get_tag_by_path(&conn, "/science/cs/algorithms") + .unwrap() + .unwrap(); // Rename "science" → "natural-science" let updated = rename_tag(&conn, &science.tag_uid, "natural-science") .unwrap() .expect("should return updated tag"); - assert_eq!(updated.slug, "natural-science"); - assert_eq!(updated.name, "Natural Science"); + assert_eq!(updated.slug, "natural-science"); + assert_eq!(updated.name, "Natural Science"); assert_eq!(updated.full_path, "/natural-science"); // /science must no longer exist @@ -3032,7 +3214,11 @@ mod tests { assert_eq!(cs_new.full_path, "/natural-science/cs"); // /science/cs/algorithms must have moved - assert!(get_tag_by_path(&conn, "/science/cs/algorithms").unwrap().is_none()); + assert!( + get_tag_by_path(&conn, "/science/cs/algorithms") + .unwrap() + .is_none() + ); let algo_new = get_tag_by_uid(&conn, &algo.tag_uid).unwrap().unwrap(); assert_eq!(algo_new.full_path, "/natural-science/cs/algorithms"); } @@ -3048,7 +3234,11 @@ mod tests { // Renaming /science → natural-science should collide let result = rename_tag(&conn, &science.tag_uid, "natural-science"); - assert!(result.is_err(), "expected collision error, got {:?}", result); + assert!( + result.is_err(), + "expected collision error, got {:?}", + result + ); } #[test] @@ -3074,7 +3264,7 @@ mod tests { fn delete_tag_removes_subtree_and_cascades_assignments() { let conn = conn(); // Build /science/cs and /science/math - let cs_id = create_tag_path(&conn, "science/cs").unwrap(); + let cs_id = create_tag_path(&conn, "science/cs").unwrap(); let math_id = create_tag_path(&conn, "science/math").unwrap(); let science = get_tag_by_path(&conn, "/science").unwrap().unwrap(); @@ -3114,12 +3304,16 @@ mod tests { // Verify by uid too (subtree ids: science, cs, math) assert!(get_tag_by_uid(&conn, &science.tag_uid).unwrap().is_none()); let cs_tag = conn - .query_row("SELECT tag_uid FROM tags WHERE id = ?1", [cs_id], |r| r.get::<_, String>(0)) + .query_row("SELECT tag_uid FROM tags WHERE id = ?1", [cs_id], |r| { + r.get::<_, String>(0) + }) .optional() .unwrap(); assert!(cs_tag.is_none(), "/science/cs should be deleted"); let math_tag = conn - .query_row("SELECT tag_uid FROM tags WHERE id = ?1", [math_id], |r| r.get::<_, String>(0)) + .query_row("SELECT tag_uid FROM tags WHERE id = ?1", [math_id], |r| { + r.get::<_, String>(0) + }) .optional() .unwrap(); assert!(math_tag.is_none(), "/science/math should be deleted"); @@ -3139,6 +3333,207 @@ mod tests { assert_eq!(updated.full_path, "/Natural-Science"); } + // ── move_tag tests ──────────────────────────────────────────────────────── + + #[test] + fn move_tag_unknown_uid_returns_none() { + let conn = conn(); + let result = move_tag(&conn, "tag_doesnotexist", None).unwrap(); + assert!(result.is_none()); + } + + #[test] + fn move_tag_to_root_clears_parent_and_updates_path() { + let conn = conn(); + // Build /science/cs/algorithms + let _ = create_tag_path(&conn, "science/cs/algorithms").unwrap(); + let cs = get_tag_by_path(&conn, "/science/cs").unwrap().unwrap(); + let algo = get_tag_by_path(&conn, "/science/cs/algorithms") + .unwrap() + .unwrap(); + + // Move /science/cs to root — new path should be /cs + let updated = move_tag(&conn, &cs.tag_uid, None) + .unwrap() + .expect("should return updated tag"); + + assert_eq!(updated.full_path, "/cs"); + assert!(updated.parent_tag_id.is_none()); + + // /science/cs must no longer exist at old path + assert!(get_tag_by_path(&conn, "/science/cs").unwrap().is_none()); + + // Descendant /science/cs/algorithms must have its path updated + let algo_updated = get_tag_by_uid(&conn, &algo.tag_uid).unwrap().unwrap(); + assert_eq!(algo_updated.full_path, "/cs/algorithms"); + } + + #[test] + fn move_tag_to_new_parent_updates_subtree_paths() { + let conn = conn(); + // Build /science/cs/algorithms and /archive + let _ = create_tag_path(&conn, "science/cs/algorithms").unwrap(); + let _ = create_tag_path(&conn, "archive").unwrap(); + + let cs = get_tag_by_path(&conn, "/science/cs").unwrap().unwrap(); + let algo = get_tag_by_path(&conn, "/science/cs/algorithms") + .unwrap() + .unwrap(); + let archive = get_tag_by_path(&conn, "/archive").unwrap().unwrap(); + + // Move /science/cs under /archive + let updated = move_tag(&conn, &cs.tag_uid, Some(&archive.tag_uid)) + .unwrap() + .expect("should return updated tag"); + + assert_eq!(updated.full_path, "/archive/cs"); + assert_eq!(updated.parent_tag_id, Some(archive.id)); + + // Old path must be gone + assert!(get_tag_by_path(&conn, "/science/cs").unwrap().is_none()); + + // Descendant must have cascaded path + let algo_updated = get_tag_by_uid(&conn, &algo.tag_uid).unwrap().unwrap(); + assert_eq!(algo_updated.full_path, "/archive/cs/algorithms"); + } + + #[test] + fn move_tag_noop_when_parent_unchanged() { + let conn = conn(); + let _ = create_tag_path(&conn, "science/cs").unwrap(); + let science = get_tag_by_path(&conn, "/science").unwrap().unwrap(); + let cs = get_tag_by_path(&conn, "/science/cs").unwrap().unwrap(); + + // Moving /science/cs under /science again is a no-op + let updated = move_tag(&conn, &cs.tag_uid, Some(&science.tag_uid)) + .unwrap() + .expect("should return tag"); + assert_eq!(updated.full_path, "/science/cs"); + } + + #[test] + fn move_tag_rejects_self_move() { + let conn = conn(); + let _ = create_tag_path(&conn, "science").unwrap(); + let science = get_tag_by_path(&conn, "/science").unwrap().unwrap(); + let result = move_tag(&conn, &science.tag_uid, Some(&science.tag_uid)); + assert!( + result.is_err(), + "expected error when moving tag under itself" + ); + } + + #[test] + fn move_tag_rejects_descendant_as_parent() { + let conn = conn(); + let _ = create_tag_path(&conn, "science/cs/algorithms").unwrap(); + let science = get_tag_by_path(&conn, "/science").unwrap().unwrap(); + let algo = get_tag_by_path(&conn, "/science/cs/algorithms") + .unwrap() + .unwrap(); + + // Moving /science under one of its own descendants must be rejected + let result = move_tag(&conn, &science.tag_uid, Some(&algo.tag_uid)); + assert!( + result.is_err(), + "expected error when moving tag under a descendant" + ); + } + + #[test] + fn move_tag_rejects_path_collision() { + let conn = conn(); + // /archive/cs and /science/cs both exist; moving /science/cs under /archive collides + let _ = create_tag_path(&conn, "science/cs").unwrap(); + let _ = create_tag_path(&conn, "archive/cs").unwrap(); + let science_cs = get_tag_by_path(&conn, "/science/cs").unwrap().unwrap(); + let archive = get_tag_by_path(&conn, "/archive").unwrap().unwrap(); + + let result = move_tag(&conn, &science_cs.tag_uid, Some(&archive.tag_uid)); + assert!( + result.is_err(), + "expected collision error; /archive/cs already exists" + ); + } + + #[test] + fn move_tag_rejects_unknown_parent_uid() { + let conn = conn(); + let _ = create_tag_path(&conn, "science").unwrap(); + let science = get_tag_by_path(&conn, "/science").unwrap().unwrap(); + let result = move_tag(&conn, &science.tag_uid, Some("uid_does_not_exist")); + assert!(result.is_err(), "expected error for unknown parent uid"); + } + + #[test] + fn move_tag_cascade_only_replaces_leading_prefix() { + // Regression: SQLite REPLACE(full_path, old_prefix, new_prefix) rewrites + // every non-overlapping occurrence of the pattern in the string, not just + // the leading one. /foo/foo/bar is NOT a triggering case (the overlapping + // '/' hides the second match), but /foo/other/foo/bar has a second /foo/ + // at a non-overlapping position and does expose the bug. + let conn = conn(); + let _ = create_tag_path(&conn, "foo/other/foo/bar").unwrap(); + let foo = get_tag_by_path(&conn, "/foo").unwrap().unwrap(); + let other = get_tag_by_path(&conn, "/foo/other").unwrap().unwrap(); + let other_foo = get_tag_by_path(&conn, "/foo/other/foo").unwrap().unwrap(); + let bar = get_tag_by_path(&conn, "/foo/other/foo/bar") + .unwrap() + .unwrap(); + + let _ = create_tag_path(&conn, "dest").unwrap(); + let dest = get_tag_by_path(&conn, "/dest").unwrap().unwrap(); + + let updated = move_tag(&conn, &foo.tag_uid, Some(&dest.tag_uid)) + .unwrap() + .expect("should return updated tag"); + assert_eq!(updated.full_path, "/dest/foo"); + + let other_new = get_tag_by_uid(&conn, &other.tag_uid).unwrap().unwrap(); + assert_eq!(other_new.full_path, "/dest/foo/other"); + + // /foo/other/foo must become /dest/foo/other/foo — REPLACE gives /dest/foo/other/dest/foo. + let other_foo_new = get_tag_by_uid(&conn, &other_foo.tag_uid).unwrap().unwrap(); + assert_eq!( + other_foo_new.full_path, "/dest/foo/other/foo", + "cascade must only replace the leading /foo/ prefix, not every occurrence" + ); + + let bar_new = get_tag_by_uid(&conn, &bar.tag_uid).unwrap().unwrap(); + assert_eq!(bar_new.full_path, "/dest/foo/other/foo/bar"); + } + + #[test] + fn rename_tag_cascade_only_replaces_leading_prefix() { + // Same REPLACE bug applies to rename_tag's cascade. + let conn = conn(); + let _ = create_tag_path(&conn, "foo/other/foo/bar").unwrap(); + let foo = get_tag_by_path(&conn, "/foo").unwrap().unwrap(); + let other = get_tag_by_path(&conn, "/foo/other").unwrap().unwrap(); + let other_foo = get_tag_by_path(&conn, "/foo/other/foo").unwrap().unwrap(); + let bar = get_tag_by_path(&conn, "/foo/other/foo/bar") + .unwrap() + .unwrap(); + + let updated = rename_tag(&conn, &foo.tag_uid, "renamed") + .unwrap() + .expect("should return updated tag"); + assert_eq!(updated.full_path, "/renamed"); + + let other_new = get_tag_by_uid(&conn, &other.tag_uid).unwrap().unwrap(); + assert_eq!(other_new.full_path, "/renamed/other"); + + // /foo/other/foo must become /renamed/other/foo — REPLACE gives /renamed/other/renamed. + let other_foo_new = get_tag_by_uid(&conn, &other_foo.tag_uid).unwrap().unwrap(); + assert_eq!( + other_foo_new.full_path, "/renamed/other/foo", + "cascade must only replace the leading /foo/ prefix, not every occurrence" + ); + + let bar_new = get_tag_by_uid(&conn, &bar.tag_uid).unwrap().unwrap(); + assert_eq!(bar_new.full_path, "/renamed/other/foo/bar"); + } + // ── delete_entry tests ──────────────────────────────────────────────────── /// Helper: attach a shared blob to an entry and return the blob id. @@ -3151,15 +3546,19 @@ mod tests { raw_relpath: format!("raw/{sha256}"), }; let blob_id = upsert_blob(conn, &blob).unwrap(); - add_entry_artifact(conn, &NewArtifact { - entry_id, - artifact_role: "main".to_string(), - storage_area: "raw".to_string(), - relpath: format!("raw/{sha256}"), - blob_id: Some(blob_id), - logical_path: None, - metadata_json: None, - }).unwrap(); + add_entry_artifact( + conn, + &NewArtifact { + entry_id, + artifact_role: "main".to_string(), + storage_area: "raw".to_string(), + relpath: format!("raw/{sha256}"), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); blob_id } @@ -3178,11 +3577,21 @@ mod tests { delete_entry(&conn, &root.entry_uid).unwrap(); let root_gone: Option = conn - .query_row("SELECT id FROM archived_entries WHERE id = ?1", [root.id], |r| r.get(0)) - .optional().unwrap(); + .query_row( + "SELECT id FROM archived_entries WHERE id = ?1", + [root.id], + |r| r.get(0), + ) + .optional() + .unwrap(); let child_gone: Option = conn - .query_row("SELECT id FROM archived_entries WHERE id = ?1", [child.id], |r| r.get(0)) - .optional().unwrap(); + .query_row( + "SELECT id FROM archived_entries WHERE id = ?1", + [child.id], + |r| r.get(0), + ) + .optional() + .unwrap(); assert!(root_gone.is_none(), "root should be gone"); assert!(child_gone.is_none(), "child should be gone"); } @@ -3194,8 +3603,16 @@ mod tests { let root = create_entry_fixture(&conn, "private", None, None); let run = create_archive_run(&conn, user_id, 1).unwrap(); let item = create_archive_run_item( - &conn, run.id, None, 0, "https://example.com", None, "web", "page", - ).unwrap(); + &conn, + run.id, + None, + 0, + "https://example.com", + None, + "web", + "page", + ) + .unwrap(); complete_archive_run_item(&conn, item.id, root.id).unwrap(); delete_entry(&conn, &root.entry_uid).unwrap(); @@ -3207,7 +3624,10 @@ mod tests { |r| r.get(0), ) .unwrap(); - assert!(produced.is_none(), "produced_entry_id should be NULL after delete"); + assert!( + produced.is_none(), + "produced_entry_id should be NULL after delete" + ); } #[test] @@ -3230,17 +3650,31 @@ mod tests { // Compute external.cached_bytes before delete — root and child are older by id. refresh_entry_cached_bytes(&conn, external.id).unwrap(); let before: i64 = conn - .query_row("SELECT cached_bytes FROM archived_entries WHERE id = ?1", [external.id], |r| r.get(0)) + .query_row( + "SELECT cached_bytes FROM archived_entries WHERE id = ?1", + [external.id], + |r| r.get(0), + ) .unwrap(); - assert_eq!(before, 100, "external should see blob as cached before delete"); + assert_eq!( + before, 100, + "external should see blob as cached before delete" + ); delete_entry(&conn, &root.entry_uid).unwrap(); // external must still exist but with cached_bytes = 0. let after: i64 = conn - .query_row("SELECT cached_bytes FROM archived_entries WHERE id = ?1", [external.id], |r| r.get(0)) + .query_row( + "SELECT cached_bytes FROM archived_entries WHERE id = ?1", + [external.id], + |r| r.get(0), + ) .unwrap(); - assert_eq!(after, 0, "cached_bytes must be 0 after whole subtree is deleted"); + assert_eq!( + after, 0, + "cached_bytes must be 0 after whole subtree is deleted" + ); } // ── Orphan blob cleanup ─────────────────────────────────────────────────────── @@ -3286,29 +3720,39 @@ mod tests { raw_relpath: "raw/a/a/aaa111.mp4".to_string(), }; let blob_id = upsert_blob(&conn, &blob).unwrap(); - add_entry_artifact(&conn, &NewArtifact { - entry_id: entry.id, - artifact_role: "main".to_string(), - storage_area: "raw".to_string(), - relpath: blob.raw_relpath.clone(), - blob_id: Some(blob_id), - logical_path: None, - metadata_json: None, - }).unwrap(); - assert!(list_orphaned_blob_rows(&conn).unwrap().is_empty(), - "referenced blob must not appear as orphan"); + add_entry_artifact( + &conn, + &NewArtifact { + entry_id: entry.id, + artifact_role: "main".to_string(), + storage_area: "raw".to_string(), + relpath: blob.raw_relpath.clone(), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + assert!( + list_orphaned_blob_rows(&conn).unwrap().is_empty(), + "referenced blob must not appear as orphan" + ); } #[test] fn list_orphaned_blob_rows_finds_unreferenced_blob() { let conn = conn(); - upsert_blob(&conn, &BlobRecord { - sha256: "bbb222".to_string(), - byte_size: 200, - mime_type: None, - extension: Some("jpg".to_string()), - raw_relpath: "raw/b/b/bbb222.jpg".to_string(), - }).unwrap(); + upsert_blob( + &conn, + &BlobRecord { + sha256: "bbb222".to_string(), + byte_size: 200, + mime_type: None, + extension: Some("jpg".to_string()), + raw_relpath: "raw/b/b/bbb222.jpg".to_string(), + }, + ) + .unwrap(); let orphans = list_orphaned_blob_rows(&conn).unwrap(); assert_eq!(orphans.len(), 1, "unreferenced blob must appear as orphan"); assert_eq!(orphans[0].1, "raw/b/b/bbb222.jpg"); @@ -3320,31 +3764,49 @@ mod tests { let entry = create_entry_fixture(&conn, "private", None, None); // Live blob: linked via blob_id let blob = BlobRecord { - sha256: "live1".to_string(), byte_size: 50, - mime_type: None, extension: None, + sha256: "live1".to_string(), + byte_size: 50, + mime_type: None, + extension: None, raw_relpath: "raw/l/i/live1".to_string(), }; let blob_id = upsert_blob(&conn, &blob).unwrap(); - add_entry_artifact(&conn, &NewArtifact { - entry_id: entry.id, - artifact_role: "main".to_string(), - storage_area: "raw".to_string(), - relpath: blob.raw_relpath.clone(), - blob_id: Some(blob_id), - logical_path: None, metadata_json: None, - }).unwrap(); + add_entry_artifact( + &conn, + &NewArtifact { + entry_id: entry.id, + artifact_role: "main".to_string(), + storage_area: "raw".to_string(), + relpath: blob.raw_relpath.clone(), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); // Artifact referencing a file directly (no blob_id) - add_entry_artifact(&conn, &NewArtifact { - entry_id: entry.id, - artifact_role: "sidecar".to_string(), - storage_area: "raw".to_string(), - relpath: "raw/s/i/sidecar.vtt".to_string(), - blob_id: None, - logical_path: None, metadata_json: None, - }).unwrap(); + add_entry_artifact( + &conn, + &NewArtifact { + entry_id: entry.id, + artifact_role: "sidecar".to_string(), + storage_area: "raw".to_string(), + relpath: "raw/s/i/sidecar.vtt".to_string(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); let refs = all_referenced_file_relpaths(&conn).unwrap(); - assert!(refs.contains("raw/l/i/live1"), "live blob relpath must be protected"); - assert!(refs.contains("raw/s/i/sidecar.vtt"), "direct artifact relpath must be protected"); + assert!( + refs.contains("raw/l/i/live1"), + "live blob relpath must be protected" + ); + assert!( + refs.contains("raw/s/i/sidecar.vtt"), + "direct artifact relpath must be protected" + ); } #[test] @@ -3353,29 +3815,47 @@ mod tests { let entry = create_entry_fixture(&conn, "private", None, None); // Referenced blob let live = BlobRecord { - sha256: "live9999".to_string(), byte_size: 10, - mime_type: None, extension: None, + sha256: "live9999".to_string(), + byte_size: 10, + mime_type: None, + extension: None, raw_relpath: "raw/l/v/live9999".to_string(), }; let live_id = upsert_blob(&conn, &live).unwrap(); - add_entry_artifact(&conn, &NewArtifact { - entry_id: entry.id, - artifact_role: "main".to_string(), - storage_area: "raw".to_string(), - relpath: live.raw_relpath.clone(), - blob_id: Some(live_id), - logical_path: None, metadata_json: None, - }).unwrap(); + add_entry_artifact( + &conn, + &NewArtifact { + entry_id: entry.id, + artifact_role: "main".to_string(), + storage_area: "raw".to_string(), + relpath: live.raw_relpath.clone(), + blob_id: Some(live_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); // Orphaned blob - upsert_blob(&conn, &BlobRecord { - sha256: "dead0000".to_string(), byte_size: 20, - mime_type: None, extension: None, - raw_relpath: "raw/d/e/dead0000".to_string(), - }).unwrap(); + upsert_blob( + &conn, + &BlobRecord { + sha256: "dead0000".to_string(), + byte_size: 20, + mime_type: None, + extension: None, + raw_relpath: "raw/d/e/dead0000".to_string(), + }, + ) + .unwrap(); let deleted = delete_orphaned_blob_rows(&conn).unwrap(); - assert_eq!(deleted, 1, "only the unreferenced blob row should be deleted"); - assert!(get_blob_by_sha256(&conn, "live9999").unwrap().is_some(), - "referenced blob row must be preserved"); + assert_eq!( + deleted, 1, + "only the unreferenced blob row should be deleted" + ); + assert!( + get_blob_by_sha256(&conn, "live9999").unwrap().is_some(), + "referenced blob row must be preserved" + ); } #[test] @@ -3386,26 +3866,34 @@ mod tests { let conn = conn(); let entry = create_entry_fixture(&conn, "private", None, None); let blob = BlobRecord { - sha256: "edgecase".to_string(), byte_size: 30, - mime_type: None, extension: None, + sha256: "edgecase".to_string(), + byte_size: 30, + mime_type: None, + extension: None, raw_relpath: "raw/e/d/edgecase".to_string(), }; upsert_blob(&conn, &blob).unwrap(); // artifact uses same relpath but no blob_id - add_entry_artifact(&conn, &NewArtifact { - entry_id: entry.id, - artifact_role: "sidecar".to_string(), - storage_area: "raw".to_string(), - relpath: blob.raw_relpath.clone(), - blob_id: None, - logical_path: None, metadata_json: None, - }).unwrap(); + add_entry_artifact( + &conn, + &NewArtifact { + entry_id: entry.id, + artifact_role: "sidecar".to_string(), + storage_area: "raw".to_string(), + relpath: blob.raw_relpath.clone(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); // blob row is orphaned (no blob_id reference) assert_eq!(list_orphaned_blob_rows(&conn).unwrap().len(), 1); // but the file relpath is still protected let refs = all_referenced_file_relpaths(&conn).unwrap(); - assert!(refs.contains(&blob.raw_relpath), - "file must be protected because artifact.relpath references it directly"); + assert!( + refs.contains(&blob.raw_relpath), + "file must be protected because artifact.relpath references it directly" + ); } - } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 28a86b6..3388a05 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -20,6 +20,7 @@ // GET/PATCH /api/admin/instance-settings // ──────────────────────────────────────────────────────────────────────────── +use parking_lot::Mutex; use std::{ collections::{HashMap, VecDeque}, net::{IpAddr, SocketAddr}, @@ -27,7 +28,6 @@ use std::{ sync::Arc, time::{Duration, Instant}, }; -use parking_lot::Mutex; use archivr_core::{archive, capture, database, downloader}; use axum::{ @@ -38,12 +38,12 @@ use axum::{ response::{IntoResponse, Response}, routing::{delete, get, patch, post}, }; -use tower_http::services::{ServeDir, ServeFile}; use tower::ServiceExt; +use tower_http::services::{ServeDir, ServeFile}; -use crate::registry::{MountedArchive, ServerRegistry}; use crate::auth; pub use crate::auth::{AuthUser, ROLE_ADMIN, ROLE_GUEST, ROLE_OWNER, ROLE_USER}; +use crate::registry::{MountedArchive, ServerRegistry}; use axum_extra::extract::CookieJar; use rusqlite::OptionalExtension; @@ -64,11 +64,7 @@ pub struct EntrySearchParams { } /// Tower middleware: returns 503 on all non-exempt routes if setup hasn't been completed. -async fn setup_guard( - State(state): State, - req: Request, - next: Next, -) -> Response { +async fn setup_guard(State(state): State, req: Request, next: Next) -> Response { let path = req.uri().path().to_owned(); let exempt = path.starts_with("/api/auth/") || path.starts_with("/assets") @@ -105,7 +101,9 @@ async fn security_headers(req: Request, next: Next) -> Response { ); headers.insert( axum::http::header::HeaderName::from_static("permissions-policy"), - axum::http::HeaderValue::from_static("camera=(), microphone=(), geolocation=(), autoplay=()"), + axum::http::HeaderValue::from_static( + "camera=(), microphone=(), geolocation=(), autoplay=()", + ), ); if is_artifact { // Artifact responses are iframed by the preview modal (sandboxed, no allow-scripts). @@ -149,11 +147,7 @@ async fn security_headers(req: Request, next: Next) -> Response { response } -async fn login_rate_limit( - State(state): State, - req: Request, - next: Next, -) -> Response { +async fn login_rate_limit(State(state): State, req: Request, next: Next) -> Response { if req.method() != axum::http::Method::POST || req.uri().path() != "/api/auth/login" { return next.run(req).await; } @@ -237,10 +231,15 @@ pub fn app_with_state(state: AppState) -> Router { .route("/health", get(|| async { "ok" })) .route("/api/archives", get(list_archives)) .route("/api/archives/:archive_id/entries", get(list_entries)) - .route("/api/archives/:archive_id/entries/search", get(search_entries_handler)) + .route( + "/api/archives/:archive_id/entries/search", + get(search_entries_handler), + ) .route( "/api/archives/:archive_id/entries/:entry_uid", - get(entry_detail).patch(patch_entry_handler).delete(delete_entry_handler), + get(entry_detail) + .patch(patch_entry_handler) + .delete(delete_entry_handler), ) .route( "/api/archives/:archive_id/entries/:entry_uid/artifacts/:artifact_index", @@ -254,22 +253,29 @@ pub fn app_with_state(state: AppState) -> Router { "/api/archives/:archive_id/entries/:entry_uid/favicon", get(serve_entry_favicon), ) - .route( - "/api/archives/:archive_id/blobs/:sha256", - get(serve_blob), - ) + .route("/api/archives/:archive_id/blobs/:sha256", get(serve_blob)) .route("/api/archives/:archive_id/runs", get(list_runs)) .route("/api/archives/:archive_id/captures", post(capture_handler)) - .route("/api/archives/:archive_id/captures/probe", get(probe_handler)) + .route( + "/api/archives/:archive_id/captures/probe", + get(probe_handler), + ) .route( "/api/archives/:archive_id/capture_jobs/:job_uid", get(get_capture_job_handler), ) - .route("/api/archives/:archive_id/tags", get(list_tags).post(create_tag_handler)) + .route( + "/api/archives/:archive_id/tags", + get(list_tags).post(create_tag_handler), + ) .route( "/api/archives/:archive_id/tags/:tag_uid", patch(patch_tag_handler).delete(delete_tag_handler), ) + .route( + "/api/archives/:archive_id/tags/:tag_uid/move", + post(move_tag_handler), + ) .route( "/api/archives/:archive_id/entries/:entry_uid/tags", get(list_entry_tags).post(assign_entry_tag_handler), @@ -278,17 +284,41 @@ pub fn app_with_state(state: AppState) -> Router { "/api/archives/:archive_id/entries/:entry_uid/tags/:tag_uid", delete(remove_entry_tag_handler), ) - .route("/api/auth/setup", axum::routing::get(auth_setup_status).post(auth_setup)) - .route("/api/auth/login", axum::routing::post(auth_login)) + .route( + "/api/auth/setup", + axum::routing::get(auth_setup_status).post(auth_setup), + ) + .route("/api/auth/login", axum::routing::post(auth_login)) .route("/api/auth/logout", axum::routing::post(auth_logout)) - .route("/api/auth/me", axum::routing::get(auth_me).patch(patch_me)) - .route("/api/auth/tokens", axum::routing::get(list_tokens).post(create_token)) - .route("/api/auth/tokens/:token_uid", axum::routing::delete(delete_token)) - .route("/api/admin/users", get(admin_list_users).post(admin_create_user)) - .route("/api/admin/users/:uid/status", axum::routing::patch(admin_set_user_status)) - .route("/api/admin/users/:uid/roles", axum::routing::post(admin_assign_role)) - .route("/api/admin/users/:uid/roles/:role_slug", axum::routing::delete(admin_remove_role)) - .route("/api/admin/roles", get(admin_list_roles).post(admin_create_role)) + .route("/api/auth/me", axum::routing::get(auth_me).patch(patch_me)) + .route( + "/api/auth/tokens", + axum::routing::get(list_tokens).post(create_token), + ) + .route( + "/api/auth/tokens/:token_uid", + axum::routing::delete(delete_token), + ) + .route( + "/api/admin/users", + get(admin_list_users).post(admin_create_user), + ) + .route( + "/api/admin/users/:uid/status", + axum::routing::patch(admin_set_user_status), + ) + .route( + "/api/admin/users/:uid/roles", + axum::routing::post(admin_assign_role), + ) + .route( + "/api/admin/users/:uid/roles/:role_slug", + axum::routing::delete(admin_remove_role), + ) + .route( + "/api/admin/roles", + get(admin_list_roles).post(admin_create_role), + ) .route( "/api/admin/instance-settings", get(get_instance_settings_handler).patch(update_instance_settings_handler), @@ -317,8 +347,7 @@ pub fn app_with_state(state: AppState) -> Router { ) .route( "/api/archives/:archive_id/collections/:coll_uid/entries/:entry_uid", - delete(remove_entry_from_collection_handler) - .patch(update_entry_visibility_handler), + delete(remove_entry_from_collection_handler).patch(update_entry_visibility_handler), ) .route( "/api/archives/:archive_id/entries/:entry_uid/collections", @@ -331,8 +360,14 @@ pub fn app_with_state(state: AppState) -> Router { .route("/api/util/resolve-tco", post(resolve_tco_handler)) .nest_service("/assets", ServeDir::new(static_dir.join("assets"))) .fallback_service(ServeFile::new(static_dir.join("index.html"))) - .layer(axum::middleware::from_fn_with_state(state.clone(), setup_guard)) - .layer(axum::middleware::from_fn_with_state(state.clone(), login_rate_limit)) + .layer(axum::middleware::from_fn_with_state( + state.clone(), + setup_guard, + )) + .layer(axum::middleware::from_fn_with_state( + state.clone(), + login_rate_limit, + )) .layer(axum::middleware::from_fn(security_headers)) .with_state(state) } @@ -509,7 +544,9 @@ struct CreateCollectionBody { default_visibility_bits: u32, } -fn default_user_visibility() -> u32 { 2 } +fn default_user_visibility() -> u32 { + 2 +} #[derive(Debug, serde::Deserialize)] struct AddEntryBody { @@ -638,6 +675,26 @@ async fn delete_tag_handler( } } +async fn move_tag_handler( + State(state): State, + auth_user: AuthUser, + Path((archive_id, tag_uid)): Path<(String, String)>, + Json(body): Json, +) -> Result, ApiError> { + auth_user.require_role(ROLE_USER)?; + let mounted = mounted_archive(&state, &archive_id)?; + let conn = database::open_or_initialize(&mounted.archive_path)?; + match database::move_tag(&conn, &tag_uid, body.parent_uid.as_deref())? { + Some(record) => Ok(Json(archive::Tag { + tag_uid: record.tag_uid, + name: record.name, + slug: record.slug, + full_path: record.full_path, + })), + None => Err(ApiError::not_found("tag not found")), + } +} + async fn patch_entry_handler( State(state): State, auth_user: AuthUser, @@ -647,10 +704,14 @@ async fn patch_entry_handler( auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; - let title = body.title.as_deref().map(|s| { - let t = s.trim(); - if t.is_empty() { None } else { Some(t) } - }).flatten(); + let title = body + .title + .as_deref() + .map(|s| { + let t = s.trim(); + if t.is_empty() { None } else { Some(t) } + }) + .flatten(); if database::update_entry_title(&conn, &entry_uid, title)? { Ok(StatusCode::NO_CONTENT) } else { @@ -720,6 +781,12 @@ struct PatchTagBody { name: String, } +#[derive(Debug, serde::Deserialize)] +struct MoveTagBody { + /// `None` promotes the tag to root; `Some(uid)` sets a new parent. + parent_uid: Option, +} + #[derive(Debug, serde::Deserialize)] struct CreateCookieRuleBody { url_pattern: Option, @@ -758,8 +825,8 @@ async fn capture_handler( } } let mounted = mounted_archive(&state, &archive_id)?; - let archive_paths = archive::read_archive_paths(&mounted.archive_path) - .map_err(ApiError::from)?; + let archive_paths = + archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; // Create job record in the archive DB. let conn = database::open_or_initialize(&mounted.archive_path)?; @@ -772,7 +839,10 @@ async fn capture_handler( let rules = database::list_cookie_rules(&conn).unwrap_or_default(); let settings = database::get_instance_settings(&conn); let ublock = settings.as_ref().map(|s| s.ublock_enabled).unwrap_or(true); - let cookie_ext = settings.as_ref().map(|s| s.cookie_ext_enabled).unwrap_or(true); + let cookie_ext = settings + .as_ref() + .map(|s| s.cookie_ext_enabled) + .unwrap_or(true); let modal_closer = settings.map(|s| s.modal_closer_enabled).unwrap_or(true); (rules, ublock, cookie_ext, modal_closer) } @@ -807,7 +877,13 @@ async fn capture_handler( } }; database::update_capture_job_status(&conn, &job_uid_bg, "running", None, None, None).ok(); - match capture::perform_capture(&archive_paths, &locator, Some(&archive_id_bg), quality.as_deref(), &capture_config) { + match capture::perform_capture( + &archive_paths, + &locator, + Some(&archive_id_bg), + quality.as_deref(), + &capture_config, + ) { Ok(result) => { let mut notes_map = serde_json::Map::new(); if result.ublock_skipped { @@ -882,8 +958,8 @@ async fn rearchive_handler( ) -> Result<(StatusCode, Json), ApiError> { auth_user.require_role(ROLE_USER)?; let mounted = mounted_archive(&state, &archive_id)?; - let archive_paths = archive::read_archive_paths(&mounted.archive_path) - .map_err(ApiError::from)?; + let archive_paths = + archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; // Create a capture job record so the client can poll for completion. let conn = database::open_or_initialize(&mounted.archive_path)?; @@ -918,22 +994,38 @@ async fn rearchive_handler( Ok(result) => { if result.status == "completed" { database::update_capture_job_status( - &conn, &job_uid_bg, "completed", None, None, None, - ).ok(); + &conn, + &job_uid_bg, + "completed", + None, + None, + None, + ) + .ok(); } else { // "not_a_tweet" or "scraper_failed" — surface as a job failure // so the client sees a meaningful error message. database::update_capture_job_status( - &conn, &job_uid_bg, "failed", - None, Some(&result.message), None, - ).ok(); + &conn, + &job_uid_bg, + "failed", + None, + Some(&result.message), + None, + ) + .ok(); } } Err(e) => { database::update_capture_job_status( - &conn, &job_uid_bg, "failed", - None, Some(&format!("{e:#}")), None, - ).ok(); + &conn, + &job_uid_bg, + "failed", + None, + Some(&format!("{e:#}")), + None, + ) + .ok(); } } }); @@ -974,7 +1066,9 @@ async fn probe_handler( // Resolve to a yt-dlp URL; return empty result immediately for non-video sources. let Some(ytdlp_url) = capture::locator_to_ytdlp_url(&locator) else { - return Ok(Json(serde_json::json!({ "has_video": false, "has_audio": false, "qualities": [] }))); + return Ok(Json( + serde_json::json!({ "has_video": false, "has_audio": false, "qualities": [] }), + )); }; // fetch_metadata shells out and can take several seconds — keep the async runtime free. @@ -999,7 +1093,11 @@ async fn probe_handler( message: "yt-dlp metadata fetch failed".to_string(), })?; - let qualities: Vec = result.video_heights.iter().map(|h| format!("{h}p")).collect(); + let qualities: Vec = result + .video_heights + .iter() + .map(|h| format!("{h}p")) + .collect(); Ok(Json(serde_json::json!({ "has_video": !qualities.is_empty(), "qualities": qualities, @@ -1027,16 +1125,21 @@ async fn auth_setup( }); } if body.username.trim().is_empty() || body.password.len() < 8 { - return Err(ApiError::bad_request("username required and password must be at least 8 characters")); + return Err(ApiError::bad_request( + "username required and password must be at least 8 characters", + )); } let hash = auth::hash_password(&body.password).map_err(ApiError::from)?; database::create_owner(&conn, &body.username, &hash)?; let user = database::get_user_by_username(&conn, &body.username)? .ok_or_else(|| ApiError::internal("user not found after creation"))?; - Ok((StatusCode::CREATED, Json(serde_json::json!({ - "user_uid": user.user_uid, - "username": user.username, - })))) + Ok(( + StatusCode::CREATED, + Json(serde_json::json!({ + "user_uid": user.user_uid, + "username": user.username, + })), + )) } async fn auth_login( @@ -1048,9 +1151,7 @@ async fn auth_login( let user = database::get_user_by_username(&conn, &body.username)? .filter(|u| u.status == "active") .ok_or_else(|| ApiError::unauthorized("invalid_credentials"))?; - if !auth::verify_password(&body.password, &user.password_hash) - .map_err(ApiError::from)? - { + if !auth::verify_password(&body.password, &user.password_hash).map_err(ApiError::from)? { return Err(ApiError::unauthorized("invalid_credentials")); } let role_bits = database::compute_role_bits(&conn, user.id)?; @@ -1070,14 +1171,20 @@ async fn auth_login( let mut resp_headers = axum::http::HeaderMap::new(); resp_headers.insert( axum::http::header::SET_COOKIE, - cookie_value.parse().map_err(|_| ApiError::internal("cookie error"))?, + cookie_value + .parse() + .map_err(|_| ApiError::internal("cookie error"))?, ); - Ok((StatusCode::OK, resp_headers, Json(serde_json::json!({ - "user_uid": user.user_uid, - "username": user.username, - "role_bits": role_bits, - })))) + Ok(( + StatusCode::OK, + resp_headers, + Json(serde_json::json!({ + "user_uid": user.user_uid, + "username": user.username, + "role_bits": role_bits, + })), + )) } async fn auth_logout( @@ -1108,7 +1215,7 @@ async fn auth_me( .query_row( "SELECT username, display_name, COALESCE(humanize_slugs, 0) FROM users WHERE id = ?1", [user_id], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)) + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), ) .map_err(|e| ApiError::from(anyhow::anyhow!("db error: {e}")))?; let humanize_slugs = humanize_slugs_int != 0; @@ -1143,7 +1250,11 @@ async fn patch_me( } if let Some(ref dn) = body.display_name { - let v: Option<&str> = if dn.trim().is_empty() { None } else { Some(dn.as_str()) }; + let v: Option<&str> = if dn.trim().is_empty() { + None + } else { + Some(dn.as_str()) + }; database::update_user_display_name(&conn, user_id, v)?; } @@ -1173,8 +1284,14 @@ async fn get_instance_settings_handler( .unwrap_or(false); let mut val = serde_json::to_value(&settings).unwrap_or_default(); if let Some(obj) = val.as_object_mut() { - obj.insert("ublock_ext_available".into(), serde_json::Value::Bool(ublock_ext_available)); - obj.insert("cookie_ext_available".into(), serde_json::Value::Bool(cookie_ext_available)); + obj.insert( + "ublock_ext_available".into(), + serde_json::Value::Bool(ublock_ext_available), + ); + obj.insert( + "cookie_ext_available".into(), + serde_json::Value::Bool(cookie_ext_available), + ); } Ok(Json(val)) } @@ -1187,13 +1304,27 @@ async fn update_instance_settings_handler( auth_user.require_role(ROLE_ADMIN)?; let conn = database::open_auth_db(&state.auth_db_path)?; let mut settings = database::get_instance_settings(&conn)?; - if let Some(v) = body.public_index_enabled { settings.public_index_enabled = v; } - if let Some(v) = body.public_entry_content_enabled { settings.public_entry_content_enabled = v; } - if let Some(v) = body.open_registration_enabled { settings.open_registration_enabled = v; } - if let Some(v) = body.default_entry_visibility { settings.default_entry_visibility = v; } - if let Some(v) = body.ublock_enabled { settings.ublock_enabled = v; } - if let Some(v) = body.cookie_ext_enabled { settings.cookie_ext_enabled = v; } - if let Some(v) = body.modal_closer_enabled { settings.modal_closer_enabled = v; } + if let Some(v) = body.public_index_enabled { + settings.public_index_enabled = v; + } + if let Some(v) = body.public_entry_content_enabled { + settings.public_entry_content_enabled = v; + } + if let Some(v) = body.open_registration_enabled { + settings.open_registration_enabled = v; + } + if let Some(v) = body.default_entry_visibility { + settings.default_entry_visibility = v; + } + if let Some(v) = body.ublock_enabled { + settings.ublock_enabled = v; + } + if let Some(v) = body.cookie_ext_enabled { + settings.cookie_ext_enabled = v; + } + if let Some(v) = body.modal_closer_enabled { + settings.modal_closer_enabled = v; + } database::update_instance_settings(&conn, &settings)?; Ok(StatusCode::NO_CONTENT) } @@ -1220,13 +1351,14 @@ async fn create_cookie_rule_handler( "pattern_kind must be 'global', 'wildcard', or 'regex'", )); } - if serde_json::from_str::>(&body.cookies_json).is_err() { + if serde_json::from_str::>(&body.cookies_json) + .is_err() + { return Err(ApiError::bad_request( "cookies_json must be a JSON object whose values are all strings, e.g. {\"name\": \"value\"}", )); } - if body.pattern_kind != "global" - && body.url_pattern.as_deref().unwrap_or("").trim().is_empty() + if body.pattern_kind != "global" && body.url_pattern.as_deref().unwrap_or("").trim().is_empty() { return Err(ApiError::bad_request( "url_pattern is required for non-global rules", @@ -1239,11 +1371,9 @@ async fn create_cookie_rule_handler( } } let conn = database::open_auth_db(&state.auth_db_path)?; - let url_pattern = body - .url_pattern - .as_deref() - .filter(|s| !s.trim().is_empty()); - let rule = database::create_cookie_rule(&conn, url_pattern, &body.pattern_kind, &body.cookies_json)?; + let url_pattern = body.url_pattern.as_deref().filter(|s| !s.trim().is_empty()); + let rule = + database::create_cookie_rule(&conn, url_pattern, &body.pattern_kind, &body.cookies_json)?; Ok((StatusCode::CREATED, Json(rule))) } @@ -1386,7 +1516,6 @@ async fn blob_cleanup_delete_handler( )); } - // Delete orphaned blob rows from the database. let deleted_blob_rows = database::delete_orphaned_blob_rows(&conn)?; @@ -1406,7 +1535,11 @@ async fn blob_cleanup_delete_handler( eprintln!( "info: blob cleanup for '{}': {} blob rows, {} files deleted, {} bytes freed, {} errors", - archive_id, deleted_blob_rows, deleted_files, freed_bytes, errors.len() + archive_id, + deleted_blob_rows, + deleted_files, + freed_bytes, + errors.len() ); Ok(Json(serde_json::json!({ @@ -1467,11 +1600,14 @@ async fn create_token( let token_hash = auth::hash_token(&raw_token); let conn = database::open_auth_db(&state.auth_db_path)?; let token_uid = database::create_api_token(&conn, user_id, &token_hash, &body.name)?; - Ok((StatusCode::CREATED, Json(serde_json::json!({ - "token_uid": token_uid, - "raw_token": raw_token, - "name": body.name, - })))) + Ok(( + StatusCode::CREATED, + Json(serde_json::json!({ + "token_uid": token_uid, + "raw_token": raw_token, + "name": body.name, + })), + )) } async fn list_tokens( @@ -1498,16 +1634,27 @@ async fn delete_token( } #[derive(Debug, serde::Deserialize)] -struct AdminCreateUserBody { username: String, password: String, email: Option } +struct AdminCreateUserBody { + username: String, + password: String, + email: Option, +} #[derive(Debug, serde::Deserialize)] -struct AdminSetStatusBody { status: String } +struct AdminSetStatusBody { + status: String, +} #[derive(Debug, serde::Deserialize)] -struct AdminAssignRoleBody { role_slug: String } +struct AdminAssignRoleBody { + role_slug: String, +} #[derive(Debug, serde::Deserialize)] -struct AdminCreateRoleBody { slug: String, name: String } +struct AdminCreateRoleBody { + slug: String, + name: String, +} #[derive(Debug, serde::Deserialize)] struct UpdateProfileBody { @@ -1545,12 +1692,23 @@ async fn admin_create_user( auth_user.require_role(ROLE_ADMIN)?; let (caller_id, _) = auth_user.require_auth()?; if body.username.trim().is_empty() || body.password.len() < 8 { - return Err(ApiError::bad_request("username required, password >= 8 chars")); + return Err(ApiError::bad_request( + "username required, password >= 8 chars", + )); } let conn = database::open_auth_db(&state.auth_db_path)?; let hash = auth::hash_password(&body.password).map_err(ApiError::from)?; - let uid = database::create_user(&conn, &body.username, body.email.as_deref(), &hash, caller_id)?; - Ok((StatusCode::CREATED, Json(serde_json::json!({ "user_uid": uid, "username": body.username })))) + let uid = database::create_user( + &conn, + &body.username, + body.email.as_deref(), + &hash, + caller_id, + )?; + Ok(( + StatusCode::CREATED, + Json(serde_json::json!({ "user_uid": uid, "username": body.username })), + )) } async fn admin_set_user_status( @@ -1561,13 +1719,17 @@ async fn admin_set_user_status( ) -> Result, ApiError> { auth_user.require_role(ROLE_ADMIN)?; if body.status != "active" && body.status != "disabled" { - return Err(ApiError::bad_request("status must be 'active' or 'disabled'")); + return Err(ApiError::bad_request( + "status must be 'active' or 'disabled'", + )); } let conn = database::open_auth_db(&state.auth_db_path)?; if !database::set_user_status(&conn, &uid, &body.status)? { return Err(ApiError::not_found("user not found")); } - Ok(Json(serde_json::json!({ "user_uid": uid, "status": body.status }))) + Ok(Json( + serde_json::json!({ "user_uid": uid, "status": body.status }), + )) } async fn admin_assign_role( @@ -1614,8 +1776,8 @@ async fn admin_create_role( ) -> Result<(StatusCode, Json), ApiError> { auth_user.require_role(ROLE_ADMIN)?; let conn = database::open_auth_db(&state.auth_db_path)?; - let role = database::create_custom_role(&conn, &body.slug, &body.name) - .map_err(ApiError::from)?; + let role = + database::create_custom_role(&conn, &body.slug, &body.name).map_err(ApiError::from)?; Ok((StatusCode::CREATED, Json(role))) } @@ -1667,15 +1829,24 @@ impl ApiError { } pub fn unauthorized(message: &str) -> Self { - Self { status: StatusCode::UNAUTHORIZED, message: message.to_string() } + Self { + status: StatusCode::UNAUTHORIZED, + message: message.to_string(), + } } pub fn forbidden(message: &str) -> Self { - Self { status: StatusCode::FORBIDDEN, message: message.to_string() } + Self { + status: StatusCode::FORBIDDEN, + message: message.to_string(), + } } fn conflict(message: &str) -> Self { - Self { status: StatusCode::CONFLICT, message: message.to_string() } + Self { + status: StatusCode::CONFLICT, + message: message.to_string(), + } } } @@ -1723,19 +1894,25 @@ async fn create_collection_handler( return Err(ApiError::bad_request("collection name must not be empty")); } if body.slug.trim().is_empty() || body.slug.starts_with('_') { - return Err(ApiError::bad_request("collection slug must not be empty or start with underscore")); + return Err(ApiError::bad_request( + "collection slug must not be empty or start with underscore", + )); } let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; - let record = database::create_collection(&conn, &body.name, &body.slug, body.default_visibility_bits) - .map_err(|e| ApiError::bad_request(&format!("{e:#}")))?; - Ok((StatusCode::CREATED, Json(archive::CollectionSummary { - collection_uid: record.collection_uid, - name: record.name, - slug: record.slug, - default_visibility_bits: record.default_visibility_bits, - created_at: record.created_at, - }))) + let record = + database::create_collection(&conn, &body.name, &body.slug, body.default_visibility_bits) + .map_err(|e| ApiError::bad_request(&format!("{e:#}")))?; + Ok(( + StatusCode::CREATED, + Json(archive::CollectionSummary { + collection_uid: record.collection_uid, + name: record.name, + slug: record.slug, + default_visibility_bits: record.default_visibility_bits, + created_at: record.created_at, + }), + )) } async fn get_collection_handler( @@ -1768,16 +1945,22 @@ async fn get_collection_handler( } } } - let entries_json: Vec = entries.iter().map(|e| { - let vis = vis_map.get(&e.entry_uid).copied().unwrap_or(record.default_visibility_bits); - serde_json::json!({ - "entry_uid": e.entry_uid, - "title": e.title, - "source_kind": e.source_kind, - "archived_at": e.archived_at, - "collection_visibility_bits": vis, + let entries_json: Vec = entries + .iter() + .map(|e| { + let vis = vis_map + .get(&e.entry_uid) + .copied() + .unwrap_or(record.default_visibility_bits); + serde_json::json!({ + "entry_uid": e.entry_uid, + "title": e.title, + "source_kind": e.source_kind, + "archived_at": e.archived_at, + "collection_visibility_bits": vis, + }) }) - }).collect(); + .collect(); Ok(Json(serde_json::json!({ "collection_uid": record.collection_uid, "name": record.name, @@ -1800,7 +1983,9 @@ async fn add_entry_to_collection_handler( let coll = database::get_collection_by_uid(&conn, &coll_uid)? .ok_or(ApiError::not_found("collection not found"))?; if coll.slug == "_default_" { - return Err(ApiError::bad_request("cannot manually add entries to the default collection")); + return Err(ApiError::bad_request( + "cannot manually add entries to the default collection", + )); } let entry_id: i64 = conn .query_row( @@ -1825,7 +2010,9 @@ async fn remove_entry_from_collection_handler( let coll = database::get_collection_by_uid(&conn, &coll_uid)? .ok_or(ApiError::not_found("collection not found"))?; if coll.slug == "_default_" { - return Err(ApiError::bad_request("cannot manually remove entries from the default collection")); + return Err(ApiError::bad_request( + "cannot manually remove entries from the default collection", + )); } let entry_id: i64 = conn .query_row( @@ -1861,7 +2048,8 @@ async fn update_entry_visibility_handler( ) .optional()? .ok_or(ApiError::not_found("entry not found"))?; - if database::update_collection_entry_visibility(&conn, coll.id, entry_id, body.visibility_bits)? { + if database::update_collection_entry_visibility(&conn, coll.id, entry_id, body.visibility_bits)? + { Ok(StatusCode::NO_CONTENT) } else { Err(ApiError::not_found("entry not in collection")) @@ -1892,7 +2080,8 @@ async fn patch_collection_handler( let mounted = mounted_archive(&state, &archive_id)?; let conn = database::open_or_initialize(&mounted.archive_path)?; let name_ref: Option<&str> = body.name.as_deref(); - let updated = database::update_collection(&conn, &coll_uid, name_ref, body.default_visibility_bits)?; + let updated = + database::update_collection(&conn, &coll_uid, name_ref, body.default_visibility_bits)?; if updated { Ok(StatusCode::NO_CONTENT) } else { @@ -1928,9 +2117,8 @@ async fn delete_collection_handler( // - 3 s timeout, 1-hop max. // - No auth required (t.co is public; no data exposed). -static TCO_RE: std::sync::LazyLock = std::sync::LazyLock::new(|| { - regex::Regex::new(r"^https://t\.co/[A-Za-z0-9]+$").unwrap() -}); +static TCO_RE: std::sync::LazyLock = + std::sync::LazyLock::new(|| regex::Regex::new(r"^https://t\.co/[A-Za-z0-9]+$").unwrap()); async fn resolve_tco_handler( Json(urls): Json>, @@ -1949,31 +2137,34 @@ async fn resolve_tco_handler( .map_err(|e| ApiError::internal(&format!("http client: {e}")))?; let mut map = std::collections::HashMap::new(); - let futs: Vec<_> = urls.iter().map(|url| { - let client = client.clone(); - let url = url.clone(); - tokio::spawn(async move { - // Try HEAD first; fall back to GET if HEAD returns no Location. - // Neither follows redirects (Policy::none), so the server only - // ever connects to t.co itself — never to the destination. - // Only accept http/https destinations — never javascript:, data:, etc. - let safe_location = |resp: reqwest::Response| { - resp.headers() - .get(reqwest::header::LOCATION) - .and_then(|v| v.to_str().ok()) - .map(|s| s.to_string()) - .filter(|s| s.starts_with("http://") || s.starts_with("https://")) - }; - let expanded = match client.head(&url).send().await.ok().and_then(safe_location) { - Some(loc) => loc, - None => match client.get(&url).send().await.ok().and_then(safe_location) { + let futs: Vec<_> = urls + .iter() + .map(|url| { + let client = client.clone(); + let url = url.clone(); + tokio::spawn(async move { + // Try HEAD first; fall back to GET if HEAD returns no Location. + // Neither follows redirects (Policy::none), so the server only + // ever connects to t.co itself — never to the destination. + // Only accept http/https destinations — never javascript:, data:, etc. + let safe_location = |resp: reqwest::Response| { + resp.headers() + .get(reqwest::header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(|s| s.to_string()) + .filter(|s| s.starts_with("http://") || s.starts_with("https://")) + }; + let expanded = match client.head(&url).send().await.ok().and_then(safe_location) { Some(loc) => loc, - None => url.clone(), - }, - }; - (url, expanded) + None => match client.get(&url).send().await.ok().and_then(safe_location) { + Some(loc) => loc, + None => url.clone(), + }, + }; + (url, expanded) + }) }) - }).collect(); + .collect(); for fut in futs { if let Ok((k, v)) = fut.await { @@ -1999,7 +2190,11 @@ mod tests { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "test_hash_not_real").unwrap(); } - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; (app(registry, auth_path), dir) } @@ -2007,17 +2202,24 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let auth_path = dir.path().join("auth.sqlite"); // NO owner seeded - for testing setup-required behavior - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; (app(registry, auth_path), dir) } - fn make_test_registry(dir: &tempfile::TempDir) -> (ServerRegistry, std::path::PathBuf, std::path::PathBuf) { + fn make_test_registry( + dir: &tempfile::TempDir, + ) -> (ServerRegistry, std::path::PathBuf, std::path::PathBuf) { let paths = archivr_core::archive::initialize_archive( dir.path(), &dir.path().join("store"), "test", false, - ).unwrap(); + ) + .unwrap(); let auth_path = dir.path().join("auth.sqlite"); { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); @@ -2039,7 +2241,11 @@ mod tests { fn make_test_session(auth_path: &std::path::Path) -> String { let conn = archivr_core::database::open_auth_db(auth_path).unwrap(); let user_id: i64 = conn - .query_row("SELECT id FROM users WHERE username = 'testowner'", [], |r| r.get(0)) + .query_row( + "SELECT id FROM users WHERE username = 'testowner'", + [], + |r| r.get(0), + ) .unwrap(); let role_bits = archivr_core::database::compute_role_bits(&conn, user_id).unwrap(); let sess_uid = @@ -2052,7 +2258,10 @@ mod tests { let user_id = database::ensure_default_user(&conn).unwrap(); let run = database::create_archive_run(&conn, user_id, 1).unwrap(); let si = database::upsert_source_identity( - &conn, "web", "page", None, + &conn, + "web", + "page", + None, Some("https://example.com/test"), "https://example.com/test", ) @@ -2123,12 +2332,26 @@ mod tests { async fn missing_archive_returns_404() { let dir = tempfile::tempdir().unwrap(); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/missing/entries").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/missing/entries") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); } @@ -2136,12 +2359,26 @@ mod tests { async fn artifact_missing_archive_returns_404() { let dir = tempfile::tempdir().unwrap(); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/nope/entries/entry_abc/artifacts/0").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/nope/entries/entry_abc/artifacts/0") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); } @@ -2311,12 +2548,15 @@ mod tests { bind: None, auth_db_path: None, }; - let uri = format!( - "/api/archives/test/entries/{}/artifacts/0", - entry.entry_uid - ); + let uri = format!("/api/archives/test/entries/{}/artifacts/0", entry.entry_uid); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); @@ -2326,12 +2566,26 @@ mod tests { async fn search_missing_archive_returns_404() { let dir = tempfile::tempdir().unwrap(); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/nope/entries/search?q=anything").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/nope/entries/search?q=anything") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); } @@ -2341,8 +2595,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/search").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/search") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -2352,8 +2613,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/search?q=unknownprefix%3Aval").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/search?q=unknownprefix%3Aval") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); } @@ -2363,12 +2631,26 @@ mod tests { async fn test_list_tags_unknown_archive() { let dir = tempfile::tempdir().unwrap(); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/ghost/tags").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/ghost/tags") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); } @@ -2444,7 +2726,10 @@ mod tests { .iter() .map(|n| n["tag"]["slug"].as_str().unwrap()) .collect(); - assert!(slugs.contains(&"science"), "expected 'science' in tag tree, got {slugs:?}"); + assert!( + slugs.contains(&"science"), + "expected 'science' in tag tree, got {slugs:?}" + ); } #[tokio::test] @@ -2516,7 +2801,10 @@ mod tests { .unwrap(); assert_eq!(list2_response.status(), StatusCode::OK); let tags2 = body_json(list2_response).await; - assert!(tags2.as_array().unwrap().is_empty(), "tags should be empty after removal"); + assert!( + tags2.as_array().unwrap().is_empty(), + "tags should be empty after removal" + ); } #[tokio::test] @@ -2540,7 +2828,11 @@ mod tests { ) .await .unwrap(); - assert_eq!(assign_resp.status(), StatusCode::CREATED, "assign tag should return 201"); + assert_eq!( + assign_resp.status(), + StatusCode::CREATED, + "assign tag should return 201" + ); // Search with ?tag=/science — entry should appear (requires auth since entry is private) let response = app(registry.clone(), auth_path.clone()) @@ -2587,8 +2879,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/ghost_uid/tags").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/ghost_uid/tags") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); } @@ -2724,10 +3023,18 @@ mod tests { async fn setup_required_before_owner_created() { let (test_app, _dir) = make_setup_test_app(); let response = test_app - .oneshot(Request::builder().uri("/api/auth/setup").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/auth/setup") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(json["setup_required"], true); } @@ -2741,14 +3048,23 @@ mod tests { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "owner", "dummy").unwrap(); } - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; let second_app = app(registry, auth_path); let r2 = second_app - .oneshot(Request::builder().method("POST").uri("/api/auth/setup") - .header("content-type", "application/json") - .body(Body::from(r#"{"username":"owner2","password":"hunter2!"}"#)) - .unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .method("POST") + .uri("/api/auth/setup") + .header("content-type", "application/json") + .body(Body::from(r#"{"username":"owner2","password":"hunter2!"}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(r2.status(), StatusCode::CONFLICT); } @@ -2761,13 +3077,22 @@ mod tests { let hash = crate::auth::hash_password("correct_password").unwrap(); archivr_core::database::create_owner(&conn, "owner", &hash).unwrap(); } - let registry = ServerRegistry { archives: vec![], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }; let response = app(registry, auth_path) - .oneshot(Request::builder().method("POST").uri("/api/auth/login") - .header("content-type", "application/json") - .body(Body::from(r#"{"username":"owner","password":"wrong"}"#)) - .unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .method("POST") + .uri("/api/auth/login") + .header("content-type", "application/json") + .body(Body::from(r#"{"username":"owner","password":"wrong"}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -2775,11 +3100,16 @@ mod tests { async fn create_token_requires_auth() { let (test_app, _dir) = make_test_app(); let response = test_app - .oneshot(Request::builder().method("POST").uri("/api/auth/tokens") - .header("content-type", "application/json") - .body(Body::from(r#"{"name":"my token"}"#)) - .unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .method("POST") + .uri("/api/auth/tokens") + .header("content-type", "application/json") + .body(Body::from(r#"{"name":"my token"}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -2787,16 +3117,19 @@ mod tests { async fn capture_returns_401_for_unauthenticated() { let (test_app, _dir) = make_test_app(); let response = test_app - .oneshot(Request::builder().method("POST") - .uri("/api/archives/test/captures") - .header("content-type", "application/json") - .body(Body::from(r#"{"locator":"https://example.com"}"#)) - .unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures") + .header("content-type", "application/json") + .body(Body::from(r#"{"locator":"https://example.com"}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } - #[tokio::test] async fn capture_post_returns_accepted_with_job_uid() { let dir = tempfile::tempdir().unwrap(); @@ -2815,9 +3148,14 @@ mod tests { .await .unwrap(); assert_eq!(response.status(), StatusCode::ACCEPTED); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert!(json["job_uid"].as_str().is_some(), "response must have job_uid"); + assert!( + json["job_uid"].as_str().is_some(), + "response must have job_uid" + ); assert_eq!(json["status"], "pending"); } @@ -2833,15 +3171,22 @@ mod tests { .uri("/api/archives/test/captures") .header("content-type", "application/json") .header("cookie", &session_cookie) - .body(Body::from(r#"{"locator":"local:/nonexistent","quality":"720p"}"#)) + .body(Body::from( + r#"{"locator":"local:/nonexistent","quality":"720p"}"#, + )) .unwrap(), ) .await .unwrap(); assert_eq!(response.status(), StatusCode::ACCEPTED); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert!(json["job_uid"].as_str().is_some(), "response must have job_uid"); + assert!( + json["job_uid"].as_str().is_some(), + "response must have job_uid" + ); assert_eq!(json["status"], "pending"); } @@ -2857,15 +3202,23 @@ mod tests { .uri("/api/archives/test/captures") .header("content-type", "application/json") .header("cookie", &session_cookie) - .body(Body::from(r#"{"locator":"local:/nonexistent","quality":"4K"}"#)) + .body(Body::from( + r#"{"locator":"local:/nonexistent","quality":"4K"}"#, + )) .unwrap(), ) .await .unwrap(); assert_eq!(response.status(), StatusCode::BAD_REQUEST); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert!(json["error"].as_str().is_some_and(|e| e.contains("invalid quality"))); + assert!( + json["error"] + .as_str() + .is_some_and(|e| e.contains("invalid quality")) + ); } #[tokio::test] @@ -2901,7 +3254,9 @@ mod tests { .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(json["has_video"], false); assert_eq!(json["qualities"], serde_json::json!([])); @@ -2911,9 +3266,15 @@ mod tests { #[tokio::test] async fn admin_users_requires_admin_role() { let (test_app, _dir) = make_test_app(); - let response = test_app.oneshot( - Request::builder().uri("/api/admin/users").body(Body::empty()).unwrap() - ).await.unwrap(); + let response = test_app + .oneshot( + Request::builder() + .uri("/api/admin/users") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -2922,11 +3283,16 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); - let response = app(registry, auth_path).oneshot( - Request::builder().uri("/api/admin/users") - .header("cookie", &session_cookie) - .body(Body::empty()).unwrap() - ).await.unwrap(); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .uri("/api/admin/users") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -2935,15 +3301,25 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); - let response = app(registry, auth_path).oneshot( - Request::builder().uri("/api/auth/me") - .header("cookie", &session_cookie) - .body(Body::empty()).unwrap() - ).await.unwrap(); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .uri("/api/auth/me") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); - assert!(json.get("display_name").is_some(), "auth/me must include display_name field"); + assert!( + json.get("display_name").is_some(), + "auth/me must include display_name field" + ); assert!(json.get("username").is_some()); } @@ -2952,25 +3328,35 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); - let response = app(registry, auth_path).oneshot( - Request::builder().method("PATCH").uri("/api/auth/me") - .header("content-type", "application/json") - .header("cookie", &session_cookie) - .body(Body::from(r#"{"display_name":"Test Owner"}"#)) - .unwrap() - ).await.unwrap(); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("PATCH") + .uri("/api/auth/me") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(r#"{"display_name":"Test Owner"}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NO_CONTENT); } #[tokio::test] async fn patch_me_requires_auth() { let (test_app, _dir) = make_test_app(); - let response = test_app.oneshot( - Request::builder().method("PATCH").uri("/api/auth/me") - .header("content-type", "application/json") - .body(Body::from(r#"{"display_name":"anon"}"#)) - .unwrap() - ).await.unwrap(); + let response = test_app + .oneshot( + Request::builder() + .method("PATCH") + .uri("/api/auth/me") + .header("content-type", "application/json") + .body(Body::from(r#"{"display_name":"anon"}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -2982,29 +3368,45 @@ mod tests { { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); let hash = crate::auth::hash_password("real_password").unwrap(); - let user_id: i64 = conn.query_row( - "SELECT id FROM users WHERE username = 'testowner'", [], |r| r.get(0) - ).unwrap(); + let user_id: i64 = conn + .query_row( + "SELECT id FROM users WHERE username = 'testowner'", + [], + |r| r.get(0), + ) + .unwrap(); archivr_core::database::update_user_password(&conn, user_id, &hash).unwrap(); } let session_cookie = make_test_session(&auth_path); - let response = app(registry, auth_path).oneshot( - Request::builder().method("PATCH").uri("/api/auth/me") - .header("content-type", "application/json") - .header("cookie", &session_cookie) - .body(Body::from(r#"{"current_password":"wrong","new_password":"newpass"}"#)) - .unwrap() - ).await.unwrap(); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("PATCH") + .uri("/api/auth/me") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from( + r#"{"current_password":"wrong","new_password":"newpass"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } #[tokio::test] async fn instance_settings_requires_admin() { let (test_app, _dir) = make_test_app(); - let response = test_app.oneshot( - Request::builder().uri("/api/admin/instance-settings") - .body(Body::empty()).unwrap() - ).await.unwrap(); + let response = test_app + .oneshot( + Request::builder() + .uri("/api/admin/instance-settings") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3013,13 +3415,20 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); - let response = app(registry, auth_path).oneshot( - Request::builder().uri("/api/admin/instance-settings") - .header("cookie", &session_cookie) - .body(Body::empty()).unwrap() - ).await.unwrap(); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .uri("/api/admin/instance-settings") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); assert_eq!(json["public_index_enabled"], false); assert_eq!(json["open_registration_enabled"], false); @@ -3030,13 +3439,18 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); - let response = app(registry, auth_path).oneshot( - Request::builder().method("PATCH").uri("/api/admin/instance-settings") - .header("content-type", "application/json") - .header("cookie", &session_cookie) - .body(Body::from(r#"{"open_registration_enabled":true}"#)) - .unwrap() - ).await.unwrap(); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("PATCH") + .uri("/api/admin/instance-settings") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(r#"{"open_registration_enabled":true}"#)) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::NO_CONTENT); } #[tokio::test] @@ -3044,7 +3458,12 @@ mod tests { // Non-admin (no session) should get 401. let (test_app, _dir) = make_test_app(); let response = test_app - .oneshot(Request::builder().uri("/api/admin/cookie-rules").body(Body::empty()).unwrap()) + .oneshot( + Request::builder() + .uri("/api/admin/cookie-rules") + .body(Body::empty()) + .unwrap(), + ) .await .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); @@ -3067,15 +3486,20 @@ mod tests { .uri("/api/admin/cookie-rules") .header("content-type", "application/json") .header("cookie", &session) - .body(Body::from(r#"{"pattern_kind":"global","cookies_json":"{\"session\":\"abc\"}"}"#)) + .body(Body::from( + r#"{"pattern_kind":"global","cookies_json":"{\"session\":\"abc\"}"}"#, + )) .unwrap(), ) .await .unwrap(); assert_eq!(create_resp.status(), StatusCode::CREATED); let body: serde_json::Value = serde_json::from_slice( - &axum::body::to_bytes(create_resp.into_body(), usize::MAX).await.unwrap(), - ).unwrap(); + &axum::body::to_bytes(create_resp.into_body(), usize::MAX) + .await + .unwrap(), + ) + .unwrap(); let rule_uid = body["rule_uid"].as_str().unwrap().to_string(); assert_eq!(body["pattern_kind"], "global"); @@ -3093,8 +3517,11 @@ mod tests { .unwrap(); assert_eq!(list_resp.status(), StatusCode::OK); let list: serde_json::Value = serde_json::from_slice( - &axum::body::to_bytes(list_resp.into_body(), usize::MAX).await.unwrap(), - ).unwrap(); + &axum::body::to_bytes(list_resp.into_body(), usize::MAX) + .await + .unwrap(), + ) + .unwrap(); assert_eq!(list.as_array().unwrap().len(), 1); // Delete. @@ -3127,7 +3554,9 @@ mod tests { .uri("/api/admin/cookie-rules") .header("content-type", "application/json") .header("cookie", &session) - .body(Body::from(r#"{"pattern_kind":"global","cookies_json":"{\"session\":123}"}"#)) + .body(Body::from( + r#"{"pattern_kind":"global","cookies_json":"{\"session\":123}"}"#, + )) .unwrap(), ) .await @@ -3172,10 +3601,7 @@ mod tests { response.headers().get("x-content-type-options").unwrap(), "nosniff" ); - assert_eq!( - response.headers().get("x-frame-options").unwrap(), - "DENY" - ); + assert_eq!(response.headers().get("x-frame-options").unwrap(), "DENY"); assert_eq!( response.headers().get("referrer-policy").unwrap(), "strict-origin-when-cross-origin" @@ -3241,7 +3667,11 @@ mod tests { ) .await .unwrap(); - assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "attempt within limit should reach handler"); + assert_eq!( + resp.status(), + StatusCode::UNAUTHORIZED, + "attempt within limit should reach handler" + ); } let resp = app_with_state(state) .oneshot( @@ -3255,8 +3685,15 @@ mod tests { ) .await .unwrap(); - assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS, "attempt over limit must be 429"); - assert!(resp.headers().contains_key("retry-after"), "429 must carry Retry-After header"); + assert_eq!( + resp.status(), + StatusCode::TOO_MANY_REQUESTS, + "attempt over limit must be 429" + ); + assert!( + resp.headers().contains_key("retry-after"), + "429 must carry Retry-After header" + ); let body = body_json(resp).await; assert_eq!(body["error"], "rate_limited"); assert!(body["retry_after_secs"].as_i64().unwrap() > 0); @@ -3271,7 +3708,11 @@ mod tests { archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } let state = AppState { - registry: Arc::new(ServerRegistry { archives: vec![], bind: None, auth_db_path: None }), + registry: Arc::new(ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }), auth_db_path: Arc::new(auth_path), login_attempts: Arc::new(Mutex::new(HashMap::new())), }; @@ -3291,7 +3732,12 @@ mod tests { .unwrap(); } let resp = app_with_state(state) - .oneshot(Request::builder().uri("/health").body(Body::empty()).unwrap()) + .oneshot( + Request::builder() + .uri("/health") + .body(Body::empty()) + .unwrap(), + ) .await .unwrap(); assert_eq!(resp.status(), StatusCode::OK, "/health must be unaffected"); @@ -3304,8 +3750,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/fake_uid").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/fake_uid") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3317,8 +3769,15 @@ mod tests { let session_cookie = make_test_session(&auth_path); let uri = format!("/api/archives/test/entries/{}", entry.entry_uid); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3327,8 +3786,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/runs").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/runs") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3338,8 +3803,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/runs").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/runs") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3348,8 +3820,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/fake_uid/artifacts/0").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/fake_uid/artifacts/0") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3357,41 +3835,96 @@ mod tests { async fn serve_artifact_with_auth_returns_ok() { let dir = tempfile::tempdir().unwrap(); let store_path = dir.path().join("store"); - let paths = archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false).unwrap(); + let paths = + archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false) + .unwrap(); let artifact_relpath = "raw/a/u/page.html"; let artifact_dir = store_path.join("raw").join("a").join("u"); std::fs::create_dir_all(&artifact_dir).unwrap(); std::fs::write(artifact_dir.join("page.html"), b"auth test").unwrap(); let conn = database::open_or_initialize(&paths.archive_path).unwrap(); let user_id = database::ensure_default_user(&conn).unwrap(); - let sid = database::upsert_source_identity(&conn, "web", "page", Some("auth-page"), Some("https://example.com/auth"), "https://example.com/auth").unwrap(); + let sid = database::upsert_source_identity( + &conn, + "web", + "page", + Some("auth-page"), + Some("https://example.com/auth"), + "https://example.com/auth", + ) + .unwrap(); let run = database::create_archive_run(&conn, user_id, 1).unwrap(); - let entry = database::create_archived_entry(&conn, &database::NewEntry { - source_identity_id: sid, archive_run_id: run.id, parent_entry_id: None, root_entry_id: None, - created_by_user_id: user_id, owned_by_user_id: user_id, - source_kind: "web".to_string(), entity_kind: "page".to_string(), - title: Some("Auth Test Page".to_string()), visibility: "private".to_string(), - representation_kind: "html".to_string(), source_metadata_json: "{}".to_string(), display_metadata_json: None, - }).unwrap(); - let blob_id = database::upsert_blob(&conn, &database::BlobRecord { - sha256: "aaaa1111bbbb2222cccc3333dddd4444aaaa1111bbbb2222cccc3333dddd4444".to_string(), - byte_size: 21, mime_type: Some("text/html".to_string()), extension: Some("html".to_string()), - raw_relpath: artifact_relpath.to_string(), - }).unwrap(); - database::add_entry_artifact(&conn, &database::NewArtifact { - entry_id: entry.id, artifact_role: "primary_media".to_string(), - storage_area: "raw".to_string(), relpath: artifact_relpath.to_string(), - blob_id: Some(blob_id), logical_path: None, metadata_json: None, - }).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: sid, + archive_run_id: run.id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: user_id, + owned_by_user_id: user_id, + source_kind: "web".to_string(), + entity_kind: "page".to_string(), + title: Some("Auth Test Page".to_string()), + visibility: "private".to_string(), + representation_kind: "html".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ) + .unwrap(); + let blob_id = database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: "aaaa1111bbbb2222cccc3333dddd4444aaaa1111bbbb2222cccc3333dddd4444" + .to_string(), + byte_size: 21, + mime_type: Some("text/html".to_string()), + extension: Some("html".to_string()), + raw_relpath: artifact_relpath.to_string(), + }, + ) + .unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath: artifact_relpath.to_string(), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); drop(conn); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![MountedArchive { id: "test".to_string(), label: "Test".to_string(), archive_path: paths.archive_path.clone() }], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![MountedArchive { + id: "test".to_string(), + label: "Test".to_string(), + archive_path: paths.archive_path.clone(), + }], + bind: None, + auth_db_path: None, + }; let uri = format!("/api/archives/test/entries/{}/artifacts/0", entry.entry_uid); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3400,8 +3933,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/fake_uid/favicon").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/fake_uid/favicon") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3409,41 +3948,100 @@ mod tests { async fn serve_entry_favicon_with_auth_returns_ok() { let dir = tempfile::tempdir().unwrap(); let store_path = dir.path().join("store"); - let paths = archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false).unwrap(); + let paths = + archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false) + .unwrap(); let favicon_relpath = "raw/f/a/favicon.png"; let favicon_dir = store_path.join("raw").join("f").join("a"); std::fs::create_dir_all(&favicon_dir).unwrap(); - std::fs::write(favicon_dir.join("favicon.png"), &[0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]).unwrap(); + std::fs::write( + favicon_dir.join("favicon.png"), + &[0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], + ) + .unwrap(); let conn = database::open_or_initialize(&paths.archive_path).unwrap(); let user_id = database::ensure_default_user(&conn).unwrap(); - let sid = database::upsert_source_identity(&conn, "web", "page", Some("fav-page"), Some("https://example.com/fav"), "https://example.com/fav").unwrap(); + let sid = database::upsert_source_identity( + &conn, + "web", + "page", + Some("fav-page"), + Some("https://example.com/fav"), + "https://example.com/fav", + ) + .unwrap(); let run = database::create_archive_run(&conn, user_id, 1).unwrap(); - let entry = database::create_archived_entry(&conn, &database::NewEntry { - source_identity_id: sid, archive_run_id: run.id, parent_entry_id: None, root_entry_id: None, - created_by_user_id: user_id, owned_by_user_id: user_id, - source_kind: "web".to_string(), entity_kind: "page".to_string(), - title: Some("Favicon Test".to_string()), visibility: "private".to_string(), - representation_kind: "html".to_string(), source_metadata_json: "{}".to_string(), display_metadata_json: None, - }).unwrap(); - let blob_id = database::upsert_blob(&conn, &database::BlobRecord { - sha256: "ffffffffffff1111ffffffffffff1111ffffffffffff1111ffffffffffff1111".to_string(), - byte_size: 8, mime_type: Some("image/png".to_string()), extension: Some("png".to_string()), - raw_relpath: favicon_relpath.to_string(), - }).unwrap(); - database::add_entry_artifact(&conn, &database::NewArtifact { - entry_id: entry.id, artifact_role: "favicon".to_string(), - storage_area: "raw".to_string(), relpath: favicon_relpath.to_string(), - blob_id: Some(blob_id), logical_path: None, metadata_json: None, - }).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: sid, + archive_run_id: run.id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: user_id, + owned_by_user_id: user_id, + source_kind: "web".to_string(), + entity_kind: "page".to_string(), + title: Some("Favicon Test".to_string()), + visibility: "private".to_string(), + representation_kind: "html".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ) + .unwrap(); + let blob_id = database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: "ffffffffffff1111ffffffffffff1111ffffffffffff1111ffffffffffff1111" + .to_string(), + byte_size: 8, + mime_type: Some("image/png".to_string()), + extension: Some("png".to_string()), + raw_relpath: favicon_relpath.to_string(), + }, + ) + .unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "favicon".to_string(), + storage_area: "raw".to_string(), + relpath: favicon_relpath.to_string(), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); drop(conn); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![MountedArchive { id: "test".to_string(), label: "Test".to_string(), archive_path: paths.archive_path.clone() }], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![MountedArchive { + id: "test".to_string(), + label: "Test".to_string(), + archive_path: paths.archive_path.clone(), + }], + bind: None, + auth_db_path: None, + }; let uri = format!("/api/archives/test/entries/{}/favicon", entry.entry_uid); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3453,8 +4051,14 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let sha256 = "0000000000000000000000000000000000000000000000000000000000000000"; let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&format!("/api/archives/test/blobs/{sha256}")).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&format!("/api/archives/test/blobs/{sha256}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3462,26 +4066,52 @@ mod tests { async fn serve_blob_with_auth_returns_ok() { let dir = tempfile::tempdir().unwrap(); let store_path = dir.path().join("store"); - let paths = archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false).unwrap(); + let paths = + archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false) + .unwrap(); let blob_relpath = "raw/b/l/data.bin"; let blob_dir = store_path.join("raw").join("b").join("l"); std::fs::create_dir_all(&blob_dir).unwrap(); std::fs::write(blob_dir.join("data.bin"), b"blob content here").unwrap(); let sha256 = "bbbb2222cccc4444bbbb2222cccc4444bbbb2222cccc4444bbbb2222cccc4444"; let conn = database::open_or_initialize(&paths.archive_path).unwrap(); - database::upsert_blob(&conn, &database::BlobRecord { - sha256: sha256.to_string(), byte_size: 17, - mime_type: Some("application/octet-stream".to_string()), extension: Some("bin".to_string()), - raw_relpath: blob_relpath.to_string(), - }).unwrap(); + database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: sha256.to_string(), + byte_size: 17, + mime_type: Some("application/octet-stream".to_string()), + extension: Some("bin".to_string()), + raw_relpath: blob_relpath.to_string(), + }, + ) + .unwrap(); drop(conn); let auth_path = dir.path().join("auth.sqlite"); - { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } + { + let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); + archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); + } let session_cookie = make_test_session(&auth_path); - let registry = ServerRegistry { archives: vec![MountedArchive { id: "test".to_string(), label: "Test".to_string(), archive_path: paths.archive_path.clone() }], bind: None, auth_db_path: None }; + let registry = ServerRegistry { + archives: vec![MountedArchive { + id: "test".to_string(), + label: "Test".to_string(), + archive_path: paths.archive_path.clone(), + }], + bind: None, + auth_db_path: None, + }; let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&format!("/api/archives/test/blobs/{sha256}")).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&format!("/api/archives/test/blobs/{sha256}")) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3490,8 +4120,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/tags").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/tags") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3501,8 +4137,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/tags").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/tags") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3511,8 +4154,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/fake_uid/tags").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/fake_uid/tags") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3524,8 +4173,15 @@ mod tests { let session_cookie = make_test_session(&auth_path); let uri = format!("/api/archives/test/entries/{}/tags", entry.entry_uid); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3534,8 +4190,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/collections").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/collections") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3545,8 +4207,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/collections").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/collections") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3555,8 +4224,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/fake_uid/collections").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/fake_uid/collections") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3568,8 +4243,15 @@ mod tests { let session_cookie = make_test_session(&auth_path); let uri = format!("/api/archives/test/entries/{}/collections", entry.entry_uid); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3578,8 +4260,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/collections/coll_notexist").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/collections/coll_notexist") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3598,8 +4286,15 @@ mod tests { let coll_uid = coll["collection_uid"].as_str().unwrap().to_string(); let uri = format!("/api/archives/test/collections/{coll_uid}"); let response = app(registry, auth_path) - .oneshot(Request::builder().uri(&uri).header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri(&uri) + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3610,8 +4305,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3621,8 +4322,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3631,8 +4339,14 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let (registry, _, auth_path) = make_test_registry(&dir); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/search").body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/search") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::UNAUTHORIZED); } @@ -3642,8 +4356,15 @@ mod tests { let (registry, _, auth_path) = make_test_registry(&dir); let session_cookie = make_test_session(&auth_path); let response = app(registry, auth_path) - .oneshot(Request::builder().uri("/api/archives/test/entries/search").header("cookie", &session_cookie).body(Body::empty()).unwrap()) - .await.unwrap(); + .oneshot( + Request::builder() + .uri("/api/archives/test/entries/search") + .header("cookie", &session_cookie) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -3755,7 +4476,11 @@ mod tests { archivr_core::database::create_owner(&conn, "testowner", "dummy").unwrap(); } let state = AppState { - registry: Arc::new(ServerRegistry { archives: vec![], bind: None, auth_db_path: None }), + registry: Arc::new(ServerRegistry { + archives: vec![], + bind: None, + auth_db_path: None, + }), auth_db_path: Arc::new(auth_path.clone()), login_attempts: Arc::new(Mutex::new(HashMap::new())), }; @@ -3947,9 +4672,9 @@ mod tests { async fn blob_cleanup_delete_removes_orphan_and_preserves_referenced() { let dir = tempfile::tempdir().unwrap(); let store_path = dir.path().join("store"); - let paths = archivr_core::archive::initialize_archive( - dir.path(), &store_path, "test", false, - ).unwrap(); + let paths = + archivr_core::archive::initialize_archive(dir.path(), &store_path, "test", false) + .unwrap(); let auth_path = dir.path().join("auth.sqlite"); { let conn = archivr_core::database::open_auth_db(&auth_path).unwrap(); @@ -3965,25 +4690,44 @@ mod tests { { let conn = database::open_or_initialize(&paths.archive_path).unwrap(); // Referenced blob - let live_id = database::upsert_blob(&conn, &database::BlobRecord { - sha256: "aaaa1111bbbb2222cccc3333dddd4444aaaa1111bbbb2222cccc3333dddd4444".to_string(), - byte_size: 10, mime_type: None, extension: Some("bin".to_string()), - raw_relpath: live_relpath.to_string(), - }).unwrap(); - database::add_entry_artifact(&conn, &database::NewArtifact { - entry_id: entry.id, - artifact_role: "main".to_string(), - storage_area: "raw".to_string(), - relpath: live_relpath.to_string(), - blob_id: Some(live_id), - logical_path: None, metadata_json: None, - }).unwrap(); + let live_id = database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: "aaaa1111bbbb2222cccc3333dddd4444aaaa1111bbbb2222cccc3333dddd4444" + .to_string(), + byte_size: 10, + mime_type: None, + extension: Some("bin".to_string()), + raw_relpath: live_relpath.to_string(), + }, + ) + .unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "main".to_string(), + storage_area: "raw".to_string(), + relpath: live_relpath.to_string(), + blob_id: Some(live_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); // Orphaned blob (no artifact references it) - database::upsert_blob(&conn, &database::BlobRecord { - sha256: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".to_string(), - byte_size: 20, mime_type: None, extension: Some("bin".to_string()), - raw_relpath: orphan_relpath.to_string(), - }).unwrap(); + database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + .to_string(), + byte_size: 20, + mime_type: None, + extension: Some("bin".to_string()), + raw_relpath: orphan_relpath.to_string(), + }, + ) + .unwrap(); } // Write all three files to disk @@ -4018,12 +4762,23 @@ mod tests { assert_eq!(response.status(), StatusCode::OK); let body = body_json(response).await; assert_eq!(body["deleted_blob_rows"], 1, "one orphaned DB row removed"); - assert_eq!(body["deleted_files"], 2, "orphan blob file and extra disk file removed"); + assert_eq!( + body["deleted_files"], 2, + "orphan blob file and extra disk file removed" + ); assert!(body["errors"].as_array().unwrap().is_empty()); - assert!(store_path.join(live_relpath).exists(), "referenced file must be preserved"); - assert!(!store_path.join(orphan_relpath).exists(), "orphaned blob file must be deleted"); - assert!(!store_path.join(extra_relpath).exists(), "extra disk-only file must be deleted"); + assert!( + store_path.join(live_relpath).exists(), + "referenced file must be preserved" + ); + assert!( + !store_path.join(orphan_relpath).exists(), + "orphaned blob file must be deleted" + ); + assert!( + !store_path.join(extra_relpath).exists(), + "extra disk-only file must be deleted" + ); } - } diff --git a/crates/archivr-server/static/assets/index-BpGwC-YY.js b/crates/archivr-server/static/assets/index-BpGwC-YY.js new file mode 100644 index 0000000..361ee45 --- /dev/null +++ b/crates/archivr-server/static/assets/index-BpGwC-YY.js @@ -0,0 +1,47 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var fu={exports:{}},Gl={},pu={exports:{}},ee={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Mr=Symbol.for("react.element"),Fd=Symbol.for("react.portal"),Bd=Symbol.for("react.fragment"),Ud=Symbol.for("react.strict_mode"),Hd=Symbol.for("react.profiler"),Wd=Symbol.for("react.provider"),Vd=Symbol.for("react.context"),Qd=Symbol.for("react.forward_ref"),Kd=Symbol.for("react.suspense"),Xd=Symbol.for("react.memo"),Jd=Symbol.for("react.lazy"),Wa=Symbol.iterator;function qd(e){return e===null||typeof e!="object"?null:(e=Wa&&e[Wa]||e["@@iterator"],typeof e=="function"?e:null)}var hu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},mu=Object.assign,gu={};function Wn(e,t,n){this.props=e,this.context=t,this.refs=gu,this.updater=n||hu}Wn.prototype.isReactComponent={};Wn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Wn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function vu(){}vu.prototype=Wn.prototype;function Ki(e,t,n){this.props=e,this.context=t,this.refs=gu,this.updater=n||hu}var Xi=Ki.prototype=new vu;Xi.constructor=Ki;mu(Xi,Wn.prototype);Xi.isPureReactComponent=!0;var Va=Array.isArray,yu=Object.prototype.hasOwnProperty,Ji={current:null},xu={key:!0,ref:!0,__self:!0,__source:!0};function wu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)yu.call(t,r)&&!xu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,H=R[q];if(0>>1;ql(U,M))Bl(Q,U)?(R[q]=Q,R[B]=M,q=B):(R[q]=U,R[O]=M,q=O);else if(Bl(Q,M))R[q]=Q,R[B]=M,q=B;else break e}}return T}function l(R,T){var M=R.sortIndex-T.sortIndex;return M!==0?M:R.id-T.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],g=1,m=null,h=3,y=!1,x=!1,k=!1,j=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(R){for(var T=n(c);T!==null;){if(T.callback===null)r(c);else if(T.startTime<=R)r(c),T.sortIndex=T.expirationTime,t(u,T);else break;T=n(c)}}function w(R){if(k=!1,v(R),!x)if(n(u)!==null)x=!0,fe(_);else{var T=n(c);T!==null&&le(w,T.startTime-R)}}function _(R,T){x=!1,k&&(k=!1,p(S),S=-1),y=!0;var M=h;try{for(v(T),m=n(u);m!==null&&(!(m.expirationTime>T)||R&&!K());){var q=m.callback;if(typeof q=="function"){m.callback=null,h=m.priorityLevel;var H=q(m.expirationTime<=T);T=e.unstable_now(),typeof H=="function"?m.callback=H:m===n(u)&&r(u),v(T)}else r(u);m=n(u)}if(m!==null)var N=!0;else{var O=n(c);O!==null&&le(w,O.startTime-T),N=!1}return N}finally{m=null,h=M,y=!1}}var b=!1,C=null,S=-1,$=5,P=-1;function K(){return!(e.unstable_now()-P<$)}function F(){if(C!==null){var R=e.unstable_now();P=R;var T=!0;try{T=C(!0,R)}finally{T?W():(b=!1,C=null)}}else b=!1}var W;if(typeof d=="function")W=function(){d(F)};else if(typeof MessageChannel<"u"){var te=new MessageChannel,oe=te.port2;te.port1.onmessage=F,W=function(){oe.postMessage(null)}}else W=function(){j(F,0)};function fe(R){C=R,b||(b=!0,W())}function le(R,T){S=j(function(){R(e.unstable_now())},T)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(R){R.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,fe(_))},e.unstable_forceFrameRate=function(R){0>R||125q?(R.sortIndex=M,t(c,R),n(u)===null&&R===n(c)&&(k?(p(S),S=-1):k=!0,le(w,M-q))):(R.sortIndex=H,t(u,R),x||y||(x=!0,fe(_))),R},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(R){var T=h;return function(){var M=h;h=T;try{return R.apply(this,arguments)}finally{h=M}}}})(_u);Nu.exports=_u;var of=Nu.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var uf=f,qe=of;function L(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Zs=Object.prototype.hasOwnProperty,cf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Ka={},Xa={};function df(e){return Zs.call(Xa,e)?!0:Zs.call(Ka,e)?!1:cf.test(e)?Xa[e]=!0:(Ka[e]=!0,!1)}function ff(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function pf(e,t,n,r){if(t===null||typeof t>"u"||ff(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Fe(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var Le={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Le[e]=new Fe(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Le[t]=new Fe(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Le[e]=new Fe(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Le[e]=new Fe(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Le[e]=new Fe(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Le[e]=new Fe(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Le[e]=new Fe(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Le[e]=new Fe(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Le[e]=new Fe(e,5,!1,e.toLowerCase(),null,!1,!1)});var Gi=/[\-:]([a-z])/g;function Yi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Fe(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Fe(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Fe(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Le[e]=new Fe(e,1,!1,e.toLowerCase(),null,!1,!1)});Le.xlinkHref=new Fe("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Le[e]=new Fe(e,1,!1,e.toLowerCase(),null,!0,!0)});function Zi(e,t,n,r){var l=Le.hasOwnProperty(t)?Le[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` +`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{_s=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?or(e):""}function hf(e){switch(e.tag){case 5:return or(e.type);case 16:return or("Lazy");case 13:return or("Suspense");case 19:return or("SuspenseList");case 0:case 2:case 15:return e=Cs(e.type,!1),e;case 11:return e=Cs(e.type.render,!1),e;case 1:return e=Cs(e.type,!0),e;default:return""}}function ri(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case xn:return"Fragment";case yn:return"Portal";case ei:return"Profiler";case ea:return"StrictMode";case ti:return"Suspense";case ni:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Tu:return(e.displayName||"Context")+".Consumer";case Eu:return(e._context.displayName||"Context")+".Provider";case ta:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case na:return t=e.displayName||null,t!==null?t:ri(e.type)||"Memo";case Pt:t=e._payload,e=e._init;try{return ri(e(t))}catch{}}return null}function mf(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ri(t);case 8:return t===ea?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Wt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Pu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function gf(e){var t=Pu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Jr(e){e._valueTracker||(e._valueTracker=gf(e))}function Lu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Pu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _l(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function li(e,t){var n=t.checked;return ve({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function qa(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Wt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function zu(e,t){t=t.checked,t!=null&&Zi(e,"checked",t,!1)}function si(e,t){zu(e,t);var n=Wt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ii(e,t.type,n):t.hasOwnProperty("defaultValue")&&ii(e,t.type,Wt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ga(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ii(e,t,n){(t!=="number"||_l(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ur=Array.isArray;function Pn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=qr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var pr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},vf=["Webkit","ms","Moz","O"];Object.keys(pr).forEach(function(e){vf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),pr[t]=pr[e]})});function Iu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||pr.hasOwnProperty(e)&&pr[e]?(""+t).trim():t+"px"}function Ou(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Iu(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var yf=ve({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ui(e,t){if(t){if(yf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(L(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(L(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(L(61))}if(t.style!=null&&typeof t.style!="object")throw Error(L(62))}}function ci(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var di=null;function ra(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var fi=null,Ln=null,zn=null;function eo(e){if(e=Ur(e)){if(typeof fi!="function")throw Error(L(280));var t=e.stateNode;t&&(t=ns(t),fi(e.stateNode,e.type,t))}}function Au(e){Ln?zn?zn.push(e):zn=[e]:Ln=e}function Mu(){if(Ln){var e=Ln,t=zn;if(zn=Ln=null,eo(e),t)for(e=0;e>>=0,e===0?32:31-(bf(e)/Pf|0)|0}var Gr=64,Yr=4194304;function cr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function bl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=cr(o):(i&=a,i!==0&&(r=cr(i)))}else a=n&~l,a!==0?r=cr(a):i!==0&&(r=cr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Fr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ct(t),e[t]=n}function Df(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=mr),uo=" ",co=!1;function sc(e,t){switch(e){case"keyup":return op.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ic(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var wn=!1;function cp(e,t){switch(e){case"compositionend":return ic(t);case"keypress":return t.which!==32?null:(co=!0,uo);case"textInput":return e=t.data,e===uo&&co?null:e;default:return null}}function dp(e,t){if(wn)return e==="compositionend"||!da&&sc(e,t)?(e=rc(),ml=oa=Dt=null,wn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=mo(n)}}function cc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?cc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function dc(){for(var e=window,t=_l();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_l(e.document)}return t}function fa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function wp(e){var t=dc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&cc(n.ownerDocument.documentElement,n)){if(r!==null&&fa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=go(n,i);var a=go(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,kn=null,yi=null,vr=null,xi=!1;function vo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;xi||kn==null||kn!==_l(r)||(r=kn,"selectionStart"in r&&fa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),vr&&br(vr,r)||(vr=r,r=zl(yi,"onSelect"),0Nn||(e.current=_i[Nn],_i[Nn]=null,Nn--)}function ae(e,t){Nn++,_i[Nn]=e.current,e.current=t}var Vt={},Ie=Kt(Vt),He=Kt(!1),sn=Vt;function An(e,t){var n=e.type.contextTypes;if(!n)return Vt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function We(e){return e=e.childContextTypes,e!=null}function Dl(){de(He),de(Ie)}function No(e,t,n){if(Ie.current!==Vt)throw Error(L(168));ae(Ie,t),ae(He,n)}function wc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(L(108,mf(e)||"Unknown",l));return ve({},n,r)}function $l(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Vt,sn=Ie.current,ae(Ie,e),ae(He,He.current),!0}function _o(e,t,n){var r=e.stateNode;if(!r)throw Error(L(169));n?(e=wc(e,t,sn),r.__reactInternalMemoizedMergedChildContext=e,de(He),de(Ie),ae(Ie,e)):de(He),ae(He,n)}var xt=null,rs=!1,Fs=!1;function kc(e){xt===null?xt=[e]:xt.push(e)}function zp(e){rs=!0,kc(e)}function Xt(){if(!Fs&&xt!==null){Fs=!0;var e=0,t=ie;try{var n=xt;for(ie=1;e>=a,l-=a,wt=1<<32-ct(t)+l|n<S?($=C,C=null):$=C.sibling;var P=h(p,C,v[S],w);if(P===null){C===null&&(C=$);break}e&&C&&P.alternate===null&&t(p,C),d=i(P,d,S),b===null?_=P:b.sibling=P,b=P,C=$}if(S===v.length)return n(p,C),he&&Gt(p,S),_;if(C===null){for(;SS?($=C,C=null):$=C.sibling;var K=h(p,C,P.value,w);if(K===null){C===null&&(C=$);break}e&&C&&K.alternate===null&&t(p,C),d=i(K,d,S),b===null?_=K:b.sibling=K,b=K,C=$}if(P.done)return n(p,C),he&&Gt(p,S),_;if(C===null){for(;!P.done;S++,P=v.next())P=m(p,P.value,w),P!==null&&(d=i(P,d,S),b===null?_=P:b.sibling=P,b=P);return he&&Gt(p,S),_}for(C=r(p,C);!P.done;S++,P=v.next())P=y(C,p,S,P.value,w),P!==null&&(e&&P.alternate!==null&&C.delete(P.key===null?S:P.key),d=i(P,d,S),b===null?_=P:b.sibling=P,b=P);return e&&C.forEach(function(F){return t(p,F)}),he&&Gt(p,S),_}function j(p,d,v,w){if(typeof v=="object"&&v!==null&&v.type===xn&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Xr:e:{for(var _=v.key,b=d;b!==null;){if(b.key===_){if(_=v.type,_===xn){if(b.tag===7){n(p,b.sibling),d=l(b,v.props.children),d.return=p,p=d;break e}}else if(b.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===Pt&&To(_)===b.type){n(p,b.sibling),d=l(b,v.props),d.ref=rr(p,b,v),d.return=p,p=d;break e}n(p,b);break}else t(p,b);b=b.sibling}v.type===xn?(d=ln(v.props.children,p.mode,w,v.key),d.return=p,p=d):(w=Sl(v.type,v.key,v.props,null,p.mode,w),w.ref=rr(p,d,v),w.return=p,p=w)}return a(p);case yn:e:{for(b=v.key;d!==null;){if(d.key===b)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){n(p,d.sibling),d=l(d,v.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=Xs(v,p.mode,w),d.return=p,p=d}return a(p);case Pt:return b=v._init,j(p,d,b(v._payload),w)}if(ur(v))return x(p,d,v,w);if(Yn(v))return k(p,d,v,w);sl(p,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,v),d.return=p,p=d):(n(p,d),d=Ks(v,p.mode,w),d.return=p,p=d),a(p)):n(p,d)}return j}var Fn=_c(!0),Cc=_c(!1),Al=Kt(null),Ml=null,En=null,ga=null;function va(){ga=En=Ml=null}function ya(e){var t=Al.current;de(Al),e._currentValue=t}function Ti(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Dn(e,t){Ml=e,ga=En=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ue=!0),e.firstContext=null)}function lt(e){var t=e._currentValue;if(ga!==e)if(e={context:e,memoizedValue:t,next:null},En===null){if(Ml===null)throw Error(L(308));En=e,Ml.dependencies={lanes:0,firstContext:e}}else En=En.next=e;return t}var en=null;function xa(e){en===null?en=[e]:en.push(e)}function Ec(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,xa(t)):(n.next=l.next,l.next=n),t.interleaved=n,_t(e,r)}function _t(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Lt=!1;function wa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Tc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ft(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ne&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,_t(e,n)}return l=r.interleaved,l===null?(t.next=t,xa(r)):(t.next=l.next,l.next=t),r.interleaved=t,_t(e,n)}function vl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}function bo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Fl(e,t,n,r){var l=e.updateQueue;Lt=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var g=e.alternate;g!==null&&(g=g.updateQueue,o=g.lastBaseUpdate,o!==a&&(o===null?g.firstBaseUpdate=c:o.next=c,g.lastBaseUpdate=u))}if(i!==null){var m=l.baseState;a=0,g=c=u=null,o=i;do{var h=o.lane,y=o.eventTime;if((r&h)===h){g!==null&&(g=g.next={eventTime:y,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,k=o;switch(h=t,y=n,k.tag){case 1:if(x=k.payload,typeof x=="function"){m=x.call(y,m,h);break e}m=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=k.payload,h=typeof x=="function"?x.call(y,m,h):x,h==null)break e;m=ve({},m,h);break e;case 2:Lt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else y={eventTime:y,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},g===null?(c=g=y,u=m):g=g.next=y,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(g===null&&(u=m),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=g,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);un|=a,e.lanes=a,e.memoizedState=m}}function Po(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Us.transition;Us.transition={};try{e(!1),t()}finally{ie=n,Us.transition=r}}function Vc(){return st().memoizedState}function Ip(e,t,n){var r=Ut(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Qc(e))Kc(t,n);else if(n=Ec(e,t,n,r),n!==null){var l=Ae();dt(n,e,r,l),Xc(n,t,r)}}function Op(e,t,n){var r=Ut(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Qc(e))Kc(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,ft(o,a)){var u=t.interleaved;u===null?(l.next=l,xa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Ec(e,t,l,r),n!==null&&(l=Ae(),dt(n,e,r,l),Xc(n,t,r))}}function Qc(e){var t=e.alternate;return e===ge||t!==null&&t===ge}function Kc(e,t){yr=Ul=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Xc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}var Hl={readContext:lt,useCallback:Re,useContext:Re,useEffect:Re,useImperativeHandle:Re,useInsertionEffect:Re,useLayoutEffect:Re,useMemo:Re,useReducer:Re,useRef:Re,useState:Re,useDebugValue:Re,useDeferredValue:Re,useTransition:Re,useMutableSource:Re,useSyncExternalStore:Re,useId:Re,unstable_isNewReconciler:!1},Ap={readContext:lt,useCallback:function(e,t){return ht().memoizedState=[e,t===void 0?null:t],e},useContext:lt,useEffect:zo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,xl(4194308,4,Fc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return xl(4194308,4,e,t)},useInsertionEffect:function(e,t){return xl(4,2,e,t)},useMemo:function(e,t){var n=ht();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ht();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Ip.bind(null,ge,e),[r.memoizedState,e]},useRef:function(e){var t=ht();return e={current:e},t.memoizedState=e},useState:Lo,useDebugValue:Ta,useDeferredValue:function(e){return ht().memoizedState=e},useTransition:function(){var e=Lo(!1),t=e[0];return e=$p.bind(null,e[1]),ht().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=ge,l=ht();if(he){if(n===void 0)throw Error(L(407));n=n()}else{if(n=t(),Te===null)throw Error(L(349));on&30||zc(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,zo(Dc.bind(null,r,i,e),[e]),r.flags|=2048,Or(9,Rc.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ht(),t=Te.identifierPrefix;if(he){var n=kt,r=wt;n=(r&~(1<<32-ct(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=$r++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[mt]=t,e[zr]=r,ld(e,t,!1,!1),t.stateNode=e;e:{switch(a=ci(n,r),n){case"dialog":ce("cancel",e),ce("close",e),l=r;break;case"iframe":case"object":case"embed":ce("load",e),l=r;break;case"video":case"audio":for(l=0;lHn&&(t.flags|=128,r=!0,lr(i,!1),t.lanes=4194304)}else{if(!r)if(e=Bl(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),lr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!he)return De(t),null}else 2*we()-i.renderingStartTime>Hn&&n!==1073741824&&(t.flags|=128,r=!0,lr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=we(),t.sibling=null,n=me.current,ae(me,r?n&1|2:n&1),t):(De(t),null);case 22:case 23:return Da(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ke&1073741824&&(De(t),t.subtreeFlags&6&&(t.flags|=8192)):De(t),null;case 24:return null;case 25:return null}throw Error(L(156,t.tag))}function Qp(e,t){switch(ha(t),t.tag){case 1:return We(t.type)&&Dl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Bn(),de(He),de(Ie),Sa(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ja(t),null;case 13:if(de(me),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(L(340));Mn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return de(me),null;case 4:return Bn(),null;case 10:return ya(t.type._context),null;case 22:case 23:return Da(),null;case 24:return null;default:return null}}var al=!1,$e=!1,Kp=typeof WeakSet=="function"?WeakSet:Set,A=null;function Tn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(e,t,r)}else n.current=null}function Oi(e,t,n){try{n()}catch(r){ye(e,t,r)}}var Ho=!1;function Xp(e,t){if(wi=Pl,e=dc(),fa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,g=0,m=e,h=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(o=a+l),m!==i||r!==0&&m.nodeType!==3||(u=a+r),m.nodeType===3&&(a+=m.nodeValue.length),(y=m.firstChild)!==null;)h=m,m=y;for(;;){if(m===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++g===r&&(u=a),(y=m.nextSibling)!==null)break;m=h,h=m.parentNode}m=y}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(ki={focusedElem:e,selectionRange:n},Pl=!1,A=t;A!==null;)if(t=A,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,A=e;else for(;A!==null;){t=A;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var k=x.memoizedProps,j=x.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?k:at(t.type,k),j);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(L(163))}}catch(w){ye(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,A=e;break}A=t.return}return x=Ho,Ho=!1,x}function xr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Oi(t,n,i)}l=l.next}while(l!==r)}}function is(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ai(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function ad(e){var t=e.alternate;t!==null&&(e.alternate=null,ad(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[mt],delete t[zr],delete t[Ni],delete t[Pp],delete t[Lp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function od(e){return e.tag===5||e.tag===3||e.tag===4}function Wo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||od(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Mi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Rl));else if(r!==4&&(e=e.child,e!==null))for(Mi(e,t,n),e=e.sibling;e!==null;)Mi(e,t,n),e=e.sibling}function Fi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Fi(e,t,n),e=e.sibling;e!==null;)Fi(e,t,n),e=e.sibling}var be=null,ot=!1;function bt(e,t,n){for(n=n.child;n!==null;)ud(e,t,n),n=n.sibling}function ud(e,t,n){if(gt&&typeof gt.onCommitFiberUnmount=="function")try{gt.onCommitFiberUnmount(Yl,n)}catch{}switch(n.tag){case 5:$e||Tn(n,t);case 6:var r=be,l=ot;be=null,bt(e,t,n),be=r,ot=l,be!==null&&(ot?(e=be,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):be.removeChild(n.stateNode));break;case 18:be!==null&&(ot?(e=be,n=n.stateNode,e.nodeType===8?Ms(e.parentNode,n):e.nodeType===1&&Ms(e,n),Er(e)):Ms(be,n.stateNode));break;case 4:r=be,l=ot,be=n.stateNode.containerInfo,ot=!0,bt(e,t,n),be=r,ot=l;break;case 0:case 11:case 14:case 15:if(!$e&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&Oi(n,t,a),l=l.next}while(l!==r)}bt(e,t,n);break;case 1:if(!$e&&(Tn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ye(n,t,o)}bt(e,t,n);break;case 21:bt(e,t,n);break;case 22:n.mode&1?($e=(r=$e)||n.memoizedState!==null,bt(e,t,n),$e=r):bt(e,t,n);break;default:bt(e,t,n)}}function Vo(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Kp),t.forEach(function(r){var l=rh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function it(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=we()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*qp(r/1960))-r,10e?16:e,$t===null)var r=!1;else{if(e=$t,$t=null,Ql=0,ne&6)throw Error(L(331));var l=ne;for(ne|=4,A=e.current;A!==null;){var i=A,a=i.child;if(A.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uwe()-za?rn(e,0):La|=n),Ve(e,t)}function vd(e,t){t===0&&(e.mode&1?(t=Yr,Yr<<=1,!(Yr&130023424)&&(Yr=4194304)):t=1);var n=Ae();e=_t(e,t),e!==null&&(Fr(e,t,n),Ve(e,n))}function nh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),vd(e,n)}function rh(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(L(314))}r!==null&&r.delete(t),vd(e,n)}var yd;yd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||He.current)Ue=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ue=!1,Wp(e,t,n);Ue=!!(e.flags&131072)}else Ue=!1,he&&t.flags&1048576&&jc(t,Ol,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;wl(e,t),e=t.pendingProps;var l=An(t,Ie.current);Dn(t,n),l=_a(null,t,r,e,l,n);var i=Ca();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,We(r)?(i=!0,$l(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,wa(t),l.updater=ss,t.stateNode=l,l._reactInternals=t,Pi(t,r,e,n),t=Ri(null,t,r,!0,i,n)):(t.tag=0,he&&i&&pa(t),Oe(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(wl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=sh(r),e=at(r,e),l){case 0:t=zi(null,t,r,e,n);break e;case 1:t=Fo(null,t,r,e,n);break e;case 11:t=Ao(null,t,r,e,n);break e;case 14:t=Mo(null,t,r,at(r.type,e),n);break e}throw Error(L(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),zi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),Fo(e,t,r,l,n);case 3:e:{if(td(t),e===null)throw Error(L(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Tc(e,t),Fl(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=Un(Error(L(423)),t),t=Bo(e,t,r,n,l);break e}else if(r!==l){l=Un(Error(L(424)),t),t=Bo(e,t,r,n,l);break e}else for(Xe=Mt(t.stateNode.containerInfo.firstChild),Je=t,he=!0,ut=null,n=Cc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Mn(),r===l){t=Ct(e,t,n);break e}Oe(e,t,r,n)}t=t.child}return t;case 5:return bc(t),e===null&&Ei(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,ji(r,l)?a=null:i!==null&&ji(r,i)&&(t.flags|=32),ed(e,t),Oe(e,t,a,n),t.child;case 6:return e===null&&Ei(t),null;case 13:return nd(e,t,n);case 4:return ka(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Fn(t,null,r,n):Oe(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),Ao(e,t,r,l,n);case 7:return Oe(e,t,t.pendingProps,n),t.child;case 8:return Oe(e,t,t.pendingProps.children,n),t.child;case 12:return Oe(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,ae(Al,r._currentValue),r._currentValue=a,i!==null)if(ft(i.value,a)){if(i.children===l.children&&!He.current){t=Ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=jt(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var g=c.pending;g===null?u.next=u:(u.next=g.next,g.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Ti(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(L(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Ti(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Oe(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Dn(t,n),l=lt(l),r=r(l),t.flags|=1,Oe(e,t,r,n),t.child;case 14:return r=t.type,l=at(r,t.pendingProps),l=at(r.type,l),Mo(e,t,r,l,n);case 15:return Yc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),wl(e,t),t.tag=1,We(r)?(e=!0,$l(t)):e=!1,Dn(t,n),Jc(t,r,l),Pi(t,r,l,n),Ri(null,t,r,!0,e,n);case 19:return rd(e,t,n);case 22:return Zc(e,t,n)}throw Error(L(156,t.tag))};function xd(e,t){return Qu(e,t)}function lh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function nt(e,t,n,r){return new lh(e,t,n,r)}function Ia(e){return e=e.prototype,!(!e||!e.isReactComponent)}function sh(e){if(typeof e=="function")return Ia(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ta)return 11;if(e===na)return 14}return 2}function Ht(e,t){var n=e.alternate;return n===null?(n=nt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Sl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")Ia(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case xn:return ln(n.children,l,i,t);case ea:a=8,l|=8;break;case ei:return e=nt(12,n,t,l|2),e.elementType=ei,e.lanes=i,e;case ti:return e=nt(13,n,t,l),e.elementType=ti,e.lanes=i,e;case ni:return e=nt(19,n,t,l),e.elementType=ni,e.lanes=i,e;case bu:return os(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Eu:a=10;break e;case Tu:a=9;break e;case ta:a=11;break e;case na:a=14;break e;case Pt:a=16,r=null;break e}throw Error(L(130,e==null?e:typeof e,""))}return t=nt(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function ln(e,t,n,r){return e=nt(7,e,r,t),e.lanes=n,e}function os(e,t,n,r){return e=nt(22,e,r,t),e.elementType=bu,e.lanes=n,e.stateNode={isHidden:!1},e}function Ks(e,t,n){return e=nt(6,e,null,t),e.lanes=n,e}function Xs(e,t,n){return t=nt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function ih(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ts(0),this.expirationTimes=Ts(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ts(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Oa(e,t,n,r,l,i,a,o,u){return e=new ih(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=nt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wa(i),e}function ah(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Sd)}catch(e){console.error(e)}}Sd(),Su.exports=Ge;var fh=Su.exports,Nd,Zo=fh;Nd=Zo.createRoot,Zo.hydrateRoot;async function _e(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ph(){return _e("/api/archives")}async function hh(e){return _e(`/api/archives/${e}/entries`)}async function mh(e,t,n){const r=new URLSearchParams;return t&&r.set("q",t),n&&r.set("tag",n),_e(`/api/archives/${e}/entries/search?${r}`)}async function Vi(e,t){return _e(`/api/archives/${e}/entries/${t}`)}function gh(e,t,n){return Promise.all(n.map(r=>_e(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function vh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function yh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function cl(e,t){return _e(`/api/archives/${e}/entries/${t}/tags`)}async function eu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function xh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function tu(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function wh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function kh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function jh(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function Sh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function Js(e){return _e(`/api/archives/${e}/runs`)}async function dl(e){return _e(`/api/archives/${e}/tags`)}async function Nh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||`HTTP ${i.status}`)}return i.json()}async function _h(e,t){return _e(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function _d(e,t){return _e(`/api/archives/${e}/capture_jobs/${t}`)}async function Ch(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Eh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Th(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function bh(){await fetch("/api/auth/logout",{method:"POST"})}async function Ph(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function Lh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function zh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Rh(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function Dh(){return _e("/api/auth/tokens")}async function $h(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function Ih(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function Ba(){return _e("/api/admin/instance-settings")}async function Nl(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Oh(){return _e("/api/admin/users")}async function Ah(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function Mh(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Fh(){return _e("/api/admin/roles")}async function Bh(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Cd(e){return _e(`/api/archives/${e}/collections`)}async function Uh(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}return l.json()}async function Hh(e,t){return _e(`/api/archives/${e}/collections/${t}`)}async function Ed(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Wh(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function Vh(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Qh(e,t){return _e(`/api/archives/${e}/entries/${t}/collections`)}async function nu(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function Kh(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function Xh(e){return _e(`/api/archives/${e}/blob-cleanup`)}async function Jh(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function qh(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function Gh(){return _e("/api/admin/cookie-rules")}async function Yh(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function Zh(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function em(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}const tm=window.fetch;window.fetch=async(...e)=>{var n;const t=await tm(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function nm({onLogin:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(null),[o,u]=f.useState(!1);async function c(g){g.preventDefault(),a(null),u(!0);try{const m=await Th(t,r);e(m)}catch(m){a(m.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:g=>n(g.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:g=>l(g.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function rm({onComplete:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(""),[o,u]=f.useState(null),[c,g]=f.useState(!1);async function m(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),g(!0);try{await Eh(t,r),e()}catch(y){u(y.message)}finally{g(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function lm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i}){const{currentUser:a,setCurrentUser:o}=f.useContext(ps)??{},[u,c]=f.useState(!1);async function g(){c(!0),await bh(),o(null),window.location.reload()}return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),a&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:a.display_name||a.username}),s.jsx("button",{className:"logout-btn",onClick:g,disabled:u,children:u?"Logging out…":"Log out"})]})]})}let Qi=1;function Td(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function ir(e=""){return{id:Qi++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null}}function ru(e){return e.some(t=>t.status==="submitting"||t.status==="running")}function sm({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l}){const i=f.useRef(null),a=f.useRef(!0),o=f.useRef(new Map),u=f.useRef(new Map),c=f.useRef(new Map),g=f.useRef(t);f.useEffect(()=>{g.current=t},[t]);const m=f.useRef(r),h=f.useRef(l);f.useEffect(()=>{m.current=r},[r]),f.useEffect(()=>{h.current=l},[l]);const[y,x]=f.useState(()=>{try{const N=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(N)&&N.length>0)return N.forEach(O=>{O.id>=Qi&&(Qi=O.id+1)}),N}catch{}return[ir()]});f.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(y))},[y]);const[k,j]=f.useState(!1),[p,d]=f.useState(null),[v,w]=f.useState(null),[_,b]=f.useState(!0),[C,S]=f.useState(!0);f.useEffect(()=>{Ba().then(N=>{w(N),b(N.cookie_ext_enabled??!0),S(N.modal_closer_enabled??!0)}).catch(()=>w({}))},[]);const $=p!==null?p:(v==null?void 0:v.ublock_enabled)??!0,[P,K]=f.useState(!1);f.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(N=>sessionStorage.removeItem(N)),x(N=>N.map(O=>O.status==="submitting"?{...O,status:"idle",error:null}:O)),y.forEach(N=>{N.status==="running"&&N.jobUid&&N.archiveId&&!o.current.has(N.jobUid)&&F(N.id,N.jobUid,N.locator,N.archiveId)})},[]),f.useEffect(()=>{const N=i.current;if(!N)return;const O=()=>{u.current.forEach(U=>clearTimeout(U)),u.current.clear(),n()};return N.addEventListener("close",O),()=>N.removeEventListener("close",O)},[n]),f.useEffect(()=>{const N=i.current;N&&(e?(!a.current&&!ru(y)&&x([ir()]),a.current=!1,N.open||N.showModal()):(u.current.forEach(O=>clearTimeout(O)),u.current.clear(),N.open&&N.close()))},[e]),f.useEffect(()=>()=>{o.current.forEach(N=>clearInterval(N)),u.current.forEach(N=>clearTimeout(N))},[]);function F(N,O,U,B,Q=null){if(o.current.has(O))return;const pe=setInterval(async()=>{try{const G=await _d(B,O);if(G.status==="completed"){clearInterval(o.current.get(O)),o.current.delete(O),x(Y=>Y.map(Z=>Z.id===N?{...Z,status:"completed"}:Z)),setTimeout(()=>{x(Y=>{const Z=Y.filter(ue=>ue.id!==N);return Z.length===0?[ir()]:Z})},1400),m.current();try{const Y=G.notes_json?JSON.parse(G.notes_json):null;if(Y!=null&&Y.ublock_skipped||Y!=null&&Y.cookie_ext_skipped){const ue=Y.ublock_skipped&&Y.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":Y.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";h.current(ue,U,"warning"),W(Q,"warning",U)}else Q||h.current(null,U,"success"),W(Q,"archived")}catch{Q||h.current(null,U,"success"),W(Q,"archived")}}else if(G.status==="failed"){clearInterval(o.current.get(O)),o.current.delete(O);const Y=G.error_text||"Capture failed.";x(Z=>Z.map(ue=>ue.id===N?{...ue,status:"failed",error:Y}:ue)),h.current(Y,U),W(Q,"failed",U)}}catch(G){clearInterval(o.current.get(O)),o.current.delete(O);const Y=G.message||"Network error";x(Z=>Z.map(ue=>ue.id===N?{...ue,status:"failed",error:Y}:ue)),h.current(Y,U),W(Q,"failed",U)}},500);o.current.set(O,pe)}function W(N,O,U=null){if(!N)return;const B=c.current.get(N);if(!B||(O==="archived"||O==="warning"?(B.archived++,O==="warning"&&(B.warnings++,U&&B.warningLocators.push(U))):(B.failed++,U&&B.failedLocators.push(U)),B.archived+B.failed0?`${Q} archived (${pe} with warnings)`:`${Q} archived`;ue=G>0?`${xe}, ${G} failed`:xe}const D=Q===0?"error":G>0||pe>0?"warning":"success",X=[];Y.length>0&&X.push(`Failed: +${Y.map(xe=>` ${xe}`).join(` +`)}`),Z.length>0&&X.push(`With warnings: +${Z.map(xe=>` ${xe}`).join(` +`)}`);const Ce=X.length>0?X.join(` +`):null;h.current(Ce,null,D,ue)}async function te(N,O=null){if(!N.locator.trim())return;const U=t,B=N.locator.trim(),Q=N.quality||"best";x(pe=>pe.map(G=>G.id===N.id?{...G,status:"submitting",error:null}:G));try{const G=await Nh(U,B,Q,{ublock_enabled:$,reader_mode:P,cookie_ext_enabled:_,modal_closer_enabled:C});x(Y=>Y.map(Z=>Z.id===N.id?{...Z,status:"running",jobUid:G.job_uid,archiveId:U}:Z)),F(N.id,G.job_uid,B,U,O)}catch(pe){const G=pe.message||"Submission failed.";x(Y=>Y.map(Z=>Z.id===N.id?{...Z,status:"failed",error:G}:Z)),h.current(G,B),W(O,"failed",B)}}function oe(){var U,B;const N=y.filter(Q=>Q.status==="idle"&&Q.locator.trim());if(N.length===0)return;const O=N.length>1?((U=crypto.randomUUID)==null?void 0:U.call(crypto))??`batch-${Date.now()}`:null;O&&c.current.set(O,{total:N.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]}),N.forEach(Q=>te(Q,O)),(B=i.current)==null||B.close()}function fe(){x(N=>[...N,ir()])}function le(N){clearTimeout(u.current.get(N)),u.current.delete(N),x(O=>{const U=O.filter(B=>B.id!==N);return U.length===0?[ir()]:U})}function R(N){x(O=>O.map(U=>U.id===N?{...U,status:"idle",error:null}:U))}function T(N,O){if(clearTimeout(u.current.get(N)),x(B=>B.map(Q=>Q.id===N?{...Q,locator:O,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best"}:Q)),!Td(O))return;const U=setTimeout(async()=>{u.current.delete(N),x(B=>B.map(Q=>Q.id===N?{...Q,probeState:"probing"}:Q));try{const B=await _h(g.current,O.trim());x(Q=>Q.map(pe=>{if(pe.id!==N||pe.locator!==O)return pe;const G=B.qualities??[],Y=B.has_audio??!1,Z=G.length===0&&Y?"audio":"best";return{...pe,probeState:"done",probeQualities:G,probeHasAudio:Y,quality:Z}}))}catch{x(B=>B.map(Q=>Q.id===N?{...Q,probeState:"idle",probeQualities:null}:Q))}},600);u.current.set(N,U)}function M(N,O){x(U=>U.map(B=>B.id===N?{...B,quality:O}:B))}const q=y.filter(N=>N.status==="idle"&&N.locator.trim()).length,H=ru(y);return s.jsx("dialog",{ref:i,className:"capture-dialog",children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:y.map((N,O)=>s.jsx(im,{item:N,autoFocus:O===y.length-1&&N.status==="idle",onLocatorChange:U=>T(N.id,U),onQualityChange:U=>M(N.id,U),onRemove:()=>le(N.id),onReset:()=>R(N.id),onSubmit:oe},N.id))}),s.jsxs("button",{type:"button",className:"capture-add-row",onClick:fe,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add another"]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>j(N=>!N),"aria-expanded":k,children:[s.jsx("svg",{className:`capture-chevron${k?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),k&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":$,className:`ext-toggle ext-toggle--sm${$?" ext-toggle--on":""}`,onClick:()=>d(N=>N===null?!$:!N),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(v!=null&&v.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":_,className:`ext-toggle ext-toggle--sm${_?" ext-toggle--on":""}`,onClick:()=>b(N=>!N),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":P,className:`ext-toggle ext-toggle--sm${P?" ext-toggle--on":""}`,onClick:()=>K(N=>!N),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":C,className:`ext-toggle ext-toggle--sm${C?" ext-toggle--on":""}`,onClick:()=>S(N=>!N),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:oe,disabled:q===0,children:q>1?`Archive ${q}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},children:H?"Close":"Cancel"})]})]})})}function im({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onReset:i,onSubmit:a}){const o=f.useRef(null),u=e.status==="submitting"||e.status==="running";f.useEffect(()=>{var g;t&&e.status==="idle"&&((g=o.current)==null||g.focus())},[t]);const c=(()=>{if(e.status==="completed"||u||!Td(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const g=e.probeQualities??[],m=e.probeHasAudio??!1;return g.length===0&&!m?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):g.length===0&&m?s.jsx("select",{className:"capture-quality",value:"audio",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),g.map(h=>s.jsx("option",{value:h,children:h},h)),m&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})();return s.jsxs("div",{className:`capture-row capture-row--${e.status}`,children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx(am,{status:e.status}),s.jsx("input",{ref:o,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"&&a()},disabled:u||e.status==="completed",autoComplete:"off",spellCheck:!1}),c,e.status==="failed"&&s.jsx("button",{type:"button",className:"capture-row-action",onClick:i,title:"Retry",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M13 2.5A7 7 0 1 1 6.5 1"}),s.jsx("polyline",{points:"6.5 1 4 3.5 6.5 6"})]})}),!u&&e.status!=="completed"&&e.status!=="failed"&&s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error})]})}function am({status:e}){return e==="submitting"||e==="running"?s.jsx("span",{className:"cap-dot cap-dot--running","aria-label":"Running",children:s.jsx("span",{className:"cap-spinner"})}):e==="completed"?s.jsx("span",{className:"cap-dot cap-dot--ok","aria-label":"Done",children:"✓"}):e==="failed"?s.jsx("span",{className:"cap-dot cap-dot--err","aria-label":"Failed",children:"✕"}):s.jsx("span",{className:"cap-dot cap-dot--idle","aria-hidden":"true"})}function Jl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function nn(e){return om(e)??""}function bd(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const lu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Ua(e){return lu[e]??lu.other}function Pd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function um({entry:e,archiveId:t,isSelected:n,isMultiSelected:r,onRowClick:l}){const[i,a]=f.useState(!1),u=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!i?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>a(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Ua(e.source_kind)}}),c=n||r;function g(m){m.stopPropagation(),l(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}return s.jsxs("div",{className:[n&&"is-selected",r&&"is-multi-selected"].filter(Boolean).join(" ")||void 0,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:m=>{m.shiftKey&&m.preventDefault()},onClick:m=>l(e,m),onKeyDown:m=>{m.key==="Enter"&&l(e,m)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${c?" is-checked":""}`,"aria-pressed":c,"aria-label":c?"Deselect entry":"Select entry",onClick:g,onKeyDown:m=>m.stopPropagation()})}),s.jsx("div",{className:"col-added",children:bd(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:u}),s.jsx("span",{className:"entry-title",children:nn(e.title)||nn(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:nn(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:Jl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${Jl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:nn(e.original_url)})]})}function cm({entries:e,selectedUids:t,onRowClick:n,archiveId:r}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsx("div",{id:"entries-body",children:e.map(l=>s.jsx(um,{entry:l,archiveId:r,isSelected:t.size===1&&t.has(l.entry_uid),isMultiSelected:t.size>=2&&t.has(l.entry_uid),onRowClick:n},l.entry_uid))})]})})}function dm(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function fm({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function pm({runs:e}){const[t,n]=f.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:dm(l.started_at)}),s.jsxs("td",{children:[s.jsx(fm,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const hm=4;function mm({archives:e}){const{currentUser:t}=f.useContext(ps)??{},n=t&&(t.role_bits&hm)!==0,[r,l]=f.useState("users"),[i,a]=f.useState([]),[o,u]=f.useState([]),[c,g]=f.useState(!1),[m,h]=f.useState(null),[y,x]=f.useState(""),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(null),[_,b]=f.useState(!1),[C,S]=f.useState(""),[$,P]=f.useState(""),[K,F]=f.useState(null),[W,te]=f.useState(!1),oe=f.useCallback(async()=>{if(n){g(!0),h(null);try{const[T,M]=await Promise.all([Oh(),Fh()]);a(T),u(M)}catch(T){h(T.message)}finally{g(!1)}}},[n]);f.useEffect(()=>{oe()},[oe]);async function fe(T){const M=T.status==="active"?"disabled":"active";try{await Mh(T.user_uid,M),a(q=>q.map(H=>H.user_uid===T.user_uid?{...H,status:M}:H))}catch(q){h(q.message)}}async function le(T){if(T.preventDefault(),!y.trim()||!k){w("Username and password required");return}b(!0),w(null);try{await Ah(y.trim(),k,p.trim()||void 0),x(""),j(""),d(""),await oe()}catch(M){w(M.message)}finally{b(!1)}}async function R(T){if(T.preventDefault(),!C.trim()||!$.trim()){F("Slug and name required");return}te(!0),F(null);try{await Bh(C.trim(),$.trim()),S(""),P(""),await oe()}catch(M){F(M.message)}finally{te(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(T=>s.jsxs("tr",{className:T.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:T.username}),s.jsx("td",{className:"muted",children:T.email||"—"}),s.jsx("td",{children:T.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${T.status}`,children:T.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>fe(T),children:T.status==="active"?"Ban":"Unban"})})]},T.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:le,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:y,onChange:T=>x(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:k,onChange:T=>j(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:T=>d(T.target.value)}),v&&s.jsx("div",{className:"form-msg form-msg--err",children:v}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.slug})}),s.jsx("td",{children:T.name}),s.jsx("td",{children:T.level}),s.jsx("td",{children:T.bit_position}),s.jsx("td",{children:T.is_builtin?"✓":""})]},T.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:R,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:C,onChange:T=>S(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:$,onChange:T=>P(T.target.value),required:!0}),K&&s.jsx("div",{className:"form-msg form-msg--err",children:K}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:W,children:W?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})}function Ld({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(Ld,{node:r,onPick:t},r.tag.tag_uid))})})]})}function su({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){f.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(Ld,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function zd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=f.useState(""),a=f.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await jh(t,c),n()}catch(g){alert(g.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function Rd({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:g,pendingCreateParentUid:m,onCreateDone:h,onCreateCancel:y}){var K;const x=n===e.tag.full_path,[k,j]=f.useState(!1),[p,d]=f.useState(""),v=f.useRef(!1);function w(){if(k)return;if(c){g(e);return}const F=x?null:e.tag.full_path;r(F),l("archive")}function _(F){F.stopPropagation(),!c&&(d(e.tag.slug),j(!0))}async function b(){const F=p.trim();if(!F||F===e.tag.slug){j(!1);return}try{const W=await wh(t,e.tag.tag_uid,F);i(e.tag.full_path,W.full_path),o()}catch{}finally{j(!1)}}async function C(F){var te;F.stopPropagation();const W=((te=e.children)==null?void 0:te.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(W))try{await kh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const S={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:g,pendingCreateParentUid:m,onCreateDone:h,onCreateCancel:y},$=m===e.tag.tag_uid,P=((K=e.children)==null?void 0:K.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${c?" tag-node-row--move-select":""}`,children:[k?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:F=>d(F.target.value),onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur(),F.key==="Escape"&&(v.current=!0,F.currentTarget.blur())},onBlur:()=>{v.current?(v.current=!1,j(!1)):b()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${c?" tag-node-btn--move-select":""}`,title:c?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:w,onDoubleClick:c?void 0:_,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!c&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:F=>{F.stopPropagation(),_(F)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!k&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:C,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(P||$)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(F=>s.jsx(Rd,{node:F,...S},F.tag.tag_uid)),$&&s.jsx("li",{children:s.jsx(zd,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:y})})]})})]})}function gm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,g]=f.useState(null),[m,h]=f.useState(null);function y(){g("select-source"),h(null)}function x(){g(null),h(null)}f.useEffect(()=>{if(c!=="select-source")return;function W(te){te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),x())}return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[c]);function k(W){h(W),g("select-dest")}async function j(W){const te=m.tag.full_path,oe=m.tag.tag_uid,fe=(W==null?void 0:W.tag_uid)??null;x();try{const le=await Sh(e,oe,fe);i(te,le.full_path),o()}catch(le){alert(le.message||"Move failed")}}const[p,d]=f.useState(null),[v,w]=f.useState(void 0);function _(){d("select-parent"),w(void 0)}function b(){d(null),w(void 0)}function C(W){w(W??null),d("input")}function S(){d(null),w(void 0),o()}const $=c==="select-source",P=p==="input"?v?v.tag_uid:"__root__":void 0,K={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:$,onMoveSourceSelect:k,pendingCreateParentUid:P,onCreateDone:S,onCreateCancel:b},F=P==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:$?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:_,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:y,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!F?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(W=>s.jsx(Rd,{node:W,...K},W.tag.tag_uid)),F&&s.jsx("li",{children:s.jsx(zd,{parentPath:null,archiveId:e,onDone:S,onCancel:b})})]})]}),p==="select-parent"&&s.jsx(su,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:C,onCancel:b}),c==="select-dest"&&m&&s.jsx(su,{title:`Move "${m.tag.slug}" under…`,tagNodes:t,excludeUid:m.tag.tag_uid,onPick:j,onCancel:x})]})}const fr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],vm=e=>{var t;return((t=fr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function ym({archiveId:e}){const[t,n]=f.useState([]),[r,l]=f.useState(!1),[i,a]=f.useState(null),[o,u]=f.useState(null),[c,g]=f.useState(null),[m,h]=f.useState(!1),[y,x]=f.useState(null),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(2),[_,b]=f.useState(!1),[C,S]=f.useState(null),[$,P]=f.useState(""),[K,F]=f.useState(2),[W,te]=f.useState(!1),[oe,fe]=f.useState(null),[le,R]=f.useState(!1),[T,M]=f.useState(""),q=f.useRef(null),H=t.find(D=>D.collection_uid===o)??null,N=(H==null?void 0:H.slug)==="_default_",O=f.useCallback(async()=>{if(e){l(!0),a(null);try{const D=await Cd(e);n(D)}catch(D){a(D.message)}finally{l(!1)}}},[e]),U=f.useCallback(async D=>{if(!D){g(null);return}h(!0),x(null);try{const X=await Hh(e,D);g(X)}catch(X){x(X.message)}finally{h(!1)}},[e]);f.useEffect(()=>{O()},[O]),f.useEffect(()=>{U(o)},[o,U]),f.useEffect(()=>{le&&q.current&&q.current.focus()},[le]);async function B(D){D.preventDefault();const X=k.trim(),Ce=p.trim();if(!(!X||!Ce)){b(!0),S(null);try{const xe=await Uh(e,X,Ce,v);j(""),d(""),w(2),await O(),u(xe.collection_uid)}catch(xe){S(xe.message)}finally{b(!1)}}}async function Q(){const D=T.trim();if(!D||!H){R(!1);return}try{await nu(e,H.collection_uid,{name:D}),await O(),g(X=>X&&{...X,name:D})}catch(X){a(X.message)}finally{R(!1)}}async function pe(D){if(H)try{await nu(e,H.collection_uid,{default_visibility_bits:D}),await O(),g(X=>X&&{...X,default_visibility_bits:D})}catch(X){a(X.message)}}async function G(){if(H&&window.confirm(`Delete collection "${H.name}"? Entries will not be deleted.`))try{await Kh(e,H.collection_uid),u(null),g(null),await O()}catch(D){a(D.message)}}async function Y(D){D.preventDefault();const X=$.trim();if(!(!X||!H)){te(!0),fe(null);try{await Ed(e,H.collection_uid,X,K),P(""),await U(H.collection_uid)}catch(Ce){fe(Ce.message)}finally{te(!1)}}}async function Z(D){if(H)try{await Wh(e,H.collection_uid,D),await U(H.collection_uid)}catch(X){x(X.message)}}async function ue(D,X){if(H)try{await Vh(e,H.collection_uid,D,X),g(Ce=>Ce&&{...Ce,entries:Ce.entries.map(xe=>xe.entry_uid===D?{...xe,collection_visibility_bits:X}:xe)})}catch(Ce){x(Ce.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(D=>s.jsxs("button",{className:`coll-sidebar-row${o===D.collection_uid?" is-active":""}`,onClick:()=>u(D.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:D.name}),s.jsx("span",{className:"coll-row-meta",children:vm(D.default_visibility_bits)})]},D.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),H?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[le?s.jsx("input",{ref:q,className:"coll-rename-input",value:T,onChange:D=>M(D.target.value),onBlur:Q,onKeyDown:D=>{D.key==="Enter"&&Q(),D.key==="Escape"&&R(!1)}}):s.jsxs("h3",{className:`coll-detail-name${N?"":" coll-detail-name--editable"}`,title:N?void 0:"Click to rename",onClick:()=>{N||(M(H.name),R(!0))},children:[(c==null?void 0:c.name)??H.name,!N&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!N&&s.jsx("button",{className:"coll-delete-btn",onClick:G,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??H.default_visibility_bits,onChange:D=>pe(Number(D.target.value)),disabled:N,children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),m&&s.jsx("div",{className:"muted",children:"Loading…"}),y&&s.jsx("div",{className:"collections-error",children:y}),!m&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(D=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:D.title||D.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:D.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:D.collection_visibility_bits,onChange:X=>ue(D.entry_uid,Number(X.target.value)),children:fr.map(X=>s.jsx("option",{value:X.value,children:X.label},X.value))}),!N&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>Z(D.entry_uid),title:"Remove from collection",children:"×"})]})]},D.entry_uid))}))]}),!N&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:Y,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:$,onChange:D=>P(D.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:K,onChange:D=>F(Number(D.target.value)),children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:W,children:W?"…":"Add"})]}),oe&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:oe})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:B,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:k,onChange:D=>{j(D.target.value),p||d(D.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:D=>d(D.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:v,onChange:D=>w(Number(D.target.value)),children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),C&&s.jsx("div",{className:"collections-error",children:C}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const xm=4;function wm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=f.useContext(ps)??{},i=r&&(r.role_bits&xm)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(km,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(jm,{}),e==="instance"&&i&&s.jsx(Sm,{}),e==="cookies"&&i&&s.jsx(_m,{}),e==="extensions"&&i&&s.jsx(Cm,{}),e==="storage"&&i&&s.jsx(Nm,{archiveId:n})]})}function km({currentUser:e,setCurrentUser:t}){const[n,r]=f.useState((e==null?void 0:e.display_name)??""),[l,i]=f.useState(!1),[a,o]=f.useState(null),[u,c]=f.useState(""),[g,m]=f.useState(""),[h,y]=f.useState(""),[x,k]=f.useState(!1),[j,p]=f.useState(null);async function d(w){w.preventDefault(),i(!0),o(null);try{await Lh(n),t(_=>({..._,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(_){o({ok:!1,text:_.message})}finally{i(!1)}}async function v(w){if(w.preventDefault(),g!==h){p({ok:!1,text:"Passwords do not match."});return}k(!0),p(null);try{await Rh(u,g),c(""),m(""),y(""),p({ok:!0,text:"Password changed."})}catch(_){p({ok:!1,text:_.message})}finally{k(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:d,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const _=w.target.checked;try{await zh({humanize_slugs:_}),t(b=>({...b,humanize_slugs:_}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:g,onChange:w=>m(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:w=>y(w.target.value),required:!0})]}),j&&s.jsx("div",{className:`form-msg form-msg--${j.ok?"ok":"err"}`,children:j.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function jm(){const[e,t]=f.useState([]),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(""),[u,c]=f.useState(!1),[g,m]=f.useState(null),h=f.useCallback(async()=>{r(!0),i(null);try{t(await Dh())}catch(k){i(k.message)}finally{r(!1)}},[]);f.useEffect(()=>{h()},[h]);async function y(k){if(k.preventDefault(),!!a.trim()){c(!0);try{const j=await $h(a.trim());m(j),o(""),h()}catch(j){i(j.message)}finally{c(!1)}}}async function x(k){try{await Ih(k),t(j=>j.filter(p=>p.token_uid!==k))}catch(j){i(j.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),g&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:g.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>m(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:y,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:k=>o(k.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(k=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:k.name}),s.jsxs("div",{className:"muted",children:["Created ",k.created_at.slice(0,10),k.last_used_at&&` · Last used ${k.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(k.token_uid),children:"Revoke"})]},k.token_uid))]})]})})}function Sm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(!1),[u,c]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(m){i(m.message)}finally{r(!1)}})()},[]);async function g(m){m.preventDefault(),o(!0),c(null);try{await Nl(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:g,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([m,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[m],onChange:y=>t(x=>({...x,[m]:y.target.checked}))}),h]},m)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:m=>t(h=>({...h,default_entry_visibility:Number(m.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function qs(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function Nm({archiveId:e}){const[t,n]=f.useState("idle"),[r,l]=f.useState(null),[i,a]=f.useState(null),[o,u]=f.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function g(){n("scanning"),u(null),l(null);try{const y=await Xh(e);l(y),n("scanned")}catch(y){u(y.message),n("error")}}async function m(){n("deleting"),u(null);try{const y=await Jh(e);a(y),n("done")}catch(y){u(y.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:g,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:qs(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:m,children:["Delete (",qs(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:qs(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function _m(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState("global"),[u,c]=f.useState(""),[g,m]=f.useState("{}"),[h,y]=f.useState(null),[x,k]=f.useState(!1),[j,p]=f.useState({});f.useEffect(()=>{d()},[]);async function d(){r(!0),i(null);try{t(await Gh())}catch(S){i(S.message)}finally{r(!1)}}async function v(S){S.preventDefault();try{JSON.parse(g)}catch{y({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}k(!0),y(null);try{await Yh(a==="global"?null:u.trim(),a,g),c(""),m("{}"),o("global"),y({ok:!0,text:"Rule added."}),await d()}catch($){y({ok:!1,text:$.message})}finally{k(!1)}}async function w(S){try{await em(S),await d()}catch($){i($.message)}}function _(S){p($=>({...$,[S.rule_uid]:{cookiesInput:S.cookies_json,saving:!1,msg:null}}))}function b(S){p($=>{const P={...$};return delete P[S],P})}async function C(S){const $=j[S.rule_uid];try{JSON.parse($.cookiesInput)}catch{p(P=>({...P,[S.rule_uid]:{...P[S.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(P=>({...P,[S.rule_uid]:{...P[S.rule_uid],saving:!0,msg:null}}));try{await Zh(S.rule_uid,{cookies_json:$.cookiesInput}),b(S.rule_uid),await d()}catch(P){p(K=>({...K,[S.rule_uid]:{...K[S.rule_uid],saving:!1,msg:{ok:!1,text:P.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(S=>{const $=j[S.rule_uid],P=S.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[S.pattern_kind,":"]})," ",s.jsx("code",{children:S.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:P}),s.jsx("td",{children:$?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:$.cookiesInput,onChange:K=>p(F=>({...F,[S.rule_uid]:{...F[S.rule_uid],cookiesInput:K.target.value}}))}),$.msg&&s.jsx("div",{className:`form-msg form-msg--${$.msg.ok?"ok":"err"}`,children:$.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:$.saving,onClick:()=>C(S),children:$.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>b(S.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:S.cookies_json})}),s.jsx("td",{children:!$&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>_(S),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(S.rule_uid),children:"Del"})]})})]},S.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:S=>o(S.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:S=>c(S.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:g,onChange:S=>m(S.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function Cm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(!1),[a,o]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(j){o({ok:!1,text:j.message})}finally{r(!1)}})()},[]);async function u(j){i(!0),o(null);try{await Nl({ublock_enabled:j}),t(p=>({...p,ublock_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(j){i(!0),o(null);try{await Nl({cookie_ext_enabled:j}),t(p=>({...p,cookie_ext_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function g(j){i(!0),o(null);try{await Nl({modal_closer_enabled:j}),t(p=>({...p,modal_closer_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const m=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,y=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,k=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!m&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!y&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":k,className:`ext-toggle${k?" ext-toggle--on":""}`,onClick:()=>g(!k),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const iu={0:"Private",1:"Public",2:"Users only",3:"Public"},Em=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Tm({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:g,humanizeTags:m,onDetailRefresh:h,onOpenPreview:y,onPlay:x}){var Tt;const[k,j]=f.useState([]),[p,d]=f.useState(""),[v,w]=f.useState([]),[_,b]=f.useState(""),C=f.useRef(0),S=f.useRef(!1),[$,P]=f.useState(!1),[K,F]=f.useState(""),[W,te]=f.useState("idle"),[oe,fe]=f.useState(""),le=f.useRef(null),[R,T]=f.useState(!1);f.useEffect(()=>{T(!1)},[(Tt=l==null?void 0:l.summary)==null?void 0:Tt.entry_uid]);const M=(n==null?void 0:n.size)>=2,[q,H]=f.useState(""),[N,O]=f.useState("idle"),[U,B]=f.useState(""),[Q,pe]=f.useState([]),[G,Y]=f.useState(""),[Z,ue]=f.useState("idle"),[D,X]=f.useState(""),[Ce,xe]=f.useState("idle");f.useEffect(()=>{const I=++C.current;if(le.current&&(clearInterval(le.current),le.current=null),te("idle"),fe(""),!t||!e){j([]),w([]);return}P(!1),F(""),S.current=!1,j([]),Promise.all([cl(e,t.entry_uid),Qh(e,t.entry_uid)]).then(([se,Qe])=>{I===C.current&&(j(se),w(Qe))}).catch(()=>{})},[t,e]),f.useEffect(()=>()=>{clearInterval(le.current)},[]),f.useEffect(()=>{if(!M||!e){pe([]);return}Cd(e).then(pe).catch(()=>pe([]))},[M,e]),f.useEffect(()=>{H(""),O("idle"),B(""),Y(""),ue("idle"),X(""),xe("idle")},[n]);async function hs(){const I=n.size;if(!window.confirm(`Delete ${I} entr${I===1?"y":"ies"}? This cannot be undone.`))return;xe("running");const se=new Set;for(const Qe of n)try{await tu(e,Qe),se.add(Qe)}catch{}xe("idle"),g==null||g(se)}async function Kn(){const I=q.trim();if(I){O("running"),B("");try{for(const se of n)await eu(e,se,I);H(""),O("done"),o==null||o(),setTimeout(()=>O("idle"),1800)}catch(se){B(se.message),O("error")}}}async function ms(){if(!G)return;ue("running"),X("");const I=[];for(const se of n)try{await Ed(e,G,se)}catch{I.push(se)}I.length>0?(X(`Failed for ${I.length} entr${I.length===1?"y":"ies"}.`),ue("error")):(ue("done"),setTimeout(()=>ue("idle"),1800))}async function gs(){const I=K.trim()||null;try{await yh(e,t.entry_uid,I),u==null||u(t.entry_uid,I)}catch{}finally{P(!1)}}async function Wr(){const I=p.trim();if(!(!I||!t))try{await eu(e,t.entry_uid,I),d(""),b("");const se=await cl(e,t.entry_uid);j(se),o()}catch(se){b(se.message)}}async function vs(I){try{await xh(e,t.entry_uid,I);const se=await cl(e,t.entry_uid);j(se),o()}catch{}}async function ys(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await tu(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function xs(){if(!t||!e||W==="running")return;const I=C.current,se=t.entry_uid;te("running"),fe("");try{const{job_uid:Qe}=await qh(e,se);if(C.current!==I)return;le.current=setInterval(async()=>{try{const Jt=await _d(e,Qe);if(Jt.status==="completed"){if(clearInterval(le.current),le.current=null,C.current!==I)return;te("done");const Jn=await cl(e,se);if(C.current!==I)return;j(Jn),h==null||h()}else if(Jt.status==="failed"){if(clearInterval(le.current),le.current=null,C.current!==I)return;te("error"),fe(Jt.error_text||"Re-archive failed.")}}catch{if(clearInterval(le.current),le.current=null,C.current!==I)return;te("error"),fe("Network error while polling.")}},500)}catch(Qe){if(C.current!==I)return;te("error"),fe(Qe.message||"Failed to start re-archive.")}}const ws=l?[["Added",bd(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",iu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],ks=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),js=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),pn=l?l.artifacts.findIndex(I=>I.artifact_role==="primary_media"):-1,hn=pn>=0?l.artifacts[pn]:null,Vr=hn?hn.relpath.split(".").pop().toLowerCase():"",Qr=hn&&ks.has(Vr),mn=pn>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${pn}`:null,Xn=l&&!Qr&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||hn&&js.has(Vr));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),M?s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),U&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:U}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:q,onChange:I=>H(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Kn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Kn,disabled:N==="running"||!q.trim(),children:N==="running"?"…":N==="done"?"✓":"Add"})]})]}),Q.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:G,onChange:I=>Y(I.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Q.map(I=>s.jsx("option",{value:I.collection_uid,children:I.name},I.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:ms,disabled:!G||Z==="running",children:Z==="running"?"…":Z==="done"?"✓":Z==="error"?"!":"Add"})]}),D&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:D})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:hs,disabled:Ce==="running",children:Ce==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[$?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:K,onChange:I=>F(I.target.value),onKeyDown:I=>{I.key==="Enter"&&I.currentTarget.blur(),I.key==="Escape"&&(S.current=!0,I.currentTarget.blur())},onBlur:()=>{S.current?P(!1):gs(),S.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{F(l.summary.title??""),P(!0)},children:[nn(l.summary.title)||nn(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Ua(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Em,{})})]}),Qr&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(mn,t),children:"▶ Play"}),Xn&&y&&s.jsx("button",{className:"rail-preview-btn",onClick:y,children:"Preview"}),s.jsx("div",{className:"meta-list",children:ws.filter(([,I])=>I!=null&&I!=="").map(([I,se])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:I}),s.jsx("span",{className:`meta-v${I==="Root"?" mono":""}`,children:nn(se)})]},I))}),l.artifacts.length>0&&(()=>{const I=l.artifacts.map((z,V)=>({...z,_idx:V})),se=I.filter(z=>z.artifact_role==="font"),Qe=I.filter(z=>z.artifact_role!=="font"),Jt=se.reduce((z,V)=>z+(V.byte_size||0),0),Jn=l.summary.entry_uid,E=z=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Jn}/artifacts/${z._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:z.artifact_role==="font"?z.relpath.split("/").pop():z.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:z.byte_size!=null?Jl(z.byte_size):"—"})]})},z._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[Qe.map(E),se.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":R,onClick:()=>T(z=>!z),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${R?" open":""}`,children:"›"}),` fonts (${se.length})`]}),s.jsx("span",{className:"artifact-size",children:Jl(Jt)})]}),R&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:se.map(E)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!M&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),k.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:k.map(I=>s.jsxs("span",{className:"tag-pill",title:I.full_path,children:[m?Pd(I.full_path):I.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${I.full_path}`,onClick:()=>vs(I.tag_uid),children:"×"})]},I.tag_uid))}),_&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:_}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:p,onChange:I=>d(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Wr()}}),s.jsx("button",{className:"tag-add-btn",onClick:Wr,children:"Add"})]})]}),v.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),v.map(I=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:I.collection_uid}),s.jsx("span",{className:"vis-badge",children:iu[I.visibility_bits]??`bits:${I.visibility_bits}`})]},I.collection_uid))]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:xs,disabled:W==="running",children:W==="running"?"Re-archiving…":"Re-archive"}),W==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),W==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:oe})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:ys,children:"Delete entry"})})]})]})}function bm({src:e}){const t=f.useRef(null);return f.useEffect(()=>{t.current&&t.current.load()},[e]),s.jsx("div",{className:"preview-video-wrap",style:{background:"#111",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",minHeight:"240px"},children:e?s.jsxs("video",{ref:t,controls:!0,autoPlay:!1,style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:e}),"Your browser does not support the video element."]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function au({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function Pm({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function Dd(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function ou(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const J={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},je={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Gs={article:{background:je.bg,color:je.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:je.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:je.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:je.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:je.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${je.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${je.border}`,padding:"2px 14px",margin:"14px 0",color:je.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${je.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${je.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:je.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:je.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:je.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:je.accent,textDecoration:"none"}};function Lm(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function In(e,t,n){return e&&n[e]?n[e]:t||null}function $d(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function Ha(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function Id(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=Ha(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function Od(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=Ha(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const uu=/https?:\/\/[^\s<>"'\])]+/g,zm=/[.,;:!?)()]+$/;function ql(e,t){const n=[];let r=0,l;for(uu.lastIndex=0;(l=uu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(zm,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rId(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>Od(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return ql(ou(e),J.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,g])=>c<=o&&g>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const g=e.slice(o,c),m=r.filter(x=>x.s<=o&&x.e>=c),h=m.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:J.link,children:h.display||g},u);const y=m.find(x=>x.kind==="mention");return y?s.jsx("a",{href:`https://x.com/${y.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:J.link,children:g},u):s.jsx("span",{children:ql(ou(g),J.link)},u)}).filter(o=>o!==null)}function Dm(e,t,n,r,l=J){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=Id(u,e);c&&i.push(c)}for(const u of r){const c=Od(u,e);c&&i.push(c)}if(i.length===0)return ql(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const g=o[c+1],m=i.filter(j=>j.s<=u&&j.e>=g),h=e.slice(u,g);let y;if(h.includes(` +`)){const j=h.split(` +`);y=j.flatMap((p,d)=>dj.kind==="style"&&j.style==="Code")&&(y=s.jsx("code",{style:l.iCode,children:y})),m.some(j=>j.kind==="style"&&j.style==="Bold")&&(y=s.jsx("strong",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Italic")&&(y=s.jsx("em",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Underline")&&(y=s.jsx("u",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Strikethrough")&&(y=s.jsx("s",{children:y}));const x=m.find(j=>j.kind==="url");if(x){const j=/^https?:\/\/t\.co\//i.test(y);y=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:j?x.display:y})}const k=m.find(j=>j.kind==="mention");return k&&(y=s.jsx("a",{href:`https://x.com/${k.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:y})),s.jsx("span",{children:typeof y=="string"?ql(y,l.link):y},c)})}function $m(e,t,n){const r=(n==null?void 0:n.st)||J,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=In(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var g;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(g=n==null?void 0:n.onImgClick)==null||g.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx($d,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function Ys(e,t,n,r){const l=(r==null?void 0:r.st)||J,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=Dm(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const g=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return g?s.jsxs("a",{href:`https://x.com/i/status/${g[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx($d,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:$m(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function Im(e,t,n){const r=(n==null?void 0:n.st)||J,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Gs:J,u=e.cover_media||{},c=e.author||t||{},g=e.first_published_at_secs?Dd(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",g].filter(Boolean).join(" · "),y=In(u.local_path,u.url,n),x=In(c.avatar_local_path,c.avatar_url,n),k=s.jsxs(s.Fragment,{children:[i&&s.jsx(Ad,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),y&&s.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:j=>{!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),a(y))},children:s.jsx("img",{src:y,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Im(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:Gs.article,children:s.jsx("div",{style:Gs.articleInner,children:k})}):s.jsx("div",{style:J.article,children:k})}function Am({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:J.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function Ad({items:e,startIndex:t,onClose:n}){const[r,l]=f.useState(t);f.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:J.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:J.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:J.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:J.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:J.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:J.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:J.lightboxImg}),e.length>1&&s.jsxs("div",{style:J.lightboxNav,children:[s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function cu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var d,v;const[l,i]=f.useState(null),a=e.author||{},o=e.created_at_secs?Dd(e.created_at_secs):"",u=e.entities||{},c=In(a.avatar_local_path,a.avatar_url,r),g=t&&!n,m=e.is_quote_status===!0,h=t?J.tweetRowThread:J.tweetRow,y=e.full_text||"",x=((v=(d=e.extended_entities)==null?void 0:d.media)!=null&&v.length?e.extended_entities.media:u.media)||[],k=[],j=[];for(const w of x)if(w.type==="photo"){const _=In(w.local_path,w.media_url_https,r);_&&k.push({kind:"photo",src:_,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const _=w.local_path&&r[w.local_path]||(()=>{var C,S;return(S=(((C=w.video_info)==null?void 0:C.variants)||[]).filter($=>$.content_type==="video/mp4").sort(($,P)=>(P.bitrate||0)-($.bitrate||0))[0])==null?void 0:S.url})();_&&j.push({kind:w.type==="animated_gif"?"gif":"video",src:_})}const p=[];for(const w of x){if(!w.url||!(w.type==="photo"?k.some(C=>C.src===In(w.local_path,w.media_url_https,r)):j.length>0))continue;const b=Ha(w,y,w.url);b&&p.push([b.s,b.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Ad,{items:k,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:J.leftCol,children:[c?s.jsx("img",{src:c,style:J.avatar,alt:a.name||""}):s.jsx("div",{style:J.avatarPh}),g&&s.jsx("div",{style:J.threadLine})]}),s.jsxs("div",{style:J.rightCol,children:[s.jsxs("div",{style:J.authorRow,children:[s.jsx("span",{style:J.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:J.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:J.datePart,children:["· ",o]}),m&&s.jsx("span",{style:J.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:J.tweetText,children:Rm(y,u,p)}),k.length>0&&s.jsx("div",{style:J.mediaGrid,children:s.jsx(Am,{photos:k,onOpen:w=>i(w)})}),j.map((w,_)=>s.jsx("div",{style:J.mediaGrid,children:s.jsx("video",{src:w.src,style:J.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},_)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:J.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function Mm({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=f.useState(!0),[u,c]=f.useState(null),[g,m]=f.useState([]);if(f.useEffect(()=>{if(o(!0),c(null),m([]),!n||!e||!t){o(!1);return}const x=n.map((j,p)=>({...j,index:p})).filter(j=>j.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let k=!1;return gh(e,t,x.map(j=>j.index)).then(async j=>{if(k)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,d=C=>{var $;const S=C.full_text||"";return((($=C.entities)==null?void 0:$.urls)||[]).map(P=>{var K;if(P.fromIndex!=null&&P.toIndex!=null)return[P.fromIndex,P.toIndex];if(((K=P.indices)==null?void 0:K.length)===2)return[P.indices[0],P.indices[1]];if(P.url){const F=S.indexOf(P.url);if(F!==-1)return[F,F+P.url.length]}return null}).filter(Boolean)},v=(C,S,$)=>C.some(([P,K])=>P<=S&&K>=$),w=new Set;for(const C of j){const S=C.full_text||"",$=d(C);let P;for(p.lastIndex=0;(P=p.exec(S))!==null;)v($,P.index,P.index+P[0].length)||w.add(P[0])}const _=w.size>0?await vh([...w]).catch(()=>({})):{},b=j.map(C=>{var F;const S=C.full_text||"",$=d(C),P=[];let K;for(p.lastIndex=0;(K=p.exec(S))!==null;){const W=K[0],te=_[W];te&&te!==W&&!v($,K.index,K.index+W.length)&&P.push({url:W,expanded_url:te,display_url:(()=>{try{const oe=new URL(te);return oe.hostname+(oe.pathname.length>1?"/…":"")}catch{return te}})(),fromIndex:K.index,toIndex:K.index+W.length})}return P.length===0?C:{...C,entities:{...C.entities||{},urls:[...((F=C.entities)==null?void 0:F.urls)||[],...P]}}});k||m(b)}).catch(j=>{k||c(j.message||"Failed to load tweet.")}).finally(()=>{k||o(!1)}),()=>{k=!0}},[e,t,n]),a)return s.jsx("div",{style:J.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:J.error,children:["Error: ",u]});if(g.length===0)return null;const h=Lm(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:J.threadOuter,children:g.map((x,k)=>s.jsx(cu,{tweet:x,isInThread:!0,isLast:k===g.length-1,artifactMap:h},x.id||k))});const y=g[0];return y.is_article&&y.article?s.jsx(Om,{article:y.article,tweetAuthor:y.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:J.card,children:s.jsx(cu,{tweet:y,isInThread:!1,isLast:!0,artifactMap:h})})}const Fm=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Bm=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Um=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]);function Md({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const y=s.jsx(Mm,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?y:s.jsx("div",{className:"preview-tweet-wrap",children:y})}const c=a.findIndex(y=>y.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]});const g=a[c],m=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=g.relpath.split(".").pop().toLowerCase();return Fm.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(bm,{src:m})}):Bm.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:m,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(au,{src:m,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(au,{src:m,type:"page",title:i.title,originalUrl:i.original_url})}):Um.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Pm,{src:m,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]})}function Hm({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return f.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(Md,{archiveId:e,entry:t,detail:n})})]})})}function du(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function Wm({entry:e,src:t,archiveId:n,onClose:r}){const l=f.useRef(null),[i,a]=f.useState(!1),[o,u]=f.useState(0),[c,g]=f.useState(NaN),[m,h]=f.useState(1);f.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),g(NaN),a(!1))},[t]),f.useEffect(()=>{l.current&&(l.current.volume=m)},[m]);function y(){const d=l.current;d&&(i?d.pause():d.play().catch(()=>{}))}function x(d){const v=l.current;if(!v||!isFinite(c))return;const w=Number(d.target.value);v.currentTime=w,u(w)}function k(d){h(Number(d.target.value))}const j=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var d;return u(((d=l.current)==null?void 0:d.currentTime)??0)},onLoadedMetadata:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},onDurationChange:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Ua(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:j,children:j})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:y,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:du(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:du(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:m,onChange:k,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function Vm({archiveId:e,entryUid:t}){var h,y;const[n,r]=f.useState(null),[l,i]=f.useState(!0),[a,o]=f.useState(null),[u,c]=f.useState(!1);f.useEffect(()=>{if(!u)return;const x=document.documentElement,k=document.body,j=x.style.colorScheme,p=k.style.background;return x.style.colorScheme="dark",k.style.background="#000",()=>{x.style.colorScheme=j,k.style.background=p}},[u]),f.useEffect(()=>{c(!1),Vi(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const g=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,m=(y=n==null?void 0:n.summary)==null?void 0:y.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g}),m&&s.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(Md,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Qm=7e3;function Km({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Jm,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Xm(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Jm({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=f.useState(!1),i=e.type==="warning",a=e.type==="success";f.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Qm);return()=>clearTimeout(u)},[r,e.id,t]);const o=Xm(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const ps=f.createContext(null),ar=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})(),qm=["archive","tags","collections","runs","admin","settings"],Gm=["profile","tokens","instance","cookies","extensions","storage"];function qt(){const e=window.location.pathname.split("/").filter(Boolean),t=qm.includes(e[0])?e[0]:"archive",n=t==="settings"&&Gm.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null;return{view:t,settingsTab:n,q:l,tag:i,entry:a}}function Ym(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Zm(){const[e,t]=f.useState("loading"),[n,r]=f.useState(null);f.useEffect(()=>{(async()=>{if(await Ch()){t("setup");return}const z=await Ph();if(!z){t("login");return}r(z),t("authenticated")})()},[]),f.useEffect(()=>{const E=()=>{r(null),t("login")};return window.addEventListener("auth:expired",E),()=>window.removeEventListener("auth:expired",E)},[]),f.useEffect(()=>{const E=()=>{const{view:z,settingsTab:V,q:re,tag:ze,entry:Ze}=qt();v(z),_(V),C(re),p(ze),m(Ze),y(null),k(Ze?new Set([Ze]):new Set)};return window.addEventListener("popstate",E),()=>window.removeEventListener("popstate",E)},[]);const[l,i]=f.useState([]),[a,o]=f.useState(null),[u,c]=f.useState([]),[g,m]=f.useState(()=>qt().entry),[h,y]=f.useState(null),[x,k]=f.useState(()=>{const E=qt().entry;return E?new Set([E]):new Set}),[j,p]=f.useState(()=>qt().tag),[d,v]=f.useState(()=>qt().view),[w,_]=f.useState(()=>qt().settingsTab),[b,C]=f.useState(()=>qt().q),[S,$]=f.useState(""),[P,K]=f.useState(!1),[F,W]=f.useState([]),[te,oe]=f.useState([]),[fe,le]=f.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[R,T]=f.useState([]),M=f.useRef(0),[q,H]=f.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[N,O]=f.useState(null),U=f.useRef(0),B=f.useRef(null),Q=f.useRef(!1),pe=f.useRef(!0),G=f.useRef(null),Y=(n==null?void 0:n.humanize_slugs)??!1;f.useEffect(()=>{const E=++U.current;O(null),!(!h||!a)&&Vi(a,h.entry_uid).then(z=>{E===U.current&&O(z)}).catch(()=>{})},[h,a]),f.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",fe)},[fe]);const Z=f.useCallback(async(E,z,V)=>{if(E){K(!0);try{let re;z||V?re=await mh(E,z,V):re=await hh(E),c(re),k(ze=>{if(ze.size<2)return ze;const Ze=new Set(re.map(gn=>gn.entry_uid)),qn=new Set([...ze].filter(gn=>Ze.has(gn)));return qn.size===ze.size?ze:qn}),$(re.length===0?"No results":`${re.length} result${re.length===1?"":"s"}`)}catch{c([]),$("Search failed. Try again.")}finally{K(!1)}}},[]);f.useEffect(()=>{e==="authenticated"&&ph().then(E=>{if(i(E),E.length>0){const z=E[0].id;o(z)}})},[e]),f.useEffect(()=>{if(a){if(pe.current){pe.current=!1,Promise.all([Js(a).then(W),dl(a).then(oe)]);return}p(null),y(null),m(null),k(new Set),Promise.all([Z(a,"",null),Js(a).then(W),dl(a).then(oe)])}},[a]),f.useEffect(()=>{if(a===null)return;const E=setTimeout(()=>{Z(a,b,j)},300);return()=>clearTimeout(E)},[b,a]),f.useEffect(()=>{a!==null&&(j!==null&&v("archive"),Z(a,b,j))},[j,a]);const ue=f.useCallback(E=>{o(E)},[]),D=f.useCallback(E=>{v(E),E==="tags"&&a&&dl(a).then(oe)},[a]);f.useEffect(()=>{if(ar)return;const E=Ym(d,w);window.location.pathname!==E&&history.pushState(null,"",E+window.location.search)},[d,w]);const X=f.useCallback(E=>{m(E?E.entry_uid:null),y(E)},[]),Ce=f.useCallback((E,z)=>{if(z.shiftKey&&G.current!==null){z.preventDefault();const V=u.findIndex(Gn=>Gn.entry_uid===G.current),re=u.findIndex(Gn=>Gn.entry_uid===E.entry_uid);if(V===-1||re===-1){G.current=E.entry_uid,k(new Set([E.entry_uid])),X(E);return}const ze=Math.min(V,re),Ze=Math.max(V,re),qn=u.slice(ze,Ze+1),gn=new Set(qn.map(Gn=>Gn.entry_uid));k(gn),gn.size===1&&X(qn[0])}else z.ctrlKey||z.metaKey?(G.current=E.entry_uid,k(V=>{const re=new Set(V);return re.has(E.entry_uid)?re.delete(E.entry_uid):re.add(E.entry_uid),re})):(G.current=E.entry_uid,k(new Set([E.entry_uid])),X(E))},[u,X]),xe=f.useCallback(E=>{p(E)},[]),hs=f.useCallback(()=>{p(null)},[]),Kn=f.useCallback(()=>{a&&dl(a).then(oe)},[a]),ms=f.useCallback((E,z)=>{j===E?p(z):j!=null&&j.startsWith(E+"/")&&p(z+j.slice(E.length))},[j]),gs=f.useCallback(E=>{(j===E||j!=null&&j.startsWith(E+"/"))&&p(null)},[j]),Wr=f.useCallback((E,z)=>{c(V=>V.map(re=>re.entry_uid===E?{...re,title:z}:re)),y(V=>V&&V.entry_uid===E?{...V,title:z}:V),O(V=>V&&V.summary.entry_uid===E?{...V,summary:{...V.summary,title:z}}:V)},[]),vs=f.useCallback(()=>{if(!a||!h)return;const E=++U.current;Vi(a,h.entry_uid).then(z=>{E===U.current&&O(z)}).catch(()=>{})},[a,h]),ys=f.useCallback(E=>{c(z=>z.filter(V=>V.entry_uid!==E)),y(z=>(z==null?void 0:z.entry_uid)===E?null:z),m(z=>z===E?null:z),k(z=>{const V=new Set(z);return V.delete(E),V})},[]),xs=f.useCallback(E=>{c(z=>z.filter(V=>!E.has(V.entry_uid))),k(new Set),y(null),m(null)},[]);f.useEffect(()=>{if(x.size>=2)m(null),y(null);else if(x.size===1){const[E]=x;m(E)}else m(null),y(null)},[x]);const ws=f.useMemo(()=>u.filter(E=>x.has(E.entry_uid)),[u,x]);f.useEffect(()=>{if(!g||h)return;const E=u.find(z=>z.entry_uid===g);E&&y(E)},[u,g,h]),f.useEffect(()=>{if(ar)return;const E=new URLSearchParams;b&&E.set("q",b),d==="archive"&&j&&E.set("tag",j),d==="archive"&&g&&E.set("entry",g);const z=E.toString(),V=window.location.pathname+(z?"?"+z:"");window.location.pathname+window.location.search!==V&&history.replaceState(null,"",V)},[b,j,g,d]),f.useEffect(()=>{const E=z=>{var V,re;(z.metaKey||z.ctrlKey)&&z.key==="k"&&(z.preventDefault(),d==="archive"?((V=B.current)==null||V.focus(),(re=B.current)==null||re.select()):(Q.current=!0,v("archive")))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[d]),f.useEffect(()=>{d==="archive"&&Q.current&&(Q.current=!1,requestAnimationFrame(()=>{var E,z;(E=B.current)==null||E.focus(),(z=B.current)==null||z.select()}))},[d]);const ks=f.useCallback(()=>{le(!0)},[]),js=f.useCallback(()=>{le(!1)},[]),pn=f.useCallback(()=>{a&&Promise.all([Z(a,b,j),Js(a).then(W)])},[a,b,j,Z]),hn=f.useCallback((E,z,V="error",re=null)=>{if(V==="warning"&&q&&z)return;const ze=++M.current;T(Ze=>[...Ze,{id:ze,text:E,locator:z,type:V,headline:re}])},[q]),Vr=f.useCallback(E=>{T(z=>z.filter(V=>V.id!==E))},[]),Qr=f.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),H(!0),T(E=>E.filter(z=>!(z.type==="warning"&&z.locator)))},[]),[mn,Xn]=f.useState(null),[Tt,I]=f.useState(null),se=f.useCallback(()=>{h&&Xn(h.entry_uid)},[h]),Qe=f.useCallback(()=>Xn(null),[]),Jt=f.useCallback((E,z)=>{I({src:E,entry:z})},[]),Jn=f.useCallback(()=>I(null),[]);return f.useEffect(()=>{Xn(null)},[h]),f.useEffect(()=>{const E=z=>{var re,ze,Ze;if(z.key!=="Escape"||fe||mn)return;const V=(re=document.activeElement)==null?void 0:re.tagName;V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||x.size>0&&(z.preventDefault(),k(new Set),(Ze=(ze=document.activeElement)==null?void 0:ze.blur)==null||Ze.call(ze))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[fe,mn,x]),f.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Tt),()=>document.body.classList.remove("has-audio-bar")),[Tt]),e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(rm,{onComplete:()=>t("login")}):e==="login"?s.jsx(nm,{onLogin:E=>{r(E),t("authenticated")}}):ar?s.jsx(Vm,{archiveId:ar.archiveId,entryUid:ar.entryUid}):s.jsx(ps.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(lm,{archives:l,archiveId:a,onArchiveChange:ue,view:d,onViewChange:D,onCaptureClick:ks}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[d==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:B,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":P,placeholder:"Search titles, URLs, types, tags…",value:b,onChange:E=>C(E.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[S&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:S.split(" ")[0]})," ",S.split(" ").slice(1).join(" ")]}),j&&s.jsxs("button",{className:"tag-filter-badge",onClick:hs,children:["× ",Y?Pd(j):j]})]})]}),d==="archive"&&s.jsx(cm,{entries:u,selectedUids:x,onRowClick:Ce,archiveId:a}),d==="runs"&&s.jsx(pm,{runs:F}),d==="admin"&&s.jsx(mm,{archives:l}),d==="tags"&&s.jsx(gm,{archiveId:a,tagNodes:te,tagFilter:j,onTagFilterSet:xe,onViewChange:D,onTagRenamed:ms,onTagDeleted:gs,onTagsRefresh:Kn,humanizeTags:Y}),d==="collections"&&s.jsx(ym,{archiveId:a}),d==="settings"&&s.jsx(wm,{tab:w,onTabChange:_,archiveId:a})]}),s.jsx(Tm,{archiveId:a,selectedEntry:h,selectedUids:x,selectedEntries:ws,detail:N,onTagFilterSet:xe,tagNodes:te,onTagsRefresh:Kn,onEntryTitleChange:Wr,onEntryDeleted:ys,onBulkDeleted:xs,humanizeTags:Y,onDetailRefresh:vs,onOpenPreview:se,onPlay:Jt})]}),mn&&h&&h.entry_uid===mn&&s.jsx(Hm,{archiveId:a,entry:h,detail:N,onClose:Qe}),Tt&&s.jsx(Wm,{entry:Tt.entry,src:Tt.src,archiveId:a,onClose:Jn}),s.jsx(sm,{open:fe,archiveId:a,onClose:js,onCaptured:pn,onToast:hn}),s.jsx(Km,{toasts:R,onDismiss:Vr,onIgnoreUblock:Qr})]})})}Nd(document.getElementById("root")).render(s.jsx(f.StrictMode,{children:s.jsx(Zm,{})})); diff --git a/crates/archivr-server/static/assets/index-C0COQCCD.css b/crates/archivr-server/static/assets/index-DLdY9nrw.css similarity index 50% rename from crates/archivr-server/static/assets/index-C0COQCCD.css rename to crates/archivr-server/static/assets/index-DLdY9nrw.css index 305feb9..a2a5f32 100644 --- a/crates/archivr-server/static/assets/index-C0COQCCD.css +++ b/crates/archivr-server/static/assets/index-DLdY9nrw.css @@ -1 +1 @@ -@import"https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600&family=Spectral:wght@500;600&display=swap";:root{color-scheme:light;--ink: #20251f;--muted: #6b6f66;--muted-2: #8a8d83;--paper: #f5f0e7;--paper-2: #e9e1d2;--paper-3: #fffaf0;--line: #d2c6b5;--line-soft: #e5dccd;--accent: #8d3f30;--accent-2: #b78342;--link: #245f72;--top: #141d18;--field: #fffdf7;--r: 3px;--r2: 6px;--r3: 10px;--sans: "Helvetica Neue", Helvetica, Arial, sans-serif;--serif: "Spectral", Georgia, "Times New Roman", serif;--display: "Cormorant Garamond", Georgia, serif}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:14px;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button,input,select{font:inherit}.workspace,.context-rail{scrollbar-width:thin;scrollbar-color:var(--line) transparent}.workspace::-webkit-scrollbar,.context-rail::-webkit-scrollbar{width:11px;height:11px}.workspace::-webkit-scrollbar-track,.context-rail::-webkit-scrollbar-track{background:transparent}.workspace::-webkit-scrollbar-thumb,.context-rail::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:3px solid transparent;background-clip:padding-box}.workspace::-webkit-scrollbar-thumb:hover,.context-rail::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:3px solid transparent}.topbar{height:58px;display:grid;grid-template-columns:auto auto 1fr auto auto;align-items:center;gap:26px;padding:0 22px;background:var(--top);color:#efe6d6;border-bottom:3px solid var(--accent)}.brand{font-family:var(--display);font-weight:600;font-size:30px;line-height:1;letter-spacing:.01em;color:#f4ead8}.switcher{position:relative;display:inline-flex;align-items:center}.switcher select{-moz-appearance:none;appearance:none;-webkit-appearance:none;border:1px solid rgba(247,238,223,.2);background:#f7eedf0f;color:#f1e8d8;font-family:var(--sans);font-weight:550;font-size:13.5px;letter-spacing:.04em;padding:8px 32px 8px 15px;cursor:pointer;border-radius:6px;transition:background .15s ease,border-color .15s ease}.switcher select:hover{background:#f7eedf1c;border-color:#f7eedf57}.switcher:after{content:"";position:absolute;right:15px;top:50%;width:6px;height:6px;margin-top:-5px;border-right:1.2px solid #b6ab98;border-bottom:1.2px solid #b6ab98;transform:rotate(45deg);pointer-events:none}.nav{display:flex;gap:22px;justify-content:flex-end;min-width:0}.nav-link{border:0;background:transparent;color:#cdc1ad;cursor:pointer;padding:6px 0;font-size:12.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;position:relative}.nav-link:hover,.nav-link.is-active{color:#f4ead8}.nav-link.is-active:after{content:"";position:absolute;left:0;right:0;bottom:-2px;height:1px;background:var(--accent-2)}.capture-button{display:inline-flex;align-items:center;gap:8px;position:relative;overflow:hidden;border:0;background:linear-gradient(180deg,color-mix(in srgb,var(--accent) 88%,#fff) 0%,var(--accent) 55%);color:#f7eddd;padding:10px 18px;cursor:pointer;font-size:12px;font-weight:600;letter-spacing:.15em;text-transform:uppercase;border-radius:var(--r);box-shadow:inset 0 1px #fff5e629,0 1px 2px #141d184d;transition:filter .18s ease,box-shadow .18s ease}.capture-button:hover{filter:brightness(.93);box-shadow:inset 0 1px #fff5e61f,0 2px 6px #141d1857}.capture-button:before{content:"";position:absolute;top:0;bottom:0;left:0;width:45%;background:linear-gradient(100deg,transparent 0%,rgba(255,246,232,.45) 50%,transparent 100%);transform:translate(-180%) skew(-18deg);pointer-events:none}@media (prefers-reduced-motion: no-preference){.capture-button:hover:before{animation:cap-sheen .7s ease}}@keyframes cap-sheen{0%{transform:translate(-180%) skew(-18deg)}to{transform:translate(340%) skew(-18deg)}}.app-shell{height:calc(100vh - 58px);display:grid;grid-template-columns:minmax(0,1fr) 340px}.workspace{min-width:0;overflow:auto;display:flex;flex-direction:column}.view{display:none}.view.is-active{display:block}.toolbar{position:sticky;top:0;z-index:3;display:flex;align-items:center;gap:16px;padding:12px 22px;background:color-mix(in srgb,var(--paper) 88%,white);border-bottom:1px solid var(--line-soft)}.search-field{position:relative;flex:1 1 auto;min-width:0;display:flex;align-items:center;height:42px;background:var(--field);border:1px solid var(--line);border-radius:20px;transition:border-color .15s ease,box-shadow .15s ease}.search-field:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.search-field .ico{display:grid;place-items:center;width:46px;height:100%;color:var(--muted-2);flex-shrink:0}.search-field .ico svg{width:16px;height:16px}.search-input{flex:1;min-width:0;height:100%;border:0;background:transparent;color:var(--ink);padding:0 6px 0 0;font-size:14px;letter-spacing:.01em;outline:none}.search-input::placeholder{color:var(--muted-2)}.search-field .kbd{margin-right:12px;display:inline-flex;align-items:center;padding:3px 7px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:var(--r);flex-shrink:0}.result-count{flex-shrink:0;font-size:13px;color:var(--muted);letter-spacing:.02em;white-space:nowrap}.result-count b{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums}.tag-filter-badge{display:inline-flex;align-items:center;gap:4px;background:var(--accent);color:#fff;border:0;border-radius:var(--r);font-size:12px;padding:2px 8px;cursor:pointer;margin-left:8px}.tag-filter-badge:hover{opacity:.85}.entry-table{width:100%;font-size:12.5px}.entry-header-row{display:flex;align-items:stretch;position:sticky;top:67px;z-index:2;background:color-mix(in srgb,var(--paper) 92%,white);border-bottom:1px solid var(--line-soft);color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600;display:flex;align-items:center}#entries-body>div{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft)}#entries-body>div>div{padding:7px 10px;flex-shrink:0;overflow:hidden}#entries-body>div:nth-child(2n){background:#f2ede5}#entries-body>div:nth-child(odd){background:var(--paper-3)}#entries-body>div.is-selected{background:#eee2d2;outline:2px solid var(--accent);outline-offset:-2px}#entries-body>div.is-multi-selected{background:#eee2d2;outline:2px solid var(--accent);outline-offset:-2px}.col-added{width:162px;color:var(--muted)}.col-title{flex:1 1 0;min-width:0;overflow:hidden;display:flex;align-items:center;gap:.42em}.col-type{width:116px}.col-size{width:100px;display:flex;flex-direction:column;justify-content:center;gap:1px}.size-total{font-variant-numeric:tabular-nums}.size-cached-pct{font-size:10px;color:var(--muted);opacity:.8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.col-url{flex:0 0 30%;min-width:0;overflow:hidden}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:22px}.entry-header-row>div:last-child,#entries-body>div>div:last-child{padding-right:22px}.entry-title{color:var(--link);font-weight:700;min-width:0}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600}.source-icon{display:flex;align-items:center;justify-content:center;width:1.05em;height:1.05em;flex-shrink:0}.source-icon>*{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.source-icon svg{width:100%;height:100%}.url-cell{color:#555b55;white-space:nowrap;text-overflow:ellipsis;word-break:break-all}#entries-body .url-cell:hover,#entries-body .is-selected .url-cell{overflow:visible;white-space:normal}.type-pill{display:inline-block;padding:2px 6px;background:#d8e3df;color:#275a5f;border:1px solid #bfd0ca;border-radius:var(--r)}.col-check{display:none;width:40px;flex-shrink:0;align-items:center;justify-content:center;padding:0!important;cursor:pointer}.row-checkbox{-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:0;border:1.5px solid var(--line);cursor:pointer;display:block;width:17px;height:17px;border-radius:4px;background:var(--paper-3);transition:border-color .15s ease,background .15s ease;position:relative;flex-shrink:0}.row-checkbox.is-checked{background:var(--accent);border-color:var(--accent)}.row-checkbox.is-checked:after{content:"";position:absolute;left:4px;top:2px;width:5px;height:8px;border:2px solid #fff;border-top:none;border-left:none;transform:rotate(45deg)}@media (pointer: coarse){.col-check{display:flex}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:10px}}#runs-view .entry-table{border-collapse:collapse;table-layout:auto}#runs-view .entry-table th{position:sticky;top:0;z-index:1;text-align:left;padding:10px;background:color-mix(in srgb,var(--paper) 92%,white);color:var(--muted);border-bottom:1px solid var(--line-soft);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}#runs-view .entry-table td{padding:10px;border-bottom:1px solid var(--line-soft);vertical-align:top}#runs-view .entry-table tr:nth-child(2n) td{background:#f2ede5}#runs-view .entry-table tr:nth-child(odd) td{background:var(--paper-3)}.context-rail{border-left:1px solid var(--line);background:var(--paper);padding:20px 20px 32px;overflow:auto}.rail-eyebrow{font-size:10.5px;font-weight:600;letter-spacing:.16em;text-transform:uppercase;color:var(--muted-2);margin-bottom:16px}.rail-title{display:block;font-family:var(--sans);font-weight:700;font-size:15.5px;line-height:1.4;color:var(--ink);margin:0 0 16px;word-break:break-word}.url-tile{display:flex;align-items:center;gap:9px;padding:10px 12px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);margin-bottom:20px;text-decoration:none}.url-tile:hover{background:var(--field);border-color:var(--accent)}.url-tile .ico{color:var(--ink);flex-shrink:0;display:grid;place-items:center}.url-tile .ico svg{width:15px;height:15px}.url-tile .u-text{min-width:0;flex:1;font-size:12.5px;color:var(--link);font-family:ui-monospace,SF Mono,Menlo,monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.url-tile .ext{color:var(--muted-2);flex-shrink:0}.url-tile .ext svg{width:13px;height:13px;display:block}.meta-list{margin-bottom:24px;border-top:1px solid var(--line-soft)}.meta-item{display:grid;grid-template-columns:92px 1fr;gap:14px;align-items:baseline;padding:9px 0;border-bottom:1px solid var(--line-soft)}.meta-k{font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted-2)}.meta-v{font-size:13.5px;color:var(--ink);word-break:break-word;line-height:1.4}.meta-v.mono{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:12px;color:var(--muted)}.rail-section{margin-bottom:24px}.rail-section-heading{display:flex;align-items:baseline;gap:8px;font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.12em;color:var(--muted-2);margin-bottom:9px;padding-bottom:8px;border-bottom:1px solid var(--line)}.rail-section-heading .num{color:var(--muted-2);font-weight:600}.artifact-list{list-style:none;margin:0;padding:0}.artifact-link{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:7px 2px;border-bottom:1px solid var(--line-soft);text-decoration:none}.artifact-link:last-child{border-bottom:0}.artifact-name{font-size:13px;color:var(--link);min-width:0;word-break:break-word}.artifact-link:hover .artifact-name{text-decoration:underline}.artifact-size{font-size:11.5px;color:var(--muted-2);flex-shrink:0;font-variant-numeric:tabular-nums}.artifact-group{list-style:none}.artifact-group-header{width:100%;background:none;border:none;border-bottom:1px solid var(--line-soft);cursor:pointer;text-align:left;color:inherit;font:inherit}.artifact-group-header:hover .artifact-name{text-decoration:underline}.artifact-group-chevron{display:inline-block;font-style:normal;transition:transform .15s ease;transform:rotate(0);transform-origin:45% 50%;margin-right:3px}.artifact-group-chevron.open{transform:rotate(90deg)}.artifact-group-body{padding-left:14px}.tags-wrap{display:flex;flex-wrap:wrap;gap:7px;margin:0 0 12px}.tag-pill{display:inline-flex;align-items:center;gap:7px;background:var(--paper-2);border:1px solid var(--line);border-radius:var(--r);font-size:12px;padding:4px 7px 4px 10px;color:var(--ink)}.tag-pill .remove{border:0;background:transparent;cursor:pointer;color:var(--muted-2);width:15px;height:15px;display:grid;place-items:center;font-size:13px;line-height:1}.tag-pill .remove:hover{color:var(--accent)}.tags-empty{font-size:13px;color:var(--muted);margin:0 0 11px}.tag-input-wrap{display:flex;align-items:center;gap:8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);padding:2px 2px 2px 11px;transition:border-color .15s ease,box-shadow .15s ease}.tag-input-wrap:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 12%,transparent)}.tag-input-wrap .hash{color:var(--muted-2);font-size:13px}.tag-input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font-size:13px;padding:6px 0;outline:none;font-family:ui-monospace,SF Mono,Menlo,monospace}.tag-add-btn{border:0;background:var(--ink);color:var(--paper-3);padding:6px 13px;font-size:11.5px;letter-spacing:.06em;text-transform:uppercase;border-radius:var(--r);cursor:pointer;white-space:nowrap}.tag-add-btn:hover{background:#2c332b}.coll-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 13px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);margin-bottom:6px;transition:border-color .15s ease}.coll-row:hover{border-color:var(--accent)}.coll-name{font-size:13px;color:var(--ink);font-weight:500}.vis-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:999px;padding:3px 10px}.vis-badge:before{content:"";width:6px;height:6px;border-radius:50%;background:var(--accent-2)}.bulk-panel{padding-top:2px}.bulk-count{font-size:13px;color:var(--muted);margin-bottom:22px}.bulk-count-num{font-size:22px;font-weight:700;color:var(--ink);line-height:1;margin-right:4px}.bulk-coll-row{display:flex;align-items:center;gap:8px}.bulk-coll-select{flex:1;min-width:0;height:32px;padding:0 8px;border:1px solid var(--line);border-radius:var(--r);background:var(--field);color:var(--ink);font-size:13px;cursor:pointer;outline:none;transition:border-color .15s ease}.bulk-coll-select:focus{border-color:var(--accent)}.tag-add-btn:disabled{opacity:.45;cursor:default}.rail-delete-zone{margin-top:24px;padding-top:20px;border-top:1px solid var(--line-soft)}.rail-delete-btn{width:100%;padding:8px 14px;background:none;border:1px solid color-mix(in srgb,var(--accent) 45%,transparent);color:var(--accent);border-radius:var(--r);cursor:pointer;font-size:12.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;transition:background .15s ease,border-color .15s ease}.rail-delete-btn:hover{background:color-mix(in srgb,var(--accent) 8%,transparent);border-color:var(--accent)}.rail-rearchive-btn{width:100%;padding:6px 12px;background:var(--surface-2, #2a2a2a);color:var(--text, #e0e0e0);border:1px solid var(--border, #444);border-radius:4px;cursor:pointer;font-size:13px}.rail-rearchive-btn:hover:not(:disabled){background:var(--surface-3, #333)}.rail-rearchive-btn:disabled{opacity:.6;cursor:not-allowed}.capture-dialog{border:1px solid var(--line);background:var(--paper);padding:0;width:min(540px,calc(100vw - 32px));border-radius:var(--r3);box-shadow:0 20px 60px #141d1847}.capture-dialog::backdrop{background:#141d1873}.capture-dialog-inner{padding:28px}.capture-dialog-title{margin:0;font-size:22px;font-family:var(--display);font-weight:600}.capture-label{display:block;font-size:11px;font-weight:600;margin-bottom:6px;color:var(--muted-2);text-transform:uppercase;letter-spacing:.06em}.capture-input{width:100%;height:44px;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:0 14px;font-size:15px;margin-bottom:10px;border-radius:var(--r2);outline:none;transition:border-color .15s ease,box-shadow .15s ease}.capture-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.form-field .capture-input{margin-bottom:0}.capture-error{color:var(--accent);font-size:13px;margin-bottom:10px;min-height:18px}.capture-actions{display:flex;flex-direction:column;gap:8px;margin-top:18px}.capture-submit{border:0;background:var(--ink);color:var(--paper);padding:13px 20px;border-radius:var(--r2);cursor:pointer;font-weight:600;font-size:15px;width:100%;min-width:220px;letter-spacing:.01em}.capture-submit:hover{opacity:.85}.capture-submit:disabled{opacity:.45;cursor:default}.capture-cancel{border:0;background:none;color:var(--muted);padding:7px 18px;border-radius:var(--r);cursor:pointer;font-size:13px;text-align:center;width:100%}.capture-cancel:hover{color:var(--ink);background:var(--paper-2)}.capture-advanced{margin-top:12px}.capture-advanced-toggle{display:flex;align-items:center;gap:5px;background:none;border:0;cursor:pointer;color:var(--muted);font-size:12.5px;padding:4px 0;border-radius:var(--r)}.capture-advanced-toggle:hover{color:var(--ink)}.capture-chevron{width:14px;height:14px;flex-shrink:0;transition:transform .18s ease}.capture-chevron--open{transform:rotate(180deg)}.capture-advanced-panel{margin-top:8px;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r2);background:var(--paper-2)}.capture-ext-row{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:default}.capture-ext-label{flex:1;min-width:0}.capture-ext-name{display:block;font-size:13px;font-weight:600;color:var(--ink)}.capture-ext-desc{display:block;font-size:11.5px;color:var(--muted);margin-top:1px}.capture-dialog-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}.capture-dialog-close{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-dialog-close svg{width:14px;height:14px}.capture-dialog-close:hover{background:var(--paper-2);color:var(--ink)}.capture-rows{display:flex;flex-direction:column;gap:8px;margin-bottom:8px}.capture-row{display:flex;flex-direction:column;gap:3px}.capture-row-main{display:flex;align-items:center;gap:8px}.capture-row-main .capture-input{margin-bottom:0}.capture-quality{flex-shrink:0;height:32px;padding:0 6px;border:1px solid var(--line);border-radius:var(--r);background:var(--paper);color:var(--ink);font-size:12px;cursor:pointer;outline:none;transition:border-color .15s}.capture-quality:hover{border-color:var(--accent-2)}.capture-quality:focus{border-color:var(--accent)}.capture-quality:disabled{opacity:.5;cursor:default}.capture-quality-probing{flex-shrink:0;font-size:12px;color:var(--muted);padding:0 4px;letter-spacing:.05em}.capture-quality-hint{flex-shrink:0;font-size:12px;color:var(--muted);font-style:italic}.cap-dot{flex-shrink:0;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:700;line-height:1}.cap-dot--idle{background:var(--paper-2)}.cap-dot--running{background:#fdefd8;color:#8a4f10}.cap-dot--ok{background:#d8eddf;color:#235c35}.cap-dot--err{background:#f5ddd8;color:#8d3f30}.cap-spinner{display:block;width:10px;height:10px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:cap-spin .7s linear infinite}@keyframes cap-spin{to{transform:rotate(360deg)}}.capture-row-action{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-row-action svg{width:12px;height:12px}.capture-row-action:hover{color:var(--accent);background:var(--paper-2)}.capture-row-remove:hover{color:var(--accent)}.capture-row-error{margin:0;padding-left:28px;font-size:12px;color:var(--accent);line-height:1.45}.capture-add-row{display:flex;align-items:center;gap:7px;width:100%;background:none;border:1px dashed var(--line);border-radius:var(--r);color:var(--muted);font-size:13px;cursor:pointer;padding:7px 12px;margin-top:4px;margin-bottom:18px;transition:border-color .15s,color .15s,background .15s}.capture-add-row svg{width:13px;height:13px;flex-shrink:0}.capture-add-row:hover{border-color:var(--accent-2);color:var(--ink);background:var(--paper-2)}.toast-stack{position:fixed;bottom:24px;right:24px;z-index:9000;display:flex;flex-direction:column;gap:10px;width:340px;max-width:calc(100vw - 32px);pointer-events:none}.toast{pointer-events:auto;background:var(--paper);border:1px solid var(--line);border-radius:var(--r2);box-shadow:0 6px 24px #141d182e,0 1px 4px #141d181a;overflow:hidden;animation:toast-slide-in .22s cubic-bezier(.22,.68,0,1.2)}@keyframes toast-slide-in{0%{opacity:0;transform:translateY(10px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}.toast--error{border-left:3px solid var(--accent)}.toast--warning{border-left:3px solid #e8a000}.toast--success{border-left:3px solid #22a855}.toast-top{display:flex;align-items:flex-start;gap:10px;padding:12px 12px 12px 14px}.toast-icon{flex-shrink:0;font-size:13px;font-weight:700;color:var(--accent);margin-top:2px}.toast--success .toast-icon{color:#22a855}.toast--warning .toast-icon{color:#e8a000}.toast-body{flex:1;min-width:0}.toast-headline{display:block;font-size:13.5px;font-weight:600;color:var(--ink);line-height:1.3}.toast-locator{display:block;font-size:12px;color:var(--muted);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toast-btns{display:flex;align-items:center;gap:6px;flex-shrink:0}.toast-view-btn{background:none;border:1px solid var(--line);color:var(--link);font-size:12px;cursor:pointer;padding:3px 9px;border-radius:var(--r);white-space:nowrap}.toast-view-btn:hover{background:var(--paper-2);border-color:var(--link)}.toast-dismiss{background:none;border:0;cursor:pointer;color:var(--muted);font-size:20px;line-height:1;width:24px;height:24px;display:grid;place-items:center;border-radius:var(--r);padding:0}.toast-dismiss:hover{color:var(--ink);background:var(--paper-2)}.toast-error-detail{margin:0;padding:10px 14px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto}.toast-warning-detail{margin:0;padding:10px 14px 12px;font-size:12px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word}.toast-ignore-btn{color:var(--muted)}.ext-toggle{flex-shrink:0;position:relative;width:44px;height:24px;border-radius:12px;background:var(--line);border:0;cursor:pointer;transition:background .18s ease;padding:0}.ext-toggle--sm{width:36px;height:20px;border-radius:10px}.ext-toggle--on{background:var(--ink)}.ext-toggle:disabled{opacity:.4;cursor:default}.ext-toggle-knob{position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--paper);transition:transform .18s ease;display:block;box-shadow:0 1px 3px #0003}.ext-toggle--sm .ext-toggle-knob{width:14px;height:14px;top:3px;left:3px}.ext-toggle--on .ext-toggle-knob{transform:translate(20px)}.ext-toggle--sm.ext-toggle--on .ext-toggle-knob{transform:translate(16px)}.ext-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px}.ext-card{border:1px solid var(--line);border-radius:var(--r2);padding:16px 18px;background:var(--paper)}.ext-card-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.ext-card-info{flex:1;min-width:0}.ext-card-name{display:block;font-weight:600;font-size:14px;margin-bottom:4px}.ext-card-desc{display:block;font-size:13px;color:var(--muted);line-height:1.5}.ext-card-hint{display:block;font-size:12px;color:#e8a000;margin-top:6px}.ext-card-hint code{font-size:11.5px}.form-hint{font-size:13px;color:var(--muted);line-height:1.55;margin:0}.muted{color:var(--muted)}.admin-view{padding:22px}.admin-list{display:grid;gap:10px;max-width:780px}.admin-archive{border:1px solid var(--line);background:var(--paper-3);padding:12px;border-radius:var(--r2)}.tag-tree{padding:20px 22px;max-width:320px}.tag-tree-header{display:flex;align-items:baseline;gap:10px;margin-bottom:14px;border-bottom:1px solid var(--line-soft);padding-bottom:10px}.tag-tree-title{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.07em}.tag-tree-active{font-size:12px;color:var(--muted-2);font-style:italic}.tag-tree-list{list-style:none;margin:0;padding:0}.tag-children{padding-left:16px}.tag-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 0;text-align:left;font-size:13px;display:block;width:100%}.tag-node-btn:hover{text-decoration:underline}.tag-node-btn.is-active{font-weight:600;color:var(--ink)}.tag-node-row{display:flex;align-items:center;gap:4px}.tag-node-row .tag-node-btn{flex:1 1 0;min-width:0;display:flex;align-items:center;gap:4px;width:auto}.tag-node-btn .edit-icon{width:.75em;height:.75em;flex-shrink:0;vertical-align:-.1em;opacity:.35}.tag-node-btn:hover .edit-icon{opacity:.65}.tag-node-delete{flex-shrink:0;border:0;background:transparent;color:var(--muted-2);cursor:pointer;padding:0 3px;font-size:14px;line-height:1;opacity:0}.tag-node-row:hover .tag-node-delete{opacity:1}.tag-node-delete:hover{color:var(--accent)}.tag-rename-input{font-size:13px;flex:1 1 0;min-width:0;padding:2px 5px;border:1px solid var(--accent);border-radius:var(--r);background:var(--field);color:var(--ink);outline:none}.collections-view{padding:24px}.collections-heading{margin:0 0 16px;font-size:22px;font-family:var(--display);font-weight:600}.collections-error{color:var(--accent);font-size:13px;margin-bottom:8px}.coll-dismiss{background:none;border:none;cursor:pointer;color:var(--accent);font-size:16px;line-height:1;padding:0 4px}.collections-layout{display:grid;grid-template-columns:220px 1fr;gap:0;border:1px solid var(--line);border-radius:var(--r2);min-height:340px}.collections-sidebar{border-right:1px solid var(--line);overflow-y:auto}.coll-sidebar-row{display:flex;flex-direction:column;width:100%;padding:10px 14px;border:none;border-bottom:1px solid var(--line-soft);background:none;cursor:pointer;text-align:left;gap:2px}.coll-sidebar-row:hover{background:var(--paper-2)}.coll-sidebar-row.is-active{background:var(--paper-2);border-left:3px solid var(--accent)}.coll-row-name{font-size:14px;font-weight:600;color:var(--ink)}.coll-row-meta{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}.coll-detail{padding:20px 24px;display:flex;flex-direction:column;gap:16px}.coll-detail--empty{justify-content:center;align-items:center}.coll-detail-header{display:flex;align-items:center;gap:12px}.coll-detail-name{margin:0;font-size:18px;font-family:var(--display);font-weight:600;flex:1}.coll-detail-name--editable{cursor:pointer}.coll-detail-name--editable:hover{color:var(--link)}.coll-edit-hint{font-size:14px;opacity:.5;margin-left:4px}.coll-rename-input{flex:1;font-size:16px;font-family:var(--display);border:1px solid var(--line);padding:4px 8px;background:var(--field);color:var(--ink);border-radius:var(--r)}.coll-delete-btn{border:1px solid var(--accent);background:none;color:var(--accent);padding:5px 12px;font-size:13px;cursor:pointer;border-radius:var(--r)}.coll-delete-btn:hover{background:var(--accent);color:var(--paper)}.coll-detail-vis{display:flex;align-items:center;gap:10px}.coll-vis-label{font-size:13px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}.coll-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:4px 8px;font-size:13px;border-radius:var(--r)}.coll-section-heading{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px}.coll-entries-section{flex:1}.coll-entries-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}.coll-entry-row{display:flex;align-items:center;gap:10px;padding:7px 0;border-bottom:1px solid var(--line-soft)}.coll-entry-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.coll-entry-title{font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.coll-entry-kind{font-size:11px;text-transform:uppercase;letter-spacing:.04em}.coll-entry-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.coll-entry-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:3px 6px;font-size:12px;border-radius:var(--r)}.coll-entry-remove{border:none;background:none;cursor:pointer;color:var(--muted);font-size:18px;line-height:1;padding:0 4px}.coll-entry-remove:hover{color:var(--accent)}.coll-add-entry-form{border-top:1px solid var(--line-soft);padding-top:12px}.coll-add-entry-row{display:flex;gap:8px;align-items:center}.coll-add-entry-input{flex:1;border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:6px 10px;font-size:13px;min-width:0;border-radius:var(--r)}.coll-add-btn{border:none;background:var(--ink);color:var(--paper);padding:6px 14px;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;border-radius:var(--r)}.coll-add-btn:hover{opacity:.85}.coll-add-btn:disabled{opacity:.45;cursor:default}.auth-loading{min-height:100vh;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:15px;background:var(--paper)}.user-menu{display:flex;align-items:center;gap:14px;padding-left:6px;flex-shrink:0}.user-name{font-size:12.5px;color:var(--muted-2);letter-spacing:.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px}.logout-btn{border:1px solid rgba(255,255,255,.18);background:transparent;color:#c8bfb0;font-size:12px;padding:4px 11px;border-radius:var(--r);cursor:pointer;white-space:nowrap;transition:background .15s,color .15s}.logout-btn:hover{background:#ffffff1a;color:var(--paper)}.logout-btn:disabled{opacity:.5;cursor:default}.login-page,.setup-page{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--paper)}.login-card,.setup-card{width:100%;max-width:360px;padding:40px 36px 44px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);box-shadow:0 2px 20px #141d1812}.login-brand,.setup-brand{font-family:var(--display);font-size:32px;font-weight:600;color:var(--ink);letter-spacing:-.01em;margin:0 0 6px}.login-tagline,.setup-tagline{font-size:13px;color:var(--muted);margin:0 0 28px}.login-field,.setup-field{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}.login-label,.setup-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}.login-input,.setup-input{width:100%;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:9px 11px;font-size:14px;border-radius:var(--r2);outline:none;transition:border-color .15s}.login-input:focus,.setup-input:focus{border-color:var(--accent)}.login-error,.setup-error{font-size:13px;color:var(--accent);margin:4px 0 8px}.login-submit,.setup-submit{width:100%;margin-top:8px;border:none;background:var(--top);color:var(--paper);font-size:14px;font-weight:600;padding:11px 16px;border-radius:var(--r2);cursor:pointer;letter-spacing:.02em;transition:opacity .15s}.login-submit:hover,.setup-submit:hover{opacity:.85}.login-submit:disabled,.setup-submit:disabled{opacity:.45;cursor:default}.view-tabs{display:flex;gap:2px;margin-bottom:22px;border-bottom:1px solid var(--line-soft);padding-bottom:0}.view-tab{border:none;background:none;color:var(--muted);font-size:13px;font-weight:600;padding:7px 14px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;letter-spacing:.02em;transition:color .12s;text-transform:uppercase;letter-spacing:.06em;font-size:11.5px}.view-tab:hover{color:var(--ink)}.view-tab.is-active{color:var(--ink);border-bottom-color:var(--accent)}.form-section{margin-bottom:32px}.form-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.form-row{display:flex;gap:8px;margin-bottom:10px}.form-field{display:flex;flex-direction:column;gap:5px;margin-bottom:12px}.form-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}.field-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s;min-width:0}.field-input:focus{border-color:var(--accent)}.field-input--flex{flex:1}.form-msg{font-size:13px;margin:6px 0}.form-msg--ok{color:var(--link)}.form-msg--err{color:var(--accent)}.btn-primary{border:none;background:var(--top);color:var(--paper);font-size:13px;font-weight:600;padding:8px 16px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.btn-primary:hover{opacity:.85}.btn-primary:disabled{opacity:.45;cursor:default}.btn-ghost{border:1px solid var(--line);background:none;color:var(--ink);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-ghost:hover{background:var(--paper-2)}.btn-danger{border:1px solid var(--accent);background:none;color:var(--accent);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-danger:hover{background:var(--accent);color:var(--paper)}.admin-view h1{font-family:var(--display);font-weight:600;font-size:26px;margin:0 0 20px}.admin-table{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:28px}.admin-table th{text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);padding:8px 10px;border-bottom:1px solid var(--line);background:var(--paper-2)}.admin-table th:first-child{padding-left:16px}.admin-table td{padding:9px 10px;border-bottom:1px solid var(--line-soft);color:var(--ink);vertical-align:middle}.admin-table td:first-child{padding-left:16px}.admin-table tr:hover td{background:var(--paper-2)}.admin-row-disabled td{opacity:.45}.admin-section{margin-bottom:36px;max-width:860px}.admin-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.admin-section h3{font-size:13px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin:22px 0 10px}.admin-form{display:flex;flex-direction:column;gap:8px;max-width:480px}.admin-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s}.admin-input:focus{border-color:var(--accent)}.admin-action-btn{border:1px solid var(--line);background:none;color:var(--ink);font-size:12px;padding:4px 10px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.admin-action-btn:hover{border-color:var(--accent);color:var(--accent)}.status-badge{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.status-active{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.status-disabled{background:#ede8e0;color:var(--muted);border:1px solid var(--line)}.run-status{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.run-status--completed{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.run-status--failed{background:#f5ddd8;color:#8d3f30;border:1px solid #e0b8b0}.run-status--in-progress{background:#fdefd8;color:#8a4f10;border:1px solid #f0cfa0}.run-row--failed{cursor:pointer}.run-row--failed:hover td{background:#fdf0ed!important}.run-expand-hint{margin-left:6px;font-size:10px;color:var(--accent);vertical-align:middle}.run-error-row td{padding:0!important;background:var(--paper-2)!important}.run-error-detail{margin:0;padding:10px 16px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);white-space:pre-wrap;word-break:break-word;max-height:220px;overflow-y:auto}.token-banner{background:#d8eddf;border:1px solid #b4d9be;padding:12px 14px;margin-bottom:16px;font-size:13px;border-radius:var(--r2)}.token-banner code{word-break:break-all;display:block;margin-top:6px;padding:6px 8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r);font-size:12px;font-family:ui-monospace,SF Mono,Menlo,monospace}.token-dismiss{margin-top:8px;font-size:12px;border:1px solid var(--line);background:none;cursor:pointer;padding:3px 8px;border-radius:var(--r);color:var(--muted)}.token-dismiss:hover{background:var(--paper-2)}.token-row{display:flex;align-items:center;justify-content:space-between;border:1px solid var(--line);background:var(--paper-3);padding:10px 12px;border-radius:var(--r);margin-bottom:6px}.token-row-info strong{font-size:14px;display:block}.token-row-info .muted{font-size:12px;margin-top:2px}.token-create-row{display:flex;gap:8px;margin-bottom:16px}.checkbox-row{display:flex;align-items:center;gap:10px;margin-bottom:12px;cursor:pointer;font-size:14px}.checkbox-row input[type=checkbox]{width:15px;height:15px;accent-color:var(--accent)}.coll-create-details{margin-top:16px}.coll-create-details summary{font-weight:600;cursor:pointer;font-size:13px;color:var(--link);list-style:none;display:flex;align-items:center;gap:6px;padding:8px 12px;border:1px solid var(--line-soft);border-radius:var(--r2);background:var(--paper-3);width:fit-content}.coll-create-details summary:hover{background:var(--paper-2)}.coll-create-details[open] summary{border-bottom-left-radius:0;border-bottom-right-radius:0}.coll-create-form{border:1px solid var(--line-soft);border-top:none;padding:14px;border-radius:0 0 var(--r2) var(--r2);background:var(--paper-3);display:flex;flex-direction:column;gap:10px;max-width:440px}@media (max-width: 900px){.topbar{grid-template-columns:1fr auto;height:auto;min-height:58px;padding:12px}.switcher,.nav{grid-column:1 / -1}.nav{justify-content:flex-start;overflow-x:auto}.app-shell{height:auto;grid-template-columns:1fr}.context-rail{border-left:0;border-top:1px solid var(--line)}.entry-table{min-width:860px}}.rail-title--editable{cursor:pointer}.rail-title--editable:hover{opacity:.75}.rail-title--editable .edit-icon{display:inline-block;width:.75em;height:.75em;margin-left:.35em;vertical-align:middle;opacity:0;transition:opacity .1s;flex-shrink:0}.rail-title--editable:hover .edit-icon{opacity:.5}.rail-title-input{width:100%;font:inherit;font-size:inherit;font-weight:600;background:transparent;border:none;border-bottom:1px solid currentColor;color:inherit;padding:0;margin:0 0 8px;outline:none}.preview-panel{flex:1;display:flex;flex-direction:column;min-height:0}.preview-panel-loading,.preview-panel-empty{flex:1;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--muted-2);font-size:14px;text-align:center;padding:24px}.preview-video-wrap{flex:1;display:flex;align-items:center;justify-content:center;background:#0d0d0b;min-height:200px}.preview-video-wrap video{max-width:100%;max-height:100%;width:100%;display:block}.preview-iframe-wrap{flex:1;display:flex;flex-direction:column;min-height:0}.preview-iframe-toolbar{display:flex;flex-direction:column;gap:2px;padding:6px 12px;background:var(--paper-2);border-bottom:1px solid var(--line);flex-shrink:0;text-transform:none;letter-spacing:normal}.preview-iframe-toolbar span{font-size:11px;color:var(--muted-2)}.preview-iframe-toolbar a{margin-left:auto;color:var(--link);font-size:12px;text-decoration:none;padding:3px 8px;border:1px solid var(--line);border-radius:var(--r2);background:var(--field);transition:border-color .12s}.preview-iframe-toolbar a:hover{border-color:var(--accent);text-decoration:none}.preview-iframe-wrap iframe{flex:1;width:100%;border:none;background:#fff;min-height:0}.preview-image-wrap{flex:1;display:flex;align-items:center;justify-content:center;padding:20px;background:var(--paper-2)}.preview-image-wrap img{max-width:100%;max-height:100%;object-fit:contain;border-radius:var(--r3);cursor:zoom-in;display:block;box-shadow:0 4px 24px #0000001a}.preview-tweet-wrap{flex:1;min-height:0;overflow-y:auto;padding:12px 16px;background:var(--paper-2);scrollbar-width:thin;scrollbar-color:var(--line) transparent}.preview-tweet-wrap::-webkit-scrollbar{width:8px}.preview-tweet-wrap::-webkit-scrollbar-track{background:transparent}.preview-tweet-wrap::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:2px solid transparent;background-clip:padding-box}.preview-tweet-wrap::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:2px solid transparent}.tw-card{border:1px solid var(--line);border-radius:12px;padding:16px;background:var(--paper);max-width:560px;margin:0 auto 12px}.tw-thread{max-width:560px;margin:0 auto}.tw-thread-item{display:flex;gap:0;margin-bottom:0}.tw-thread-connector{display:flex;flex-direction:column;align-items:center;flex-shrink:0;width:52px;padding-top:2px}.tw-thread-avatar-col{display:flex;flex-direction:column;align-items:center;flex-shrink:0}.tw-thread-line{width:2px;background:var(--line);flex:1;min-height:16px;margin:4px 0}.tw-thread-body{flex:1;min-width:0;padding:0 0 16px 12px}.tw-thread-body:last-child{padding-bottom:0}.tw-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;flex-shrink:0;display:block}.tw-avatar-ph{width:40px;height:40px;border-radius:50%;background:var(--paper-2);border:1px solid var(--line);flex-shrink:0}.tw-header{display:flex;align-items:baseline;gap:6px;flex-wrap:wrap;margin-bottom:6px}.tw-author-name{font-size:14.5px;font-weight:700;color:var(--ink)}.tw-author-handle{font-size:13px;color:var(--muted-2)}.tw-dot{color:var(--muted-2);font-size:13px}.tw-date{font-size:13px;color:var(--muted-2)}.tw-text{font-size:15px;line-height:1.65;color:var(--ink);white-space:pre-line;word-break:break-word;margin-bottom:10px}.tw-text a{color:var(--link);text-decoration:none}.tw-text a:hover{text-decoration:underline}.tw-stats{display:flex;gap:20px;color:var(--muted-2);font-size:13px;margin-top:10px;padding-top:10px;border-top:1px solid var(--line-soft)}.tw-stats span{display:flex;align-items:center;gap:4px}.tw-article{max-width:598px;margin:0 auto}.tw-article-cover{width:100%;display:block;object-fit:cover;max-height:380px}.tw-article-meta{padding:20px 16px 0}.tw-article-title{font-size:22px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.3;margin-bottom:14px}.tw-article-author-row{display:flex;align-items:center;gap:12px;margin-bottom:14px}.tw-article-author-name{font-size:14px;font-weight:700;color:var(--ink)}.tw-article-author-sub{font-size:13px;color:var(--muted-2)}.tw-article-divider{border:none;border-top:1px solid var(--line);margin:0}.tw-article-body{padding:8px 16px 60px}.tw-b-h1{font-size:24px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.25;margin:22px 0 10px}.tw-b-h2{font-size:19px;font-weight:700;letter-spacing:-.15px;color:var(--ink);line-height:1.3;margin:20px 0 8px}.tw-b-p{font-size:16px;color:var(--ink);line-height:1.72;margin-bottom:14px}.tw-b-p:empty{display:none}.tw-b-spacer{height:6px;display:block}.tw-b-blockquote{border-left:3px solid var(--line);padding:2px 14px;margin:14px 0;color:var(--muted);font-size:16px;line-height:1.65}.tw-b-hr{border:none;border-top:1px solid var(--line);margin:24px 0}.tw-b-img{width:100%;display:block;border-radius:10px;margin:14px 0}.tw-b-ul,.tw-b-ol{margin:10px 0 14px;padding-left:26px}.tw-b-li{font-size:16px;color:var(--ink);line-height:1.65;margin-bottom:6px}.tw-b-code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:.875em;background:var(--paper-2);padding:2px 5px;border-radius:4px;color:var(--ink)}.tw-b-pre{background:var(--paper-2);border:1px solid var(--line);border-radius:8px;padding:14px 16px;overflow-x:auto;margin:12px 0}.tw-b-pre code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:13px;line-height:1.6}.tw-b-tweet-link{display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:10px;padding:12px 14px;margin:12px 0;color:var(--muted);font-size:14px;text-decoration:none;background:var(--paper-3);transition:background .12s}.tw-b-tweet-link:hover{background:var(--field)}.tw-b-tweet-link svg{flex-shrink:0;color:var(--ink)}.audio-bar{position:fixed;bottom:0;left:0;right:0;height:72px;background:var(--paper);border-top:1px solid var(--line);display:flex;align-items:center;gap:20px;padding:0 24px;z-index:100;box-shadow:0 -2px 16px #00000014}.audio-bar-info{display:flex;align-items:center;gap:10px;min-width:0;flex:0 0 200px}.audio-bar-icon{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center}.audio-bar-icon svg{width:20px;height:20px}.audio-bar-title{font-size:13px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;font-weight:500}.audio-bar-controls{flex:1;display:flex;align-items:center;gap:12px;min-width:0}.audio-bar-play-btn{width:38px;height:38px;border-radius:50%;background:var(--accent);color:var(--paper);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,transform .1s}.audio-bar-play-btn:hover{background:var(--accent-2)}.audio-bar-play-btn:active{transform:scale(.93)}.audio-bar-play-btn svg{width:15px;height:15px}.audio-bar-seek{flex:1;min-width:0;display:flex;align-items:center;gap:8px}.audio-bar-seek input[type=range]{flex:1;accent-color:var(--accent);height:4px;cursor:pointer;min-width:0}.audio-bar-time{font-size:11.5px;color:var(--muted-2);white-space:nowrap;min-width:80px;text-align:right;font-variant-numeric:tabular-nums}.audio-bar-right{flex:0 0 auto;display:flex;align-items:center;gap:10px}.audio-bar-volume{display:flex;align-items:center;gap:6px}.audio-bar-volume svg{width:14px;height:14px;color:var(--muted-2);flex-shrink:0}.audio-bar-volume input[type=range]{width:72px;accent-color:var(--accent);cursor:pointer}.audio-bar-close{width:28px;height:28px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:18px;padding:0;line-height:1;transition:background .12s,color .12s}.audio-bar-close:hover{background:var(--field);color:var(--ink)}.preview-modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#0000008c;display:flex;align-items:center;justify-content:center;padding:20px}.preview-modal{background:var(--paper);border-radius:12px;box-shadow:0 24px 80px #00000047;width:90vw;max-width:1100px;max-height:88vh;display:flex;flex-direction:column;overflow:hidden}.preview-modal--full{height:88vh}.preview-modal--full .preview-modal-body{max-height:none}.preview-modal-header{display:flex;align-items:center;padding:14px 18px;border-bottom:1px solid var(--line);flex-shrink:0;gap:12px}.preview-modal-title{flex:1;min-width:0;font-size:14px;font-weight:600;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.preview-modal-close{width:30px;height:30px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-close:hover{background:var(--field);color:var(--ink)}.preview-modal-body{flex:1;min-height:0;overflow:hidden;display:flex;flex-direction:column;max-height:calc(88vh - 52px)}.rail-preview-btn{display:block;width:100%;padding:8px 12px;margin-bottom:16px;background:var(--accent);color:var(--paper);border:none;border-radius:var(--r3);font-size:13px;font-weight:600;cursor:pointer;text-align:center;transition:background .12s}.rail-preview-btn:hover{background:var(--accent-2)}.preview-modal-newtab{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:var(--r2);color:var(--muted-2);text-decoration:none;font-size:16px;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-newtab:hover{background:var(--field);color:var(--ink)}body.has-audio-bar{padding-bottom:56px} +@import"https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600&family=Spectral:wght@500;600&display=swap";:root{color-scheme:light;--ink: #20251f;--muted: #6b6f66;--muted-2: #8a8d83;--paper: #f5f0e7;--paper-2: #e9e1d2;--paper-3: #fffaf0;--line: #d2c6b5;--line-soft: #e5dccd;--accent: #8d3f30;--accent-2: #b78342;--link: #245f72;--top: #141d18;--field: #fffdf7;--r: 3px;--r2: 6px;--r3: 10px;--sans: "Helvetica Neue", Helvetica, Arial, sans-serif;--serif: "Spectral", Georgia, "Times New Roman", serif;--display: "Cormorant Garamond", Georgia, serif}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:14px;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button,input,select{font:inherit}.workspace,.context-rail{scrollbar-width:thin;scrollbar-color:var(--line) transparent}.workspace::-webkit-scrollbar,.context-rail::-webkit-scrollbar{width:11px;height:11px}.workspace::-webkit-scrollbar-track,.context-rail::-webkit-scrollbar-track{background:transparent}.workspace::-webkit-scrollbar-thumb,.context-rail::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:3px solid transparent;background-clip:padding-box}.workspace::-webkit-scrollbar-thumb:hover,.context-rail::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:3px solid transparent}.topbar{height:58px;display:grid;grid-template-columns:auto auto 1fr auto auto;align-items:center;gap:26px;padding:0 22px;background:var(--top);color:#efe6d6;border-bottom:3px solid var(--accent)}.brand{font-family:var(--display);font-weight:600;font-size:30px;line-height:1;letter-spacing:.01em;color:#f4ead8}.switcher{position:relative;display:inline-flex;align-items:center}.switcher select{-moz-appearance:none;appearance:none;-webkit-appearance:none;border:1px solid rgba(247,238,223,.2);background:#f7eedf0f;color:#f1e8d8;font-family:var(--sans);font-weight:550;font-size:13.5px;letter-spacing:.04em;padding:8px 32px 8px 15px;cursor:pointer;border-radius:6px;transition:background .15s ease,border-color .15s ease}.switcher select:hover{background:#f7eedf1c;border-color:#f7eedf57}.switcher:after{content:"";position:absolute;right:15px;top:50%;width:6px;height:6px;margin-top:-5px;border-right:1.2px solid #b6ab98;border-bottom:1.2px solid #b6ab98;transform:rotate(45deg);pointer-events:none}.nav{display:flex;gap:22px;justify-content:flex-end;min-width:0}.nav-link{border:0;background:transparent;color:#cdc1ad;cursor:pointer;padding:6px 0;font-size:12.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;position:relative}.nav-link:hover,.nav-link.is-active{color:#f4ead8}.nav-link.is-active:after{content:"";position:absolute;left:0;right:0;bottom:-2px;height:1px;background:var(--accent-2)}.capture-button{display:inline-flex;align-items:center;gap:8px;position:relative;overflow:hidden;border:0;background:linear-gradient(180deg,color-mix(in srgb,var(--accent) 88%,#fff) 0%,var(--accent) 55%);color:#f7eddd;padding:10px 18px;cursor:pointer;font-size:12px;font-weight:600;letter-spacing:.15em;text-transform:uppercase;border-radius:var(--r);box-shadow:inset 0 1px #fff5e629,0 1px 2px #141d184d;transition:filter .18s ease,box-shadow .18s ease}.capture-button:hover{filter:brightness(.93);box-shadow:inset 0 1px #fff5e61f,0 2px 6px #141d1857}.capture-button:before{content:"";position:absolute;top:0;bottom:0;left:0;width:45%;background:linear-gradient(100deg,transparent 0%,rgba(255,246,232,.45) 50%,transparent 100%);transform:translate(-180%) skew(-18deg);pointer-events:none}@media (prefers-reduced-motion: no-preference){.capture-button:hover:before{animation:cap-sheen .7s ease}}@keyframes cap-sheen{0%{transform:translate(-180%) skew(-18deg)}to{transform:translate(340%) skew(-18deg)}}.app-shell{height:calc(100vh - 58px);display:grid;grid-template-columns:minmax(0,1fr) 340px}.workspace{min-width:0;overflow:auto;display:flex;flex-direction:column}.view{display:none}.view.is-active{display:block}.toolbar{position:sticky;top:0;z-index:3;display:flex;align-items:center;gap:16px;padding:12px 22px;background:color-mix(in srgb,var(--paper) 88%,white);border-bottom:1px solid var(--line-soft)}.search-field{position:relative;flex:1 1 auto;min-width:0;display:flex;align-items:center;height:42px;background:var(--field);border:1px solid var(--line);border-radius:20px;transition:border-color .15s ease,box-shadow .15s ease}.search-field:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.search-field .ico{display:grid;place-items:center;width:46px;height:100%;color:var(--muted-2);flex-shrink:0}.search-field .ico svg{width:16px;height:16px}.search-input{flex:1;min-width:0;height:100%;border:0;background:transparent;color:var(--ink);padding:0 6px 0 0;font-size:14px;letter-spacing:.01em;outline:none}.search-input::placeholder{color:var(--muted-2)}.search-field .kbd{margin-right:12px;display:inline-flex;align-items:center;padding:3px 7px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:var(--r);flex-shrink:0}.result-count{flex-shrink:0;font-size:13px;color:var(--muted);letter-spacing:.02em;white-space:nowrap}.result-count b{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums}.tag-filter-badge{display:inline-flex;align-items:center;gap:4px;background:var(--accent);color:#fff;border:0;border-radius:var(--r);font-size:12px;padding:2px 8px;cursor:pointer;margin-left:8px}.tag-filter-badge:hover{opacity:.85}.entry-table{width:100%;font-size:12.5px}.entry-header-row{display:flex;align-items:stretch;position:sticky;top:67px;z-index:2;background:color-mix(in srgb,var(--paper) 92%,white);border-bottom:1px solid var(--line-soft);color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600;display:flex;align-items:center}#entries-body>div{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft)}#entries-body>div>div{padding:7px 10px;flex-shrink:0;overflow:hidden}#entries-body>div:nth-child(2n){background:#f2ede5}#entries-body>div:nth-child(odd){background:var(--paper-3)}#entries-body>div.is-selected{background:#eee2d2;outline:2px solid var(--accent);outline-offset:-2px}#entries-body>div.is-multi-selected{background:#eee2d2;outline:2px solid var(--accent);outline-offset:-2px}.col-added{width:162px;color:var(--muted)}.col-title{flex:1 1 0;min-width:0;overflow:hidden;display:flex;align-items:center;gap:.42em}.col-type{width:116px}.col-size{width:100px;display:flex;flex-direction:column;justify-content:center;gap:1px}.size-total{font-variant-numeric:tabular-nums}.size-cached-pct{font-size:10px;color:var(--muted);opacity:.8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.col-url{flex:0 0 30%;min-width:0;overflow:hidden}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:22px}.entry-header-row>div:last-child,#entries-body>div>div:last-child{padding-right:22px}.entry-title{color:var(--link);font-weight:700;min-width:0}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600}.source-icon{display:flex;align-items:center;justify-content:center;width:1.05em;height:1.05em;flex-shrink:0}.source-icon>*{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.source-icon svg{width:100%;height:100%}.url-cell{color:#555b55;white-space:nowrap;text-overflow:ellipsis;word-break:break-all}#entries-body .url-cell:hover,#entries-body .is-selected .url-cell{overflow:visible;white-space:normal}.type-pill{display:inline-block;padding:2px 6px;background:#d8e3df;color:#275a5f;border:1px solid #bfd0ca;border-radius:var(--r)}.col-check{display:none;width:40px;flex-shrink:0;align-items:center;justify-content:center;padding:0!important;cursor:pointer}.row-checkbox{-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:0;border:1.5px solid var(--line);cursor:pointer;display:block;width:17px;height:17px;border-radius:4px;background:var(--paper-3);transition:border-color .15s ease,background .15s ease;position:relative;flex-shrink:0}.row-checkbox.is-checked{background:var(--accent);border-color:var(--accent)}.row-checkbox.is-checked:after{content:"";position:absolute;left:4px;top:2px;width:5px;height:8px;border:2px solid #fff;border-top:none;border-left:none;transform:rotate(45deg)}@media (pointer: coarse){.col-check{display:flex}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:10px}}#runs-view .entry-table{border-collapse:collapse;table-layout:auto}#runs-view .entry-table th{position:sticky;top:0;z-index:1;text-align:left;padding:10px;background:color-mix(in srgb,var(--paper) 92%,white);color:var(--muted);border-bottom:1px solid var(--line-soft);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}#runs-view .entry-table td{padding:10px;border-bottom:1px solid var(--line-soft);vertical-align:top}#runs-view .entry-table tr:nth-child(2n) td{background:#f2ede5}#runs-view .entry-table tr:nth-child(odd) td{background:var(--paper-3)}.context-rail{border-left:1px solid var(--line);background:var(--paper);padding:20px 20px 32px;overflow:auto}.rail-eyebrow{font-size:10.5px;font-weight:600;letter-spacing:.16em;text-transform:uppercase;color:var(--muted-2);margin-bottom:16px}.rail-title{display:block;font-family:var(--sans);font-weight:700;font-size:15.5px;line-height:1.4;color:var(--ink);margin:0 0 16px;word-break:break-word}.url-tile{display:flex;align-items:center;gap:9px;padding:10px 12px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);margin-bottom:20px;text-decoration:none}.url-tile:hover{background:var(--field);border-color:var(--accent)}.url-tile .ico{color:var(--ink);flex-shrink:0;display:grid;place-items:center}.url-tile .ico svg{width:15px;height:15px}.url-tile .u-text{min-width:0;flex:1;font-size:12.5px;color:var(--link);font-family:ui-monospace,SF Mono,Menlo,monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.url-tile .ext{color:var(--muted-2);flex-shrink:0}.url-tile .ext svg{width:13px;height:13px;display:block}.meta-list{margin-bottom:24px;border-top:1px solid var(--line-soft)}.meta-item{display:grid;grid-template-columns:92px 1fr;gap:14px;align-items:baseline;padding:9px 0;border-bottom:1px solid var(--line-soft)}.meta-k{font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted-2)}.meta-v{font-size:13.5px;color:var(--ink);word-break:break-word;line-height:1.4}.meta-v.mono{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:12px;color:var(--muted)}.rail-section{margin-bottom:24px}.rail-section-heading{display:flex;align-items:baseline;gap:8px;font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.12em;color:var(--muted-2);margin-bottom:9px;padding-bottom:8px;border-bottom:1px solid var(--line)}.rail-section-heading .num{color:var(--muted-2);font-weight:600}.artifact-list{list-style:none;margin:0;padding:0}.artifact-link{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:7px 2px;border-bottom:1px solid var(--line-soft);text-decoration:none}.artifact-link:last-child{border-bottom:0}.artifact-name{font-size:13px;color:var(--link);min-width:0;word-break:break-word}.artifact-link:hover .artifact-name{text-decoration:underline}.artifact-size{font-size:11.5px;color:var(--muted-2);flex-shrink:0;font-variant-numeric:tabular-nums}.artifact-group{list-style:none}.artifact-group-header{width:100%;background:none;border:none;border-bottom:1px solid var(--line-soft);cursor:pointer;text-align:left;color:inherit;font:inherit}.artifact-group-header:hover .artifact-name{text-decoration:underline}.artifact-group-chevron{display:inline-block;font-style:normal;transition:transform .15s ease;transform:rotate(0);transform-origin:45% 50%;margin-right:3px}.artifact-group-chevron.open{transform:rotate(90deg)}.artifact-group-body{padding-left:14px}.tags-wrap{display:flex;flex-wrap:wrap;gap:7px;margin:0 0 12px}.tag-pill{display:inline-flex;align-items:center;gap:7px;background:var(--paper-2);border:1px solid var(--line);border-radius:var(--r);font-size:12px;padding:4px 7px 4px 10px;color:var(--ink)}.tag-pill .remove{border:0;background:transparent;cursor:pointer;color:var(--muted-2);width:15px;height:15px;display:grid;place-items:center;font-size:13px;line-height:1}.tag-pill .remove:hover{color:var(--accent)}.tags-empty{font-size:13px;color:var(--muted);margin:0 0 11px}.tag-input-wrap{display:flex;align-items:center;gap:8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);padding:2px 2px 2px 11px;transition:border-color .15s ease,box-shadow .15s ease}.tag-input-wrap:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 12%,transparent)}.tag-input-wrap .hash{color:var(--muted-2);font-size:13px}.tag-input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font-size:13px;padding:6px 0;outline:none;font-family:ui-monospace,SF Mono,Menlo,monospace}.tag-add-btn{border:0;background:var(--ink);color:var(--paper-3);padding:6px 13px;font-size:11.5px;letter-spacing:.06em;text-transform:uppercase;border-radius:var(--r);cursor:pointer;white-space:nowrap}.tag-add-btn:hover{background:#2c332b}.coll-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 13px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);margin-bottom:6px;transition:border-color .15s ease}.coll-row:hover{border-color:var(--accent)}.coll-name{font-size:13px;color:var(--ink);font-weight:500}.vis-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:999px;padding:3px 10px}.vis-badge:before{content:"";width:6px;height:6px;border-radius:50%;background:var(--accent-2)}.bulk-panel{padding-top:2px}.bulk-count{font-size:13px;color:var(--muted);margin-bottom:22px}.bulk-count-num{font-size:22px;font-weight:700;color:var(--ink);line-height:1;margin-right:4px}.bulk-coll-row{display:flex;align-items:center;gap:8px}.bulk-coll-select{flex:1;min-width:0;height:32px;padding:0 8px;border:1px solid var(--line);border-radius:var(--r);background:var(--field);color:var(--ink);font-size:13px;cursor:pointer;outline:none;transition:border-color .15s ease}.bulk-coll-select:focus{border-color:var(--accent)}.tag-add-btn:disabled{opacity:.45;cursor:default}.rail-delete-zone{margin-top:24px;padding-top:20px;border-top:1px solid var(--line-soft)}.rail-delete-btn{width:100%;padding:8px 14px;background:none;border:1px solid color-mix(in srgb,var(--accent) 45%,transparent);color:var(--accent);border-radius:var(--r);cursor:pointer;font-size:12.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;transition:background .15s ease,border-color .15s ease}.rail-delete-btn:hover{background:color-mix(in srgb,var(--accent) 8%,transparent);border-color:var(--accent)}.rail-rearchive-btn{width:100%;padding:6px 12px;background:var(--surface-2, #2a2a2a);color:var(--text, #e0e0e0);border:1px solid var(--border, #444);border-radius:4px;cursor:pointer;font-size:13px}.rail-rearchive-btn:hover:not(:disabled){background:var(--surface-3, #333)}.rail-rearchive-btn:disabled{opacity:.6;cursor:not-allowed}.capture-dialog{border:1px solid var(--line);background:var(--paper);padding:0;width:min(540px,calc(100vw - 32px));border-radius:var(--r3);box-shadow:0 20px 60px #141d1847}.capture-dialog::backdrop{background:#141d1873}.capture-dialog-inner{padding:28px}.capture-dialog-title{margin:0;font-size:22px;font-family:var(--display);font-weight:600}.capture-label{display:block;font-size:11px;font-weight:600;margin-bottom:6px;color:var(--muted-2);text-transform:uppercase;letter-spacing:.06em}.capture-input{width:100%;height:44px;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:0 14px;font-size:15px;margin-bottom:10px;border-radius:var(--r2);outline:none;transition:border-color .15s ease,box-shadow .15s ease}.capture-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.form-field .capture-input{margin-bottom:0}.capture-error{color:var(--accent);font-size:13px;margin-bottom:10px;min-height:18px}.capture-actions{display:flex;flex-direction:column;gap:8px;margin-top:18px}.capture-submit{border:0;background:var(--ink);color:var(--paper);padding:13px 20px;border-radius:var(--r2);cursor:pointer;font-weight:600;font-size:15px;width:100%;min-width:220px;letter-spacing:.01em}.capture-submit:hover{opacity:.85}.capture-submit:disabled{opacity:.45;cursor:default}.capture-cancel{border:0;background:none;color:var(--muted);padding:7px 18px;border-radius:var(--r);cursor:pointer;font-size:13px;text-align:center;width:100%}.capture-cancel:hover{color:var(--ink);background:var(--paper-2)}.capture-advanced{margin-top:12px}.capture-advanced-toggle{display:flex;align-items:center;gap:5px;background:none;border:0;cursor:pointer;color:var(--muted);font-size:12.5px;padding:4px 0;border-radius:var(--r)}.capture-advanced-toggle:hover{color:var(--ink)}.capture-chevron{width:14px;height:14px;flex-shrink:0;transition:transform .18s ease}.capture-chevron--open{transform:rotate(180deg)}.capture-advanced-panel{margin-top:8px;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r2);background:var(--paper-2)}.capture-ext-row{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:default}.capture-ext-label{flex:1;min-width:0}.capture-ext-name{display:block;font-size:13px;font-weight:600;color:var(--ink)}.capture-ext-desc{display:block;font-size:11.5px;color:var(--muted);margin-top:1px}.capture-dialog-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}.capture-dialog-close{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-dialog-close svg{width:14px;height:14px}.capture-dialog-close:hover{background:var(--paper-2);color:var(--ink)}.capture-rows{display:flex;flex-direction:column;gap:8px;margin-bottom:8px}.capture-row{display:flex;flex-direction:column;gap:3px}.capture-row-main{display:flex;align-items:center;gap:8px}.capture-row-main .capture-input{margin-bottom:0}.capture-quality{flex-shrink:0;height:32px;padding:0 6px;border:1px solid var(--line);border-radius:var(--r);background:var(--paper);color:var(--ink);font-size:12px;cursor:pointer;outline:none;transition:border-color .15s}.capture-quality:hover{border-color:var(--accent-2)}.capture-quality:focus{border-color:var(--accent)}.capture-quality:disabled{opacity:.5;cursor:default}.capture-quality-probing{flex-shrink:0;font-size:12px;color:var(--muted);padding:0 4px;letter-spacing:.05em}.capture-quality-hint{flex-shrink:0;font-size:12px;color:var(--muted);font-style:italic}.cap-dot{flex-shrink:0;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:700;line-height:1}.cap-dot--idle{background:var(--paper-2)}.cap-dot--running{background:#fdefd8;color:#8a4f10}.cap-dot--ok{background:#d8eddf;color:#235c35}.cap-dot--err{background:#f5ddd8;color:#8d3f30}.cap-spinner{display:block;width:10px;height:10px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:cap-spin .7s linear infinite}@keyframes cap-spin{to{transform:rotate(360deg)}}.capture-row-action{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-row-action svg{width:12px;height:12px}.capture-row-action:hover{color:var(--accent);background:var(--paper-2)}.capture-row-remove:hover{color:var(--accent)}.capture-row-error{margin:0;padding-left:28px;font-size:12px;color:var(--accent);line-height:1.45}.capture-add-row{display:flex;align-items:center;gap:7px;width:100%;background:none;border:1px dashed var(--line);border-radius:var(--r);color:var(--muted);font-size:13px;cursor:pointer;padding:7px 12px;margin-top:4px;margin-bottom:18px;transition:border-color .15s,color .15s,background .15s}.capture-add-row svg{width:13px;height:13px;flex-shrink:0}.capture-add-row:hover{border-color:var(--accent-2);color:var(--ink);background:var(--paper-2)}.toast-stack{position:fixed;bottom:24px;right:24px;z-index:9000;display:flex;flex-direction:column;gap:10px;width:340px;max-width:calc(100vw - 32px);pointer-events:none}.toast{pointer-events:auto;background:var(--paper);border:1px solid var(--line);border-radius:var(--r2);box-shadow:0 6px 24px #141d182e,0 1px 4px #141d181a;overflow:hidden;animation:toast-slide-in .22s cubic-bezier(.22,.68,0,1.2)}@keyframes toast-slide-in{0%{opacity:0;transform:translateY(10px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}.toast--error{border-left:3px solid var(--accent)}.toast--warning{border-left:3px solid #e8a000}.toast--success{border-left:3px solid #22a855}.toast-top{display:flex;align-items:flex-start;gap:10px;padding:12px 12px 12px 14px}.toast-icon{flex-shrink:0;font-size:13px;font-weight:700;color:var(--accent);margin-top:2px}.toast--success .toast-icon{color:#22a855}.toast--warning .toast-icon{color:#e8a000}.toast-body{flex:1;min-width:0}.toast-headline{display:block;font-size:13.5px;font-weight:600;color:var(--ink);line-height:1.3}.toast-locator{display:block;font-size:12px;color:var(--muted);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toast-btns{display:flex;align-items:center;gap:6px;flex-shrink:0}.toast-view-btn{background:none;border:1px solid var(--line);color:var(--link);font-size:12px;cursor:pointer;padding:3px 9px;border-radius:var(--r);white-space:nowrap}.toast-view-btn:hover{background:var(--paper-2);border-color:var(--link)}.toast-dismiss{background:none;border:0;cursor:pointer;color:var(--muted);font-size:20px;line-height:1;width:24px;height:24px;display:grid;place-items:center;border-radius:var(--r);padding:0}.toast-dismiss:hover{color:var(--ink);background:var(--paper-2)}.toast-error-detail{margin:0;padding:10px 14px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto}.toast-warning-detail{margin:0;padding:10px 14px 12px;font-size:12px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word}.toast-ignore-btn{color:var(--muted)}.ext-toggle{flex-shrink:0;position:relative;width:44px;height:24px;border-radius:12px;background:var(--line);border:0;cursor:pointer;transition:background .18s ease;padding:0}.ext-toggle--sm{width:36px;height:20px;border-radius:10px}.ext-toggle--on{background:var(--ink)}.ext-toggle:disabled{opacity:.4;cursor:default}.ext-toggle-knob{position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--paper);transition:transform .18s ease;display:block;box-shadow:0 1px 3px #0003}.ext-toggle--sm .ext-toggle-knob{width:14px;height:14px;top:3px;left:3px}.ext-toggle--on .ext-toggle-knob{transform:translate(20px)}.ext-toggle--sm.ext-toggle--on .ext-toggle-knob{transform:translate(16px)}.ext-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px}.ext-card{border:1px solid var(--line);border-radius:var(--r2);padding:16px 18px;background:var(--paper)}.ext-card-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.ext-card-info{flex:1;min-width:0}.ext-card-name{display:block;font-weight:600;font-size:14px;margin-bottom:4px}.ext-card-desc{display:block;font-size:13px;color:var(--muted);line-height:1.5}.ext-card-hint{display:block;font-size:12px;color:#e8a000;margin-top:6px}.ext-card-hint code{font-size:11.5px}.form-hint{font-size:13px;color:var(--muted);line-height:1.55;margin:0}.muted{color:var(--muted)}.admin-view{padding:22px}.admin-list{display:grid;gap:10px;max-width:780px}.admin-archive{border:1px solid var(--line);background:var(--paper-3);padding:12px;border-radius:var(--r2)}.tag-tree{padding:20px 22px;max-width:320px}.tag-tree-header{display:flex;align-items:baseline;gap:10px;margin-bottom:14px;border-bottom:1px solid var(--line-soft);padding-bottom:10px}.tag-tree-title{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.07em}.tag-tree-active{font-size:12px;color:var(--muted-2);font-style:italic}.tag-tree-list{list-style:none;margin:0;padding:0}.tag-children{padding-left:16px}.tag-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 0;text-align:left;font-size:13px;display:block;width:100%}.tag-node-btn:hover{text-decoration:underline}.tag-node-btn.is-active{font-weight:600;color:var(--ink)}.tag-node-row{display:flex;align-items:center;gap:4px}.tag-node-row .tag-node-btn{flex:1 1 0;min-width:0;display:flex;align-items:center;gap:4px;width:auto}.tag-node-btn .edit-icon{width:.75em;height:.75em;flex-shrink:0;vertical-align:-.1em;opacity:.35}.tag-node-btn:hover .edit-icon{opacity:.65}.tag-node-delete{flex-shrink:0;border:0;background:transparent;color:var(--muted-2);cursor:pointer;padding:0 3px;font-size:14px;line-height:1;opacity:0}.tag-node-row:hover .tag-node-delete{opacity:1}.tag-node-delete:hover{color:var(--accent)}.tag-rename-input{font-size:13px;flex:1 1 0;min-width:0;padding:2px 5px;border:1px solid var(--accent);border-radius:var(--r);background:var(--field);color:var(--ink);outline:none}.tag-node-label{flex-shrink:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tag-node-count{font-size:11px;color:var(--muted-2);font-weight:400;flex-shrink:0;margin-left:3px}.tag-tree-header{align-items:center}.tag-tree-actions{margin-left:auto;display:flex;gap:4px}.tag-tree-action-btn{font-size:11px;padding:2px 7px;border:1px solid var(--line);border-radius:var(--r);background:transparent;color:var(--muted);cursor:pointer;line-height:1.5;white-space:nowrap;transition:background .1s,color .1s}.tag-tree-action-btn:hover:not(:disabled){background:var(--paper-2);color:var(--ink)}.tag-tree-action-btn:disabled{opacity:.4;cursor:default}.tag-tree-action-btn--cancel{border-color:var(--accent);color:var(--accent)}.tag-tree-action-btn--cancel:hover{background:color-mix(in srgb,var(--accent) 8%,transparent)}.tag-tree-title--move{font-style:italic;color:var(--accent-2)}.tag-node-row--move-select .tag-node-btn{cursor:crosshair;color:var(--ink)}.tag-node-row--move-select .tag-node-btn:hover{background:color-mix(in srgb,var(--link) 10%,transparent);text-decoration:none;border-radius:var(--r)}.tag-picker-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#00000073;display:flex;align-items:center;justify-content:center;padding:20px}.tag-picker-modal{background:var(--paper);border-radius:var(--r3);box-shadow:0 16px 56px #0000003d;width:300px;max-width:100%;display:flex;flex-direction:column;max-height:60vh}.tag-picker-header{display:flex;align-items:center;padding:12px 14px;border-bottom:1px solid var(--line);flex-shrink:0;gap:8px}.tag-picker-title{flex:1;font-size:13px;font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tag-picker-close{width:26px;height:26px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:18px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0}.tag-picker-close:hover{background:var(--paper-2);color:var(--ink)}.tag-picker-body{flex:1;min-height:0;overflow-y:auto;padding:8px 12px 12px}.tag-picker-root-btn{display:block;width:100%;text-align:left;padding:5px 8px;margin-bottom:6px;border:1px dashed var(--line);border-radius:var(--r);background:transparent;color:var(--muted);font-size:12px;cursor:pointer}.tag-picker-root-btn:hover{background:var(--paper-2);color:var(--ink);border-color:var(--muted-2)}.tag-picker-tree{border-top:1px solid var(--line-soft);padding-top:6px;margin-top:2px}.tag-picker-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 6px;text-align:left;font-size:13px;display:block;width:100%;border-radius:var(--r)}.tag-picker-node-btn:hover{background:var(--paper-2);text-decoration:none}.tag-picker-empty{font-size:13px;color:var(--muted-2);margin:6px 0 0}.collections-view{padding:24px}.collections-heading{margin:0 0 16px;font-size:22px;font-family:var(--display);font-weight:600}.collections-error{color:var(--accent);font-size:13px;margin-bottom:8px}.coll-dismiss{background:none;border:none;cursor:pointer;color:var(--accent);font-size:16px;line-height:1;padding:0 4px}.collections-layout{display:grid;grid-template-columns:220px 1fr;gap:0;border:1px solid var(--line);border-radius:var(--r2);min-height:340px}.collections-sidebar{border-right:1px solid var(--line);overflow-y:auto}.coll-sidebar-row{display:flex;flex-direction:column;width:100%;padding:10px 14px;border:none;border-bottom:1px solid var(--line-soft);background:none;cursor:pointer;text-align:left;gap:2px}.coll-sidebar-row:hover{background:var(--paper-2)}.coll-sidebar-row.is-active{background:var(--paper-2);border-left:3px solid var(--accent)}.coll-row-name{font-size:14px;font-weight:600;color:var(--ink)}.coll-row-meta{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}.coll-detail{padding:20px 24px;display:flex;flex-direction:column;gap:16px}.coll-detail--empty{justify-content:center;align-items:center}.coll-detail-header{display:flex;align-items:center;gap:12px}.coll-detail-name{margin:0;font-size:18px;font-family:var(--display);font-weight:600;flex:1}.coll-detail-name--editable{cursor:pointer}.coll-detail-name--editable:hover{color:var(--link)}.coll-edit-hint{font-size:14px;opacity:.5;margin-left:4px}.coll-rename-input{flex:1;font-size:16px;font-family:var(--display);border:1px solid var(--line);padding:4px 8px;background:var(--field);color:var(--ink);border-radius:var(--r)}.coll-delete-btn{border:1px solid var(--accent);background:none;color:var(--accent);padding:5px 12px;font-size:13px;cursor:pointer;border-radius:var(--r)}.coll-delete-btn:hover{background:var(--accent);color:var(--paper)}.coll-detail-vis{display:flex;align-items:center;gap:10px}.coll-vis-label{font-size:13px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}.coll-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:4px 8px;font-size:13px;border-radius:var(--r)}.coll-section-heading{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px}.coll-entries-section{flex:1}.coll-entries-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}.coll-entry-row{display:flex;align-items:center;gap:10px;padding:7px 0;border-bottom:1px solid var(--line-soft)}.coll-entry-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.coll-entry-title{font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.coll-entry-kind{font-size:11px;text-transform:uppercase;letter-spacing:.04em}.coll-entry-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.coll-entry-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:3px 6px;font-size:12px;border-radius:var(--r)}.coll-entry-remove{border:none;background:none;cursor:pointer;color:var(--muted);font-size:18px;line-height:1;padding:0 4px}.coll-entry-remove:hover{color:var(--accent)}.coll-add-entry-form{border-top:1px solid var(--line-soft);padding-top:12px}.coll-add-entry-row{display:flex;gap:8px;align-items:center}.coll-add-entry-input{flex:1;border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:6px 10px;font-size:13px;min-width:0;border-radius:var(--r)}.coll-add-btn{border:none;background:var(--ink);color:var(--paper);padding:6px 14px;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;border-radius:var(--r)}.coll-add-btn:hover{opacity:.85}.coll-add-btn:disabled{opacity:.45;cursor:default}.auth-loading{min-height:100vh;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:15px;background:var(--paper)}.user-menu{display:flex;align-items:center;gap:14px;padding-left:6px;flex-shrink:0}.user-name{font-size:12.5px;color:var(--muted-2);letter-spacing:.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px}.logout-btn{border:1px solid rgba(255,255,255,.18);background:transparent;color:#c8bfb0;font-size:12px;padding:4px 11px;border-radius:var(--r);cursor:pointer;white-space:nowrap;transition:background .15s,color .15s}.logout-btn:hover{background:#ffffff1a;color:var(--paper)}.logout-btn:disabled{opacity:.5;cursor:default}.login-page,.setup-page{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--paper)}.login-card,.setup-card{width:100%;max-width:360px;padding:40px 36px 44px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);box-shadow:0 2px 20px #141d1812}.login-brand,.setup-brand{font-family:var(--display);font-size:32px;font-weight:600;color:var(--ink);letter-spacing:-.01em;margin:0 0 6px}.login-tagline,.setup-tagline{font-size:13px;color:var(--muted);margin:0 0 28px}.login-field,.setup-field{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}.login-label,.setup-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}.login-input,.setup-input{width:100%;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:9px 11px;font-size:14px;border-radius:var(--r2);outline:none;transition:border-color .15s}.login-input:focus,.setup-input:focus{border-color:var(--accent)}.login-error,.setup-error{font-size:13px;color:var(--accent);margin:4px 0 8px}.login-submit,.setup-submit{width:100%;margin-top:8px;border:none;background:var(--top);color:var(--paper);font-size:14px;font-weight:600;padding:11px 16px;border-radius:var(--r2);cursor:pointer;letter-spacing:.02em;transition:opacity .15s}.login-submit:hover,.setup-submit:hover{opacity:.85}.login-submit:disabled,.setup-submit:disabled{opacity:.45;cursor:default}.view-tabs{display:flex;gap:2px;margin-bottom:22px;border-bottom:1px solid var(--line-soft);padding-bottom:0}.view-tab{border:none;background:none;color:var(--muted);font-size:13px;font-weight:600;padding:7px 14px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;letter-spacing:.02em;transition:color .12s;text-transform:uppercase;letter-spacing:.06em;font-size:11.5px}.view-tab:hover{color:var(--ink)}.view-tab.is-active{color:var(--ink);border-bottom-color:var(--accent)}.form-section{margin-bottom:32px}.form-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.form-row{display:flex;gap:8px;margin-bottom:10px}.form-field{display:flex;flex-direction:column;gap:5px;margin-bottom:12px}.form-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}.field-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s;min-width:0}.field-input:focus{border-color:var(--accent)}.field-input--flex{flex:1}.form-msg{font-size:13px;margin:6px 0}.form-msg--ok{color:var(--link)}.form-msg--err{color:var(--accent)}.btn-primary{border:none;background:var(--top);color:var(--paper);font-size:13px;font-weight:600;padding:8px 16px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.btn-primary:hover{opacity:.85}.btn-primary:disabled{opacity:.45;cursor:default}.btn-ghost{border:1px solid var(--line);background:none;color:var(--ink);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-ghost:hover{background:var(--paper-2)}.btn-danger{border:1px solid var(--accent);background:none;color:var(--accent);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-danger:hover{background:var(--accent);color:var(--paper)}.admin-view h1{font-family:var(--display);font-weight:600;font-size:26px;margin:0 0 20px}.admin-table{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:28px}.admin-table th{text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);padding:8px 10px;border-bottom:1px solid var(--line);background:var(--paper-2)}.admin-table th:first-child{padding-left:16px}.admin-table td{padding:9px 10px;border-bottom:1px solid var(--line-soft);color:var(--ink);vertical-align:middle}.admin-table td:first-child{padding-left:16px}.admin-table tr:hover td{background:var(--paper-2)}.admin-row-disabled td{opacity:.45}.admin-section{margin-bottom:36px;max-width:860px}.admin-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.admin-section h3{font-size:13px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin:22px 0 10px}.admin-form{display:flex;flex-direction:column;gap:8px;max-width:480px}.admin-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s}.admin-input:focus{border-color:var(--accent)}.admin-action-btn{border:1px solid var(--line);background:none;color:var(--ink);font-size:12px;padding:4px 10px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.admin-action-btn:hover{border-color:var(--accent);color:var(--accent)}.status-badge{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.status-active{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.status-disabled{background:#ede8e0;color:var(--muted);border:1px solid var(--line)}.run-status{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.run-status--completed{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.run-status--failed{background:#f5ddd8;color:#8d3f30;border:1px solid #e0b8b0}.run-status--in-progress{background:#fdefd8;color:#8a4f10;border:1px solid #f0cfa0}.run-row--failed{cursor:pointer}.run-row--failed:hover td{background:#fdf0ed!important}.run-expand-hint{margin-left:6px;font-size:10px;color:var(--accent);vertical-align:middle}.run-error-row td{padding:0!important;background:var(--paper-2)!important}.run-error-detail{margin:0;padding:10px 16px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);white-space:pre-wrap;word-break:break-word;max-height:220px;overflow-y:auto}.token-banner{background:#d8eddf;border:1px solid #b4d9be;padding:12px 14px;margin-bottom:16px;font-size:13px;border-radius:var(--r2)}.token-banner code{word-break:break-all;display:block;margin-top:6px;padding:6px 8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r);font-size:12px;font-family:ui-monospace,SF Mono,Menlo,monospace}.token-dismiss{margin-top:8px;font-size:12px;border:1px solid var(--line);background:none;cursor:pointer;padding:3px 8px;border-radius:var(--r);color:var(--muted)}.token-dismiss:hover{background:var(--paper-2)}.token-row{display:flex;align-items:center;justify-content:space-between;border:1px solid var(--line);background:var(--paper-3);padding:10px 12px;border-radius:var(--r);margin-bottom:6px}.token-row-info strong{font-size:14px;display:block}.token-row-info .muted{font-size:12px;margin-top:2px}.token-create-row{display:flex;gap:8px;margin-bottom:16px}.checkbox-row{display:flex;align-items:center;gap:10px;margin-bottom:12px;cursor:pointer;font-size:14px}.checkbox-row input[type=checkbox]{width:15px;height:15px;accent-color:var(--accent)}.coll-create-details{margin-top:16px}.coll-create-details summary{font-weight:600;cursor:pointer;font-size:13px;color:var(--link);list-style:none;display:flex;align-items:center;gap:6px;padding:8px 12px;border:1px solid var(--line-soft);border-radius:var(--r2);background:var(--paper-3);width:fit-content}.coll-create-details summary:hover{background:var(--paper-2)}.coll-create-details[open] summary{border-bottom-left-radius:0;border-bottom-right-radius:0}.coll-create-form{border:1px solid var(--line-soft);border-top:none;padding:14px;border-radius:0 0 var(--r2) var(--r2);background:var(--paper-3);display:flex;flex-direction:column;gap:10px;max-width:440px}@media (max-width: 900px){.topbar{grid-template-columns:1fr auto;height:auto;min-height:58px;padding:12px}.switcher,.nav{grid-column:1 / -1}.nav{justify-content:flex-start;overflow-x:auto}.app-shell{height:auto;grid-template-columns:1fr}.context-rail{border-left:0;border-top:1px solid var(--line)}.entry-table{min-width:860px}}.rail-title--editable{cursor:pointer}.rail-title--editable:hover{opacity:.75}.rail-title--editable .edit-icon{display:inline-block;width:.75em;height:.75em;margin-left:.35em;vertical-align:middle;opacity:0;transition:opacity .1s;flex-shrink:0}.rail-title--editable:hover .edit-icon{opacity:.5}.rail-title-input{width:100%;font:inherit;font-size:inherit;font-weight:600;background:transparent;border:none;border-bottom:1px solid currentColor;color:inherit;padding:0;margin:0 0 8px;outline:none}.preview-panel{flex:1;display:flex;flex-direction:column;min-height:0}.preview-panel-loading,.preview-panel-empty{flex:1;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--muted-2);font-size:14px;text-align:center;padding:24px}.preview-video-wrap{flex:1;display:flex;align-items:center;justify-content:center;background:#0d0d0b;min-height:200px}.preview-video-wrap video{max-width:100%;max-height:100%;width:100%;display:block}.preview-iframe-wrap{flex:1;display:flex;flex-direction:column;min-height:0}.preview-iframe-toolbar{display:flex;flex-direction:column;gap:2px;padding:6px 12px;background:var(--paper-2);border-bottom:1px solid var(--line);flex-shrink:0;text-transform:none;letter-spacing:normal}.preview-iframe-toolbar span{font-size:11px;color:var(--muted-2)}.preview-iframe-toolbar a{margin-left:auto;color:var(--link);font-size:12px;text-decoration:none;padding:3px 8px;border:1px solid var(--line);border-radius:var(--r2);background:var(--field);transition:border-color .12s}.preview-iframe-toolbar a:hover{border-color:var(--accent);text-decoration:none}.preview-iframe-wrap iframe{flex:1;width:100%;border:none;background:#fff;min-height:0}.preview-image-wrap{flex:1;display:flex;align-items:center;justify-content:center;padding:20px;background:var(--paper-2)}.preview-image-wrap img{max-width:100%;max-height:100%;object-fit:contain;border-radius:var(--r3);cursor:zoom-in;display:block;box-shadow:0 4px 24px #0000001a}.preview-tweet-wrap{flex:1;min-height:0;overflow-y:auto;padding:12px 16px;background:var(--paper-2);scrollbar-width:thin;scrollbar-color:var(--line) transparent}.preview-tweet-wrap::-webkit-scrollbar{width:8px}.preview-tweet-wrap::-webkit-scrollbar-track{background:transparent}.preview-tweet-wrap::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:2px solid transparent;background-clip:padding-box}.preview-tweet-wrap::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:2px solid transparent}.tw-card{border:1px solid var(--line);border-radius:12px;padding:16px;background:var(--paper);max-width:560px;margin:0 auto 12px}.tw-thread{max-width:560px;margin:0 auto}.tw-thread-item{display:flex;gap:0;margin-bottom:0}.tw-thread-connector{display:flex;flex-direction:column;align-items:center;flex-shrink:0;width:52px;padding-top:2px}.tw-thread-avatar-col{display:flex;flex-direction:column;align-items:center;flex-shrink:0}.tw-thread-line{width:2px;background:var(--line);flex:1;min-height:16px;margin:4px 0}.tw-thread-body{flex:1;min-width:0;padding:0 0 16px 12px}.tw-thread-body:last-child{padding-bottom:0}.tw-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;flex-shrink:0;display:block}.tw-avatar-ph{width:40px;height:40px;border-radius:50%;background:var(--paper-2);border:1px solid var(--line);flex-shrink:0}.tw-header{display:flex;align-items:baseline;gap:6px;flex-wrap:wrap;margin-bottom:6px}.tw-author-name{font-size:14.5px;font-weight:700;color:var(--ink)}.tw-author-handle{font-size:13px;color:var(--muted-2)}.tw-dot{color:var(--muted-2);font-size:13px}.tw-date{font-size:13px;color:var(--muted-2)}.tw-text{font-size:15px;line-height:1.65;color:var(--ink);white-space:pre-line;word-break:break-word;margin-bottom:10px}.tw-text a{color:var(--link);text-decoration:none}.tw-text a:hover{text-decoration:underline}.tw-stats{display:flex;gap:20px;color:var(--muted-2);font-size:13px;margin-top:10px;padding-top:10px;border-top:1px solid var(--line-soft)}.tw-stats span{display:flex;align-items:center;gap:4px}.tw-article{max-width:598px;margin:0 auto}.tw-article-cover{width:100%;display:block;object-fit:cover;max-height:380px}.tw-article-meta{padding:20px 16px 0}.tw-article-title{font-size:22px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.3;margin-bottom:14px}.tw-article-author-row{display:flex;align-items:center;gap:12px;margin-bottom:14px}.tw-article-author-name{font-size:14px;font-weight:700;color:var(--ink)}.tw-article-author-sub{font-size:13px;color:var(--muted-2)}.tw-article-divider{border:none;border-top:1px solid var(--line);margin:0}.tw-article-body{padding:8px 16px 60px}.tw-b-h1{font-size:24px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.25;margin:22px 0 10px}.tw-b-h2{font-size:19px;font-weight:700;letter-spacing:-.15px;color:var(--ink);line-height:1.3;margin:20px 0 8px}.tw-b-p{font-size:16px;color:var(--ink);line-height:1.72;margin-bottom:14px}.tw-b-p:empty{display:none}.tw-b-spacer{height:6px;display:block}.tw-b-blockquote{border-left:3px solid var(--line);padding:2px 14px;margin:14px 0;color:var(--muted);font-size:16px;line-height:1.65}.tw-b-hr{border:none;border-top:1px solid var(--line);margin:24px 0}.tw-b-img{width:100%;display:block;border-radius:10px;margin:14px 0}.tw-b-ul,.tw-b-ol{margin:10px 0 14px;padding-left:26px}.tw-b-li{font-size:16px;color:var(--ink);line-height:1.65;margin-bottom:6px}.tw-b-code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:.875em;background:var(--paper-2);padding:2px 5px;border-radius:4px;color:var(--ink)}.tw-b-pre{background:var(--paper-2);border:1px solid var(--line);border-radius:8px;padding:14px 16px;overflow-x:auto;margin:12px 0}.tw-b-pre code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:13px;line-height:1.6}.tw-b-tweet-link{display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:10px;padding:12px 14px;margin:12px 0;color:var(--muted);font-size:14px;text-decoration:none;background:var(--paper-3);transition:background .12s}.tw-b-tweet-link:hover{background:var(--field)}.tw-b-tweet-link svg{flex-shrink:0;color:var(--ink)}.audio-bar{position:fixed;bottom:0;left:0;right:0;height:72px;background:var(--paper);border-top:1px solid var(--line);display:flex;align-items:center;gap:20px;padding:0 24px;z-index:100;box-shadow:0 -2px 16px #00000014}.audio-bar-info{display:flex;align-items:center;gap:10px;min-width:0;flex:0 0 200px}.audio-bar-icon{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center}.audio-bar-icon svg{width:20px;height:20px}.audio-bar-title{font-size:13px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;font-weight:500}.audio-bar-controls{flex:1;display:flex;align-items:center;gap:12px;min-width:0}.audio-bar-play-btn{width:38px;height:38px;border-radius:50%;background:var(--accent);color:var(--paper);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,transform .1s}.audio-bar-play-btn:hover{background:var(--accent-2)}.audio-bar-play-btn:active{transform:scale(.93)}.audio-bar-play-btn svg{width:15px;height:15px}.audio-bar-seek{flex:1;min-width:0;display:flex;align-items:center;gap:8px}.audio-bar-seek input[type=range]{flex:1;accent-color:var(--accent);height:4px;cursor:pointer;min-width:0}.audio-bar-time{font-size:11.5px;color:var(--muted-2);white-space:nowrap;min-width:80px;text-align:right;font-variant-numeric:tabular-nums}.audio-bar-right{flex:0 0 auto;display:flex;align-items:center;gap:10px}.audio-bar-volume{display:flex;align-items:center;gap:6px}.audio-bar-volume svg{width:14px;height:14px;color:var(--muted-2);flex-shrink:0}.audio-bar-volume input[type=range]{width:72px;accent-color:var(--accent);cursor:pointer}.audio-bar-close{width:28px;height:28px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:18px;padding:0;line-height:1;transition:background .12s,color .12s}.audio-bar-close:hover{background:var(--field);color:var(--ink)}.preview-modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#0000008c;display:flex;align-items:center;justify-content:center;padding:20px}.preview-modal{background:var(--paper);border-radius:12px;box-shadow:0 24px 80px #00000047;width:90vw;max-width:1100px;max-height:88vh;display:flex;flex-direction:column;overflow:hidden}.preview-modal--full{height:88vh}.preview-modal--full .preview-modal-body{max-height:none}.preview-modal-header{display:flex;align-items:center;padding:14px 18px;border-bottom:1px solid var(--line);flex-shrink:0;gap:12px}.preview-modal-title{flex:1;min-width:0;font-size:14px;font-weight:600;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.preview-modal-close{width:30px;height:30px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-close:hover{background:var(--field);color:var(--ink)}.preview-modal-body{flex:1;min-height:0;overflow:hidden;display:flex;flex-direction:column;max-height:calc(88vh - 52px)}.rail-preview-btn{display:block;width:100%;padding:8px 12px;margin-bottom:16px;background:var(--accent);color:var(--paper);border:none;border-radius:var(--r3);font-size:13px;font-weight:600;cursor:pointer;text-align:center;transition:background .12s}.rail-preview-btn:hover{background:var(--accent-2)}.preview-modal-newtab{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:var(--r2);color:var(--muted-2);text-decoration:none;font-size:16px;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-newtab:hover{background:var(--field);color:var(--ink)}body.has-audio-bar{padding-bottom:56px} diff --git a/crates/archivr-server/static/assets/index-Db35_tmT.js b/crates/archivr-server/static/assets/index-Db35_tmT.js deleted file mode 100644 index 22aef89..0000000 --- a/crates/archivr-server/static/assets/index-Db35_tmT.js +++ /dev/null @@ -1,47 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var du={exports:{}},Gl={},fu={exports:{}},Y={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Fr=Symbol.for("react.element"),Od=Symbol.for("react.portal"),Ad=Symbol.for("react.fragment"),Fd=Symbol.for("react.strict_mode"),Md=Symbol.for("react.profiler"),Bd=Symbol.for("react.provider"),Hd=Symbol.for("react.context"),Ud=Symbol.for("react.forward_ref"),Wd=Symbol.for("react.suspense"),Vd=Symbol.for("react.memo"),Qd=Symbol.for("react.lazy"),Wa=Symbol.iterator;function Kd(e){return e===null||typeof e!="object"?null:(e=Wa&&e[Wa]||e["@@iterator"],typeof e=="function"?e:null)}var pu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},hu=Object.assign,mu={};function Wn(e,t,n){this.props=e,this.context=t,this.refs=mu,this.updater=n||pu}Wn.prototype.isReactComponent={};Wn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Wn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function gu(){}gu.prototype=Wn.prototype;function Ki(e,t,n){this.props=e,this.context=t,this.refs=mu,this.updater=n||pu}var Xi=Ki.prototype=new gu;Xi.constructor=Ki;hu(Xi,Wn.prototype);Xi.isPureReactComponent=!0;var Va=Array.isArray,vu=Object.prototype.hasOwnProperty,Ji={current:null},yu={key:!0,ref:!0,__self:!0,__source:!0};function xu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)vu.call(t,r)&&!yu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,H=R[X];if(0>>1;Xl(B,F))Ml(W,B)?(R[X]=W,R[M]=F,X=M):(R[X]=B,R[O]=F,X=O);else if(Ml(W,F))R[X]=W,R[M]=F,X=M;else break e}}return T}function l(R,T){var F=R.sortIndex-T.sortIndex;return F!==0?F:R.id-T.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],g=1,m=null,h=3,y=!1,x=!1,k=!1,j=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(R){for(var T=n(c);T!==null;){if(T.callback===null)r(c);else if(T.startTime<=R)r(c),T.sortIndex=T.expirationTime,t(u,T);else break;T=n(c)}}function w(R){if(k=!1,v(R),!x)if(n(u)!==null)x=!0,ve(S);else{var T=n(c);T!==null&&ie(w,T.startTime-R)}}function S(R,T){x=!1,k&&(k=!1,p(_),_=-1),y=!0;var F=h;try{for(v(T),m=n(u);m!==null&&(!(m.expirationTime>T)||R&&!Q());){var X=m.callback;if(typeof X=="function"){m.callback=null,h=m.priorityLevel;var H=X(m.expirationTime<=T);T=e.unstable_now(),typeof H=="function"?m.callback=H:m===n(u)&&r(u),v(T)}else r(u);m=n(u)}if(m!==null)var N=!0;else{var O=n(c);O!==null&&ie(w,O.startTime-T),N=!1}return N}finally{m=null,h=F,y=!1}}var P=!1,C=null,_=-1,I=5,L=-1;function Q(){return!(e.unstable_now()-LR||125X?(R.sortIndex=F,t(c,R),n(u)===null&&R===n(c)&&(k?(p(_),_=-1):k=!0,ie(w,F-X))):(R.sortIndex=H,t(u,R),x||y||(x=!0,ve(S))),R},e.unstable_shouldYield=Q,e.unstable_wrapCallback=function(R){var T=h;return function(){var F=h;h=T;try{return R.apply(this,arguments)}finally{h=F}}}})(Nu);Su.exports=Nu;var lf=Su.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var sf=f,qe=lf;function b(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Zs=Object.prototype.hasOwnProperty,af=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Ka={},Xa={};function of(e){return Zs.call(Xa,e)?!0:Zs.call(Ka,e)?!1:af.test(e)?Xa[e]=!0:(Ka[e]=!0,!1)}function uf(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function cf(e,t,n,r){if(t===null||typeof t>"u"||uf(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Me(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var Le={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Le[e]=new Me(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Le[t]=new Me(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Le[e]=new Me(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Le[e]=new Me(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Le[e]=new Me(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Le[e]=new Me(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Le[e]=new Me(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Le[e]=new Me(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Le[e]=new Me(e,5,!1,e.toLowerCase(),null,!1,!1)});var Gi=/[\-:]([a-z])/g;function Yi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Me(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Me(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Me(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Le[e]=new Me(e,1,!1,e.toLowerCase(),null,!1,!1)});Le.xlinkHref=new Me("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Le[e]=new Me(e,1,!1,e.toLowerCase(),null,!0,!0)});function Zi(e,t,n,r){var l=Le.hasOwnProperty(t)?Le[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` -`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{_s=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?or(e):""}function df(e){switch(e.tag){case 5:return or(e.type);case 16:return or("Lazy");case 13:return or("Suspense");case 19:return or("SuspenseList");case 0:case 2:case 15:return e=Cs(e.type,!1),e;case 11:return e=Cs(e.type.render,!1),e;case 1:return e=Cs(e.type,!0),e;default:return""}}function ri(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case xn:return"Fragment";case yn:return"Portal";case ei:return"Profiler";case ea:return"StrictMode";case ti:return"Suspense";case ni:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Eu:return(e.displayName||"Context")+".Consumer";case Cu:return(e._context.displayName||"Context")+".Provider";case ta:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case na:return t=e.displayName||null,t!==null?t:ri(e.type)||"Memo";case bt:t=e._payload,e=e._init;try{return ri(e(t))}catch{}}return null}function ff(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ri(t);case 8:return t===ea?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Wt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Pu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function pf(e){var t=Pu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Jr(e){e._valueTracker||(e._valueTracker=pf(e))}function bu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Pu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _l(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function li(e,t){var n=t.checked;return ge({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function qa(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Wt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Lu(e,t){t=t.checked,t!=null&&Zi(e,"checked",t,!1)}function si(e,t){Lu(e,t);var n=Wt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ii(e,t.type,n):t.hasOwnProperty("defaultValue")&&ii(e,t.type,Wt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ga(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ii(e,t,n){(t!=="number"||_l(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ur=Array.isArray;function bn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=qr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var pr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},hf=["Webkit","ms","Moz","O"];Object.keys(pr).forEach(function(e){hf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),pr[t]=pr[e]})});function $u(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||pr.hasOwnProperty(e)&&pr[e]?(""+t).trim():t+"px"}function Iu(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=$u(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var mf=ge({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ui(e,t){if(t){if(mf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(b(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(b(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(b(61))}if(t.style!=null&&typeof t.style!="object")throw Error(b(62))}}function ci(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var di=null;function ra(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var fi=null,Ln=null,zn=null;function eo(e){if(e=Hr(e)){if(typeof fi!="function")throw Error(b(280));var t=e.stateNode;t&&(t=ns(t),fi(e.stateNode,e.type,t))}}function Ou(e){Ln?zn?zn.push(e):zn=[e]:Ln=e}function Au(){if(Ln){var e=Ln,t=zn;if(zn=Ln=null,eo(e),t)for(e=0;e>>=0,e===0?32:31-(Cf(e)/Ef|0)|0}var Gr=64,Yr=4194304;function cr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Pl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=cr(o):(i&=a,i!==0&&(r=cr(i)))}else a=n&~l,a!==0?r=cr(a):i!==0&&(r=cr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Mr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ct(t),e[t]=n}function Lf(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=mr),uo=" ",co=!1;function lc(e,t){switch(e){case"keyup":return sp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function sc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var wn=!1;function ap(e,t){switch(e){case"compositionend":return sc(t);case"keypress":return t.which!==32?null:(co=!0,uo);case"textInput":return e=t.data,e===uo&&co?null:e;default:return null}}function op(e,t){if(wn)return e==="compositionend"||!da&&lc(e,t)?(e=nc(),ml=oa=Dt=null,wn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=mo(n)}}function uc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?uc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function cc(){for(var e=window,t=_l();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_l(e.document)}return t}function fa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function vp(e){var t=cc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&uc(n.ownerDocument.documentElement,n)){if(r!==null&&fa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=go(n,i);var a=go(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,kn=null,yi=null,vr=null,xi=!1;function vo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;xi||kn==null||kn!==_l(r)||(r=kn,"selectionStart"in r&&fa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),vr&&Pr(vr,r)||(vr=r,r=zl(yi,"onSelect"),0Nn||(e.current=_i[Nn],_i[Nn]=null,Nn--)}function ae(e,t){Nn++,_i[Nn]=e.current,e.current=t}var Vt={},Ie=Kt(Vt),Ue=Kt(!1),sn=Vt;function An(e,t){var n=e.type.contextTypes;if(!n)return Vt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function We(e){return e=e.childContextTypes,e!=null}function Dl(){ce(Ue),ce(Ie)}function No(e,t,n){if(Ie.current!==Vt)throw Error(b(168));ae(Ie,t),ae(Ue,n)}function xc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(b(108,ff(e)||"Unknown",l));return ge({},n,r)}function $l(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Vt,sn=Ie.current,ae(Ie,e),ae(Ue,Ue.current),!0}function _o(e,t,n){var r=e.stateNode;if(!r)throw Error(b(169));n?(e=xc(e,t,sn),r.__reactInternalMemoizedMergedChildContext=e,ce(Ue),ce(Ie),ae(Ie,e)):ce(Ue),ae(Ue,n)}var xt=null,rs=!1,Ms=!1;function wc(e){xt===null?xt=[e]:xt.push(e)}function Pp(e){rs=!0,wc(e)}function Xt(){if(!Ms&&xt!==null){Ms=!0;var e=0,t=le;try{var n=xt;for(le=1;e>=a,l-=a,wt=1<<32-ct(t)+l|n<_?(I=C,C=null):I=C.sibling;var L=h(p,C,v[_],w);if(L===null){C===null&&(C=I);break}e&&C&&L.alternate===null&&t(p,C),d=i(L,d,_),P===null?S=L:P.sibling=L,P=L,C=I}if(_===v.length)return n(p,C),fe&&Gt(p,_),S;if(C===null){for(;__?(I=C,C=null):I=C.sibling;var Q=h(p,C,L.value,w);if(Q===null){C===null&&(C=I);break}e&&C&&Q.alternate===null&&t(p,C),d=i(Q,d,_),P===null?S=Q:P.sibling=Q,P=Q,C=I}if(L.done)return n(p,C),fe&&Gt(p,_),S;if(C===null){for(;!L.done;_++,L=v.next())L=m(p,L.value,w),L!==null&&(d=i(L,d,_),P===null?S=L:P.sibling=L,P=L);return fe&&Gt(p,_),S}for(C=r(p,C);!L.done;_++,L=v.next())L=y(C,p,_,L.value,w),L!==null&&(e&&L.alternate!==null&&C.delete(L.key===null?_:L.key),d=i(L,d,_),P===null?S=L:P.sibling=L,P=L);return e&&C.forEach(function(ne){return t(p,ne)}),fe&&Gt(p,_),S}function j(p,d,v,w){if(typeof v=="object"&&v!==null&&v.type===xn&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Xr:e:{for(var S=v.key,P=d;P!==null;){if(P.key===S){if(S=v.type,S===xn){if(P.tag===7){n(p,P.sibling),d=l(P,v.props.children),d.return=p,p=d;break e}}else if(P.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===bt&&To(S)===P.type){n(p,P.sibling),d=l(P,v.props),d.ref=rr(p,P,v),d.return=p,p=d;break e}n(p,P);break}else t(p,P);P=P.sibling}v.type===xn?(d=ln(v.props.children,p.mode,w,v.key),d.return=p,p=d):(w=Sl(v.type,v.key,v.props,null,p.mode,w),w.ref=rr(p,d,v),w.return=p,p=w)}return a(p);case yn:e:{for(P=v.key;d!==null;){if(d.key===P)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){n(p,d.sibling),d=l(d,v.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=Xs(v,p.mode,w),d.return=p,p=d}return a(p);case bt:return P=v._init,j(p,d,P(v._payload),w)}if(ur(v))return x(p,d,v,w);if(Yn(v))return k(p,d,v,w);sl(p,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,v),d.return=p,p=d):(n(p,d),d=Ks(v,p.mode,w),d.return=p,p=d),a(p)):n(p,d)}return j}var Mn=Nc(!0),_c=Nc(!1),Al=Kt(null),Fl=null,En=null,ga=null;function va(){ga=En=Fl=null}function ya(e){var t=Al.current;ce(Al),e._currentValue=t}function Ti(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Dn(e,t){Fl=e,ga=En=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(He=!0),e.firstContext=null)}function lt(e){var t=e._currentValue;if(ga!==e)if(e={context:e,memoizedValue:t,next:null},En===null){if(Fl===null)throw Error(b(308));En=e,Fl.dependencies={lanes:0,firstContext:e}}else En=En.next=e;return t}var en=null;function xa(e){en===null?en=[e]:en.push(e)}function Cc(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,xa(t)):(n.next=l.next,l.next=n),t.interleaved=n,_t(e,r)}function _t(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Lt=!1;function wa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ec(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Mt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ee&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,_t(e,n)}return l=r.interleaved,l===null?(t.next=t,xa(r)):(t.next=l.next,l.next=t),r.interleaved=t,_t(e,n)}function vl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}function Po(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Ml(e,t,n,r){var l=e.updateQueue;Lt=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var g=e.alternate;g!==null&&(g=g.updateQueue,o=g.lastBaseUpdate,o!==a&&(o===null?g.firstBaseUpdate=c:o.next=c,g.lastBaseUpdate=u))}if(i!==null){var m=l.baseState;a=0,g=c=u=null,o=i;do{var h=o.lane,y=o.eventTime;if((r&h)===h){g!==null&&(g=g.next={eventTime:y,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,k=o;switch(h=t,y=n,k.tag){case 1:if(x=k.payload,typeof x=="function"){m=x.call(y,m,h);break e}m=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=k.payload,h=typeof x=="function"?x.call(y,m,h):x,h==null)break e;m=ge({},m,h);break e;case 2:Lt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else y={eventTime:y,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},g===null?(c=g=y,u=m):g=g.next=y,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(g===null&&(u=m),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=g,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);un|=a,e.lanes=a,e.memoizedState=m}}function bo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Hs.transition;Hs.transition={};try{e(!1),t()}finally{le=n,Hs.transition=r}}function Wc(){return st().memoizedState}function Rp(e,t,n){var r=Ht(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Vc(e))Qc(t,n);else if(n=Cc(e,t,n,r),n!==null){var l=Ae();dt(n,e,r,l),Kc(n,t,r)}}function Dp(e,t,n){var r=Ht(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Vc(e))Qc(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,ft(o,a)){var u=t.interleaved;u===null?(l.next=l,xa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Cc(e,t,l,r),n!==null&&(l=Ae(),dt(n,e,r,l),Kc(n,t,r))}}function Vc(e){var t=e.alternate;return e===me||t!==null&&t===me}function Qc(e,t){yr=Hl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Kc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}var Ul={readContext:lt,useCallback:Re,useContext:Re,useEffect:Re,useImperativeHandle:Re,useInsertionEffect:Re,useLayoutEffect:Re,useMemo:Re,useReducer:Re,useRef:Re,useState:Re,useDebugValue:Re,useDeferredValue:Re,useTransition:Re,useMutableSource:Re,useSyncExternalStore:Re,useId:Re,unstable_isNewReconciler:!1},$p={readContext:lt,useCallback:function(e,t){return ht().memoizedState=[e,t===void 0?null:t],e},useContext:lt,useEffect:zo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,xl(4194308,4,Fc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return xl(4194308,4,e,t)},useInsertionEffect:function(e,t){return xl(4,2,e,t)},useMemo:function(e,t){var n=ht();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ht();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Rp.bind(null,me,e),[r.memoizedState,e]},useRef:function(e){var t=ht();return e={current:e},t.memoizedState=e},useState:Lo,useDebugValue:Ta,useDeferredValue:function(e){return ht().memoizedState=e},useTransition:function(){var e=Lo(!1),t=e[0];return e=zp.bind(null,e[1]),ht().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=me,l=ht();if(fe){if(n===void 0)throw Error(b(407));n=n()}else{if(n=t(),Te===null)throw Error(b(349));on&30||Lc(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,zo(Rc.bind(null,r,i,e),[e]),r.flags|=2048,Or(9,zc.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ht(),t=Te.identifierPrefix;if(fe){var n=kt,r=wt;n=(r&~(1<<32-ct(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=$r++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[mt]=t,e[zr]=r,rd(e,t,!1,!1),t.stateNode=e;e:{switch(a=ci(n,r),n){case"dialog":ue("cancel",e),ue("close",e),l=r;break;case"iframe":case"object":case"embed":ue("load",e),l=r;break;case"video":case"audio":for(l=0;lUn&&(t.flags|=128,r=!0,lr(i,!1),t.lanes=4194304)}else{if(!r)if(e=Bl(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),lr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!fe)return De(t),null}else 2*we()-i.renderingStartTime>Un&&n!==1073741824&&(t.flags|=128,r=!0,lr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=we(),t.sibling=null,n=he.current,ae(he,r?n&1|2:n&1),t):(De(t),null);case 22:case 23:return Da(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ke&1073741824&&(De(t),t.subtreeFlags&6&&(t.flags|=8192)):De(t),null;case 24:return null;case 25:return null}throw Error(b(156,t.tag))}function Up(e,t){switch(ha(t),t.tag){case 1:return We(t.type)&&Dl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Bn(),ce(Ue),ce(Ie),Sa(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ja(t),null;case 13:if(ce(he),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(b(340));Fn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ce(he),null;case 4:return Bn(),null;case 10:return ya(t.type._context),null;case 22:case 23:return Da(),null;case 24:return null;default:return null}}var al=!1,$e=!1,Wp=typeof WeakSet=="function"?WeakSet:Set,A=null;function Tn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(e,t,r)}else n.current=null}function Oi(e,t,n){try{n()}catch(r){ye(e,t,r)}}var Uo=!1;function Vp(e,t){if(wi=bl,e=cc(),fa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,g=0,m=e,h=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(o=a+l),m!==i||r!==0&&m.nodeType!==3||(u=a+r),m.nodeType===3&&(a+=m.nodeValue.length),(y=m.firstChild)!==null;)h=m,m=y;for(;;){if(m===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++g===r&&(u=a),(y=m.nextSibling)!==null)break;m=h,h=m.parentNode}m=y}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(ki={focusedElem:e,selectionRange:n},bl=!1,A=t;A!==null;)if(t=A,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,A=e;else for(;A!==null;){t=A;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var k=x.memoizedProps,j=x.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?k:at(t.type,k),j);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(b(163))}}catch(w){ye(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,A=e;break}A=t.return}return x=Uo,Uo=!1,x}function xr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Oi(t,n,i)}l=l.next}while(l!==r)}}function is(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ai(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function id(e){var t=e.alternate;t!==null&&(e.alternate=null,id(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[mt],delete t[zr],delete t[Ni],delete t[Ep],delete t[Tp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ad(e){return e.tag===5||e.tag===3||e.tag===4}function Wo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ad(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Fi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Rl));else if(r!==4&&(e=e.child,e!==null))for(Fi(e,t,n),e=e.sibling;e!==null;)Fi(e,t,n),e=e.sibling}function Mi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Mi(e,t,n),e=e.sibling;e!==null;)Mi(e,t,n),e=e.sibling}var Pe=null,ot=!1;function Pt(e,t,n){for(n=n.child;n!==null;)od(e,t,n),n=n.sibling}function od(e,t,n){if(gt&&typeof gt.onCommitFiberUnmount=="function")try{gt.onCommitFiberUnmount(Yl,n)}catch{}switch(n.tag){case 5:$e||Tn(n,t);case 6:var r=Pe,l=ot;Pe=null,Pt(e,t,n),Pe=r,ot=l,Pe!==null&&(ot?(e=Pe,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Pe.removeChild(n.stateNode));break;case 18:Pe!==null&&(ot?(e=Pe,n=n.stateNode,e.nodeType===8?Fs(e.parentNode,n):e.nodeType===1&&Fs(e,n),Er(e)):Fs(Pe,n.stateNode));break;case 4:r=Pe,l=ot,Pe=n.stateNode.containerInfo,ot=!0,Pt(e,t,n),Pe=r,ot=l;break;case 0:case 11:case 14:case 15:if(!$e&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&Oi(n,t,a),l=l.next}while(l!==r)}Pt(e,t,n);break;case 1:if(!$e&&(Tn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ye(n,t,o)}Pt(e,t,n);break;case 21:Pt(e,t,n);break;case 22:n.mode&1?($e=(r=$e)||n.memoizedState!==null,Pt(e,t,n),$e=r):Pt(e,t,n);break;default:Pt(e,t,n)}}function Vo(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Wp),t.forEach(function(r){var l=eh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function it(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=we()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Kp(r/1960))-r,10e?16:e,$t===null)var r=!1;else{if(e=$t,$t=null,Ql=0,ee&6)throw Error(b(331));var l=ee;for(ee|=4,A=e.current;A!==null;){var i=A,a=i.child;if(A.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uwe()-za?rn(e,0):La|=n),Ve(e,t)}function gd(e,t){t===0&&(e.mode&1?(t=Yr,Yr<<=1,!(Yr&130023424)&&(Yr=4194304)):t=1);var n=Ae();e=_t(e,t),e!==null&&(Mr(e,t,n),Ve(e,n))}function Zp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),gd(e,n)}function eh(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(b(314))}r!==null&&r.delete(t),gd(e,n)}var vd;vd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Ue.current)He=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return He=!1,Bp(e,t,n);He=!!(e.flags&131072)}else He=!1,fe&&t.flags&1048576&&kc(t,Ol,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;wl(e,t),e=t.pendingProps;var l=An(t,Ie.current);Dn(t,n),l=_a(null,t,r,e,l,n);var i=Ca();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,We(r)?(i=!0,$l(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,wa(t),l.updater=ss,t.stateNode=l,l._reactInternals=t,bi(t,r,e,n),t=Ri(null,t,r,!0,i,n)):(t.tag=0,fe&&i&&pa(t),Oe(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(wl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=nh(r),e=at(r,e),l){case 0:t=zi(null,t,r,e,n);break e;case 1:t=Mo(null,t,r,e,n);break e;case 11:t=Ao(null,t,r,e,n);break e;case 14:t=Fo(null,t,r,at(r.type,e),n);break e}throw Error(b(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),zi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),Mo(e,t,r,l,n);case 3:e:{if(ed(t),e===null)throw Error(b(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Ec(e,t),Ml(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=Hn(Error(b(423)),t),t=Bo(e,t,r,n,l);break e}else if(r!==l){l=Hn(Error(b(424)),t),t=Bo(e,t,r,n,l);break e}else for(Xe=Ft(t.stateNode.containerInfo.firstChild),Je=t,fe=!0,ut=null,n=_c(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Fn(),r===l){t=Ct(e,t,n);break e}Oe(e,t,r,n)}t=t.child}return t;case 5:return Tc(t),e===null&&Ei(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,ji(r,l)?a=null:i!==null&&ji(r,i)&&(t.flags|=32),Zc(e,t),Oe(e,t,a,n),t.child;case 6:return e===null&&Ei(t),null;case 13:return td(e,t,n);case 4:return ka(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Mn(t,null,r,n):Oe(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),Ao(e,t,r,l,n);case 7:return Oe(e,t,t.pendingProps,n),t.child;case 8:return Oe(e,t,t.pendingProps.children,n),t.child;case 12:return Oe(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,ae(Al,r._currentValue),r._currentValue=a,i!==null)if(ft(i.value,a)){if(i.children===l.children&&!Ue.current){t=Ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=jt(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var g=c.pending;g===null?u.next=u:(u.next=g.next,g.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Ti(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(b(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Ti(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Oe(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Dn(t,n),l=lt(l),r=r(l),t.flags|=1,Oe(e,t,r,n),t.child;case 14:return r=t.type,l=at(r,t.pendingProps),l=at(r.type,l),Fo(e,t,r,l,n);case 15:return Gc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),wl(e,t),t.tag=1,We(r)?(e=!0,$l(t)):e=!1,Dn(t,n),Xc(t,r,l),bi(t,r,l,n),Ri(null,t,r,!0,e,n);case 19:return nd(e,t,n);case 22:return Yc(e,t,n)}throw Error(b(156,t.tag))};function yd(e,t){return Vu(e,t)}function th(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function nt(e,t,n,r){return new th(e,t,n,r)}function Ia(e){return e=e.prototype,!(!e||!e.isReactComponent)}function nh(e){if(typeof e=="function")return Ia(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ta)return 11;if(e===na)return 14}return 2}function Ut(e,t){var n=e.alternate;return n===null?(n=nt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Sl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")Ia(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case xn:return ln(n.children,l,i,t);case ea:a=8,l|=8;break;case ei:return e=nt(12,n,t,l|2),e.elementType=ei,e.lanes=i,e;case ti:return e=nt(13,n,t,l),e.elementType=ti,e.lanes=i,e;case ni:return e=nt(19,n,t,l),e.elementType=ni,e.lanes=i,e;case Tu:return os(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Cu:a=10;break e;case Eu:a=9;break e;case ta:a=11;break e;case na:a=14;break e;case bt:a=16,r=null;break e}throw Error(b(130,e==null?e:typeof e,""))}return t=nt(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function ln(e,t,n,r){return e=nt(7,e,r,t),e.lanes=n,e}function os(e,t,n,r){return e=nt(22,e,r,t),e.elementType=Tu,e.lanes=n,e.stateNode={isHidden:!1},e}function Ks(e,t,n){return e=nt(6,e,null,t),e.lanes=n,e}function Xs(e,t,n){return t=nt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function rh(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ts(0),this.expirationTimes=Ts(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ts(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Oa(e,t,n,r,l,i,a,o,u){return e=new rh(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=nt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wa(i),e}function lh(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(jd)}catch(e){console.error(e)}}jd(),ju.exports=Ge;var uh=ju.exports,Sd,Zo=uh;Sd=Zo.createRoot,Zo.hydrateRoot;async function _e(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ch(){return _e("/api/archives")}async function dh(e){return _e(`/api/archives/${e}/entries`)}async function fh(e,t,n){const r=new URLSearchParams;return t&&r.set("q",t),n&&r.set("tag",n),_e(`/api/archives/${e}/entries/search?${r}`)}async function Vi(e,t){return _e(`/api/archives/${e}/entries/${t}`)}function ph(e,t,n){return Promise.all(n.map(r=>_e(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function hh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function mh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function cl(e,t){return _e(`/api/archives/${e}/entries/${t}/tags`)}async function eu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function gh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function tu(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function vh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function yh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function Js(e){return _e(`/api/archives/${e}/runs`)}async function dl(e){return _e(`/api/archives/${e}/tags`)}async function xh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||`HTTP ${i.status}`)}return i.json()}async function wh(e,t){return _e(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function Nd(e,t){return _e(`/api/archives/${e}/capture_jobs/${t}`)}async function kh(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function jh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Sh(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function Nh(){await fetch("/api/auth/logout",{method:"POST"})}async function _h(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function Ch(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function Eh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Th(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function Ph(){return _e("/api/auth/tokens")}async function bh(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function Lh(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function Ba(){return _e("/api/admin/instance-settings")}async function Nl(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function zh(){return _e("/api/admin/users")}async function Rh(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function Dh(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function $h(){return _e("/api/admin/roles")}async function Ih(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function _d(e){return _e(`/api/archives/${e}/collections`)}async function Oh(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}return l.json()}async function Ah(e,t){return _e(`/api/archives/${e}/collections/${t}`)}async function Cd(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Fh(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function Mh(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Bh(e,t){return _e(`/api/archives/${e}/entries/${t}/collections`)}async function nu(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function Hh(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function Uh(e){return _e(`/api/archives/${e}/blob-cleanup`)}async function Wh(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function Vh(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function Qh(){return _e("/api/admin/cookie-rules")}async function Kh(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function Xh(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function Jh(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}const qh=window.fetch;window.fetch=async(...e)=>{var n;const t=await qh(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function Gh({onLogin:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(null),[o,u]=f.useState(!1);async function c(g){g.preventDefault(),a(null),u(!0);try{const m=await Sh(t,r);e(m)}catch(m){a(m.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:g=>n(g.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:g=>l(g.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function Yh({onComplete:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(""),[o,u]=f.useState(null),[c,g]=f.useState(!1);async function m(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),g(!0);try{await jh(t,r),e()}catch(y){u(y.message)}finally{g(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function Zh({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i}){const{currentUser:a,setCurrentUser:o}=f.useContext(ps)??{},[u,c]=f.useState(!1);async function g(){c(!0),await Nh(),o(null),window.location.reload()}return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),a&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:a.display_name||a.username}),s.jsx("button",{className:"logout-btn",onClick:g,disabled:u,children:u?"Logging out…":"Log out"})]})]})}let Qi=1;function Ed(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function ir(e=""){return{id:Qi++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null}}function ru(e){return e.some(t=>t.status==="submitting"||t.status==="running")}function em({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l}){const i=f.useRef(null),a=f.useRef(!0),o=f.useRef(new Map),u=f.useRef(new Map),c=f.useRef(new Map),g=f.useRef(t);f.useEffect(()=>{g.current=t},[t]);const m=f.useRef(r),h=f.useRef(l);f.useEffect(()=>{m.current=r},[r]),f.useEffect(()=>{h.current=l},[l]);const[y,x]=f.useState(()=>{try{const N=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(N)&&N.length>0)return N.forEach(O=>{O.id>=Qi&&(Qi=O.id+1)}),N}catch{}return[ir()]});f.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(y))},[y]);const[k,j]=f.useState(!1),[p,d]=f.useState(null),[v,w]=f.useState(null),[S,P]=f.useState(!0),[C,_]=f.useState(!0);f.useEffect(()=>{Ba().then(N=>{w(N),P(N.cookie_ext_enabled??!0),_(N.modal_closer_enabled??!0)}).catch(()=>w({}))},[]);const I=p!==null?p:(v==null?void 0:v.ublock_enabled)??!0,[L,Q]=f.useState(!1);f.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(N=>sessionStorage.removeItem(N)),x(N=>N.map(O=>O.status==="submitting"?{...O,status:"idle",error:null}:O)),y.forEach(N=>{N.status==="running"&&N.jobUid&&N.archiveId&&!o.current.has(N.jobUid)&&ne(N.id,N.jobUid,N.locator,N.archiveId)})},[]),f.useEffect(()=>{const N=i.current;if(!N)return;const O=()=>{u.current.forEach(B=>clearTimeout(B)),u.current.clear(),n()};return N.addEventListener("close",O),()=>N.removeEventListener("close",O)},[n]),f.useEffect(()=>{const N=i.current;N&&(e?(!a.current&&!ru(y)&&x([ir()]),a.current=!1,N.open||N.showModal()):(u.current.forEach(O=>clearTimeout(O)),u.current.clear(),N.open&&N.close()))},[e]),f.useEffect(()=>()=>{o.current.forEach(N=>clearInterval(N)),u.current.forEach(N=>clearTimeout(N))},[]);function ne(N,O,B,M,W=null){if(o.current.has(O))return;const de=setInterval(async()=>{try{const J=await Nd(M,O);if(J.status==="completed"){clearInterval(o.current.get(O)),o.current.delete(O),x(q=>q.map(G=>G.id===N?{...G,status:"completed"}:G)),setTimeout(()=>{x(q=>{const G=q.filter(oe=>oe.id!==N);return G.length===0?[ir()]:G})},1400),m.current();try{const q=J.notes_json?JSON.parse(J.notes_json):null;if(q!=null&&q.ublock_skipped||q!=null&&q.cookie_ext_skipped){const oe=q.ublock_skipped&&q.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":q.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";h.current(oe,B,"warning"),Z(W,"warning",B)}else W||h.current(null,B,"success"),Z(W,"archived")}catch{W||h.current(null,B,"success"),Z(W,"archived")}}else if(J.status==="failed"){clearInterval(o.current.get(O)),o.current.delete(O);const q=J.error_text||"Capture failed.";x(G=>G.map(oe=>oe.id===N?{...oe,status:"failed",error:q}:oe)),h.current(q,B),Z(W,"failed",B)}}catch(J){clearInterval(o.current.get(O)),o.current.delete(O);const q=J.message||"Network error";x(G=>G.map(oe=>oe.id===N?{...oe,status:"failed",error:q}:oe)),h.current(q,B),Z(W,"failed",B)}},500);o.current.set(O,de)}function Z(N,O,B=null){if(!N)return;const M=c.current.get(N);if(!M||(O==="archived"||O==="warning"?(M.archived++,O==="warning"&&(M.warnings++,B&&M.warningLocators.push(B))):(M.failed++,B&&M.failedLocators.push(B)),M.archived+M.failed0?`${W} archived (${de} with warnings)`:`${W} archived`;oe=J>0?`${xe}, ${J} failed`:xe}const D=W===0?"error":J>0||de>0?"warning":"success",V=[];q.length>0&&V.push(`Failed: -${q.map(xe=>` ${xe}`).join(` -`)}`),G.length>0&&V.push(`With warnings: -${G.map(xe=>` ${xe}`).join(` -`)}`);const Ce=V.length>0?V.join(` -`):null;h.current(Ce,null,D,oe)}async function se(N,O=null){if(!N.locator.trim())return;const B=t,M=N.locator.trim(),W=N.quality||"best";x(de=>de.map(J=>J.id===N.id?{...J,status:"submitting",error:null}:J));try{const J=await xh(B,M,W,{ublock_enabled:I,reader_mode:L,cookie_ext_enabled:S,modal_closer_enabled:C});x(q=>q.map(G=>G.id===N.id?{...G,status:"running",jobUid:J.job_uid,archiveId:B}:G)),ne(N.id,J.job_uid,M,B,O)}catch(de){const J=de.message||"Submission failed.";x(q=>q.map(G=>G.id===N.id?{...G,status:"failed",error:J}:G)),h.current(J,M),Z(O,"failed",M)}}function pe(){var B,M;const N=y.filter(W=>W.status==="idle"&&W.locator.trim());if(N.length===0)return;const O=N.length>1?((B=crypto.randomUUID)==null?void 0:B.call(crypto))??`batch-${Date.now()}`:null;O&&c.current.set(O,{total:N.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]}),N.forEach(W=>se(W,O)),(M=i.current)==null||M.close()}function ve(){x(N=>[...N,ir()])}function ie(N){clearTimeout(u.current.get(N)),u.current.delete(N),x(O=>{const B=O.filter(M=>M.id!==N);return B.length===0?[ir()]:B})}function R(N){x(O=>O.map(B=>B.id===N?{...B,status:"idle",error:null}:B))}function T(N,O){if(clearTimeout(u.current.get(N)),x(M=>M.map(W=>W.id===N?{...W,locator:O,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best"}:W)),!Ed(O))return;const B=setTimeout(async()=>{u.current.delete(N),x(M=>M.map(W=>W.id===N?{...W,probeState:"probing"}:W));try{const M=await wh(g.current,O.trim());x(W=>W.map(de=>{if(de.id!==N||de.locator!==O)return de;const J=M.qualities??[],q=M.has_audio??!1,G=J.length===0&&q?"audio":"best";return{...de,probeState:"done",probeQualities:J,probeHasAudio:q,quality:G}}))}catch{x(M=>M.map(W=>W.id===N?{...W,probeState:"idle",probeQualities:null}:W))}},600);u.current.set(N,B)}function F(N,O){x(B=>B.map(M=>M.id===N?{...M,quality:O}:M))}const X=y.filter(N=>N.status==="idle"&&N.locator.trim()).length,H=ru(y);return s.jsx("dialog",{ref:i,className:"capture-dialog",children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:y.map((N,O)=>s.jsx(tm,{item:N,autoFocus:O===y.length-1&&N.status==="idle",onLocatorChange:B=>T(N.id,B),onQualityChange:B=>F(N.id,B),onRemove:()=>ie(N.id),onReset:()=>R(N.id),onSubmit:pe},N.id))}),s.jsxs("button",{type:"button",className:"capture-add-row",onClick:ve,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add another"]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>j(N=>!N),"aria-expanded":k,children:[s.jsx("svg",{className:`capture-chevron${k?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),k&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":I,className:`ext-toggle ext-toggle--sm${I?" ext-toggle--on":""}`,onClick:()=>d(N=>N===null?!I:!N),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(v!=null&&v.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":S,className:`ext-toggle ext-toggle--sm${S?" ext-toggle--on":""}`,onClick:()=>P(N=>!N),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":L,className:`ext-toggle ext-toggle--sm${L?" ext-toggle--on":""}`,onClick:()=>Q(N=>!N),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":C,className:`ext-toggle ext-toggle--sm${C?" ext-toggle--on":""}`,onClick:()=>_(N=>!N),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:pe,disabled:X===0,children:X>1?`Archive ${X}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},children:H?"Close":"Cancel"})]})]})})}function tm({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onReset:i,onSubmit:a}){const o=f.useRef(null),u=e.status==="submitting"||e.status==="running";f.useEffect(()=>{var g;t&&e.status==="idle"&&((g=o.current)==null||g.focus())},[t]);const c=(()=>{if(e.status==="completed"||u||!Ed(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const g=e.probeQualities??[],m=e.probeHasAudio??!1;return g.length===0&&!m?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):g.length===0&&m?s.jsx("select",{className:"capture-quality",value:"audio",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),g.map(h=>s.jsx("option",{value:h,children:h},h)),m&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})();return s.jsxs("div",{className:`capture-row capture-row--${e.status}`,children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx(nm,{status:e.status}),s.jsx("input",{ref:o,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"&&a()},disabled:u||e.status==="completed",autoComplete:"off",spellCheck:!1}),c,e.status==="failed"&&s.jsx("button",{type:"button",className:"capture-row-action",onClick:i,title:"Retry",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M13 2.5A7 7 0 1 1 6.5 1"}),s.jsx("polyline",{points:"6.5 1 4 3.5 6.5 6"})]})}),!u&&e.status!=="completed"&&e.status!=="failed"&&s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error})]})}function nm({status:e}){return e==="submitting"||e==="running"?s.jsx("span",{className:"cap-dot cap-dot--running","aria-label":"Running",children:s.jsx("span",{className:"cap-spinner"})}):e==="completed"?s.jsx("span",{className:"cap-dot cap-dot--ok","aria-label":"Done",children:"✓"}):e==="failed"?s.jsx("span",{className:"cap-dot cap-dot--err","aria-label":"Failed",children:"✕"}):s.jsx("span",{className:"cap-dot cap-dot--idle","aria-hidden":"true"})}function Jl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function nn(e){return rm(e)??""}function Td(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const lu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Ha(e){return lu[e]??lu.other}function Pd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function lm({entry:e,archiveId:t,isSelected:n,isMultiSelected:r,onRowClick:l}){const[i,a]=f.useState(!1),u=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!i?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>a(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Ha(e.source_kind)}}),c=n||r;function g(m){m.stopPropagation(),l(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}return s.jsxs("div",{className:[n&&"is-selected",r&&"is-multi-selected"].filter(Boolean).join(" ")||void 0,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:m=>{m.shiftKey&&m.preventDefault()},onClick:m=>l(e,m),onKeyDown:m=>{m.key==="Enter"&&l(e,m)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${c?" is-checked":""}`,"aria-pressed":c,"aria-label":c?"Deselect entry":"Select entry",onClick:g,onKeyDown:m=>m.stopPropagation()})}),s.jsx("div",{className:"col-added",children:Td(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:u}),s.jsx("span",{className:"entry-title",children:nn(e.title)||nn(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:nn(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:Jl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${Jl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:nn(e.original_url)})]})}function sm({entries:e,selectedUids:t,onRowClick:n,archiveId:r}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsx("div",{id:"entries-body",children:e.map(l=>s.jsx(lm,{entry:l,archiveId:r,isSelected:t.size===1&&t.has(l.entry_uid),isMultiSelected:t.size>=2&&t.has(l.entry_uid),onRowClick:n},l.entry_uid))})]})})}function im(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function am({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function om({runs:e}){const[t,n]=f.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:im(l.started_at)}),s.jsxs("td",{children:[s.jsx(am,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const um=4;function cm({archives:e}){const{currentUser:t}=f.useContext(ps)??{},n=t&&(t.role_bits&um)!==0,[r,l]=f.useState("users"),[i,a]=f.useState([]),[o,u]=f.useState([]),[c,g]=f.useState(!1),[m,h]=f.useState(null),[y,x]=f.useState(""),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(null),[S,P]=f.useState(!1),[C,_]=f.useState(""),[I,L]=f.useState(""),[Q,ne]=f.useState(null),[Z,se]=f.useState(!1),pe=f.useCallback(async()=>{if(n){g(!0),h(null);try{const[T,F]=await Promise.all([zh(),$h()]);a(T),u(F)}catch(T){h(T.message)}finally{g(!1)}}},[n]);f.useEffect(()=>{pe()},[pe]);async function ve(T){const F=T.status==="active"?"disabled":"active";try{await Dh(T.user_uid,F),a(X=>X.map(H=>H.user_uid===T.user_uid?{...H,status:F}:H))}catch(X){h(X.message)}}async function ie(T){if(T.preventDefault(),!y.trim()||!k){w("Username and password required");return}P(!0),w(null);try{await Rh(y.trim(),k,p.trim()||void 0),x(""),j(""),d(""),await pe()}catch(F){w(F.message)}finally{P(!1)}}async function R(T){if(T.preventDefault(),!C.trim()||!I.trim()){ne("Slug and name required");return}se(!0),ne(null);try{await Ih(C.trim(),I.trim()),_(""),L(""),await pe()}catch(F){ne(F.message)}finally{se(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(T=>s.jsxs("tr",{className:T.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:T.username}),s.jsx("td",{className:"muted",children:T.email||"—"}),s.jsx("td",{children:T.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${T.status}`,children:T.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>ve(T),children:T.status==="active"?"Ban":"Unban"})})]},T.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ie,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:y,onChange:T=>x(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:k,onChange:T=>j(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:T=>d(T.target.value)}),v&&s.jsx("div",{className:"form-msg form-msg--err",children:v}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:S,children:S?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.slug})}),s.jsx("td",{children:T.name}),s.jsx("td",{children:T.level}),s.jsx("td",{children:T.bit_position}),s.jsx("td",{children:T.is_builtin?"✓":""})]},T.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:R,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:C,onChange:T=>_(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:I,onChange:T=>L(T.target.value),required:!0}),Q&&s.jsx("div",{className:"form-msg form-msg--err",children:Q}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:Z,children:Z?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})}function bd({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){var w;const c=n===e.tag.full_path,[g,m]=f.useState(!1),[h,y]=f.useState(""),x=f.useRef(!1);function k(){if(g)return;const S=c?null:e.tag.full_path;r(S),l("archive")}function j(S){S.stopPropagation(),y(e.tag.slug),m(!0)}async function p(){const S=h.trim();if(!S||S===e.tag.slug){m(!1);return}try{const P=await vh(t,e.tag.tag_uid,S);i(e.tag.full_path,P.full_path),o()}catch{}finally{m(!1)}}async function d(S){var C;S.stopPropagation();const P=((C=e.children)==null?void 0:C.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(P))try{await yh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const v={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u};return s.jsxs("li",{children:[s.jsxs("div",{className:"tag-node-row",children:[g?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:h,onChange:S=>y(S.target.value),onKeyDown:S=>{S.key==="Enter"&&S.currentTarget.blur(),S.key==="Escape"&&(x.current=!0,S.currentTarget.blur())},onBlur:()=>{x.current?(x.current=!1,m(!1)):p()}}):s.jsxs("button",{className:`tag-node-btn${c?" is-active":""}`,title:e.tag.full_path,onClick:k,onDoubleClick:j,children:[u?e.tag.name:e.tag.slug,s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",onClick:S=>{S.stopPropagation(),j(S)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),s.jsx("button",{className:"remove tag-node-delete",title:`Delete tag ${e.tag.full_path}`,onClick:d,"aria-label":`Delete tag ${e.tag.full_path}`,children:"×"})]}),((w=e.children)==null?void 0:w.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(S=>s.jsx(bd,{node:S,...v},S.tag.tag_uid))})})]})}function dm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){return s.jsx("section",{id:"tags-view",className:"view is-active",children:s.jsxs("div",{className:"tag-tree",children:[s.jsxs("div",{className:"tag-tree-header",children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",children:["Filtering: ",n]})]}),t.length===0?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsx("ul",{className:"tag-tree-list",children:t.map(c=>s.jsx(bd,{node:c,archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u},c.tag.tag_uid))})]})})}const fr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],fm=e=>{var t;return((t=fr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function pm({archiveId:e}){const[t,n]=f.useState([]),[r,l]=f.useState(!1),[i,a]=f.useState(null),[o,u]=f.useState(null),[c,g]=f.useState(null),[m,h]=f.useState(!1),[y,x]=f.useState(null),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(2),[S,P]=f.useState(!1),[C,_]=f.useState(null),[I,L]=f.useState(""),[Q,ne]=f.useState(2),[Z,se]=f.useState(!1),[pe,ve]=f.useState(null),[ie,R]=f.useState(!1),[T,F]=f.useState(""),X=f.useRef(null),H=t.find(D=>D.collection_uid===o)??null,N=(H==null?void 0:H.slug)==="_default_",O=f.useCallback(async()=>{if(e){l(!0),a(null);try{const D=await _d(e);n(D)}catch(D){a(D.message)}finally{l(!1)}}},[e]),B=f.useCallback(async D=>{if(!D){g(null);return}h(!0),x(null);try{const V=await Ah(e,D);g(V)}catch(V){x(V.message)}finally{h(!1)}},[e]);f.useEffect(()=>{O()},[O]),f.useEffect(()=>{B(o)},[o,B]),f.useEffect(()=>{ie&&X.current&&X.current.focus()},[ie]);async function M(D){D.preventDefault();const V=k.trim(),Ce=p.trim();if(!(!V||!Ce)){P(!0),_(null);try{const xe=await Oh(e,V,Ce,v);j(""),d(""),w(2),await O(),u(xe.collection_uid)}catch(xe){_(xe.message)}finally{P(!1)}}}async function W(){const D=T.trim();if(!D||!H){R(!1);return}try{await nu(e,H.collection_uid,{name:D}),await O(),g(V=>V&&{...V,name:D})}catch(V){a(V.message)}finally{R(!1)}}async function de(D){if(H)try{await nu(e,H.collection_uid,{default_visibility_bits:D}),await O(),g(V=>V&&{...V,default_visibility_bits:D})}catch(V){a(V.message)}}async function J(){if(H&&window.confirm(`Delete collection "${H.name}"? Entries will not be deleted.`))try{await Hh(e,H.collection_uid),u(null),g(null),await O()}catch(D){a(D.message)}}async function q(D){D.preventDefault();const V=I.trim();if(!(!V||!H)){se(!0),ve(null);try{await Cd(e,H.collection_uid,V,Q),L(""),await B(H.collection_uid)}catch(Ce){ve(Ce.message)}finally{se(!1)}}}async function G(D){if(H)try{await Fh(e,H.collection_uid,D),await B(H.collection_uid)}catch(V){x(V.message)}}async function oe(D,V){if(H)try{await Mh(e,H.collection_uid,D,V),g(Ce=>Ce&&{...Ce,entries:Ce.entries.map(xe=>xe.entry_uid===D?{...xe,collection_visibility_bits:V}:xe)})}catch(Ce){x(Ce.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(D=>s.jsxs("button",{className:`coll-sidebar-row${o===D.collection_uid?" is-active":""}`,onClick:()=>u(D.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:D.name}),s.jsx("span",{className:"coll-row-meta",children:fm(D.default_visibility_bits)})]},D.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),H?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[ie?s.jsx("input",{ref:X,className:"coll-rename-input",value:T,onChange:D=>F(D.target.value),onBlur:W,onKeyDown:D=>{D.key==="Enter"&&W(),D.key==="Escape"&&R(!1)}}):s.jsxs("h3",{className:`coll-detail-name${N?"":" coll-detail-name--editable"}`,title:N?void 0:"Click to rename",onClick:()=>{N||(F(H.name),R(!0))},children:[(c==null?void 0:c.name)??H.name,!N&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!N&&s.jsx("button",{className:"coll-delete-btn",onClick:J,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??H.default_visibility_bits,onChange:D=>de(Number(D.target.value)),disabled:N,children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),m&&s.jsx("div",{className:"muted",children:"Loading…"}),y&&s.jsx("div",{className:"collections-error",children:y}),!m&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(D=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:D.title||D.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:D.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:D.collection_visibility_bits,onChange:V=>oe(D.entry_uid,Number(V.target.value)),children:fr.map(V=>s.jsx("option",{value:V.value,children:V.label},V.value))}),!N&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>G(D.entry_uid),title:"Remove from collection",children:"×"})]})]},D.entry_uid))}))]}),!N&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:q,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:I,onChange:D=>L(D.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:Q,onChange:D=>ne(Number(D.target.value)),children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:Z,children:Z?"…":"Add"})]}),pe&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:pe})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:M,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:k,onChange:D=>{j(D.target.value),p||d(D.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:D=>d(D.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:v,onChange:D=>w(Number(D.target.value)),children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),C&&s.jsx("div",{className:"collections-error",children:C}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:S,children:S?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const hm=4;function mm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=f.useContext(ps)??{},i=r&&(r.role_bits&hm)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(gm,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(vm,{}),e==="instance"&&i&&s.jsx(ym,{}),e==="cookies"&&i&&s.jsx(wm,{}),e==="extensions"&&i&&s.jsx(km,{}),e==="storage"&&i&&s.jsx(xm,{archiveId:n})]})}function gm({currentUser:e,setCurrentUser:t}){const[n,r]=f.useState((e==null?void 0:e.display_name)??""),[l,i]=f.useState(!1),[a,o]=f.useState(null),[u,c]=f.useState(""),[g,m]=f.useState(""),[h,y]=f.useState(""),[x,k]=f.useState(!1),[j,p]=f.useState(null);async function d(w){w.preventDefault(),i(!0),o(null);try{await Ch(n),t(S=>({...S,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(S){o({ok:!1,text:S.message})}finally{i(!1)}}async function v(w){if(w.preventDefault(),g!==h){p({ok:!1,text:"Passwords do not match."});return}k(!0),p(null);try{await Th(u,g),c(""),m(""),y(""),p({ok:!0,text:"Password changed."})}catch(S){p({ok:!1,text:S.message})}finally{k(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:d,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const S=w.target.checked;try{await Eh({humanize_slugs:S}),t(P=>({...P,humanize_slugs:S}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:g,onChange:w=>m(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:w=>y(w.target.value),required:!0})]}),j&&s.jsx("div",{className:`form-msg form-msg--${j.ok?"ok":"err"}`,children:j.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function vm(){const[e,t]=f.useState([]),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(""),[u,c]=f.useState(!1),[g,m]=f.useState(null),h=f.useCallback(async()=>{r(!0),i(null);try{t(await Ph())}catch(k){i(k.message)}finally{r(!1)}},[]);f.useEffect(()=>{h()},[h]);async function y(k){if(k.preventDefault(),!!a.trim()){c(!0);try{const j=await bh(a.trim());m(j),o(""),h()}catch(j){i(j.message)}finally{c(!1)}}}async function x(k){try{await Lh(k),t(j=>j.filter(p=>p.token_uid!==k))}catch(j){i(j.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),g&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:g.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>m(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:y,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:k=>o(k.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(k=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:k.name}),s.jsxs("div",{className:"muted",children:["Created ",k.created_at.slice(0,10),k.last_used_at&&` · Last used ${k.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(k.token_uid),children:"Revoke"})]},k.token_uid))]})]})})}function ym(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(!1),[u,c]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(m){i(m.message)}finally{r(!1)}})()},[]);async function g(m){m.preventDefault(),o(!0),c(null);try{await Nl(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:g,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([m,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[m],onChange:y=>t(x=>({...x,[m]:y.target.checked}))}),h]},m)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:m=>t(h=>({...h,default_entry_visibility:Number(m.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function qs(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function xm({archiveId:e}){const[t,n]=f.useState("idle"),[r,l]=f.useState(null),[i,a]=f.useState(null),[o,u]=f.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function g(){n("scanning"),u(null),l(null);try{const y=await Uh(e);l(y),n("scanned")}catch(y){u(y.message),n("error")}}async function m(){n("deleting"),u(null);try{const y=await Wh(e);a(y),n("done")}catch(y){u(y.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:g,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:qs(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:m,children:["Delete (",qs(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:qs(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function wm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState("global"),[u,c]=f.useState(""),[g,m]=f.useState("{}"),[h,y]=f.useState(null),[x,k]=f.useState(!1),[j,p]=f.useState({});f.useEffect(()=>{d()},[]);async function d(){r(!0),i(null);try{t(await Qh())}catch(_){i(_.message)}finally{r(!1)}}async function v(_){_.preventDefault();try{JSON.parse(g)}catch{y({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}k(!0),y(null);try{await Kh(a==="global"?null:u.trim(),a,g),c(""),m("{}"),o("global"),y({ok:!0,text:"Rule added."}),await d()}catch(I){y({ok:!1,text:I.message})}finally{k(!1)}}async function w(_){try{await Jh(_),await d()}catch(I){i(I.message)}}function S(_){p(I=>({...I,[_.rule_uid]:{cookiesInput:_.cookies_json,saving:!1,msg:null}}))}function P(_){p(I=>{const L={...I};return delete L[_],L})}async function C(_){const I=j[_.rule_uid];try{JSON.parse(I.cookiesInput)}catch{p(L=>({...L,[_.rule_uid]:{...L[_.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[_.rule_uid]:{...L[_.rule_uid],saving:!0,msg:null}}));try{await Xh(_.rule_uid,{cookies_json:I.cookiesInput}),P(_.rule_uid),await d()}catch(L){p(Q=>({...Q,[_.rule_uid]:{...Q[_.rule_uid],saving:!1,msg:{ok:!1,text:L.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(_=>{const I=j[_.rule_uid],L=_.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[_.pattern_kind,":"]})," ",s.jsx("code",{children:_.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:L}),s.jsx("td",{children:I?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:I.cookiesInput,onChange:Q=>p(ne=>({...ne,[_.rule_uid]:{...ne[_.rule_uid],cookiesInput:Q.target.value}}))}),I.msg&&s.jsx("div",{className:`form-msg form-msg--${I.msg.ok?"ok":"err"}`,children:I.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:I.saving,onClick:()=>C(_),children:I.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(_.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:_.cookies_json})}),s.jsx("td",{children:!I&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>S(_),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(_.rule_uid),children:"Del"})]})})]},_.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:_=>o(_.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:_=>c(_.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:g,onChange:_=>m(_.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function km(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(!1),[a,o]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(j){o({ok:!1,text:j.message})}finally{r(!1)}})()},[]);async function u(j){i(!0),o(null);try{await Nl({ublock_enabled:j}),t(p=>({...p,ublock_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(j){i(!0),o(null);try{await Nl({cookie_ext_enabled:j}),t(p=>({...p,cookie_ext_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function g(j){i(!0),o(null);try{await Nl({modal_closer_enabled:j}),t(p=>({...p,modal_closer_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const m=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,y=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,k=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!m&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!y&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":k,className:`ext-toggle${k?" ext-toggle--on":""}`,onClick:()=>g(!k),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const su={0:"Private",1:"Public",2:"Users only",3:"Public"},jm=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Sm({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:g,humanizeTags:m,onDetailRefresh:h,onOpenPreview:y,onPlay:x}){var Tt;const[k,j]=f.useState([]),[p,d]=f.useState(""),[v,w]=f.useState([]),[S,P]=f.useState(""),C=f.useRef(0),_=f.useRef(!1),[I,L]=f.useState(!1),[Q,ne]=f.useState(""),[Z,se]=f.useState("idle"),[pe,ve]=f.useState(""),ie=f.useRef(null),[R,T]=f.useState(!1);f.useEffect(()=>{T(!1)},[(Tt=l==null?void 0:l.summary)==null?void 0:Tt.entry_uid]);const F=(n==null?void 0:n.size)>=2,[X,H]=f.useState(""),[N,O]=f.useState("idle"),[B,M]=f.useState(""),[W,de]=f.useState([]),[J,q]=f.useState(""),[G,oe]=f.useState("idle"),[D,V]=f.useState(""),[Ce,xe]=f.useState("idle");f.useEffect(()=>{const $=++C.current;if(ie.current&&(clearInterval(ie.current),ie.current=null),se("idle"),ve(""),!t||!e){j([]),w([]);return}L(!1),ne(""),_.current=!1,j([]),Promise.all([cl(e,t.entry_uid),Bh(e,t.entry_uid)]).then(([re,Qe])=>{$===C.current&&(j(re),w(Qe))}).catch(()=>{})},[t,e]),f.useEffect(()=>()=>{clearInterval(ie.current)},[]),f.useEffect(()=>{if(!F||!e){de([]);return}_d(e).then(de).catch(()=>de([]))},[F,e]),f.useEffect(()=>{H(""),O("idle"),M(""),q(""),oe("idle"),V(""),xe("idle")},[n]);async function hs(){const $=n.size;if(!window.confirm(`Delete ${$} entr${$===1?"y":"ies"}? This cannot be undone.`))return;xe("running");const re=new Set;for(const Qe of n)try{await tu(e,Qe),re.add(Qe)}catch{}xe("idle"),g==null||g(re)}async function Kn(){const $=X.trim();if($){O("running"),M("");try{for(const re of n)await eu(e,re,$);H(""),O("done"),o==null||o(),setTimeout(()=>O("idle"),1800)}catch(re){M(re.message),O("error")}}}async function ms(){if(!J)return;oe("running"),V("");const $=[];for(const re of n)try{await Cd(e,J,re)}catch{$.push(re)}$.length>0?(V(`Failed for ${$.length} entr${$.length===1?"y":"ies"}.`),oe("error")):(oe("done"),setTimeout(()=>oe("idle"),1800))}async function gs(){const $=Q.trim()||null;try{await mh(e,t.entry_uid,$),u==null||u(t.entry_uid,$)}catch{}finally{L(!1)}}async function Wr(){const $=p.trim();if(!(!$||!t))try{await eu(e,t.entry_uid,$),d(""),P("");const re=await cl(e,t.entry_uid);j(re),o()}catch(re){P(re.message)}}async function vs($){try{await gh(e,t.entry_uid,$);const re=await cl(e,t.entry_uid);j(re),o()}catch{}}async function ys(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await tu(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function xs(){if(!t||!e||Z==="running")return;const $=C.current,re=t.entry_uid;se("running"),ve("");try{const{job_uid:Qe}=await Vh(e,re);if(C.current!==$)return;ie.current=setInterval(async()=>{try{const Jt=await Nd(e,Qe);if(Jt.status==="completed"){if(clearInterval(ie.current),ie.current=null,C.current!==$)return;se("done");const Jn=await cl(e,re);if(C.current!==$)return;j(Jn),h==null||h()}else if(Jt.status==="failed"){if(clearInterval(ie.current),ie.current=null,C.current!==$)return;se("error"),ve(Jt.error_text||"Re-archive failed.")}}catch{if(clearInterval(ie.current),ie.current=null,C.current!==$)return;se("error"),ve("Network error while polling.")}},500)}catch(Qe){if(C.current!==$)return;se("error"),ve(Qe.message||"Failed to start re-archive.")}}const ws=l?[["Added",Td(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",su[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],ks=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),js=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),pn=l?l.artifacts.findIndex($=>$.artifact_role==="primary_media"):-1,hn=pn>=0?l.artifacts[pn]:null,Vr=hn?hn.relpath.split(".").pop().toLowerCase():"",Qr=hn&&ks.has(Vr),mn=pn>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${pn}`:null,Xn=l&&!Qr&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||hn&&js.has(Vr));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),F?s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),B&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:B}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:X,onChange:$=>H($.target.value),onKeyDown:$=>{$.key==="Enter"&&Kn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Kn,disabled:N==="running"||!X.trim(),children:N==="running"?"…":N==="done"?"✓":"Add"})]})]}),W.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:J,onChange:$=>q($.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),W.map($=>s.jsx("option",{value:$.collection_uid,children:$.name},$.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:ms,disabled:!J||G==="running",children:G==="running"?"…":G==="done"?"✓":G==="error"?"!":"Add"})]}),D&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:D})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:hs,disabled:Ce==="running",children:Ce==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[I?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:Q,onChange:$=>ne($.target.value),onKeyDown:$=>{$.key==="Enter"&&$.currentTarget.blur(),$.key==="Escape"&&(_.current=!0,$.currentTarget.blur())},onBlur:()=>{_.current?L(!1):gs(),_.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{ne(l.summary.title??""),L(!0)},children:[nn(l.summary.title)||nn(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Ha(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(jm,{})})]}),Qr&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(mn,t),children:"▶ Play"}),Xn&&y&&s.jsx("button",{className:"rail-preview-btn",onClick:y,children:"Preview"}),s.jsx("div",{className:"meta-list",children:ws.filter(([,$])=>$!=null&&$!=="").map(([$,re])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:$}),s.jsx("span",{className:`meta-v${$==="Root"?" mono":""}`,children:nn(re)})]},$))}),l.artifacts.length>0&&(()=>{const $=l.artifacts.map((z,U)=>({...z,_idx:U})),re=$.filter(z=>z.artifact_role==="font"),Qe=$.filter(z=>z.artifact_role!=="font"),Jt=re.reduce((z,U)=>z+(U.byte_size||0),0),Jn=l.summary.entry_uid,E=z=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Jn}/artifacts/${z._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:z.artifact_role==="font"?z.relpath.split("/").pop():z.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:z.byte_size!=null?Jl(z.byte_size):"—"})]})},z._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[Qe.map(E),re.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":R,onClick:()=>T(z=>!z),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${R?" open":""}`,children:"›"}),` fonts (${re.length})`]}),s.jsx("span",{className:"artifact-size",children:Jl(Jt)})]}),R&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:re.map(E)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!F&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),k.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:k.map($=>s.jsxs("span",{className:"tag-pill",title:$.full_path,children:[m?Pd($.full_path):$.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${$.full_path}`,onClick:()=>vs($.tag_uid),children:"×"})]},$.tag_uid))}),S&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:S}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:p,onChange:$=>d($.target.value),onKeyDown:$=>{$.key==="Enter"&&Wr()}}),s.jsx("button",{className:"tag-add-btn",onClick:Wr,children:"Add"})]})]}),v.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),v.map($=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:$.collection_uid}),s.jsx("span",{className:"vis-badge",children:su[$.visibility_bits]??`bits:${$.visibility_bits}`})]},$.collection_uid))]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:xs,disabled:Z==="running",children:Z==="running"?"Re-archiving…":"Re-archive"}),Z==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),Z==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:pe})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:ys,children:"Delete entry"})})]})]})}function Nm({src:e}){const t=f.useRef(null);return f.useEffect(()=>{t.current&&t.current.load()},[e]),s.jsx("div",{className:"preview-video-wrap",style:{background:"#111",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",minHeight:"240px"},children:e?s.jsxs("video",{ref:t,controls:!0,autoPlay:!1,style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:e}),"Your browser does not support the video element."]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function iu({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function _m({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function Ld(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function au(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const K={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},je={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Gs={article:{background:je.bg,color:je.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:je.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:je.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:je.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:je.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${je.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${je.border}`,padding:"2px 14px",margin:"14px 0",color:je.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${je.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${je.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:je.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:je.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:je.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:je.accent,textDecoration:"none"}};function Cm(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function In(e,t,n){return e&&n[e]?n[e]:t||null}function zd(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function Ua(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function Rd(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=Ua(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function Dd(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=Ua(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const ou=/https?:\/\/[^\s<>"'\])]+/g,Em=/[.,;:!?)()]+$/;function ql(e,t){const n=[];let r=0,l;for(ou.lastIndex=0;(l=ou.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Em,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rRd(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>Dd(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return ql(au(e),K.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,g])=>c<=o&&g>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const g=e.slice(o,c),m=r.filter(x=>x.s<=o&&x.e>=c),h=m.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:K.link,children:h.display||g},u);const y=m.find(x=>x.kind==="mention");return y?s.jsx("a",{href:`https://x.com/${y.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:K.link,children:g},u):s.jsx("span",{children:ql(au(g),K.link)},u)}).filter(o=>o!==null)}function Pm(e,t,n,r,l=K){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=Rd(u,e);c&&i.push(c)}for(const u of r){const c=Dd(u,e);c&&i.push(c)}if(i.length===0)return ql(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const g=o[c+1],m=i.filter(j=>j.s<=u&&j.e>=g),h=e.slice(u,g);let y;if(h.includes(` -`)){const j=h.split(` -`);y=j.flatMap((p,d)=>dj.kind==="style"&&j.style==="Code")&&(y=s.jsx("code",{style:l.iCode,children:y})),m.some(j=>j.kind==="style"&&j.style==="Bold")&&(y=s.jsx("strong",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Italic")&&(y=s.jsx("em",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Underline")&&(y=s.jsx("u",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Strikethrough")&&(y=s.jsx("s",{children:y}));const x=m.find(j=>j.kind==="url");if(x){const j=/^https?:\/\/t\.co\//i.test(y);y=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:j?x.display:y})}const k=m.find(j=>j.kind==="mention");return k&&(y=s.jsx("a",{href:`https://x.com/${k.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:y})),s.jsx("span",{children:typeof y=="string"?ql(y,l.link):y},c)})}function bm(e,t,n){const r=(n==null?void 0:n.st)||K,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=In(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var g;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(g=n==null?void 0:n.onImgClick)==null||g.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx(zd,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function Ys(e,t,n,r){const l=(r==null?void 0:r.st)||K,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=Pm(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const g=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return g?s.jsxs("a",{href:`https://x.com/i/status/${g[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx(zd,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:bm(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function Lm(e,t,n){const r=(n==null?void 0:n.st)||K,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Gs:K,u=e.cover_media||{},c=e.author||t||{},g=e.first_published_at_secs?Ld(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",g].filter(Boolean).join(" · "),y=In(u.local_path,u.url,n),x=In(c.avatar_local_path,c.avatar_url,n),k=s.jsxs(s.Fragment,{children:[i&&s.jsx($d,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),y&&s.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:j=>{!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),a(y))},children:s.jsx("img",{src:y,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Lm(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:Gs.article,children:s.jsx("div",{style:Gs.articleInner,children:k})}):s.jsx("div",{style:K.article,children:k})}function Rm({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:K.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function $d({items:e,startIndex:t,onClose:n}){const[r,l]=f.useState(t);f.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:K.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:K.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:K.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:K.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:K.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:K.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:K.lightboxImg}),e.length>1&&s.jsxs("div",{style:K.lightboxNav,children:[s.jsx("button",{style:K.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:K.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function uu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var d,v;const[l,i]=f.useState(null),a=e.author||{},o=e.created_at_secs?Ld(e.created_at_secs):"",u=e.entities||{},c=In(a.avatar_local_path,a.avatar_url,r),g=t&&!n,m=e.is_quote_status===!0,h=t?K.tweetRowThread:K.tweetRow,y=e.full_text||"",x=((v=(d=e.extended_entities)==null?void 0:d.media)!=null&&v.length?e.extended_entities.media:u.media)||[],k=[],j=[];for(const w of x)if(w.type==="photo"){const S=In(w.local_path,w.media_url_https,r);S&&k.push({kind:"photo",src:S,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const S=w.local_path&&r[w.local_path]||(()=>{var C,_;return(_=(((C=w.video_info)==null?void 0:C.variants)||[]).filter(I=>I.content_type==="video/mp4").sort((I,L)=>(L.bitrate||0)-(I.bitrate||0))[0])==null?void 0:_.url})();S&&j.push({kind:w.type==="animated_gif"?"gif":"video",src:S})}const p=[];for(const w of x){if(!w.url||!(w.type==="photo"?k.some(C=>C.src===In(w.local_path,w.media_url_https,r)):j.length>0))continue;const P=Ua(w,y,w.url);P&&p.push([P.s,P.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx($d,{items:k,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:K.leftCol,children:[c?s.jsx("img",{src:c,style:K.avatar,alt:a.name||""}):s.jsx("div",{style:K.avatarPh}),g&&s.jsx("div",{style:K.threadLine})]}),s.jsxs("div",{style:K.rightCol,children:[s.jsxs("div",{style:K.authorRow,children:[s.jsx("span",{style:K.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:K.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:K.datePart,children:["· ",o]}),m&&s.jsx("span",{style:K.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:K.tweetText,children:Tm(y,u,p)}),k.length>0&&s.jsx("div",{style:K.mediaGrid,children:s.jsx(Rm,{photos:k,onOpen:w=>i(w)})}),j.map((w,S)=>s.jsx("div",{style:K.mediaGrid,children:s.jsx("video",{src:w.src,style:K.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},S)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:K.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function Dm({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=f.useState(!0),[u,c]=f.useState(null),[g,m]=f.useState([]);if(f.useEffect(()=>{if(o(!0),c(null),m([]),!n||!e||!t){o(!1);return}const x=n.map((j,p)=>({...j,index:p})).filter(j=>j.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let k=!1;return ph(e,t,x.map(j=>j.index)).then(async j=>{if(k)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,d=C=>{var I;const _=C.full_text||"";return(((I=C.entities)==null?void 0:I.urls)||[]).map(L=>{var Q;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((Q=L.indices)==null?void 0:Q.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const ne=_.indexOf(L.url);if(ne!==-1)return[ne,ne+L.url.length]}return null}).filter(Boolean)},v=(C,_,I)=>C.some(([L,Q])=>L<=_&&Q>=I),w=new Set;for(const C of j){const _=C.full_text||"",I=d(C);let L;for(p.lastIndex=0;(L=p.exec(_))!==null;)v(I,L.index,L.index+L[0].length)||w.add(L[0])}const S=w.size>0?await hh([...w]).catch(()=>({})):{},P=j.map(C=>{var ne;const _=C.full_text||"",I=d(C),L=[];let Q;for(p.lastIndex=0;(Q=p.exec(_))!==null;){const Z=Q[0],se=S[Z];se&&se!==Z&&!v(I,Q.index,Q.index+Z.length)&&L.push({url:Z,expanded_url:se,display_url:(()=>{try{const pe=new URL(se);return pe.hostname+(pe.pathname.length>1?"/…":"")}catch{return se}})(),fromIndex:Q.index,toIndex:Q.index+Z.length})}return L.length===0?C:{...C,entities:{...C.entities||{},urls:[...((ne=C.entities)==null?void 0:ne.urls)||[],...L]}}});k||m(P)}).catch(j=>{k||c(j.message||"Failed to load tweet.")}).finally(()=>{k||o(!1)}),()=>{k=!0}},[e,t,n]),a)return s.jsx("div",{style:K.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:K.error,children:["Error: ",u]});if(g.length===0)return null;const h=Cm(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:K.threadOuter,children:g.map((x,k)=>s.jsx(uu,{tweet:x,isInThread:!0,isLast:k===g.length-1,artifactMap:h},x.id||k))});const y=g[0];return y.is_article&&y.article?s.jsx(zm,{article:y.article,tweetAuthor:y.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:K.card,children:s.jsx(uu,{tweet:y,isInThread:!1,isLast:!0,artifactMap:h})})}const $m=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Im=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Om=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]);function Id({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const y=s.jsx(Dm,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?y:s.jsx("div",{className:"preview-tweet-wrap",children:y})}const c=a.findIndex(y=>y.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]});const g=a[c],m=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=g.relpath.split(".").pop().toLowerCase();return $m.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(Nm,{src:m})}):Im.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:m,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(iu,{src:m,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(iu,{src:m,type:"page",title:i.title,originalUrl:i.original_url})}):Om.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(_m,{src:m,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]})}function Am({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return f.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(Id,{archiveId:e,entry:t,detail:n})})]})})}function cu(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function Fm({entry:e,src:t,archiveId:n,onClose:r}){const l=f.useRef(null),[i,a]=f.useState(!1),[o,u]=f.useState(0),[c,g]=f.useState(NaN),[m,h]=f.useState(1);f.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),g(NaN),a(!1))},[t]),f.useEffect(()=>{l.current&&(l.current.volume=m)},[m]);function y(){const d=l.current;d&&(i?d.pause():d.play().catch(()=>{}))}function x(d){const v=l.current;if(!v||!isFinite(c))return;const w=Number(d.target.value);v.currentTime=w,u(w)}function k(d){h(Number(d.target.value))}const j=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var d;return u(((d=l.current)==null?void 0:d.currentTime)??0)},onLoadedMetadata:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},onDurationChange:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Ha(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:j,children:j})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:y,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:cu(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:cu(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:m,onChange:k,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function Mm({archiveId:e,entryUid:t}){var h,y;const[n,r]=f.useState(null),[l,i]=f.useState(!0),[a,o]=f.useState(null),[u,c]=f.useState(!1);f.useEffect(()=>{if(!u)return;const x=document.documentElement,k=document.body,j=x.style.colorScheme,p=k.style.background;return x.style.colorScheme="dark",k.style.background="#000",()=>{x.style.colorScheme=j,k.style.background=p}},[u]),f.useEffect(()=>{c(!1),Vi(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const g=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,m=(y=n==null?void 0:n.summary)==null?void 0:y.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g}),m&&s.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(Id,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Bm=7e3;function Hm({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Wm,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Um(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Wm({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=f.useState(!1),i=e.type==="warning",a=e.type==="success";f.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Bm);return()=>clearTimeout(u)},[r,e.id,t]);const o=Um(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const ps=f.createContext(null),ar=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})(),Vm=["archive","tags","collections","runs","admin","settings"],Qm=["profile","tokens","instance","cookies","extensions","storage"];function qt(){const e=window.location.pathname.split("/").filter(Boolean),t=Vm.includes(e[0])?e[0]:"archive",n=t==="settings"&&Qm.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null;return{view:t,settingsTab:n,q:l,tag:i,entry:a}}function Km(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Xm(){const[e,t]=f.useState("loading"),[n,r]=f.useState(null);f.useEffect(()=>{(async()=>{if(await kh()){t("setup");return}const z=await _h();if(!z){t("login");return}r(z),t("authenticated")})()},[]),f.useEffect(()=>{const E=()=>{r(null),t("login")};return window.addEventListener("auth:expired",E),()=>window.removeEventListener("auth:expired",E)},[]),f.useEffect(()=>{const E=()=>{const{view:z,settingsTab:U,q:te,tag:ze,entry:Ze}=qt();v(z),S(U),C(te),p(ze),m(Ze),y(null),k(Ze?new Set([Ze]):new Set)};return window.addEventListener("popstate",E),()=>window.removeEventListener("popstate",E)},[]);const[l,i]=f.useState([]),[a,o]=f.useState(null),[u,c]=f.useState([]),[g,m]=f.useState(()=>qt().entry),[h,y]=f.useState(null),[x,k]=f.useState(()=>{const E=qt().entry;return E?new Set([E]):new Set}),[j,p]=f.useState(()=>qt().tag),[d,v]=f.useState(()=>qt().view),[w,S]=f.useState(()=>qt().settingsTab),[P,C]=f.useState(()=>qt().q),[_,I]=f.useState(""),[L,Q]=f.useState(!1),[ne,Z]=f.useState([]),[se,pe]=f.useState([]),[ve,ie]=f.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[R,T]=f.useState([]),F=f.useRef(0),[X,H]=f.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[N,O]=f.useState(null),B=f.useRef(0),M=f.useRef(null),W=f.useRef(!1),de=f.useRef(!0),J=f.useRef(null),q=(n==null?void 0:n.humanize_slugs)??!1;f.useEffect(()=>{const E=++B.current;O(null),!(!h||!a)&&Vi(a,h.entry_uid).then(z=>{E===B.current&&O(z)}).catch(()=>{})},[h,a]),f.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",ve)},[ve]);const G=f.useCallback(async(E,z,U)=>{if(E){Q(!0);try{let te;z||U?te=await fh(E,z,U):te=await dh(E),c(te),k(ze=>{if(ze.size<2)return ze;const Ze=new Set(te.map(gn=>gn.entry_uid)),qn=new Set([...ze].filter(gn=>Ze.has(gn)));return qn.size===ze.size?ze:qn}),I(te.length===0?"No results":`${te.length} result${te.length===1?"":"s"}`)}catch{c([]),I("Search failed. Try again.")}finally{Q(!1)}}},[]);f.useEffect(()=>{e==="authenticated"&&ch().then(E=>{if(i(E),E.length>0){const z=E[0].id;o(z)}})},[e]),f.useEffect(()=>{if(a){if(de.current){de.current=!1,Promise.all([Js(a).then(Z),dl(a).then(pe)]);return}p(null),y(null),m(null),k(new Set),Promise.all([G(a,"",null),Js(a).then(Z),dl(a).then(pe)])}},[a]),f.useEffect(()=>{if(a===null)return;const E=setTimeout(()=>{G(a,P,j)},300);return()=>clearTimeout(E)},[P,a]),f.useEffect(()=>{a!==null&&(j!==null&&v("archive"),G(a,P,j))},[j,a]);const oe=f.useCallback(E=>{o(E)},[]),D=f.useCallback(E=>{v(E),E==="tags"&&a&&dl(a).then(pe)},[a]);f.useEffect(()=>{if(ar)return;const E=Km(d,w);window.location.pathname!==E&&history.pushState(null,"",E+window.location.search)},[d,w]);const V=f.useCallback(E=>{m(E?E.entry_uid:null),y(E)},[]),Ce=f.useCallback((E,z)=>{if(z.shiftKey&&J.current!==null){z.preventDefault();const U=u.findIndex(Gn=>Gn.entry_uid===J.current),te=u.findIndex(Gn=>Gn.entry_uid===E.entry_uid);if(U===-1||te===-1){J.current=E.entry_uid,k(new Set([E.entry_uid])),V(E);return}const ze=Math.min(U,te),Ze=Math.max(U,te),qn=u.slice(ze,Ze+1),gn=new Set(qn.map(Gn=>Gn.entry_uid));k(gn),gn.size===1&&V(qn[0])}else z.ctrlKey||z.metaKey?(J.current=E.entry_uid,k(U=>{const te=new Set(U);return te.has(E.entry_uid)?te.delete(E.entry_uid):te.add(E.entry_uid),te})):(J.current=E.entry_uid,k(new Set([E.entry_uid])),V(E))},[u,V]),xe=f.useCallback(E=>{p(E)},[]),hs=f.useCallback(()=>{p(null)},[]),Kn=f.useCallback(()=>{a&&dl(a).then(pe)},[a]),ms=f.useCallback((E,z)=>{j===E?p(z):j!=null&&j.startsWith(E+"/")&&p(z+j.slice(E.length))},[j]),gs=f.useCallback(E=>{(j===E||j!=null&&j.startsWith(E+"/"))&&p(null)},[j]),Wr=f.useCallback((E,z)=>{c(U=>U.map(te=>te.entry_uid===E?{...te,title:z}:te)),y(U=>U&&U.entry_uid===E?{...U,title:z}:U),O(U=>U&&U.summary.entry_uid===E?{...U,summary:{...U.summary,title:z}}:U)},[]),vs=f.useCallback(()=>{if(!a||!h)return;const E=++B.current;Vi(a,h.entry_uid).then(z=>{E===B.current&&O(z)}).catch(()=>{})},[a,h]),ys=f.useCallback(E=>{c(z=>z.filter(U=>U.entry_uid!==E)),y(z=>(z==null?void 0:z.entry_uid)===E?null:z),m(z=>z===E?null:z),k(z=>{const U=new Set(z);return U.delete(E),U})},[]),xs=f.useCallback(E=>{c(z=>z.filter(U=>!E.has(U.entry_uid))),k(new Set),y(null),m(null)},[]);f.useEffect(()=>{if(x.size>=2)m(null),y(null);else if(x.size===1){const[E]=x;m(E)}else m(null),y(null)},[x]);const ws=f.useMemo(()=>u.filter(E=>x.has(E.entry_uid)),[u,x]);f.useEffect(()=>{if(!g||h)return;const E=u.find(z=>z.entry_uid===g);E&&y(E)},[u,g,h]),f.useEffect(()=>{if(ar)return;const E=new URLSearchParams;P&&E.set("q",P),d==="archive"&&j&&E.set("tag",j),d==="archive"&&g&&E.set("entry",g);const z=E.toString(),U=window.location.pathname+(z?"?"+z:"");window.location.pathname+window.location.search!==U&&history.replaceState(null,"",U)},[P,j,g,d]),f.useEffect(()=>{const E=z=>{var U,te;(z.metaKey||z.ctrlKey)&&z.key==="k"&&(z.preventDefault(),d==="archive"?((U=M.current)==null||U.focus(),(te=M.current)==null||te.select()):(W.current=!0,v("archive")))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[d]),f.useEffect(()=>{d==="archive"&&W.current&&(W.current=!1,requestAnimationFrame(()=>{var E,z;(E=M.current)==null||E.focus(),(z=M.current)==null||z.select()}))},[d]);const ks=f.useCallback(()=>{ie(!0)},[]),js=f.useCallback(()=>{ie(!1)},[]),pn=f.useCallback(()=>{a&&Promise.all([G(a,P,j),Js(a).then(Z)])},[a,P,j,G]),hn=f.useCallback((E,z,U="error",te=null)=>{if(U==="warning"&&X&&z)return;const ze=++F.current;T(Ze=>[...Ze,{id:ze,text:E,locator:z,type:U,headline:te}])},[X]),Vr=f.useCallback(E=>{T(z=>z.filter(U=>U.id!==E))},[]),Qr=f.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),H(!0),T(E=>E.filter(z=>!(z.type==="warning"&&z.locator)))},[]),[mn,Xn]=f.useState(null),[Tt,$]=f.useState(null),re=f.useCallback(()=>{h&&Xn(h.entry_uid)},[h]),Qe=f.useCallback(()=>Xn(null),[]),Jt=f.useCallback((E,z)=>{$({src:E,entry:z})},[]),Jn=f.useCallback(()=>$(null),[]);return f.useEffect(()=>{Xn(null)},[h]),f.useEffect(()=>{const E=z=>{var te,ze,Ze;if(z.key!=="Escape"||ve||mn)return;const U=(te=document.activeElement)==null?void 0:te.tagName;U==="INPUT"||U==="TEXTAREA"||U==="SELECT"||x.size>0&&(z.preventDefault(),k(new Set),(Ze=(ze=document.activeElement)==null?void 0:ze.blur)==null||Ze.call(ze))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[ve,mn,x]),f.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Tt),()=>document.body.classList.remove("has-audio-bar")),[Tt]),e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Yh,{onComplete:()=>t("login")}):e==="login"?s.jsx(Gh,{onLogin:E=>{r(E),t("authenticated")}}):ar?s.jsx(Mm,{archiveId:ar.archiveId,entryUid:ar.entryUid}):s.jsx(ps.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(Zh,{archives:l,archiveId:a,onArchiveChange:oe,view:d,onViewChange:D,onCaptureClick:ks}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[d==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:M,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":L,placeholder:"Search titles, URLs, types, tags…",value:P,onChange:E=>C(E.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[_&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:_.split(" ")[0]})," ",_.split(" ").slice(1).join(" ")]}),j&&s.jsxs("button",{className:"tag-filter-badge",onClick:hs,children:["× ",q?Pd(j):j]})]})]}),d==="archive"&&s.jsx(sm,{entries:u,selectedUids:x,onRowClick:Ce,archiveId:a}),d==="runs"&&s.jsx(om,{runs:ne}),d==="admin"&&s.jsx(cm,{archives:l}),d==="tags"&&s.jsx(dm,{archiveId:a,tagNodes:se,tagFilter:j,onTagFilterSet:xe,onViewChange:D,onTagRenamed:ms,onTagDeleted:gs,onTagsRefresh:Kn,humanizeTags:q}),d==="collections"&&s.jsx(pm,{archiveId:a}),d==="settings"&&s.jsx(mm,{tab:w,onTabChange:S,archiveId:a})]}),s.jsx(Sm,{archiveId:a,selectedEntry:h,selectedUids:x,selectedEntries:ws,detail:N,onTagFilterSet:xe,tagNodes:se,onTagsRefresh:Kn,onEntryTitleChange:Wr,onEntryDeleted:ys,onBulkDeleted:xs,humanizeTags:q,onDetailRefresh:vs,onOpenPreview:re,onPlay:Jt})]}),mn&&h&&h.entry_uid===mn&&s.jsx(Am,{archiveId:a,entry:h,detail:N,onClose:Qe}),Tt&&s.jsx(Fm,{entry:Tt.entry,src:Tt.src,archiveId:a,onClose:Jn}),s.jsx(em,{open:ve,archiveId:a,onClose:js,onCaptured:pn,onToast:hn}),s.jsx(Hm,{toasts:R,onDismiss:Vr,onIgnoreUblock:Qr})]})})}Sd(document.getElementById("root")).render(s.jsx(f.StrictMode,{children:s.jsx(Xm,{})})); diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index e2c29ca..b71782c 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -4,8 +4,8 @@ Archivr - - + +
diff --git a/frontend/src/api.js b/frontend/src/api.js index 03e5704..1d235e1 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -111,6 +111,26 @@ export async function deleteTag(archiveId, tagUid) { if (!res.ok) throw new Error(await res.text()); } +export async function createTag(archiveId, path) { + const res = await fetch(`/api/archives/${archiveId}/tags`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path }), + }); + if (!res.ok) throw new Error(await res.text()); + return res.json(); +} + +export async function moveTag(archiveId, tagUid, parentUid) { + const res = await fetch(`/api/archives/${archiveId}/tags/${tagUid}/move`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ parent_uid: parentUid ?? null }), + }); + if (!res.ok) throw new Error(await res.text()); + return res.json(); +} + export async function fetchRuns(archiveId) { return getJson(`/api/archives/${archiveId}/runs`); } diff --git a/frontend/src/components/TagsView.jsx b/frontend/src/components/TagsView.jsx index f0241eb..d36168b 100644 --- a/frontend/src/components/TagsView.jsx +++ b/frontend/src/components/TagsView.jsx @@ -1,14 +1,156 @@ -import { useState, useRef } from 'react'; -import { renameTag, deleteTag } from '../api'; +import { useState, useRef, useEffect } from 'react'; +import { renameTag, deleteTag, createTag, moveTag } from '../api'; -function TagNode({ node, archiveId, tagFilter, onTagFilterSet, onViewChange, onTagRenamed, onTagDeleted, onTagsRefresh, humanizeTags }) { +// ── TagPickerNode ───────────────────────────────────────────────────────── +// A node inside the destination picker modal. +function TagPickerNode({ node, onPick }) { + return ( +
  • + + {node.children?.length > 0 && ( +
    +
      + {node.children.map(child => ( + + ))} +
    +
    + )} +
  • + ); +} + +// ── TagPickerModal ──────────────────────────────────────────────────────── +// Shared modal for "create under" and "move under" destination selection. +// `excludeUid` hides that tag and all its descendants (used for move). +// `onPick(tag | null)` — null means "make root / no parent". +function TagPickerModal({ title, tagNodes, excludeUid, onPick, onCancel }) { + useEffect(() => { + function onKey(e) { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); onCancel(); } } + document.addEventListener('keydown', onKey); + return () => document.removeEventListener('keydown', onKey); + }, [onCancel]); + function filterTree(nodes) { + return nodes + .filter(n => n.tag.tag_uid !== excludeUid) + .map(n => ({ ...n, children: filterTree(n.children) })); + } + const visibleNodes = excludeUid ? filterTree(tagNodes) : tagNodes; + + return ( +
    { if (e.target === e.currentTarget) onCancel(); }} + > +
    +
    + {title} + +
    +
    + + {visibleNodes.length > 0 ? ( +
      + {visibleNodes.map(node => ( + + ))} +
    + ) : ( +

    No other tags available.

    + )} +
    +
    +
    + ); +} + +// ── CreateInput ─────────────────────────────────────────────────────────── +// Inline text input that appears in the tag tree when creating a new tag. +// Matches the rename-input UX: Enter saves, Escape cancels, blur saves. +function CreateInput({ parentPath, archiveId, onDone, onCancel }) { + const [draft, setDraft] = useState(''); + const cancelRef = useRef(false); + + async function submit() { + const name = draft.trim(); + if (!name) { onCancel(); return; } + const path = parentPath ? `${parentPath}/${name}` : `/${name}`; + try { + await createTag(archiveId, path); + onDone(); + } catch (err) { + alert(err.message || 'Create failed'); + onCancel(); + } + } + + return ( + setDraft(e.target.value)} + onKeyDown={e => { + if (e.key === 'Enter') e.currentTarget.blur(); + if (e.key === 'Escape') { cancelRef.current = true; e.currentTarget.blur(); } + }} + onBlur={() => { + if (cancelRef.current) { cancelRef.current = false; onCancel(); } + else { submit(); } + }} + /> + ); +} + +// ── TagNode ─────────────────────────────────────────────────────────────── +function TagNode({ + node, + archiveId, + tagFilter, + onTagFilterSet, + onViewChange, + onTagRenamed, + onTagDeleted, + onTagsRefresh, + humanizeTags, + // Move source-selection mode: clicking a tag selects it as the thing to move. + moveSelectMode, + onMoveSourceSelect, + // Pending create: the tag_uid of the parent that should render an inline input, + // or '__root__' for the root list (handled in TagsView, not here). + pendingCreateParentUid, + onCreateDone, + onCreateCancel, +}) { const isActive = tagFilter === node.tag.full_path; const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(''); const cancelRef = useRef(false); - function handleFilterClick() { + function handleClick() { if (editing) return; + if (moveSelectMode) { + onMoveSourceSelect(node); + return; + } const next = isActive ? null : node.tag.full_path; onTagFilterSet(next); onViewChange('archive'); @@ -16,16 +158,14 @@ function TagNode({ node, archiveId, tagFilter, onTagFilterSet, onViewChange, onT function startEdit(e) { e.stopPropagation(); + if (moveSelectMode) return; setDraft(node.tag.slug); setEditing(true); } async function handleRenameSave() { const value = draft.trim(); - if (!value || value === node.tag.slug) { - setEditing(false); - return; - } + if (!value || value === node.tag.slug) { setEditing(false); return; } try { const updated = await renameTag(archiveId, node.tag.tag_uid, value); onTagRenamed(node.tag.full_path, updated.full_path); @@ -52,11 +192,18 @@ function TagNode({ node, archiveId, tagFilter, onTagFilterSet, onViewChange, onT } } - const childProps = { archiveId, tagFilter, onTagFilterSet, onViewChange, onTagRenamed, onTagDeleted, onTagsRefresh, humanizeTags }; + const childProps = { + archiveId, tagFilter, onTagFilterSet, onViewChange, onTagRenamed, onTagDeleted, + onTagsRefresh, humanizeTags, moveSelectMode, onMoveSourceSelect, + pendingCreateParentUid, onCreateDone, onCreateCancel, + }; + + const showCreateInput = pendingCreateParentUid === node.tag.tag_uid; + const hasChildren = node.children?.length > 0; return (
  • -
    +
    {editing ? ( { - if (cancelRef.current) { - cancelRef.current = false; - setEditing(false); - } else { - handleRenameSave(); - } + if (cancelRef.current) { cancelRef.current = false; setEditing(false); } + else { handleRenameSave(); } }} /> ) : ( )} - + {!editing && !moveSelectMode && ( + + )}
    - {node.children?.length > 0 && ( + {(hasChildren || showCreateInput) && (
      {node.children.map(child => ( ))} + {showCreateInput && ( +
    • + +
    • + )}
    )} @@ -119,35 +282,162 @@ function TagNode({ node, archiveId, tagFilter, onTagFilterSet, onViewChange, onT ); } -export default function TagsView({ archiveId, tagNodes, tagFilter, onTagFilterSet, onViewChange, onTagRenamed, onTagDeleted, onTagsRefresh, humanizeTags }) { +// ── TagsView ────────────────────────────────────────────────────────────── +export default function TagsView({ + archiveId, tagNodes, tagFilter, onTagFilterSet, onViewChange, + onTagRenamed, onTagDeleted, onTagsRefresh, humanizeTags, +}) { + // ── Move state ──────────────────────────────────────────────────────── + // moveStep: null | 'select-source' | 'select-dest' + const [moveStep, setMoveStep] = useState(null); + const [moveSourceNode, setMoveSourceNode] = useState(null); + + function startMoveMode() { setMoveStep('select-source'); setMoveSourceNode(null); } + function cancelMove() { setMoveStep(null); setMoveSourceNode(null); } + // Esc while in source-selection mode cancels the move. + useEffect(() => { + if (moveStep !== 'select-source') return; + function onKey(e) { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cancelMove(); } } + document.addEventListener('keydown', onKey); + return () => document.removeEventListener('keydown', onKey); + }, [moveStep]); + + function handleMoveSourceSelect(node) { + setMoveSourceNode(node); + setMoveStep('select-dest'); + } + + async function handleMoveDest(destTag) { + // destTag: Tag object | null (null = make root) + const sourceOldPath = moveSourceNode.tag.full_path; + const sourceUid = moveSourceNode.tag.tag_uid; + const destUid = destTag?.tag_uid ?? null; + cancelMove(); + try { + const updated = await moveTag(archiveId, sourceUid, destUid); + // Keep the active tag filter consistent when the moved tag/subtree was active. + onTagRenamed(sourceOldPath, updated.full_path); + onTagsRefresh(); + } catch (err) { + alert(err.message || 'Move failed'); + } + } + + // ── Create state ────────────────────────────────────────────────────── + // createStep: null | 'select-parent' | 'input' + const [createStep, setCreateStep] = useState(null); + const [createParentTag, setCreateParentTag] = useState(undefined); + + function startCreateMode() { setCreateStep('select-parent'); setCreateParentTag(undefined); } + function cancelCreate() { setCreateStep(null); setCreateParentTag(undefined); } + + function handleCreateParentPick(tag) { + // tag: Tag | null (null = root) + setCreateParentTag(tag ?? null); + setCreateStep('input'); + } + + function handleCreateDone() { + setCreateStep(null); + setCreateParentTag(undefined); + onTagsRefresh(); + } + + // ── Derived ─────────────────────────────────────────────────────────── + const moveSelectMode = moveStep === 'select-source'; + + // The tag_uid of the parent that should render a create input inside its + // children list. '__root__' means the root-level list handles it. + const pendingCreateParentUid = createStep === 'input' + ? (createParentTag ? createParentTag.tag_uid : '__root__') + : undefined; + + const nodeProps = { + archiveId, tagFilter, onTagFilterSet, onViewChange, onTagRenamed, onTagDeleted, + onTagsRefresh, humanizeTags, moveSelectMode, onMoveSourceSelect: handleMoveSourceSelect, + pendingCreateParentUid, onCreateDone: handleCreateDone, onCreateCancel: cancelCreate, + }; + + const showRootCreateInput = pendingCreateParentUid === '__root__'; + return (
    - Tags - {tagFilter && ( - Filtering: {tagFilter} + {moveSelectMode ? ( + <> + Select a tag to move + + + ) : ( + <> + Tags + {tagFilter && ( + Filtering: {tagFilter} + )} +
    + + +
    + )}
    - {tagNodes.length === 0 ? ( + + {tagNodes.length === 0 && !showRootCreateInput ? (

    No tags yet.

    ) : (
      {tagNodes.map(node => ( - + ))} + {showRootCreateInput && ( +
    • + +
    • + )}
    )}
    + + {/* Create: pick parent modal */} + {createStep === 'select-parent' && ( + + )} + + {/* Move: pick destination modal (shown after source is selected) */} + {moveStep === 'select-dest' && moveSourceNode && ( + + )}
    ); } diff --git a/frontend/src/components/TagsView.stories.jsx b/frontend/src/components/TagsView.stories.jsx new file mode 100644 index 0000000..8c20995 --- /dev/null +++ b/frontend/src/components/TagsView.stories.jsx @@ -0,0 +1,167 @@ +import { useState, useEffect } from 'react'; +import TagsView from './TagsView'; + +// Installs a per-story fetch stub that intercepts /api/ tag mutations and +// returns realistic Tag shapes so renameTag/moveTag/createTag don't throw. +// Installed in useEffect so it never leaks into other stories and won't +// double-wrap on re-renders. +function ApiStub({ children }) { + useEffect(() => { + const realFetch = window.fetch.bind(window); + window.fetch = (url, opts) => { + if (typeof url === 'string' && url.startsWith('/api/')) { + const method = (opts?.method ?? 'GET').toUpperCase(); + if (method === 'DELETE') { + return Promise.resolve(new Response(null, { status: 204 })); + } + // Parse request body to construct a realistic Tag shape. + // renameTag sends { name }, moveTag/createTag send path info. + // full_path must be present or callers throw on updated.full_path. + let body = {}; + try { body = JSON.parse(opts?.body ?? '{}'); } catch { /* ignore */ } + const slug = (body.name ?? body.path ?? 'stub') + .trim().replace(/\s+/g, '-').replace(/[^a-zA-Z0-9-]/g, '').replace(/^-+|-+$/g, '') || 'stub'; + const stubTag = { + tag_uid: 'stub-uid', + name: slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase()), + slug, + full_path: `/${slug}`, + }; + return Promise.resolve( + new Response(JSON.stringify(stubTag), { + status: method === 'POST' ? 201 : 200, + headers: { 'Content-Type': 'application/json' }, + }) + ); + } + return realFetch(url, opts); + }; + return () => { window.fetch = realFetch; }; + }, []); + return children; +} + +function withApiStub(Story) { + return ; +} + +export default { + component: TagsView, + tags: ['autodocs'], + parameters: { layout: 'padded' }, + decorators: [withApiStub], +}; + +// ── Shared fixtures ─────────────────────────────────────────────────────── + +const noop = () => {}; + +function tag(tag_uid, name, slug, full_path, entry_count = 0, children = [], subtree_count = null) { + return { tag: { tag_uid, name, slug, full_path }, entry_count, subtree_count: subtree_count ?? entry_count, children }; +} + +const sampleTree = [ + tag('t1', 'Science', 'science', '/science', 12, [ + tag('t2', 'Computer Science', 'computer-science', '/science/computer-science', 7, [ + tag('t3', 'Algorithms', 'algorithms', '/science/computer-science/algorithms', 3), + tag('t4', 'Compilers', 'compilers', '/science/computer-science/compilers', 1), + ], 11), + tag('t5', 'Physics', 'physics', '/science/physics', 4), + ], 23), + tag('t6', 'History', 'history', '/history', 5, [ + tag('t7', 'Ancient', 'ancient', '/history/ancient', 2), + ], 7), + tag('t8', 'Reading List', 'reading-list', '/reading-list', 0), +]; + +// Wrapper that wires local state so onTagsRefresh/onTagRenamed callbacks +// keep the tree consistent within a story session. +function TagsViewSandbox({ initialNodes = sampleTree, tagFilter = null, humanizeTags = false }) { + const [nodes, setNodes] = useState(initialNodes); + const [filter, setFilter] = useState(tagFilter); + + function handleTagRenamed(oldPath, newPath) { + if (filter === oldPath) setFilter(newPath); + else if (filter?.startsWith(oldPath + '/')) setFilter(newPath + filter.slice(oldPath.length)); + } + + function handleTagDeleted(deletedPath) { + if (filter === deletedPath || filter?.startsWith(deletedPath + '/')) setFilter(null); + } + + // onTagsRefresh is a no-op here: in a real app it re-fetches; the stub + // tag returned from fetch won't match our fixture tree, so the tree stays + // as-is after mutations. That is acceptable for visual QA purposes. + + return ( +
    + +
    + ); +} + +// ── Stories ─────────────────────────────────────────────────────────────── + +/** Default view with a nested tag tree. All interactions are exercisable: + * click + New / Move to open the picker modal; click a tag to filter; + * double-click or pencil to rename; × to delete. + * API mutations are stubbed — the tree won't re-fetch after saves, + * but no network errors will occur. */ +export const Default = { + render: () => , +}; + +/** Empty archive — "No tags yet." shown; + New still works. */ +export const Empty = { + render: () => , +}; + +/** Humanize mode: slugs displayed as Title Case names. */ +export const HumanizedNames = { + render: () => , +}; + +/** Active tag filter — header shows the current filter path. */ +export const WithActiveFilter = { + render: () => ( + + ), +}; + +/** Flat list with no nesting. */ +export const FlatList = { + render: () => ( + + ), +}; + +/** Tags with large entry counts — verifies count badge layout. */ +export const HighCounts = { + render: () => ( + + ), +}; diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 6613ab3..cb5b7d2 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1279,6 +1279,135 @@ select { outline: none; } +/* entry count badge next to tag name */ +.tag-node-label { flex-shrink: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tag-node-count { + font-size: 11px; + color: var(--muted-2); + font-weight: 400; + flex-shrink: 0; + margin-left: 3px; +} + +/* header action buttons (+ New, Move) */ +.tag-tree-header { align-items: center; } +.tag-tree-actions { margin-left: auto; display: flex; gap: 4px; } +.tag-tree-action-btn { + font-size: 11px; + padding: 2px 7px; + border: 1px solid var(--line); + border-radius: var(--r); + background: transparent; + color: var(--muted); + cursor: pointer; + line-height: 1.5; + white-space: nowrap; + transition: background 0.1s, color 0.1s; +} +.tag-tree-action-btn:hover:not(:disabled) { background: var(--paper-2); color: var(--ink); } +.tag-tree-action-btn:disabled { opacity: 0.4; cursor: default; } +.tag-tree-action-btn--cancel { border-color: var(--accent); color: var(--accent); } +.tag-tree-action-btn--cancel:hover { background: color-mix(in srgb, var(--accent) 8%, transparent); } +.tag-tree-title--move { font-style: italic; color: var(--accent-2); } + +/* move source-select mode: nodes act as clickable targets */ +.tag-node-row--move-select .tag-node-btn { cursor: crosshair; color: var(--ink); } +.tag-node-row--move-select .tag-node-btn:hover { + background: color-mix(in srgb, var(--link) 10%, transparent); + text-decoration: none; + border-radius: var(--r); +} + +/* ── Tag picker modal (create/move destination) ──────────────────────────── */ +.tag-picker-backdrop { + position: fixed; + inset: 0; + z-index: 200; + background: rgba(0, 0, 0, 0.45); + display: flex; + align-items: center; + justify-content: center; + padding: 20px; +} +.tag-picker-modal { + background: var(--paper); + border-radius: var(--r3); + box-shadow: 0 16px 56px rgba(0, 0, 0, 0.24); + width: 300px; + max-width: 100%; + display: flex; + flex-direction: column; + max-height: 60vh; +} +.tag-picker-header { + display: flex; + align-items: center; + padding: 12px 14px; + border-bottom: 1px solid var(--line); + flex-shrink: 0; + gap: 8px; +} +.tag-picker-title { + flex: 1; + font-size: 13px; + font-weight: 600; + color: var(--ink); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.tag-picker-close { + width: 26px; + height: 26px; + border-radius: 50%; + border: none; + background: transparent; + color: var(--muted-2); + font-size: 18px; + line-height: 1; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} +.tag-picker-close:hover { background: var(--paper-2); color: var(--ink); } +.tag-picker-body { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 8px 12px 12px; +} +.tag-picker-root-btn { + display: block; + width: 100%; + text-align: left; + padding: 5px 8px; + margin-bottom: 6px; + border: 1px dashed var(--line); + border-radius: var(--r); + background: transparent; + color: var(--muted); + font-size: 12px; + cursor: pointer; +} +.tag-picker-root-btn:hover { background: var(--paper-2); color: var(--ink); border-color: var(--muted-2); } +.tag-picker-tree { border-top: 1px solid var(--line-soft); padding-top: 6px; margin-top: 2px; } +.tag-picker-node-btn { + border: 0; + background: transparent; + color: var(--link); + cursor: pointer; + padding: 3px 6px; + text-align: left; + font-size: 13px; + display: block; + width: 100%; + border-radius: var(--r); +} +.tag-picker-node-btn:hover { background: var(--paper-2); text-decoration: none; } +.tag-picker-empty { font-size: 13px; color: var(--muted-2); margin: 6px 0 0; } + /* ── Collections page (sidebar layout) ──────────────────────────────────── */ .collections-view { padding: 24px; From a926d7cf2d8b4927d998795796508de606e72d43 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sun, 19 Jul 2026 12:09:30 +0200 Subject: [PATCH 02/12] feat(core): add via_freedium to CaptureConfig; route WebPage captures through Freedium mirror When via_freedium is true and the locator is not already a Freedium URL, perform_capture passes https://freedium-mirror.cfd/ to singlefile::save() so paywalled articles are fetched via the mirror. The original locator is kept for requested_locator and canonical_locator in the DB entry. An empty cookie map is used for the mirror fetch to prevent original-domain credentials from being sent to freedium-mirror.cfd. --- crates/archivr-core/src/capture.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index b02fe59..1f02d58 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -87,6 +87,9 @@ pub struct CaptureConfig { pub reader_mode: bool, /// Override for modal-closer browser-script behavior during WebPage captures. pub modal_closer_enabled: Option, + /// Route WebPage captures through the Freedium mirror to bypass paywalls. + /// The original locator is still recorded in the DB; only the fetch URL changes. + pub via_freedium: bool, } /// Resolves which cookies apply to `url` by evaluating all rules in ordinal order. @@ -1038,7 +1041,17 @@ pub fn perform_capture( // Source: web page — archive as a self-contained HTML snapshot via single-file-cli if source == Source::WebPage { - match downloader::singlefile::save(locator, store_path, ×tamp, &cookies, config.ublock_enabled, config.cookie_ext_enabled, config.reader_mode, config.modal_closer_enabled) { + // When via_freedium is enabled and the URL is not already a freedium mirror, + // fetch through the mirror to bypass paywalls. Store the original locator in DB. + // Use an empty cookie jar for the mirror URL: cookies resolved for the original + // domain (e.g. NYT, Medium) must not be sent to freedium-mirror.cfd. + let (fetch_url, fetch_cookies): (String, HashMap) = + if config.via_freedium && !locator.starts_with("https://freedium-mirror.cfd/") { + (format!("https://freedium-mirror.cfd/{}", locator), HashMap::new()) + } else { + (locator.to_string(), cookies.clone()) + }; + match downloader::singlefile::save(&fetch_url, store_path, ×tamp, &fetch_cookies, config.ublock_enabled, config.cookie_ext_enabled, config.reader_mode, config.modal_closer_enabled) { Ok(result) => { let file_extension = ".html".to_string(); let temp_html = store_path From b33bf8dbd7753407c54fa0c13f5069d6871ccf26 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sun, 19 Jul 2026 12:09:37 +0200 Subject: [PATCH 03/12] feat(server): expose via_freedium in capture API (default on) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CaptureBody gains via_freedium: Option; absent defaults to true. The rearchive handler sets it to false — existing entries should not be silently re-fetched through a mirror. --- crates/archivr-server/src/routes.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 3388a05..9df6c52 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -747,6 +747,8 @@ struct CaptureBody { reader_mode: Option, cookie_ext_enabled: Option, modal_closer_enabled: Option, + /// Route through Freedium mirror for WebPage captures. Absent = true (on by default). + via_freedium: Option, } #[derive(Debug, serde::Deserialize)] @@ -860,6 +862,7 @@ async fn capture_handler( cookie_ext_enabled: Some(effective_cookie_ext), modal_closer_enabled: Some(effective_modal_closer), reader_mode: body.reader_mode.unwrap_or(false), + via_freedium: body.via_freedium.unwrap_or(true), }; // Spawn background capture. @@ -977,6 +980,7 @@ async fn rearchive_handler( cookie_ext_enabled: None, modal_closer_enabled: None, reader_mode: false, + via_freedium: false, }; let job_uid_bg = job_uid.clone(); From 5db18122f78567b93cd93a0958068cac817fabb7 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sun, 19 Jul 2026 12:09:42 +0200 Subject: [PATCH 04/12] feat(frontend): add Freedium mirror toggle to capture advanced options - freediumEnabled state defaults to true (on by default) - via_freedium forwarded through submitCapture to the capture API - Toggle rendered last in the advanced panel, matching existing rows - Built frontend static assets included --- .../static/assets/index-BpGwC-YY.js | 47 ------------------- .../static/assets/index-YmIQCrug.js | 47 +++++++++++++++++++ crates/archivr-server/static/index.html | 2 +- frontend/src/api.js | 3 +- frontend/src/components/CaptureDialog.jsx | 19 +++++++- 5 files changed, 68 insertions(+), 50 deletions(-) delete mode 100644 crates/archivr-server/static/assets/index-BpGwC-YY.js create mode 100644 crates/archivr-server/static/assets/index-YmIQCrug.js diff --git a/crates/archivr-server/static/assets/index-BpGwC-YY.js b/crates/archivr-server/static/assets/index-BpGwC-YY.js deleted file mode 100644 index 361ee45..0000000 --- a/crates/archivr-server/static/assets/index-BpGwC-YY.js +++ /dev/null @@ -1,47 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var fu={exports:{}},Gl={},pu={exports:{}},ee={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Mr=Symbol.for("react.element"),Fd=Symbol.for("react.portal"),Bd=Symbol.for("react.fragment"),Ud=Symbol.for("react.strict_mode"),Hd=Symbol.for("react.profiler"),Wd=Symbol.for("react.provider"),Vd=Symbol.for("react.context"),Qd=Symbol.for("react.forward_ref"),Kd=Symbol.for("react.suspense"),Xd=Symbol.for("react.memo"),Jd=Symbol.for("react.lazy"),Wa=Symbol.iterator;function qd(e){return e===null||typeof e!="object"?null:(e=Wa&&e[Wa]||e["@@iterator"],typeof e=="function"?e:null)}var hu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},mu=Object.assign,gu={};function Wn(e,t,n){this.props=e,this.context=t,this.refs=gu,this.updater=n||hu}Wn.prototype.isReactComponent={};Wn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Wn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function vu(){}vu.prototype=Wn.prototype;function Ki(e,t,n){this.props=e,this.context=t,this.refs=gu,this.updater=n||hu}var Xi=Ki.prototype=new vu;Xi.constructor=Ki;mu(Xi,Wn.prototype);Xi.isPureReactComponent=!0;var Va=Array.isArray,yu=Object.prototype.hasOwnProperty,Ji={current:null},xu={key:!0,ref:!0,__self:!0,__source:!0};function wu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)yu.call(t,r)&&!xu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,H=R[q];if(0>>1;ql(U,M))Bl(Q,U)?(R[q]=Q,R[B]=M,q=B):(R[q]=U,R[O]=M,q=O);else if(Bl(Q,M))R[q]=Q,R[B]=M,q=B;else break e}}return T}function l(R,T){var M=R.sortIndex-T.sortIndex;return M!==0?M:R.id-T.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],g=1,m=null,h=3,y=!1,x=!1,k=!1,j=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(R){for(var T=n(c);T!==null;){if(T.callback===null)r(c);else if(T.startTime<=R)r(c),T.sortIndex=T.expirationTime,t(u,T);else break;T=n(c)}}function w(R){if(k=!1,v(R),!x)if(n(u)!==null)x=!0,fe(_);else{var T=n(c);T!==null&&le(w,T.startTime-R)}}function _(R,T){x=!1,k&&(k=!1,p(S),S=-1),y=!0;var M=h;try{for(v(T),m=n(u);m!==null&&(!(m.expirationTime>T)||R&&!K());){var q=m.callback;if(typeof q=="function"){m.callback=null,h=m.priorityLevel;var H=q(m.expirationTime<=T);T=e.unstable_now(),typeof H=="function"?m.callback=H:m===n(u)&&r(u),v(T)}else r(u);m=n(u)}if(m!==null)var N=!0;else{var O=n(c);O!==null&&le(w,O.startTime-T),N=!1}return N}finally{m=null,h=M,y=!1}}var b=!1,C=null,S=-1,$=5,P=-1;function K(){return!(e.unstable_now()-P<$)}function F(){if(C!==null){var R=e.unstable_now();P=R;var T=!0;try{T=C(!0,R)}finally{T?W():(b=!1,C=null)}}else b=!1}var W;if(typeof d=="function")W=function(){d(F)};else if(typeof MessageChannel<"u"){var te=new MessageChannel,oe=te.port2;te.port1.onmessage=F,W=function(){oe.postMessage(null)}}else W=function(){j(F,0)};function fe(R){C=R,b||(b=!0,W())}function le(R,T){S=j(function(){R(e.unstable_now())},T)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(R){R.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,fe(_))},e.unstable_forceFrameRate=function(R){0>R||125q?(R.sortIndex=M,t(c,R),n(u)===null&&R===n(c)&&(k?(p(S),S=-1):k=!0,le(w,M-q))):(R.sortIndex=H,t(u,R),x||y||(x=!0,fe(_))),R},e.unstable_shouldYield=K,e.unstable_wrapCallback=function(R){var T=h;return function(){var M=h;h=T;try{return R.apply(this,arguments)}finally{h=M}}}})(_u);Nu.exports=_u;var of=Nu.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var uf=f,qe=of;function L(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Zs=Object.prototype.hasOwnProperty,cf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Ka={},Xa={};function df(e){return Zs.call(Xa,e)?!0:Zs.call(Ka,e)?!1:cf.test(e)?Xa[e]=!0:(Ka[e]=!0,!1)}function ff(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function pf(e,t,n,r){if(t===null||typeof t>"u"||ff(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Fe(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var Le={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Le[e]=new Fe(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Le[t]=new Fe(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Le[e]=new Fe(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Le[e]=new Fe(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Le[e]=new Fe(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Le[e]=new Fe(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Le[e]=new Fe(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Le[e]=new Fe(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Le[e]=new Fe(e,5,!1,e.toLowerCase(),null,!1,!1)});var Gi=/[\-:]([a-z])/g;function Yi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Fe(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Fe(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Gi,Yi);Le[t]=new Fe(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Le[e]=new Fe(e,1,!1,e.toLowerCase(),null,!1,!1)});Le.xlinkHref=new Fe("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Le[e]=new Fe(e,1,!1,e.toLowerCase(),null,!0,!0)});function Zi(e,t,n,r){var l=Le.hasOwnProperty(t)?Le[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` -`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{_s=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?or(e):""}function hf(e){switch(e.tag){case 5:return or(e.type);case 16:return or("Lazy");case 13:return or("Suspense");case 19:return or("SuspenseList");case 0:case 2:case 15:return e=Cs(e.type,!1),e;case 11:return e=Cs(e.type.render,!1),e;case 1:return e=Cs(e.type,!0),e;default:return""}}function ri(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case xn:return"Fragment";case yn:return"Portal";case ei:return"Profiler";case ea:return"StrictMode";case ti:return"Suspense";case ni:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Tu:return(e.displayName||"Context")+".Consumer";case Eu:return(e._context.displayName||"Context")+".Provider";case ta:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case na:return t=e.displayName||null,t!==null?t:ri(e.type)||"Memo";case Pt:t=e._payload,e=e._init;try{return ri(e(t))}catch{}}return null}function mf(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ri(t);case 8:return t===ea?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Wt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Pu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function gf(e){var t=Pu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Jr(e){e._valueTracker||(e._valueTracker=gf(e))}function Lu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Pu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function _l(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function li(e,t){var n=t.checked;return ve({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function qa(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Wt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function zu(e,t){t=t.checked,t!=null&&Zi(e,"checked",t,!1)}function si(e,t){zu(e,t);var n=Wt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ii(e,t.type,n):t.hasOwnProperty("defaultValue")&&ii(e,t.type,Wt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ga(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ii(e,t,n){(t!=="number"||_l(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ur=Array.isArray;function Pn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=qr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var pr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},vf=["Webkit","ms","Moz","O"];Object.keys(pr).forEach(function(e){vf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),pr[t]=pr[e]})});function Iu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||pr.hasOwnProperty(e)&&pr[e]?(""+t).trim():t+"px"}function Ou(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Iu(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var yf=ve({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ui(e,t){if(t){if(yf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(L(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(L(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(L(61))}if(t.style!=null&&typeof t.style!="object")throw Error(L(62))}}function ci(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var di=null;function ra(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var fi=null,Ln=null,zn=null;function eo(e){if(e=Ur(e)){if(typeof fi!="function")throw Error(L(280));var t=e.stateNode;t&&(t=ns(t),fi(e.stateNode,e.type,t))}}function Au(e){Ln?zn?zn.push(e):zn=[e]:Ln=e}function Mu(){if(Ln){var e=Ln,t=zn;if(zn=Ln=null,eo(e),t)for(e=0;e>>=0,e===0?32:31-(bf(e)/Pf|0)|0}var Gr=64,Yr=4194304;function cr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function bl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=cr(o):(i&=a,i!==0&&(r=cr(i)))}else a=n&~l,a!==0?r=cr(a):i!==0&&(r=cr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Fr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-ct(t),e[t]=n}function Df(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=mr),uo=" ",co=!1;function sc(e,t){switch(e){case"keyup":return op.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ic(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var wn=!1;function cp(e,t){switch(e){case"compositionend":return ic(t);case"keypress":return t.which!==32?null:(co=!0,uo);case"textInput":return e=t.data,e===uo&&co?null:e;default:return null}}function dp(e,t){if(wn)return e==="compositionend"||!da&&sc(e,t)?(e=rc(),ml=oa=Dt=null,wn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=mo(n)}}function cc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?cc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function dc(){for(var e=window,t=_l();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=_l(e.document)}return t}function fa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function wp(e){var t=dc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&cc(n.ownerDocument.documentElement,n)){if(r!==null&&fa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=go(n,i);var a=go(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,kn=null,yi=null,vr=null,xi=!1;function vo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;xi||kn==null||kn!==_l(r)||(r=kn,"selectionStart"in r&&fa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),vr&&br(vr,r)||(vr=r,r=zl(yi,"onSelect"),0Nn||(e.current=_i[Nn],_i[Nn]=null,Nn--)}function ae(e,t){Nn++,_i[Nn]=e.current,e.current=t}var Vt={},Ie=Kt(Vt),He=Kt(!1),sn=Vt;function An(e,t){var n=e.type.contextTypes;if(!n)return Vt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function We(e){return e=e.childContextTypes,e!=null}function Dl(){de(He),de(Ie)}function No(e,t,n){if(Ie.current!==Vt)throw Error(L(168));ae(Ie,t),ae(He,n)}function wc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(L(108,mf(e)||"Unknown",l));return ve({},n,r)}function $l(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Vt,sn=Ie.current,ae(Ie,e),ae(He,He.current),!0}function _o(e,t,n){var r=e.stateNode;if(!r)throw Error(L(169));n?(e=wc(e,t,sn),r.__reactInternalMemoizedMergedChildContext=e,de(He),de(Ie),ae(Ie,e)):de(He),ae(He,n)}var xt=null,rs=!1,Fs=!1;function kc(e){xt===null?xt=[e]:xt.push(e)}function zp(e){rs=!0,kc(e)}function Xt(){if(!Fs&&xt!==null){Fs=!0;var e=0,t=ie;try{var n=xt;for(ie=1;e>=a,l-=a,wt=1<<32-ct(t)+l|n<S?($=C,C=null):$=C.sibling;var P=h(p,C,v[S],w);if(P===null){C===null&&(C=$);break}e&&C&&P.alternate===null&&t(p,C),d=i(P,d,S),b===null?_=P:b.sibling=P,b=P,C=$}if(S===v.length)return n(p,C),he&&Gt(p,S),_;if(C===null){for(;SS?($=C,C=null):$=C.sibling;var K=h(p,C,P.value,w);if(K===null){C===null&&(C=$);break}e&&C&&K.alternate===null&&t(p,C),d=i(K,d,S),b===null?_=K:b.sibling=K,b=K,C=$}if(P.done)return n(p,C),he&&Gt(p,S),_;if(C===null){for(;!P.done;S++,P=v.next())P=m(p,P.value,w),P!==null&&(d=i(P,d,S),b===null?_=P:b.sibling=P,b=P);return he&&Gt(p,S),_}for(C=r(p,C);!P.done;S++,P=v.next())P=y(C,p,S,P.value,w),P!==null&&(e&&P.alternate!==null&&C.delete(P.key===null?S:P.key),d=i(P,d,S),b===null?_=P:b.sibling=P,b=P);return e&&C.forEach(function(F){return t(p,F)}),he&&Gt(p,S),_}function j(p,d,v,w){if(typeof v=="object"&&v!==null&&v.type===xn&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Xr:e:{for(var _=v.key,b=d;b!==null;){if(b.key===_){if(_=v.type,_===xn){if(b.tag===7){n(p,b.sibling),d=l(b,v.props.children),d.return=p,p=d;break e}}else if(b.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===Pt&&To(_)===b.type){n(p,b.sibling),d=l(b,v.props),d.ref=rr(p,b,v),d.return=p,p=d;break e}n(p,b);break}else t(p,b);b=b.sibling}v.type===xn?(d=ln(v.props.children,p.mode,w,v.key),d.return=p,p=d):(w=Sl(v.type,v.key,v.props,null,p.mode,w),w.ref=rr(p,d,v),w.return=p,p=w)}return a(p);case yn:e:{for(b=v.key;d!==null;){if(d.key===b)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){n(p,d.sibling),d=l(d,v.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=Xs(v,p.mode,w),d.return=p,p=d}return a(p);case Pt:return b=v._init,j(p,d,b(v._payload),w)}if(ur(v))return x(p,d,v,w);if(Yn(v))return k(p,d,v,w);sl(p,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,v),d.return=p,p=d):(n(p,d),d=Ks(v,p.mode,w),d.return=p,p=d),a(p)):n(p,d)}return j}var Fn=_c(!0),Cc=_c(!1),Al=Kt(null),Ml=null,En=null,ga=null;function va(){ga=En=Ml=null}function ya(e){var t=Al.current;de(Al),e._currentValue=t}function Ti(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Dn(e,t){Ml=e,ga=En=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ue=!0),e.firstContext=null)}function lt(e){var t=e._currentValue;if(ga!==e)if(e={context:e,memoizedValue:t,next:null},En===null){if(Ml===null)throw Error(L(308));En=e,Ml.dependencies={lanes:0,firstContext:e}}else En=En.next=e;return t}var en=null;function xa(e){en===null?en=[e]:en.push(e)}function Ec(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,xa(t)):(n.next=l.next,l.next=n),t.interleaved=n,_t(e,r)}function _t(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Lt=!1;function wa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Tc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function jt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ft(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ne&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,_t(e,n)}return l=r.interleaved,l===null?(t.next=t,xa(r)):(t.next=l.next,l.next=t),r.interleaved=t,_t(e,n)}function vl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}function bo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Fl(e,t,n,r){var l=e.updateQueue;Lt=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var g=e.alternate;g!==null&&(g=g.updateQueue,o=g.lastBaseUpdate,o!==a&&(o===null?g.firstBaseUpdate=c:o.next=c,g.lastBaseUpdate=u))}if(i!==null){var m=l.baseState;a=0,g=c=u=null,o=i;do{var h=o.lane,y=o.eventTime;if((r&h)===h){g!==null&&(g=g.next={eventTime:y,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,k=o;switch(h=t,y=n,k.tag){case 1:if(x=k.payload,typeof x=="function"){m=x.call(y,m,h);break e}m=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=k.payload,h=typeof x=="function"?x.call(y,m,h):x,h==null)break e;m=ve({},m,h);break e;case 2:Lt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else y={eventTime:y,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},g===null?(c=g=y,u=m):g=g.next=y,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(g===null&&(u=m),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=g,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);un|=a,e.lanes=a,e.memoizedState=m}}function Po(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Us.transition;Us.transition={};try{e(!1),t()}finally{ie=n,Us.transition=r}}function Vc(){return st().memoizedState}function Ip(e,t,n){var r=Ut(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Qc(e))Kc(t,n);else if(n=Ec(e,t,n,r),n!==null){var l=Ae();dt(n,e,r,l),Xc(n,t,r)}}function Op(e,t,n){var r=Ut(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Qc(e))Kc(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,ft(o,a)){var u=t.interleaved;u===null?(l.next=l,xa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Ec(e,t,l,r),n!==null&&(l=Ae(),dt(n,e,r,l),Xc(n,t,r))}}function Qc(e){var t=e.alternate;return e===ge||t!==null&&t===ge}function Kc(e,t){yr=Ul=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Xc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}var Hl={readContext:lt,useCallback:Re,useContext:Re,useEffect:Re,useImperativeHandle:Re,useInsertionEffect:Re,useLayoutEffect:Re,useMemo:Re,useReducer:Re,useRef:Re,useState:Re,useDebugValue:Re,useDeferredValue:Re,useTransition:Re,useMutableSource:Re,useSyncExternalStore:Re,useId:Re,unstable_isNewReconciler:!1},Ap={readContext:lt,useCallback:function(e,t){return ht().memoizedState=[e,t===void 0?null:t],e},useContext:lt,useEffect:zo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,xl(4194308,4,Fc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return xl(4194308,4,e,t)},useInsertionEffect:function(e,t){return xl(4,2,e,t)},useMemo:function(e,t){var n=ht();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ht();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Ip.bind(null,ge,e),[r.memoizedState,e]},useRef:function(e){var t=ht();return e={current:e},t.memoizedState=e},useState:Lo,useDebugValue:Ta,useDeferredValue:function(e){return ht().memoizedState=e},useTransition:function(){var e=Lo(!1),t=e[0];return e=$p.bind(null,e[1]),ht().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=ge,l=ht();if(he){if(n===void 0)throw Error(L(407));n=n()}else{if(n=t(),Te===null)throw Error(L(349));on&30||zc(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,zo(Dc.bind(null,r,i,e),[e]),r.flags|=2048,Or(9,Rc.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ht(),t=Te.identifierPrefix;if(he){var n=kt,r=wt;n=(r&~(1<<32-ct(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=$r++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[mt]=t,e[zr]=r,ld(e,t,!1,!1),t.stateNode=e;e:{switch(a=ci(n,r),n){case"dialog":ce("cancel",e),ce("close",e),l=r;break;case"iframe":case"object":case"embed":ce("load",e),l=r;break;case"video":case"audio":for(l=0;lHn&&(t.flags|=128,r=!0,lr(i,!1),t.lanes=4194304)}else{if(!r)if(e=Bl(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),lr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!he)return De(t),null}else 2*we()-i.renderingStartTime>Hn&&n!==1073741824&&(t.flags|=128,r=!0,lr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=we(),t.sibling=null,n=me.current,ae(me,r?n&1|2:n&1),t):(De(t),null);case 22:case 23:return Da(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ke&1073741824&&(De(t),t.subtreeFlags&6&&(t.flags|=8192)):De(t),null;case 24:return null;case 25:return null}throw Error(L(156,t.tag))}function Qp(e,t){switch(ha(t),t.tag){case 1:return We(t.type)&&Dl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Bn(),de(He),de(Ie),Sa(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ja(t),null;case 13:if(de(me),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(L(340));Mn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return de(me),null;case 4:return Bn(),null;case 10:return ya(t.type._context),null;case 22:case 23:return Da(),null;case 24:return null;default:return null}}var al=!1,$e=!1,Kp=typeof WeakSet=="function"?WeakSet:Set,A=null;function Tn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(e,t,r)}else n.current=null}function Oi(e,t,n){try{n()}catch(r){ye(e,t,r)}}var Ho=!1;function Xp(e,t){if(wi=Pl,e=dc(),fa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,g=0,m=e,h=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(o=a+l),m!==i||r!==0&&m.nodeType!==3||(u=a+r),m.nodeType===3&&(a+=m.nodeValue.length),(y=m.firstChild)!==null;)h=m,m=y;for(;;){if(m===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++g===r&&(u=a),(y=m.nextSibling)!==null)break;m=h,h=m.parentNode}m=y}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(ki={focusedElem:e,selectionRange:n},Pl=!1,A=t;A!==null;)if(t=A,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,A=e;else for(;A!==null;){t=A;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var k=x.memoizedProps,j=x.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?k:at(t.type,k),j);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(L(163))}}catch(w){ye(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,A=e;break}A=t.return}return x=Ho,Ho=!1,x}function xr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Oi(t,n,i)}l=l.next}while(l!==r)}}function is(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ai(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function ad(e){var t=e.alternate;t!==null&&(e.alternate=null,ad(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[mt],delete t[zr],delete t[Ni],delete t[Pp],delete t[Lp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function od(e){return e.tag===5||e.tag===3||e.tag===4}function Wo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||od(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Mi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Rl));else if(r!==4&&(e=e.child,e!==null))for(Mi(e,t,n),e=e.sibling;e!==null;)Mi(e,t,n),e=e.sibling}function Fi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Fi(e,t,n),e=e.sibling;e!==null;)Fi(e,t,n),e=e.sibling}var be=null,ot=!1;function bt(e,t,n){for(n=n.child;n!==null;)ud(e,t,n),n=n.sibling}function ud(e,t,n){if(gt&&typeof gt.onCommitFiberUnmount=="function")try{gt.onCommitFiberUnmount(Yl,n)}catch{}switch(n.tag){case 5:$e||Tn(n,t);case 6:var r=be,l=ot;be=null,bt(e,t,n),be=r,ot=l,be!==null&&(ot?(e=be,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):be.removeChild(n.stateNode));break;case 18:be!==null&&(ot?(e=be,n=n.stateNode,e.nodeType===8?Ms(e.parentNode,n):e.nodeType===1&&Ms(e,n),Er(e)):Ms(be,n.stateNode));break;case 4:r=be,l=ot,be=n.stateNode.containerInfo,ot=!0,bt(e,t,n),be=r,ot=l;break;case 0:case 11:case 14:case 15:if(!$e&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&Oi(n,t,a),l=l.next}while(l!==r)}bt(e,t,n);break;case 1:if(!$e&&(Tn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ye(n,t,o)}bt(e,t,n);break;case 21:bt(e,t,n);break;case 22:n.mode&1?($e=(r=$e)||n.memoizedState!==null,bt(e,t,n),$e=r):bt(e,t,n);break;default:bt(e,t,n)}}function Vo(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Kp),t.forEach(function(r){var l=rh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function it(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=we()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*qp(r/1960))-r,10e?16:e,$t===null)var r=!1;else{if(e=$t,$t=null,Ql=0,ne&6)throw Error(L(331));var l=ne;for(ne|=4,A=e.current;A!==null;){var i=A,a=i.child;if(A.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uwe()-za?rn(e,0):La|=n),Ve(e,t)}function vd(e,t){t===0&&(e.mode&1?(t=Yr,Yr<<=1,!(Yr&130023424)&&(Yr=4194304)):t=1);var n=Ae();e=_t(e,t),e!==null&&(Fr(e,t,n),Ve(e,n))}function nh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),vd(e,n)}function rh(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(L(314))}r!==null&&r.delete(t),vd(e,n)}var yd;yd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||He.current)Ue=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ue=!1,Wp(e,t,n);Ue=!!(e.flags&131072)}else Ue=!1,he&&t.flags&1048576&&jc(t,Ol,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;wl(e,t),e=t.pendingProps;var l=An(t,Ie.current);Dn(t,n),l=_a(null,t,r,e,l,n);var i=Ca();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,We(r)?(i=!0,$l(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,wa(t),l.updater=ss,t.stateNode=l,l._reactInternals=t,Pi(t,r,e,n),t=Ri(null,t,r,!0,i,n)):(t.tag=0,he&&i&&pa(t),Oe(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(wl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=sh(r),e=at(r,e),l){case 0:t=zi(null,t,r,e,n);break e;case 1:t=Fo(null,t,r,e,n);break e;case 11:t=Ao(null,t,r,e,n);break e;case 14:t=Mo(null,t,r,at(r.type,e),n);break e}throw Error(L(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),zi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),Fo(e,t,r,l,n);case 3:e:{if(td(t),e===null)throw Error(L(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Tc(e,t),Fl(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=Un(Error(L(423)),t),t=Bo(e,t,r,n,l);break e}else if(r!==l){l=Un(Error(L(424)),t),t=Bo(e,t,r,n,l);break e}else for(Xe=Mt(t.stateNode.containerInfo.firstChild),Je=t,he=!0,ut=null,n=Cc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Mn(),r===l){t=Ct(e,t,n);break e}Oe(e,t,r,n)}t=t.child}return t;case 5:return bc(t),e===null&&Ei(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,ji(r,l)?a=null:i!==null&&ji(r,i)&&(t.flags|=32),ed(e,t),Oe(e,t,a,n),t.child;case 6:return e===null&&Ei(t),null;case 13:return nd(e,t,n);case 4:return ka(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Fn(t,null,r,n):Oe(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),Ao(e,t,r,l,n);case 7:return Oe(e,t,t.pendingProps,n),t.child;case 8:return Oe(e,t,t.pendingProps.children,n),t.child;case 12:return Oe(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,ae(Al,r._currentValue),r._currentValue=a,i!==null)if(ft(i.value,a)){if(i.children===l.children&&!He.current){t=Ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=jt(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var g=c.pending;g===null?u.next=u:(u.next=g.next,g.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Ti(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(L(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Ti(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Oe(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Dn(t,n),l=lt(l),r=r(l),t.flags|=1,Oe(e,t,r,n),t.child;case 14:return r=t.type,l=at(r,t.pendingProps),l=at(r.type,l),Mo(e,t,r,l,n);case 15:return Yc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:at(r,l),wl(e,t),t.tag=1,We(r)?(e=!0,$l(t)):e=!1,Dn(t,n),Jc(t,r,l),Pi(t,r,l,n),Ri(null,t,r,!0,e,n);case 19:return rd(e,t,n);case 22:return Zc(e,t,n)}throw Error(L(156,t.tag))};function xd(e,t){return Qu(e,t)}function lh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function nt(e,t,n,r){return new lh(e,t,n,r)}function Ia(e){return e=e.prototype,!(!e||!e.isReactComponent)}function sh(e){if(typeof e=="function")return Ia(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ta)return 11;if(e===na)return 14}return 2}function Ht(e,t){var n=e.alternate;return n===null?(n=nt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Sl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")Ia(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case xn:return ln(n.children,l,i,t);case ea:a=8,l|=8;break;case ei:return e=nt(12,n,t,l|2),e.elementType=ei,e.lanes=i,e;case ti:return e=nt(13,n,t,l),e.elementType=ti,e.lanes=i,e;case ni:return e=nt(19,n,t,l),e.elementType=ni,e.lanes=i,e;case bu:return os(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Eu:a=10;break e;case Tu:a=9;break e;case ta:a=11;break e;case na:a=14;break e;case Pt:a=16,r=null;break e}throw Error(L(130,e==null?e:typeof e,""))}return t=nt(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function ln(e,t,n,r){return e=nt(7,e,r,t),e.lanes=n,e}function os(e,t,n,r){return e=nt(22,e,r,t),e.elementType=bu,e.lanes=n,e.stateNode={isHidden:!1},e}function Ks(e,t,n){return e=nt(6,e,null,t),e.lanes=n,e}function Xs(e,t,n){return t=nt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function ih(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ts(0),this.expirationTimes=Ts(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ts(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Oa(e,t,n,r,l,i,a,o,u){return e=new ih(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=nt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wa(i),e}function ah(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Sd)}catch(e){console.error(e)}}Sd(),Su.exports=Ge;var fh=Su.exports,Nd,Zo=fh;Nd=Zo.createRoot,Zo.hydrateRoot;async function _e(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ph(){return _e("/api/archives")}async function hh(e){return _e(`/api/archives/${e}/entries`)}async function mh(e,t,n){const r=new URLSearchParams;return t&&r.set("q",t),n&&r.set("tag",n),_e(`/api/archives/${e}/entries/search?${r}`)}async function Vi(e,t){return _e(`/api/archives/${e}/entries/${t}`)}function gh(e,t,n){return Promise.all(n.map(r=>_e(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function vh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function yh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function cl(e,t){return _e(`/api/archives/${e}/entries/${t}/tags`)}async function eu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function xh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function tu(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function wh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function kh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function jh(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function Sh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function Js(e){return _e(`/api/archives/${e}/runs`)}async function dl(e){return _e(`/api/archives/${e}/tags`)}async function Nh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||`HTTP ${i.status}`)}return i.json()}async function _h(e,t){return _e(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function _d(e,t){return _e(`/api/archives/${e}/capture_jobs/${t}`)}async function Ch(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Eh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Th(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function bh(){await fetch("/api/auth/logout",{method:"POST"})}async function Ph(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function Lh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function zh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Rh(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function Dh(){return _e("/api/auth/tokens")}async function $h(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function Ih(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function Ba(){return _e("/api/admin/instance-settings")}async function Nl(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Oh(){return _e("/api/admin/users")}async function Ah(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function Mh(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Fh(){return _e("/api/admin/roles")}async function Bh(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Cd(e){return _e(`/api/archives/${e}/collections`)}async function Uh(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}return l.json()}async function Hh(e,t){return _e(`/api/archives/${e}/collections/${t}`)}async function Ed(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Wh(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function Vh(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Qh(e,t){return _e(`/api/archives/${e}/entries/${t}/collections`)}async function nu(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function Kh(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function Xh(e){return _e(`/api/archives/${e}/blob-cleanup`)}async function Jh(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function qh(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function Gh(){return _e("/api/admin/cookie-rules")}async function Yh(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function Zh(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function em(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}const tm=window.fetch;window.fetch=async(...e)=>{var n;const t=await tm(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function nm({onLogin:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(null),[o,u]=f.useState(!1);async function c(g){g.preventDefault(),a(null),u(!0);try{const m=await Th(t,r);e(m)}catch(m){a(m.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:g=>n(g.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:g=>l(g.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function rm({onComplete:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(""),[o,u]=f.useState(null),[c,g]=f.useState(!1);async function m(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),g(!0);try{await Eh(t,r),e()}catch(y){u(y.message)}finally{g(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function lm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i}){const{currentUser:a,setCurrentUser:o}=f.useContext(ps)??{},[u,c]=f.useState(!1);async function g(){c(!0),await bh(),o(null),window.location.reload()}return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),a&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:a.display_name||a.username}),s.jsx("button",{className:"logout-btn",onClick:g,disabled:u,children:u?"Logging out…":"Log out"})]})]})}let Qi=1;function Td(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function ir(e=""){return{id:Qi++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null}}function ru(e){return e.some(t=>t.status==="submitting"||t.status==="running")}function sm({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l}){const i=f.useRef(null),a=f.useRef(!0),o=f.useRef(new Map),u=f.useRef(new Map),c=f.useRef(new Map),g=f.useRef(t);f.useEffect(()=>{g.current=t},[t]);const m=f.useRef(r),h=f.useRef(l);f.useEffect(()=>{m.current=r},[r]),f.useEffect(()=>{h.current=l},[l]);const[y,x]=f.useState(()=>{try{const N=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(N)&&N.length>0)return N.forEach(O=>{O.id>=Qi&&(Qi=O.id+1)}),N}catch{}return[ir()]});f.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(y))},[y]);const[k,j]=f.useState(!1),[p,d]=f.useState(null),[v,w]=f.useState(null),[_,b]=f.useState(!0),[C,S]=f.useState(!0);f.useEffect(()=>{Ba().then(N=>{w(N),b(N.cookie_ext_enabled??!0),S(N.modal_closer_enabled??!0)}).catch(()=>w({}))},[]);const $=p!==null?p:(v==null?void 0:v.ublock_enabled)??!0,[P,K]=f.useState(!1);f.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(N=>sessionStorage.removeItem(N)),x(N=>N.map(O=>O.status==="submitting"?{...O,status:"idle",error:null}:O)),y.forEach(N=>{N.status==="running"&&N.jobUid&&N.archiveId&&!o.current.has(N.jobUid)&&F(N.id,N.jobUid,N.locator,N.archiveId)})},[]),f.useEffect(()=>{const N=i.current;if(!N)return;const O=()=>{u.current.forEach(U=>clearTimeout(U)),u.current.clear(),n()};return N.addEventListener("close",O),()=>N.removeEventListener("close",O)},[n]),f.useEffect(()=>{const N=i.current;N&&(e?(!a.current&&!ru(y)&&x([ir()]),a.current=!1,N.open||N.showModal()):(u.current.forEach(O=>clearTimeout(O)),u.current.clear(),N.open&&N.close()))},[e]),f.useEffect(()=>()=>{o.current.forEach(N=>clearInterval(N)),u.current.forEach(N=>clearTimeout(N))},[]);function F(N,O,U,B,Q=null){if(o.current.has(O))return;const pe=setInterval(async()=>{try{const G=await _d(B,O);if(G.status==="completed"){clearInterval(o.current.get(O)),o.current.delete(O),x(Y=>Y.map(Z=>Z.id===N?{...Z,status:"completed"}:Z)),setTimeout(()=>{x(Y=>{const Z=Y.filter(ue=>ue.id!==N);return Z.length===0?[ir()]:Z})},1400),m.current();try{const Y=G.notes_json?JSON.parse(G.notes_json):null;if(Y!=null&&Y.ublock_skipped||Y!=null&&Y.cookie_ext_skipped){const ue=Y.ublock_skipped&&Y.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":Y.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";h.current(ue,U,"warning"),W(Q,"warning",U)}else Q||h.current(null,U,"success"),W(Q,"archived")}catch{Q||h.current(null,U,"success"),W(Q,"archived")}}else if(G.status==="failed"){clearInterval(o.current.get(O)),o.current.delete(O);const Y=G.error_text||"Capture failed.";x(Z=>Z.map(ue=>ue.id===N?{...ue,status:"failed",error:Y}:ue)),h.current(Y,U),W(Q,"failed",U)}}catch(G){clearInterval(o.current.get(O)),o.current.delete(O);const Y=G.message||"Network error";x(Z=>Z.map(ue=>ue.id===N?{...ue,status:"failed",error:Y}:ue)),h.current(Y,U),W(Q,"failed",U)}},500);o.current.set(O,pe)}function W(N,O,U=null){if(!N)return;const B=c.current.get(N);if(!B||(O==="archived"||O==="warning"?(B.archived++,O==="warning"&&(B.warnings++,U&&B.warningLocators.push(U))):(B.failed++,U&&B.failedLocators.push(U)),B.archived+B.failed0?`${Q} archived (${pe} with warnings)`:`${Q} archived`;ue=G>0?`${xe}, ${G} failed`:xe}const D=Q===0?"error":G>0||pe>0?"warning":"success",X=[];Y.length>0&&X.push(`Failed: -${Y.map(xe=>` ${xe}`).join(` -`)}`),Z.length>0&&X.push(`With warnings: -${Z.map(xe=>` ${xe}`).join(` -`)}`);const Ce=X.length>0?X.join(` -`):null;h.current(Ce,null,D,ue)}async function te(N,O=null){if(!N.locator.trim())return;const U=t,B=N.locator.trim(),Q=N.quality||"best";x(pe=>pe.map(G=>G.id===N.id?{...G,status:"submitting",error:null}:G));try{const G=await Nh(U,B,Q,{ublock_enabled:$,reader_mode:P,cookie_ext_enabled:_,modal_closer_enabled:C});x(Y=>Y.map(Z=>Z.id===N.id?{...Z,status:"running",jobUid:G.job_uid,archiveId:U}:Z)),F(N.id,G.job_uid,B,U,O)}catch(pe){const G=pe.message||"Submission failed.";x(Y=>Y.map(Z=>Z.id===N.id?{...Z,status:"failed",error:G}:Z)),h.current(G,B),W(O,"failed",B)}}function oe(){var U,B;const N=y.filter(Q=>Q.status==="idle"&&Q.locator.trim());if(N.length===0)return;const O=N.length>1?((U=crypto.randomUUID)==null?void 0:U.call(crypto))??`batch-${Date.now()}`:null;O&&c.current.set(O,{total:N.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]}),N.forEach(Q=>te(Q,O)),(B=i.current)==null||B.close()}function fe(){x(N=>[...N,ir()])}function le(N){clearTimeout(u.current.get(N)),u.current.delete(N),x(O=>{const U=O.filter(B=>B.id!==N);return U.length===0?[ir()]:U})}function R(N){x(O=>O.map(U=>U.id===N?{...U,status:"idle",error:null}:U))}function T(N,O){if(clearTimeout(u.current.get(N)),x(B=>B.map(Q=>Q.id===N?{...Q,locator:O,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best"}:Q)),!Td(O))return;const U=setTimeout(async()=>{u.current.delete(N),x(B=>B.map(Q=>Q.id===N?{...Q,probeState:"probing"}:Q));try{const B=await _h(g.current,O.trim());x(Q=>Q.map(pe=>{if(pe.id!==N||pe.locator!==O)return pe;const G=B.qualities??[],Y=B.has_audio??!1,Z=G.length===0&&Y?"audio":"best";return{...pe,probeState:"done",probeQualities:G,probeHasAudio:Y,quality:Z}}))}catch{x(B=>B.map(Q=>Q.id===N?{...Q,probeState:"idle",probeQualities:null}:Q))}},600);u.current.set(N,U)}function M(N,O){x(U=>U.map(B=>B.id===N?{...B,quality:O}:B))}const q=y.filter(N=>N.status==="idle"&&N.locator.trim()).length,H=ru(y);return s.jsx("dialog",{ref:i,className:"capture-dialog",children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:y.map((N,O)=>s.jsx(im,{item:N,autoFocus:O===y.length-1&&N.status==="idle",onLocatorChange:U=>T(N.id,U),onQualityChange:U=>M(N.id,U),onRemove:()=>le(N.id),onReset:()=>R(N.id),onSubmit:oe},N.id))}),s.jsxs("button",{type:"button",className:"capture-add-row",onClick:fe,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add another"]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>j(N=>!N),"aria-expanded":k,children:[s.jsx("svg",{className:`capture-chevron${k?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),k&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":$,className:`ext-toggle ext-toggle--sm${$?" ext-toggle--on":""}`,onClick:()=>d(N=>N===null?!$:!N),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(v!=null&&v.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":_,className:`ext-toggle ext-toggle--sm${_?" ext-toggle--on":""}`,onClick:()=>b(N=>!N),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":P,className:`ext-toggle ext-toggle--sm${P?" ext-toggle--on":""}`,onClick:()=>K(N=>!N),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":C,className:`ext-toggle ext-toggle--sm${C?" ext-toggle--on":""}`,onClick:()=>S(N=>!N),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:oe,disabled:q===0,children:q>1?`Archive ${q}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},children:H?"Close":"Cancel"})]})]})})}function im({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onReset:i,onSubmit:a}){const o=f.useRef(null),u=e.status==="submitting"||e.status==="running";f.useEffect(()=>{var g;t&&e.status==="idle"&&((g=o.current)==null||g.focus())},[t]);const c=(()=>{if(e.status==="completed"||u||!Td(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const g=e.probeQualities??[],m=e.probeHasAudio??!1;return g.length===0&&!m?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):g.length===0&&m?s.jsx("select",{className:"capture-quality",value:"audio",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),g.map(h=>s.jsx("option",{value:h,children:h},h)),m&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})();return s.jsxs("div",{className:`capture-row capture-row--${e.status}`,children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx(am,{status:e.status}),s.jsx("input",{ref:o,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"&&a()},disabled:u||e.status==="completed",autoComplete:"off",spellCheck:!1}),c,e.status==="failed"&&s.jsx("button",{type:"button",className:"capture-row-action",onClick:i,title:"Retry",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M13 2.5A7 7 0 1 1 6.5 1"}),s.jsx("polyline",{points:"6.5 1 4 3.5 6.5 6"})]})}),!u&&e.status!=="completed"&&e.status!=="failed"&&s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error})]})}function am({status:e}){return e==="submitting"||e==="running"?s.jsx("span",{className:"cap-dot cap-dot--running","aria-label":"Running",children:s.jsx("span",{className:"cap-spinner"})}):e==="completed"?s.jsx("span",{className:"cap-dot cap-dot--ok","aria-label":"Done",children:"✓"}):e==="failed"?s.jsx("span",{className:"cap-dot cap-dot--err","aria-label":"Failed",children:"✕"}):s.jsx("span",{className:"cap-dot cap-dot--idle","aria-hidden":"true"})}function Jl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function nn(e){return om(e)??""}function bd(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const lu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Ua(e){return lu[e]??lu.other}function Pd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function um({entry:e,archiveId:t,isSelected:n,isMultiSelected:r,onRowClick:l}){const[i,a]=f.useState(!1),u=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!i?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>a(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Ua(e.source_kind)}}),c=n||r;function g(m){m.stopPropagation(),l(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}return s.jsxs("div",{className:[n&&"is-selected",r&&"is-multi-selected"].filter(Boolean).join(" ")||void 0,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:m=>{m.shiftKey&&m.preventDefault()},onClick:m=>l(e,m),onKeyDown:m=>{m.key==="Enter"&&l(e,m)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${c?" is-checked":""}`,"aria-pressed":c,"aria-label":c?"Deselect entry":"Select entry",onClick:g,onKeyDown:m=>m.stopPropagation()})}),s.jsx("div",{className:"col-added",children:bd(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:u}),s.jsx("span",{className:"entry-title",children:nn(e.title)||nn(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:nn(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:Jl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${Jl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:nn(e.original_url)})]})}function cm({entries:e,selectedUids:t,onRowClick:n,archiveId:r}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsx("div",{id:"entries-body",children:e.map(l=>s.jsx(um,{entry:l,archiveId:r,isSelected:t.size===1&&t.has(l.entry_uid),isMultiSelected:t.size>=2&&t.has(l.entry_uid),onRowClick:n},l.entry_uid))})]})})}function dm(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function fm({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function pm({runs:e}){const[t,n]=f.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:dm(l.started_at)}),s.jsxs("td",{children:[s.jsx(fm,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const hm=4;function mm({archives:e}){const{currentUser:t}=f.useContext(ps)??{},n=t&&(t.role_bits&hm)!==0,[r,l]=f.useState("users"),[i,a]=f.useState([]),[o,u]=f.useState([]),[c,g]=f.useState(!1),[m,h]=f.useState(null),[y,x]=f.useState(""),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(null),[_,b]=f.useState(!1),[C,S]=f.useState(""),[$,P]=f.useState(""),[K,F]=f.useState(null),[W,te]=f.useState(!1),oe=f.useCallback(async()=>{if(n){g(!0),h(null);try{const[T,M]=await Promise.all([Oh(),Fh()]);a(T),u(M)}catch(T){h(T.message)}finally{g(!1)}}},[n]);f.useEffect(()=>{oe()},[oe]);async function fe(T){const M=T.status==="active"?"disabled":"active";try{await Mh(T.user_uid,M),a(q=>q.map(H=>H.user_uid===T.user_uid?{...H,status:M}:H))}catch(q){h(q.message)}}async function le(T){if(T.preventDefault(),!y.trim()||!k){w("Username and password required");return}b(!0),w(null);try{await Ah(y.trim(),k,p.trim()||void 0),x(""),j(""),d(""),await oe()}catch(M){w(M.message)}finally{b(!1)}}async function R(T){if(T.preventDefault(),!C.trim()||!$.trim()){F("Slug and name required");return}te(!0),F(null);try{await Bh(C.trim(),$.trim()),S(""),P(""),await oe()}catch(M){F(M.message)}finally{te(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(T=>s.jsxs("tr",{className:T.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:T.username}),s.jsx("td",{className:"muted",children:T.email||"—"}),s.jsx("td",{children:T.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${T.status}`,children:T.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>fe(T),children:T.status==="active"?"Ban":"Unban"})})]},T.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:le,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:y,onChange:T=>x(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:k,onChange:T=>j(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:T=>d(T.target.value)}),v&&s.jsx("div",{className:"form-msg form-msg--err",children:v}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(T=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:T.slug})}),s.jsx("td",{children:T.name}),s.jsx("td",{children:T.level}),s.jsx("td",{children:T.bit_position}),s.jsx("td",{children:T.is_builtin?"✓":""})]},T.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:R,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:C,onChange:T=>S(T.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:$,onChange:T=>P(T.target.value),required:!0}),K&&s.jsx("div",{className:"form-msg form-msg--err",children:K}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:W,children:W?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(T=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:T.label}),s.jsx("div",{className:"muted",children:T.archive_path})]},T.id))})]})}function Ld({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(Ld,{node:r,onPick:t},r.tag.tag_uid))})})]})}function su({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){f.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(Ld,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function zd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=f.useState(""),a=f.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await jh(t,c),n()}catch(g){alert(g.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function Rd({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:g,pendingCreateParentUid:m,onCreateDone:h,onCreateCancel:y}){var K;const x=n===e.tag.full_path,[k,j]=f.useState(!1),[p,d]=f.useState(""),v=f.useRef(!1);function w(){if(k)return;if(c){g(e);return}const F=x?null:e.tag.full_path;r(F),l("archive")}function _(F){F.stopPropagation(),!c&&(d(e.tag.slug),j(!0))}async function b(){const F=p.trim();if(!F||F===e.tag.slug){j(!1);return}try{const W=await wh(t,e.tag.tag_uid,F);i(e.tag.full_path,W.full_path),o()}catch{}finally{j(!1)}}async function C(F){var te;F.stopPropagation();const W=((te=e.children)==null?void 0:te.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(W))try{await kh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const S={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:g,pendingCreateParentUid:m,onCreateDone:h,onCreateCancel:y},$=m===e.tag.tag_uid,P=((K=e.children)==null?void 0:K.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${c?" tag-node-row--move-select":""}`,children:[k?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:F=>d(F.target.value),onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur(),F.key==="Escape"&&(v.current=!0,F.currentTarget.blur())},onBlur:()=>{v.current?(v.current=!1,j(!1)):b()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${c?" tag-node-btn--move-select":""}`,title:c?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:w,onDoubleClick:c?void 0:_,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!c&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:F=>{F.stopPropagation(),_(F)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!k&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:C,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(P||$)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(F=>s.jsx(Rd,{node:F,...S},F.tag.tag_uid)),$&&s.jsx("li",{children:s.jsx(zd,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:y})})]})})]})}function gm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,g]=f.useState(null),[m,h]=f.useState(null);function y(){g("select-source"),h(null)}function x(){g(null),h(null)}f.useEffect(()=>{if(c!=="select-source")return;function W(te){te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),x())}return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[c]);function k(W){h(W),g("select-dest")}async function j(W){const te=m.tag.full_path,oe=m.tag.tag_uid,fe=(W==null?void 0:W.tag_uid)??null;x();try{const le=await Sh(e,oe,fe);i(te,le.full_path),o()}catch(le){alert(le.message||"Move failed")}}const[p,d]=f.useState(null),[v,w]=f.useState(void 0);function _(){d("select-parent"),w(void 0)}function b(){d(null),w(void 0)}function C(W){w(W??null),d("input")}function S(){d(null),w(void 0),o()}const $=c==="select-source",P=p==="input"?v?v.tag_uid:"__root__":void 0,K={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:$,onMoveSourceSelect:k,pendingCreateParentUid:P,onCreateDone:S,onCreateCancel:b},F=P==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:$?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:_,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:y,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!F?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(W=>s.jsx(Rd,{node:W,...K},W.tag.tag_uid)),F&&s.jsx("li",{children:s.jsx(zd,{parentPath:null,archiveId:e,onDone:S,onCancel:b})})]})]}),p==="select-parent"&&s.jsx(su,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:C,onCancel:b}),c==="select-dest"&&m&&s.jsx(su,{title:`Move "${m.tag.slug}" under…`,tagNodes:t,excludeUid:m.tag.tag_uid,onPick:j,onCancel:x})]})}const fr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],vm=e=>{var t;return((t=fr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function ym({archiveId:e}){const[t,n]=f.useState([]),[r,l]=f.useState(!1),[i,a]=f.useState(null),[o,u]=f.useState(null),[c,g]=f.useState(null),[m,h]=f.useState(!1),[y,x]=f.useState(null),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(2),[_,b]=f.useState(!1),[C,S]=f.useState(null),[$,P]=f.useState(""),[K,F]=f.useState(2),[W,te]=f.useState(!1),[oe,fe]=f.useState(null),[le,R]=f.useState(!1),[T,M]=f.useState(""),q=f.useRef(null),H=t.find(D=>D.collection_uid===o)??null,N=(H==null?void 0:H.slug)==="_default_",O=f.useCallback(async()=>{if(e){l(!0),a(null);try{const D=await Cd(e);n(D)}catch(D){a(D.message)}finally{l(!1)}}},[e]),U=f.useCallback(async D=>{if(!D){g(null);return}h(!0),x(null);try{const X=await Hh(e,D);g(X)}catch(X){x(X.message)}finally{h(!1)}},[e]);f.useEffect(()=>{O()},[O]),f.useEffect(()=>{U(o)},[o,U]),f.useEffect(()=>{le&&q.current&&q.current.focus()},[le]);async function B(D){D.preventDefault();const X=k.trim(),Ce=p.trim();if(!(!X||!Ce)){b(!0),S(null);try{const xe=await Uh(e,X,Ce,v);j(""),d(""),w(2),await O(),u(xe.collection_uid)}catch(xe){S(xe.message)}finally{b(!1)}}}async function Q(){const D=T.trim();if(!D||!H){R(!1);return}try{await nu(e,H.collection_uid,{name:D}),await O(),g(X=>X&&{...X,name:D})}catch(X){a(X.message)}finally{R(!1)}}async function pe(D){if(H)try{await nu(e,H.collection_uid,{default_visibility_bits:D}),await O(),g(X=>X&&{...X,default_visibility_bits:D})}catch(X){a(X.message)}}async function G(){if(H&&window.confirm(`Delete collection "${H.name}"? Entries will not be deleted.`))try{await Kh(e,H.collection_uid),u(null),g(null),await O()}catch(D){a(D.message)}}async function Y(D){D.preventDefault();const X=$.trim();if(!(!X||!H)){te(!0),fe(null);try{await Ed(e,H.collection_uid,X,K),P(""),await U(H.collection_uid)}catch(Ce){fe(Ce.message)}finally{te(!1)}}}async function Z(D){if(H)try{await Wh(e,H.collection_uid,D),await U(H.collection_uid)}catch(X){x(X.message)}}async function ue(D,X){if(H)try{await Vh(e,H.collection_uid,D,X),g(Ce=>Ce&&{...Ce,entries:Ce.entries.map(xe=>xe.entry_uid===D?{...xe,collection_visibility_bits:X}:xe)})}catch(Ce){x(Ce.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(D=>s.jsxs("button",{className:`coll-sidebar-row${o===D.collection_uid?" is-active":""}`,onClick:()=>u(D.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:D.name}),s.jsx("span",{className:"coll-row-meta",children:vm(D.default_visibility_bits)})]},D.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),H?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[le?s.jsx("input",{ref:q,className:"coll-rename-input",value:T,onChange:D=>M(D.target.value),onBlur:Q,onKeyDown:D=>{D.key==="Enter"&&Q(),D.key==="Escape"&&R(!1)}}):s.jsxs("h3",{className:`coll-detail-name${N?"":" coll-detail-name--editable"}`,title:N?void 0:"Click to rename",onClick:()=>{N||(M(H.name),R(!0))},children:[(c==null?void 0:c.name)??H.name,!N&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!N&&s.jsx("button",{className:"coll-delete-btn",onClick:G,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??H.default_visibility_bits,onChange:D=>pe(Number(D.target.value)),disabled:N,children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),m&&s.jsx("div",{className:"muted",children:"Loading…"}),y&&s.jsx("div",{className:"collections-error",children:y}),!m&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(D=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:D.title||D.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:D.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:D.collection_visibility_bits,onChange:X=>ue(D.entry_uid,Number(X.target.value)),children:fr.map(X=>s.jsx("option",{value:X.value,children:X.label},X.value))}),!N&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>Z(D.entry_uid),title:"Remove from collection",children:"×"})]})]},D.entry_uid))}))]}),!N&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:Y,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:$,onChange:D=>P(D.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:K,onChange:D=>F(Number(D.target.value)),children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:W,children:W?"…":"Add"})]}),oe&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:oe})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:B,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:k,onChange:D=>{j(D.target.value),p||d(D.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:D=>d(D.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:v,onChange:D=>w(Number(D.target.value)),children:fr.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),C&&s.jsx("div",{className:"collections-error",children:C}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const xm=4;function wm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=f.useContext(ps)??{},i=r&&(r.role_bits&xm)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(km,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(jm,{}),e==="instance"&&i&&s.jsx(Sm,{}),e==="cookies"&&i&&s.jsx(_m,{}),e==="extensions"&&i&&s.jsx(Cm,{}),e==="storage"&&i&&s.jsx(Nm,{archiveId:n})]})}function km({currentUser:e,setCurrentUser:t}){const[n,r]=f.useState((e==null?void 0:e.display_name)??""),[l,i]=f.useState(!1),[a,o]=f.useState(null),[u,c]=f.useState(""),[g,m]=f.useState(""),[h,y]=f.useState(""),[x,k]=f.useState(!1),[j,p]=f.useState(null);async function d(w){w.preventDefault(),i(!0),o(null);try{await Lh(n),t(_=>({..._,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(_){o({ok:!1,text:_.message})}finally{i(!1)}}async function v(w){if(w.preventDefault(),g!==h){p({ok:!1,text:"Passwords do not match."});return}k(!0),p(null);try{await Rh(u,g),c(""),m(""),y(""),p({ok:!0,text:"Password changed."})}catch(_){p({ok:!1,text:_.message})}finally{k(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:d,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const _=w.target.checked;try{await zh({humanize_slugs:_}),t(b=>({...b,humanize_slugs:_}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:g,onChange:w=>m(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:w=>y(w.target.value),required:!0})]}),j&&s.jsx("div",{className:`form-msg form-msg--${j.ok?"ok":"err"}`,children:j.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function jm(){const[e,t]=f.useState([]),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(""),[u,c]=f.useState(!1),[g,m]=f.useState(null),h=f.useCallback(async()=>{r(!0),i(null);try{t(await Dh())}catch(k){i(k.message)}finally{r(!1)}},[]);f.useEffect(()=>{h()},[h]);async function y(k){if(k.preventDefault(),!!a.trim()){c(!0);try{const j=await $h(a.trim());m(j),o(""),h()}catch(j){i(j.message)}finally{c(!1)}}}async function x(k){try{await Ih(k),t(j=>j.filter(p=>p.token_uid!==k))}catch(j){i(j.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),g&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:g.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>m(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:y,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:k=>o(k.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(k=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:k.name}),s.jsxs("div",{className:"muted",children:["Created ",k.created_at.slice(0,10),k.last_used_at&&` · Last used ${k.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(k.token_uid),children:"Revoke"})]},k.token_uid))]})]})})}function Sm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(!1),[u,c]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(m){i(m.message)}finally{r(!1)}})()},[]);async function g(m){m.preventDefault(),o(!0),c(null);try{await Nl(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:g,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([m,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[m],onChange:y=>t(x=>({...x,[m]:y.target.checked}))}),h]},m)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:m=>t(h=>({...h,default_entry_visibility:Number(m.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function qs(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function Nm({archiveId:e}){const[t,n]=f.useState("idle"),[r,l]=f.useState(null),[i,a]=f.useState(null),[o,u]=f.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function g(){n("scanning"),u(null),l(null);try{const y=await Xh(e);l(y),n("scanned")}catch(y){u(y.message),n("error")}}async function m(){n("deleting"),u(null);try{const y=await Jh(e);a(y),n("done")}catch(y){u(y.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:g,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:qs(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:m,children:["Delete (",qs(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:qs(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function _m(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState("global"),[u,c]=f.useState(""),[g,m]=f.useState("{}"),[h,y]=f.useState(null),[x,k]=f.useState(!1),[j,p]=f.useState({});f.useEffect(()=>{d()},[]);async function d(){r(!0),i(null);try{t(await Gh())}catch(S){i(S.message)}finally{r(!1)}}async function v(S){S.preventDefault();try{JSON.parse(g)}catch{y({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}k(!0),y(null);try{await Yh(a==="global"?null:u.trim(),a,g),c(""),m("{}"),o("global"),y({ok:!0,text:"Rule added."}),await d()}catch($){y({ok:!1,text:$.message})}finally{k(!1)}}async function w(S){try{await em(S),await d()}catch($){i($.message)}}function _(S){p($=>({...$,[S.rule_uid]:{cookiesInput:S.cookies_json,saving:!1,msg:null}}))}function b(S){p($=>{const P={...$};return delete P[S],P})}async function C(S){const $=j[S.rule_uid];try{JSON.parse($.cookiesInput)}catch{p(P=>({...P,[S.rule_uid]:{...P[S.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(P=>({...P,[S.rule_uid]:{...P[S.rule_uid],saving:!0,msg:null}}));try{await Zh(S.rule_uid,{cookies_json:$.cookiesInput}),b(S.rule_uid),await d()}catch(P){p(K=>({...K,[S.rule_uid]:{...K[S.rule_uid],saving:!1,msg:{ok:!1,text:P.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(S=>{const $=j[S.rule_uid],P=S.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[S.pattern_kind,":"]})," ",s.jsx("code",{children:S.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:P}),s.jsx("td",{children:$?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:$.cookiesInput,onChange:K=>p(F=>({...F,[S.rule_uid]:{...F[S.rule_uid],cookiesInput:K.target.value}}))}),$.msg&&s.jsx("div",{className:`form-msg form-msg--${$.msg.ok?"ok":"err"}`,children:$.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:$.saving,onClick:()=>C(S),children:$.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>b(S.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:S.cookies_json})}),s.jsx("td",{children:!$&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>_(S),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(S.rule_uid),children:"Del"})]})})]},S.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:S=>o(S.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:S=>c(S.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:g,onChange:S=>m(S.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function Cm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(!1),[a,o]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(j){o({ok:!1,text:j.message})}finally{r(!1)}})()},[]);async function u(j){i(!0),o(null);try{await Nl({ublock_enabled:j}),t(p=>({...p,ublock_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(j){i(!0),o(null);try{await Nl({cookie_ext_enabled:j}),t(p=>({...p,cookie_ext_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function g(j){i(!0),o(null);try{await Nl({modal_closer_enabled:j}),t(p=>({...p,modal_closer_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const m=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,y=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,k=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!m&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!y&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":k,className:`ext-toggle${k?" ext-toggle--on":""}`,onClick:()=>g(!k),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const iu={0:"Private",1:"Public",2:"Users only",3:"Public"},Em=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Tm({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:g,humanizeTags:m,onDetailRefresh:h,onOpenPreview:y,onPlay:x}){var Tt;const[k,j]=f.useState([]),[p,d]=f.useState(""),[v,w]=f.useState([]),[_,b]=f.useState(""),C=f.useRef(0),S=f.useRef(!1),[$,P]=f.useState(!1),[K,F]=f.useState(""),[W,te]=f.useState("idle"),[oe,fe]=f.useState(""),le=f.useRef(null),[R,T]=f.useState(!1);f.useEffect(()=>{T(!1)},[(Tt=l==null?void 0:l.summary)==null?void 0:Tt.entry_uid]);const M=(n==null?void 0:n.size)>=2,[q,H]=f.useState(""),[N,O]=f.useState("idle"),[U,B]=f.useState(""),[Q,pe]=f.useState([]),[G,Y]=f.useState(""),[Z,ue]=f.useState("idle"),[D,X]=f.useState(""),[Ce,xe]=f.useState("idle");f.useEffect(()=>{const I=++C.current;if(le.current&&(clearInterval(le.current),le.current=null),te("idle"),fe(""),!t||!e){j([]),w([]);return}P(!1),F(""),S.current=!1,j([]),Promise.all([cl(e,t.entry_uid),Qh(e,t.entry_uid)]).then(([se,Qe])=>{I===C.current&&(j(se),w(Qe))}).catch(()=>{})},[t,e]),f.useEffect(()=>()=>{clearInterval(le.current)},[]),f.useEffect(()=>{if(!M||!e){pe([]);return}Cd(e).then(pe).catch(()=>pe([]))},[M,e]),f.useEffect(()=>{H(""),O("idle"),B(""),Y(""),ue("idle"),X(""),xe("idle")},[n]);async function hs(){const I=n.size;if(!window.confirm(`Delete ${I} entr${I===1?"y":"ies"}? This cannot be undone.`))return;xe("running");const se=new Set;for(const Qe of n)try{await tu(e,Qe),se.add(Qe)}catch{}xe("idle"),g==null||g(se)}async function Kn(){const I=q.trim();if(I){O("running"),B("");try{for(const se of n)await eu(e,se,I);H(""),O("done"),o==null||o(),setTimeout(()=>O("idle"),1800)}catch(se){B(se.message),O("error")}}}async function ms(){if(!G)return;ue("running"),X("");const I=[];for(const se of n)try{await Ed(e,G,se)}catch{I.push(se)}I.length>0?(X(`Failed for ${I.length} entr${I.length===1?"y":"ies"}.`),ue("error")):(ue("done"),setTimeout(()=>ue("idle"),1800))}async function gs(){const I=K.trim()||null;try{await yh(e,t.entry_uid,I),u==null||u(t.entry_uid,I)}catch{}finally{P(!1)}}async function Wr(){const I=p.trim();if(!(!I||!t))try{await eu(e,t.entry_uid,I),d(""),b("");const se=await cl(e,t.entry_uid);j(se),o()}catch(se){b(se.message)}}async function vs(I){try{await xh(e,t.entry_uid,I);const se=await cl(e,t.entry_uid);j(se),o()}catch{}}async function ys(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await tu(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function xs(){if(!t||!e||W==="running")return;const I=C.current,se=t.entry_uid;te("running"),fe("");try{const{job_uid:Qe}=await qh(e,se);if(C.current!==I)return;le.current=setInterval(async()=>{try{const Jt=await _d(e,Qe);if(Jt.status==="completed"){if(clearInterval(le.current),le.current=null,C.current!==I)return;te("done");const Jn=await cl(e,se);if(C.current!==I)return;j(Jn),h==null||h()}else if(Jt.status==="failed"){if(clearInterval(le.current),le.current=null,C.current!==I)return;te("error"),fe(Jt.error_text||"Re-archive failed.")}}catch{if(clearInterval(le.current),le.current=null,C.current!==I)return;te("error"),fe("Network error while polling.")}},500)}catch(Qe){if(C.current!==I)return;te("error"),fe(Qe.message||"Failed to start re-archive.")}}const ws=l?[["Added",bd(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",iu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],ks=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),js=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),pn=l?l.artifacts.findIndex(I=>I.artifact_role==="primary_media"):-1,hn=pn>=0?l.artifacts[pn]:null,Vr=hn?hn.relpath.split(".").pop().toLowerCase():"",Qr=hn&&ks.has(Vr),mn=pn>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${pn}`:null,Xn=l&&!Qr&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||hn&&js.has(Vr));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),M?s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),U&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:U}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:q,onChange:I=>H(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Kn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Kn,disabled:N==="running"||!q.trim(),children:N==="running"?"…":N==="done"?"✓":"Add"})]})]}),Q.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:G,onChange:I=>Y(I.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Q.map(I=>s.jsx("option",{value:I.collection_uid,children:I.name},I.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:ms,disabled:!G||Z==="running",children:Z==="running"?"…":Z==="done"?"✓":Z==="error"?"!":"Add"})]}),D&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:D})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:hs,disabled:Ce==="running",children:Ce==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[$?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:K,onChange:I=>F(I.target.value),onKeyDown:I=>{I.key==="Enter"&&I.currentTarget.blur(),I.key==="Escape"&&(S.current=!0,I.currentTarget.blur())},onBlur:()=>{S.current?P(!1):gs(),S.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{F(l.summary.title??""),P(!0)},children:[nn(l.summary.title)||nn(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Ua(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Em,{})})]}),Qr&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(mn,t),children:"▶ Play"}),Xn&&y&&s.jsx("button",{className:"rail-preview-btn",onClick:y,children:"Preview"}),s.jsx("div",{className:"meta-list",children:ws.filter(([,I])=>I!=null&&I!=="").map(([I,se])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:I}),s.jsx("span",{className:`meta-v${I==="Root"?" mono":""}`,children:nn(se)})]},I))}),l.artifacts.length>0&&(()=>{const I=l.artifacts.map((z,V)=>({...z,_idx:V})),se=I.filter(z=>z.artifact_role==="font"),Qe=I.filter(z=>z.artifact_role!=="font"),Jt=se.reduce((z,V)=>z+(V.byte_size||0),0),Jn=l.summary.entry_uid,E=z=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Jn}/artifacts/${z._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:z.artifact_role==="font"?z.relpath.split("/").pop():z.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:z.byte_size!=null?Jl(z.byte_size):"—"})]})},z._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[Qe.map(E),se.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":R,onClick:()=>T(z=>!z),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${R?" open":""}`,children:"›"}),` fonts (${se.length})`]}),s.jsx("span",{className:"artifact-size",children:Jl(Jt)})]}),R&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:se.map(E)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!M&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),k.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:k.map(I=>s.jsxs("span",{className:"tag-pill",title:I.full_path,children:[m?Pd(I.full_path):I.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${I.full_path}`,onClick:()=>vs(I.tag_uid),children:"×"})]},I.tag_uid))}),_&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:_}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:p,onChange:I=>d(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Wr()}}),s.jsx("button",{className:"tag-add-btn",onClick:Wr,children:"Add"})]})]}),v.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),v.map(I=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:I.collection_uid}),s.jsx("span",{className:"vis-badge",children:iu[I.visibility_bits]??`bits:${I.visibility_bits}`})]},I.collection_uid))]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:xs,disabled:W==="running",children:W==="running"?"Re-archiving…":"Re-archive"}),W==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),W==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:oe})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:ys,children:"Delete entry"})})]})]})}function bm({src:e}){const t=f.useRef(null);return f.useEffect(()=>{t.current&&t.current.load()},[e]),s.jsx("div",{className:"preview-video-wrap",style:{background:"#111",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",minHeight:"240px"},children:e?s.jsxs("video",{ref:t,controls:!0,autoPlay:!1,style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:e}),"Your browser does not support the video element."]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function au({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function Pm({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function Dd(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function ou(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const J={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},je={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Gs={article:{background:je.bg,color:je.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:je.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:je.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:je.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:je.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${je.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${je.border}`,padding:"2px 14px",margin:"14px 0",color:je.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${je.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${je.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:je.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:je.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:je.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:je.accent,textDecoration:"none"}};function Lm(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function In(e,t,n){return e&&n[e]?n[e]:t||null}function $d(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function Ha(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function Id(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=Ha(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function Od(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=Ha(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const uu=/https?:\/\/[^\s<>"'\])]+/g,zm=/[.,;:!?)()]+$/;function ql(e,t){const n=[];let r=0,l;for(uu.lastIndex=0;(l=uu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(zm,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rId(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>Od(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return ql(ou(e),J.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,g])=>c<=o&&g>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const g=e.slice(o,c),m=r.filter(x=>x.s<=o&&x.e>=c),h=m.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:J.link,children:h.display||g},u);const y=m.find(x=>x.kind==="mention");return y?s.jsx("a",{href:`https://x.com/${y.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:J.link,children:g},u):s.jsx("span",{children:ql(ou(g),J.link)},u)}).filter(o=>o!==null)}function Dm(e,t,n,r,l=J){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=Id(u,e);c&&i.push(c)}for(const u of r){const c=Od(u,e);c&&i.push(c)}if(i.length===0)return ql(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const g=o[c+1],m=i.filter(j=>j.s<=u&&j.e>=g),h=e.slice(u,g);let y;if(h.includes(` -`)){const j=h.split(` -`);y=j.flatMap((p,d)=>dj.kind==="style"&&j.style==="Code")&&(y=s.jsx("code",{style:l.iCode,children:y})),m.some(j=>j.kind==="style"&&j.style==="Bold")&&(y=s.jsx("strong",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Italic")&&(y=s.jsx("em",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Underline")&&(y=s.jsx("u",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Strikethrough")&&(y=s.jsx("s",{children:y}));const x=m.find(j=>j.kind==="url");if(x){const j=/^https?:\/\/t\.co\//i.test(y);y=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:j?x.display:y})}const k=m.find(j=>j.kind==="mention");return k&&(y=s.jsx("a",{href:`https://x.com/${k.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:y})),s.jsx("span",{children:typeof y=="string"?ql(y,l.link):y},c)})}function $m(e,t,n){const r=(n==null?void 0:n.st)||J,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=In(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var g;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(g=n==null?void 0:n.onImgClick)==null||g.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx($d,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function Ys(e,t,n,r){const l=(r==null?void 0:r.st)||J,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=Dm(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const g=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return g?s.jsxs("a",{href:`https://x.com/i/status/${g[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx($d,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:$m(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function Im(e,t,n){const r=(n==null?void 0:n.st)||J,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Gs:J,u=e.cover_media||{},c=e.author||t||{},g=e.first_published_at_secs?Dd(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",g].filter(Boolean).join(" · "),y=In(u.local_path,u.url,n),x=In(c.avatar_local_path,c.avatar_url,n),k=s.jsxs(s.Fragment,{children:[i&&s.jsx(Ad,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),y&&s.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:j=>{!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),a(y))},children:s.jsx("img",{src:y,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Im(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:Gs.article,children:s.jsx("div",{style:Gs.articleInner,children:k})}):s.jsx("div",{style:J.article,children:k})}function Am({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:J.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function Ad({items:e,startIndex:t,onClose:n}){const[r,l]=f.useState(t);f.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:J.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:J.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:J.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:J.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:J.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:J.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:J.lightboxImg}),e.length>1&&s.jsxs("div",{style:J.lightboxNav,children:[s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function cu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var d,v;const[l,i]=f.useState(null),a=e.author||{},o=e.created_at_secs?Dd(e.created_at_secs):"",u=e.entities||{},c=In(a.avatar_local_path,a.avatar_url,r),g=t&&!n,m=e.is_quote_status===!0,h=t?J.tweetRowThread:J.tweetRow,y=e.full_text||"",x=((v=(d=e.extended_entities)==null?void 0:d.media)!=null&&v.length?e.extended_entities.media:u.media)||[],k=[],j=[];for(const w of x)if(w.type==="photo"){const _=In(w.local_path,w.media_url_https,r);_&&k.push({kind:"photo",src:_,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const _=w.local_path&&r[w.local_path]||(()=>{var C,S;return(S=(((C=w.video_info)==null?void 0:C.variants)||[]).filter($=>$.content_type==="video/mp4").sort(($,P)=>(P.bitrate||0)-($.bitrate||0))[0])==null?void 0:S.url})();_&&j.push({kind:w.type==="animated_gif"?"gif":"video",src:_})}const p=[];for(const w of x){if(!w.url||!(w.type==="photo"?k.some(C=>C.src===In(w.local_path,w.media_url_https,r)):j.length>0))continue;const b=Ha(w,y,w.url);b&&p.push([b.s,b.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Ad,{items:k,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:J.leftCol,children:[c?s.jsx("img",{src:c,style:J.avatar,alt:a.name||""}):s.jsx("div",{style:J.avatarPh}),g&&s.jsx("div",{style:J.threadLine})]}),s.jsxs("div",{style:J.rightCol,children:[s.jsxs("div",{style:J.authorRow,children:[s.jsx("span",{style:J.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:J.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:J.datePart,children:["· ",o]}),m&&s.jsx("span",{style:J.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:J.tweetText,children:Rm(y,u,p)}),k.length>0&&s.jsx("div",{style:J.mediaGrid,children:s.jsx(Am,{photos:k,onOpen:w=>i(w)})}),j.map((w,_)=>s.jsx("div",{style:J.mediaGrid,children:s.jsx("video",{src:w.src,style:J.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},_)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:J.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function Mm({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=f.useState(!0),[u,c]=f.useState(null),[g,m]=f.useState([]);if(f.useEffect(()=>{if(o(!0),c(null),m([]),!n||!e||!t){o(!1);return}const x=n.map((j,p)=>({...j,index:p})).filter(j=>j.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let k=!1;return gh(e,t,x.map(j=>j.index)).then(async j=>{if(k)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,d=C=>{var $;const S=C.full_text||"";return((($=C.entities)==null?void 0:$.urls)||[]).map(P=>{var K;if(P.fromIndex!=null&&P.toIndex!=null)return[P.fromIndex,P.toIndex];if(((K=P.indices)==null?void 0:K.length)===2)return[P.indices[0],P.indices[1]];if(P.url){const F=S.indexOf(P.url);if(F!==-1)return[F,F+P.url.length]}return null}).filter(Boolean)},v=(C,S,$)=>C.some(([P,K])=>P<=S&&K>=$),w=new Set;for(const C of j){const S=C.full_text||"",$=d(C);let P;for(p.lastIndex=0;(P=p.exec(S))!==null;)v($,P.index,P.index+P[0].length)||w.add(P[0])}const _=w.size>0?await vh([...w]).catch(()=>({})):{},b=j.map(C=>{var F;const S=C.full_text||"",$=d(C),P=[];let K;for(p.lastIndex=0;(K=p.exec(S))!==null;){const W=K[0],te=_[W];te&&te!==W&&!v($,K.index,K.index+W.length)&&P.push({url:W,expanded_url:te,display_url:(()=>{try{const oe=new URL(te);return oe.hostname+(oe.pathname.length>1?"/…":"")}catch{return te}})(),fromIndex:K.index,toIndex:K.index+W.length})}return P.length===0?C:{...C,entities:{...C.entities||{},urls:[...((F=C.entities)==null?void 0:F.urls)||[],...P]}}});k||m(b)}).catch(j=>{k||c(j.message||"Failed to load tweet.")}).finally(()=>{k||o(!1)}),()=>{k=!0}},[e,t,n]),a)return s.jsx("div",{style:J.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:J.error,children:["Error: ",u]});if(g.length===0)return null;const h=Lm(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:J.threadOuter,children:g.map((x,k)=>s.jsx(cu,{tweet:x,isInThread:!0,isLast:k===g.length-1,artifactMap:h},x.id||k))});const y=g[0];return y.is_article&&y.article?s.jsx(Om,{article:y.article,tweetAuthor:y.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:J.card,children:s.jsx(cu,{tweet:y,isInThread:!1,isLast:!0,artifactMap:h})})}const Fm=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Bm=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Um=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]);function Md({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const y=s.jsx(Mm,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?y:s.jsx("div",{className:"preview-tweet-wrap",children:y})}const c=a.findIndex(y=>y.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]});const g=a[c],m=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=g.relpath.split(".").pop().toLowerCase();return Fm.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(bm,{src:m})}):Bm.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:m,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(au,{src:m,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(au,{src:m,type:"page",title:i.title,originalUrl:i.original_url})}):Um.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Pm,{src:m,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]})}function Hm({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return f.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(Md,{archiveId:e,entry:t,detail:n})})]})})}function du(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function Wm({entry:e,src:t,archiveId:n,onClose:r}){const l=f.useRef(null),[i,a]=f.useState(!1),[o,u]=f.useState(0),[c,g]=f.useState(NaN),[m,h]=f.useState(1);f.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),g(NaN),a(!1))},[t]),f.useEffect(()=>{l.current&&(l.current.volume=m)},[m]);function y(){const d=l.current;d&&(i?d.pause():d.play().catch(()=>{}))}function x(d){const v=l.current;if(!v||!isFinite(c))return;const w=Number(d.target.value);v.currentTime=w,u(w)}function k(d){h(Number(d.target.value))}const j=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var d;return u(((d=l.current)==null?void 0:d.currentTime)??0)},onLoadedMetadata:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},onDurationChange:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Ua(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:j,children:j})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:y,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:du(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:du(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:m,onChange:k,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function Vm({archiveId:e,entryUid:t}){var h,y;const[n,r]=f.useState(null),[l,i]=f.useState(!0),[a,o]=f.useState(null),[u,c]=f.useState(!1);f.useEffect(()=>{if(!u)return;const x=document.documentElement,k=document.body,j=x.style.colorScheme,p=k.style.background;return x.style.colorScheme="dark",k.style.background="#000",()=>{x.style.colorScheme=j,k.style.background=p}},[u]),f.useEffect(()=>{c(!1),Vi(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const g=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,m=(y=n==null?void 0:n.summary)==null?void 0:y.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g}),m&&s.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(Md,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Qm=7e3;function Km({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Jm,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Xm(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Jm({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=f.useState(!1),i=e.type==="warning",a=e.type==="success";f.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Qm);return()=>clearTimeout(u)},[r,e.id,t]);const o=Xm(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const ps=f.createContext(null),ar=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})(),qm=["archive","tags","collections","runs","admin","settings"],Gm=["profile","tokens","instance","cookies","extensions","storage"];function qt(){const e=window.location.pathname.split("/").filter(Boolean),t=qm.includes(e[0])?e[0]:"archive",n=t==="settings"&&Gm.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null;return{view:t,settingsTab:n,q:l,tag:i,entry:a}}function Ym(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Zm(){const[e,t]=f.useState("loading"),[n,r]=f.useState(null);f.useEffect(()=>{(async()=>{if(await Ch()){t("setup");return}const z=await Ph();if(!z){t("login");return}r(z),t("authenticated")})()},[]),f.useEffect(()=>{const E=()=>{r(null),t("login")};return window.addEventListener("auth:expired",E),()=>window.removeEventListener("auth:expired",E)},[]),f.useEffect(()=>{const E=()=>{const{view:z,settingsTab:V,q:re,tag:ze,entry:Ze}=qt();v(z),_(V),C(re),p(ze),m(Ze),y(null),k(Ze?new Set([Ze]):new Set)};return window.addEventListener("popstate",E),()=>window.removeEventListener("popstate",E)},[]);const[l,i]=f.useState([]),[a,o]=f.useState(null),[u,c]=f.useState([]),[g,m]=f.useState(()=>qt().entry),[h,y]=f.useState(null),[x,k]=f.useState(()=>{const E=qt().entry;return E?new Set([E]):new Set}),[j,p]=f.useState(()=>qt().tag),[d,v]=f.useState(()=>qt().view),[w,_]=f.useState(()=>qt().settingsTab),[b,C]=f.useState(()=>qt().q),[S,$]=f.useState(""),[P,K]=f.useState(!1),[F,W]=f.useState([]),[te,oe]=f.useState([]),[fe,le]=f.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[R,T]=f.useState([]),M=f.useRef(0),[q,H]=f.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[N,O]=f.useState(null),U=f.useRef(0),B=f.useRef(null),Q=f.useRef(!1),pe=f.useRef(!0),G=f.useRef(null),Y=(n==null?void 0:n.humanize_slugs)??!1;f.useEffect(()=>{const E=++U.current;O(null),!(!h||!a)&&Vi(a,h.entry_uid).then(z=>{E===U.current&&O(z)}).catch(()=>{})},[h,a]),f.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",fe)},[fe]);const Z=f.useCallback(async(E,z,V)=>{if(E){K(!0);try{let re;z||V?re=await mh(E,z,V):re=await hh(E),c(re),k(ze=>{if(ze.size<2)return ze;const Ze=new Set(re.map(gn=>gn.entry_uid)),qn=new Set([...ze].filter(gn=>Ze.has(gn)));return qn.size===ze.size?ze:qn}),$(re.length===0?"No results":`${re.length} result${re.length===1?"":"s"}`)}catch{c([]),$("Search failed. Try again.")}finally{K(!1)}}},[]);f.useEffect(()=>{e==="authenticated"&&ph().then(E=>{if(i(E),E.length>0){const z=E[0].id;o(z)}})},[e]),f.useEffect(()=>{if(a){if(pe.current){pe.current=!1,Promise.all([Js(a).then(W),dl(a).then(oe)]);return}p(null),y(null),m(null),k(new Set),Promise.all([Z(a,"",null),Js(a).then(W),dl(a).then(oe)])}},[a]),f.useEffect(()=>{if(a===null)return;const E=setTimeout(()=>{Z(a,b,j)},300);return()=>clearTimeout(E)},[b,a]),f.useEffect(()=>{a!==null&&(j!==null&&v("archive"),Z(a,b,j))},[j,a]);const ue=f.useCallback(E=>{o(E)},[]),D=f.useCallback(E=>{v(E),E==="tags"&&a&&dl(a).then(oe)},[a]);f.useEffect(()=>{if(ar)return;const E=Ym(d,w);window.location.pathname!==E&&history.pushState(null,"",E+window.location.search)},[d,w]);const X=f.useCallback(E=>{m(E?E.entry_uid:null),y(E)},[]),Ce=f.useCallback((E,z)=>{if(z.shiftKey&&G.current!==null){z.preventDefault();const V=u.findIndex(Gn=>Gn.entry_uid===G.current),re=u.findIndex(Gn=>Gn.entry_uid===E.entry_uid);if(V===-1||re===-1){G.current=E.entry_uid,k(new Set([E.entry_uid])),X(E);return}const ze=Math.min(V,re),Ze=Math.max(V,re),qn=u.slice(ze,Ze+1),gn=new Set(qn.map(Gn=>Gn.entry_uid));k(gn),gn.size===1&&X(qn[0])}else z.ctrlKey||z.metaKey?(G.current=E.entry_uid,k(V=>{const re=new Set(V);return re.has(E.entry_uid)?re.delete(E.entry_uid):re.add(E.entry_uid),re})):(G.current=E.entry_uid,k(new Set([E.entry_uid])),X(E))},[u,X]),xe=f.useCallback(E=>{p(E)},[]),hs=f.useCallback(()=>{p(null)},[]),Kn=f.useCallback(()=>{a&&dl(a).then(oe)},[a]),ms=f.useCallback((E,z)=>{j===E?p(z):j!=null&&j.startsWith(E+"/")&&p(z+j.slice(E.length))},[j]),gs=f.useCallback(E=>{(j===E||j!=null&&j.startsWith(E+"/"))&&p(null)},[j]),Wr=f.useCallback((E,z)=>{c(V=>V.map(re=>re.entry_uid===E?{...re,title:z}:re)),y(V=>V&&V.entry_uid===E?{...V,title:z}:V),O(V=>V&&V.summary.entry_uid===E?{...V,summary:{...V.summary,title:z}}:V)},[]),vs=f.useCallback(()=>{if(!a||!h)return;const E=++U.current;Vi(a,h.entry_uid).then(z=>{E===U.current&&O(z)}).catch(()=>{})},[a,h]),ys=f.useCallback(E=>{c(z=>z.filter(V=>V.entry_uid!==E)),y(z=>(z==null?void 0:z.entry_uid)===E?null:z),m(z=>z===E?null:z),k(z=>{const V=new Set(z);return V.delete(E),V})},[]),xs=f.useCallback(E=>{c(z=>z.filter(V=>!E.has(V.entry_uid))),k(new Set),y(null),m(null)},[]);f.useEffect(()=>{if(x.size>=2)m(null),y(null);else if(x.size===1){const[E]=x;m(E)}else m(null),y(null)},[x]);const ws=f.useMemo(()=>u.filter(E=>x.has(E.entry_uid)),[u,x]);f.useEffect(()=>{if(!g||h)return;const E=u.find(z=>z.entry_uid===g);E&&y(E)},[u,g,h]),f.useEffect(()=>{if(ar)return;const E=new URLSearchParams;b&&E.set("q",b),d==="archive"&&j&&E.set("tag",j),d==="archive"&&g&&E.set("entry",g);const z=E.toString(),V=window.location.pathname+(z?"?"+z:"");window.location.pathname+window.location.search!==V&&history.replaceState(null,"",V)},[b,j,g,d]),f.useEffect(()=>{const E=z=>{var V,re;(z.metaKey||z.ctrlKey)&&z.key==="k"&&(z.preventDefault(),d==="archive"?((V=B.current)==null||V.focus(),(re=B.current)==null||re.select()):(Q.current=!0,v("archive")))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[d]),f.useEffect(()=>{d==="archive"&&Q.current&&(Q.current=!1,requestAnimationFrame(()=>{var E,z;(E=B.current)==null||E.focus(),(z=B.current)==null||z.select()}))},[d]);const ks=f.useCallback(()=>{le(!0)},[]),js=f.useCallback(()=>{le(!1)},[]),pn=f.useCallback(()=>{a&&Promise.all([Z(a,b,j),Js(a).then(W)])},[a,b,j,Z]),hn=f.useCallback((E,z,V="error",re=null)=>{if(V==="warning"&&q&&z)return;const ze=++M.current;T(Ze=>[...Ze,{id:ze,text:E,locator:z,type:V,headline:re}])},[q]),Vr=f.useCallback(E=>{T(z=>z.filter(V=>V.id!==E))},[]),Qr=f.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),H(!0),T(E=>E.filter(z=>!(z.type==="warning"&&z.locator)))},[]),[mn,Xn]=f.useState(null),[Tt,I]=f.useState(null),se=f.useCallback(()=>{h&&Xn(h.entry_uid)},[h]),Qe=f.useCallback(()=>Xn(null),[]),Jt=f.useCallback((E,z)=>{I({src:E,entry:z})},[]),Jn=f.useCallback(()=>I(null),[]);return f.useEffect(()=>{Xn(null)},[h]),f.useEffect(()=>{const E=z=>{var re,ze,Ze;if(z.key!=="Escape"||fe||mn)return;const V=(re=document.activeElement)==null?void 0:re.tagName;V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||x.size>0&&(z.preventDefault(),k(new Set),(Ze=(ze=document.activeElement)==null?void 0:ze.blur)==null||Ze.call(ze))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[fe,mn,x]),f.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Tt),()=>document.body.classList.remove("has-audio-bar")),[Tt]),e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(rm,{onComplete:()=>t("login")}):e==="login"?s.jsx(nm,{onLogin:E=>{r(E),t("authenticated")}}):ar?s.jsx(Vm,{archiveId:ar.archiveId,entryUid:ar.entryUid}):s.jsx(ps.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(lm,{archives:l,archiveId:a,onArchiveChange:ue,view:d,onViewChange:D,onCaptureClick:ks}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[d==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:B,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":P,placeholder:"Search titles, URLs, types, tags…",value:b,onChange:E=>C(E.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[S&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:S.split(" ")[0]})," ",S.split(" ").slice(1).join(" ")]}),j&&s.jsxs("button",{className:"tag-filter-badge",onClick:hs,children:["× ",Y?Pd(j):j]})]})]}),d==="archive"&&s.jsx(cm,{entries:u,selectedUids:x,onRowClick:Ce,archiveId:a}),d==="runs"&&s.jsx(pm,{runs:F}),d==="admin"&&s.jsx(mm,{archives:l}),d==="tags"&&s.jsx(gm,{archiveId:a,tagNodes:te,tagFilter:j,onTagFilterSet:xe,onViewChange:D,onTagRenamed:ms,onTagDeleted:gs,onTagsRefresh:Kn,humanizeTags:Y}),d==="collections"&&s.jsx(ym,{archiveId:a}),d==="settings"&&s.jsx(wm,{tab:w,onTabChange:_,archiveId:a})]}),s.jsx(Tm,{archiveId:a,selectedEntry:h,selectedUids:x,selectedEntries:ws,detail:N,onTagFilterSet:xe,tagNodes:te,onTagsRefresh:Kn,onEntryTitleChange:Wr,onEntryDeleted:ys,onBulkDeleted:xs,humanizeTags:Y,onDetailRefresh:vs,onOpenPreview:se,onPlay:Jt})]}),mn&&h&&h.entry_uid===mn&&s.jsx(Hm,{archiveId:a,entry:h,detail:N,onClose:Qe}),Tt&&s.jsx(Wm,{entry:Tt.entry,src:Tt.src,archiveId:a,onClose:Jn}),s.jsx(sm,{open:fe,archiveId:a,onClose:js,onCaptured:pn,onToast:hn}),s.jsx(Km,{toasts:R,onDismiss:Vr,onIgnoreUblock:Qr})]})})}Nd(document.getElementById("root")).render(s.jsx(f.StrictMode,{children:s.jsx(Zm,{})})); diff --git a/crates/archivr-server/static/assets/index-YmIQCrug.js b/crates/archivr-server/static/assets/index-YmIQCrug.js new file mode 100644 index 0000000..70daba7 --- /dev/null +++ b/crates/archivr-server/static/assets/index-YmIQCrug.js @@ -0,0 +1,47 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var fu={exports:{}},Gl={},pu={exports:{}},Z={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ar=Symbol.for("react.element"),Ad=Symbol.for("react.portal"),Bd=Symbol.for("react.fragment"),Ud=Symbol.for("react.strict_mode"),Hd=Symbol.for("react.profiler"),Wd=Symbol.for("react.provider"),Vd=Symbol.for("react.context"),Qd=Symbol.for("react.forward_ref"),Kd=Symbol.for("react.suspense"),Xd=Symbol.for("react.memo"),Jd=Symbol.for("react.lazy"),Wa=Symbol.iterator;function qd(e){return e===null||typeof e!="object"?null:(e=Wa&&e[Wa]||e["@@iterator"],typeof e=="function"?e:null)}var hu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},mu=Object.assign,gu={};function Vn(e,t,n){this.props=e,this.context=t,this.refs=gu,this.updater=n||hu}Vn.prototype.isReactComponent={};Vn.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Vn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function vu(){}vu.prototype=Vn.prototype;function Ki(e,t,n){this.props=e,this.context=t,this.refs=gu,this.updater=n||hu}var Xi=Ki.prototype=new vu;Xi.constructor=Ki;mu(Xi,Vn.prototype);Xi.isPureReactComponent=!0;var Va=Array.isArray,yu=Object.prototype.hasOwnProperty,Ji={current:null},xu={key:!0,ref:!0,__self:!0,__source:!0};function wu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)yu.call(t,r)&&!xu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,U=D[Y];if(0>>1;Yl(N,M))Fl(H,N)?(D[Y]=H,D[F]=M,Y=F):(D[Y]=N,D[ae]=M,Y=ae);else if(Fl(H,M))D[Y]=H,D[F]=M,Y=F;else break e}}return b}function l(D,b){var M=D.sortIndex-b.sortIndex;return M!==0?M:D.id-b.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],g=1,m=null,h=3,y=!1,x=!1,k=!1,j=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(D){for(var b=n(c);b!==null;){if(b.callback===null)r(c);else if(b.startTime<=D)r(c),b.sortIndex=b.expirationTime,t(u,b);else break;b=n(c)}}function w(D){if(k=!1,v(D),!x)if(n(u)!==null)x=!0,de(_);else{var b=n(c);b!==null&&ne(w,b.startTime-D)}}function _(D,b){x=!1,k&&(k=!1,p(S),S=-1),y=!0;var M=h;try{for(v(b),m=n(u);m!==null&&(!(m.expirationTime>b)||D&&!W());){var Y=m.callback;if(typeof Y=="function"){m.callback=null,h=m.priorityLevel;var U=Y(m.expirationTime<=b);b=e.unstable_now(),typeof U=="function"?m.callback=U:m===n(u)&&r(u),v(b)}else r(u);m=n(u)}if(m!==null)var fe=!0;else{var ae=n(c);ae!==null&&ne(w,ae.startTime-b),fe=!1}return fe}finally{m=null,h=M,y=!1}}var P=!1,C=null,S=-1,$=5,L=-1;function W(){return!(e.unstable_now()-L<$)}function A(){if(C!==null){var D=e.unstable_now();L=D;var b=!0;try{b=C(!0,D)}finally{b?Q():(P=!1,C=null)}}else P=!1}var Q;if(typeof d=="function")Q=function(){d(A)};else if(typeof MessageChannel<"u"){var ee=new MessageChannel,le=ee.port2;ee.port1.onmessage=A,Q=function(){le.postMessage(null)}}else Q=function(){j(A,0)};function de(D){C=D,P||(P=!0,Q())}function ne(D,b){S=j(function(){D(e.unstable_now())},b)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(D){D.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,de(_))},e.unstable_forceFrameRate=function(D){0>D||125Y?(D.sortIndex=M,t(c,D),n(u)===null&&D===n(c)&&(k?(p(S),S=-1):k=!0,ne(w,M-Y))):(D.sortIndex=U,t(u,D),x||y||(x=!0,de(_))),D},e.unstable_shouldYield=W,e.unstable_wrapCallback=function(D){var b=h;return function(){var M=h;h=b;try{return D.apply(this,arguments)}finally{h=M}}}})(_u);Nu.exports=_u;var of=Nu.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var uf=f,qe=of;function z(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Zs=Object.prototype.hasOwnProperty,cf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Ka={},Xa={};function df(e){return Zs.call(Xa,e)?!0:Zs.call(Ka,e)?!1:cf.test(e)?Xa[e]=!0:(Ka[e]=!0,!1)}function ff(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function pf(e,t,n,r){if(t===null||typeof t>"u"||ff(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Ae(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var Le={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Le[e]=new Ae(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Le[t]=new Ae(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Le[e]=new Ae(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Le[e]=new Ae(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Le[e]=new Ae(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Le[e]=new Ae(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Le[e]=new Ae(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Le[e]=new Ae(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Le[e]=new Ae(e,5,!1,e.toLowerCase(),null,!1,!1)});var Yi=/[\-:]([a-z])/g;function Gi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Yi,Gi);Le[t]=new Ae(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Yi,Gi);Le[t]=new Ae(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Yi,Gi);Le[t]=new Ae(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Le[e]=new Ae(e,1,!1,e.toLowerCase(),null,!1,!1)});Le.xlinkHref=new Ae("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Le[e]=new Ae(e,1,!1,e.toLowerCase(),null,!0,!0)});function Zi(e,t,n,r){var l=Le.hasOwnProperty(t)?Le[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` +`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{_s=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ur(e):""}function hf(e){switch(e.tag){case 5:return ur(e.type);case 16:return ur("Lazy");case 13:return ur("Suspense");case 19:return ur("SuspenseList");case 0:case 2:case 15:return e=Cs(e.type,!1),e;case 11:return e=Cs(e.type.render,!1),e;case 1:return e=Cs(e.type,!0),e;default:return""}}function ri(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case wn:return"Fragment";case xn:return"Portal";case ei:return"Profiler";case ea:return"StrictMode";case ti:return"Suspense";case ni:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Tu:return(e.displayName||"Context")+".Consumer";case Eu:return(e._context.displayName||"Context")+".Provider";case ta:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case na:return t=e.displayName||null,t!==null?t:ri(e.type)||"Memo";case Lt:t=e._payload,e=e._init;try{return ri(e(t))}catch{}}return null}function mf(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ri(t);case 8:return t===ea?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Vt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Pu(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function gf(e){var t=Pu(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function qr(e){e._valueTracker||(e._valueTracker=gf(e))}function Lu(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Pu(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Cl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function li(e,t){var n=t.checked;return ve({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function qa(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Vt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function zu(e,t){t=t.checked,t!=null&&Zi(e,"checked",t,!1)}function si(e,t){zu(e,t);var n=Vt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ii(e,t.type,n):t.hasOwnProperty("defaultValue")&&ii(e,t.type,Vt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Ya(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function ii(e,t,n){(t!=="number"||Cl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var cr=Array.isArray;function Ln(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Yr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Nr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var hr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},vf=["Webkit","ms","Moz","O"];Object.keys(hr).forEach(function(e){vf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),hr[t]=hr[e]})});function Iu(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||hr.hasOwnProperty(e)&&hr[e]?(""+t).trim():t+"px"}function Ou(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Iu(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var yf=ve({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ui(e,t){if(t){if(yf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(z(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(z(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(z(61))}if(t.style!=null&&typeof t.style!="object")throw Error(z(62))}}function ci(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var di=null;function ra(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var fi=null,zn=null,Rn=null;function eo(e){if(e=Hr(e)){if(typeof fi!="function")throw Error(z(280));var t=e.stateNode;t&&(t=rs(t),fi(e.stateNode,e.type,t))}}function Fu(e){zn?Rn?Rn.push(e):Rn=[e]:zn=e}function Mu(){if(zn){var e=zn,t=Rn;if(Rn=zn=null,eo(e),t)for(e=0;e>>=0,e===0?32:31-(bf(e)/Pf|0)|0}var Gr=64,Zr=4194304;function dr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Pl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=dr(o):(i&=a,i!==0&&(r=dr(i)))}else a=n&~l,a!==0?r=dr(a):i!==0&&(r=dr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Br(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-dt(t),e[t]=n}function Df(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=gr),uo=" ",co=!1;function sc(e,t){switch(e){case"keyup":return op.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ic(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var kn=!1;function cp(e,t){switch(e){case"compositionend":return ic(t);case"keypress":return t.which!==32?null:(co=!0,uo);case"textInput":return e=t.data,e===uo&&co?null:e;default:return null}}function dp(e,t){if(kn)return e==="compositionend"||!da&&sc(e,t)?(e=rc(),gl=oa=$t=null,kn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=mo(n)}}function cc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?cc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function dc(){for(var e=window,t=Cl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Cl(e.document)}return t}function fa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function wp(e){var t=dc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&cc(n.ownerDocument.documentElement,n)){if(r!==null&&fa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=go(n,i);var a=go(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,jn=null,yi=null,yr=null,xi=!1;function vo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;xi||jn==null||jn!==Cl(r)||(r=jn,"selectionStart"in r&&fa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),yr&&Pr(yr,r)||(yr=r,r=Rl(yi,"onSelect"),0_n||(e.current=_i[_n],_i[_n]=null,_n--)}function oe(e,t){_n++,_i[_n]=e.current,e.current=t}var Qt={},Ie=Xt(Qt),He=Xt(!1),an=Qt;function Mn(e,t){var n=e.type.contextTypes;if(!n)return Qt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function We(e){return e=e.childContextTypes,e!=null}function $l(){ce(He),ce(Ie)}function No(e,t,n){if(Ie.current!==Qt)throw Error(z(168));oe(Ie,t),oe(He,n)}function wc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(z(108,mf(e)||"Unknown",l));return ve({},n,r)}function Il(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Qt,an=Ie.current,oe(Ie,e),oe(He,He.current),!0}function _o(e,t,n){var r=e.stateNode;if(!r)throw Error(z(169));n?(e=wc(e,t,an),r.__reactInternalMemoizedMergedChildContext=e,ce(He),ce(Ie),oe(Ie,e)):ce(He),oe(He,n)}var wt=null,ls=!1,As=!1;function kc(e){wt===null?wt=[e]:wt.push(e)}function zp(e){ls=!0,kc(e)}function Jt(){if(!As&&wt!==null){As=!0;var e=0,t=ie;try{var n=wt;for(ie=1;e>=a,l-=a,kt=1<<32-dt(t)+l|n<S?($=C,C=null):$=C.sibling;var L=h(p,C,v[S],w);if(L===null){C===null&&(C=$);break}e&&C&&L.alternate===null&&t(p,C),d=i(L,d,S),P===null?_=L:P.sibling=L,P=L,C=$}if(S===v.length)return n(p,C),he&&Gt(p,S),_;if(C===null){for(;SS?($=C,C=null):$=C.sibling;var W=h(p,C,L.value,w);if(W===null){C===null&&(C=$);break}e&&C&&W.alternate===null&&t(p,C),d=i(W,d,S),P===null?_=W:P.sibling=W,P=W,C=$}if(L.done)return n(p,C),he&&Gt(p,S),_;if(C===null){for(;!L.done;S++,L=v.next())L=m(p,L.value,w),L!==null&&(d=i(L,d,S),P===null?_=L:P.sibling=L,P=L);return he&&Gt(p,S),_}for(C=r(p,C);!L.done;S++,L=v.next())L=y(C,p,S,L.value,w),L!==null&&(e&&L.alternate!==null&&C.delete(L.key===null?S:L.key),d=i(L,d,S),P===null?_=L:P.sibling=L,P=L);return e&&C.forEach(function(A){return t(p,A)}),he&&Gt(p,S),_}function j(p,d,v,w){if(typeof v=="object"&&v!==null&&v.type===wn&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Jr:e:{for(var _=v.key,P=d;P!==null;){if(P.key===_){if(_=v.type,_===wn){if(P.tag===7){n(p,P.sibling),d=l(P,v.props.children),d.return=p,p=d;break e}}else if(P.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===Lt&&To(_)===P.type){n(p,P.sibling),d=l(P,v.props),d.ref=lr(p,P,v),d.return=p,p=d;break e}n(p,P);break}else t(p,P);P=P.sibling}v.type===wn?(d=sn(v.props.children,p.mode,w,v.key),d.return=p,p=d):(w=Nl(v.type,v.key,v.props,null,p.mode,w),w.ref=lr(p,d,v),w.return=p,p=w)}return a(p);case xn:e:{for(P=v.key;d!==null;){if(d.key===P)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){n(p,d.sibling),d=l(d,v.children||[]),d.return=p,p=d;break e}else{n(p,d);break}else t(p,d);d=d.sibling}d=Xs(v,p.mode,w),d.return=p,p=d}return a(p);case Lt:return P=v._init,j(p,d,P(v._payload),w)}if(cr(v))return x(p,d,v,w);if(Zn(v))return k(p,d,v,w);il(p,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,d!==null&&d.tag===6?(n(p,d.sibling),d=l(d,v),d.return=p,p=d):(n(p,d),d=Ks(v,p.mode,w),d.return=p,p=d),a(p)):n(p,d)}return j}var Bn=_c(!0),Cc=_c(!1),Ml=Xt(null),Al=null,Tn=null,ga=null;function va(){ga=Tn=Al=null}function ya(e){var t=Ml.current;ce(Ml),e._currentValue=t}function Ti(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function $n(e,t){Al=e,ga=Tn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ue=!0),e.firstContext=null)}function st(e){var t=e._currentValue;if(ga!==e)if(e={context:e,memoizedValue:t,next:null},Tn===null){if(Al===null)throw Error(z(308));Tn=e,Al.dependencies={lanes:0,firstContext:e}}else Tn=Tn.next=e;return t}var tn=null;function xa(e){tn===null?tn=[e]:tn.push(e)}function Ec(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,xa(t)):(n.next=l.next,l.next=n),t.interleaved=n,Ct(e,r)}function Ct(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var zt=!1;function wa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Tc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function St(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Bt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,te&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Ct(e,n)}return l=r.interleaved,l===null?(t.next=t,xa(r)):(t.next=l.next,l.next=t),r.interleaved=t,Ct(e,n)}function yl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}function bo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Bl(e,t,n,r){var l=e.updateQueue;zt=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var g=e.alternate;g!==null&&(g=g.updateQueue,o=g.lastBaseUpdate,o!==a&&(o===null?g.firstBaseUpdate=c:o.next=c,g.lastBaseUpdate=u))}if(i!==null){var m=l.baseState;a=0,g=c=u=null,o=i;do{var h=o.lane,y=o.eventTime;if((r&h)===h){g!==null&&(g=g.next={eventTime:y,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,k=o;switch(h=t,y=n,k.tag){case 1:if(x=k.payload,typeof x=="function"){m=x.call(y,m,h);break e}m=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=k.payload,h=typeof x=="function"?x.call(y,m,h):x,h==null)break e;m=ve({},m,h);break e;case 2:zt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else y={eventTime:y,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},g===null?(c=g=y,u=m):g=g.next=y,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(g===null&&(u=m),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=g,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);cn|=a,e.lanes=a,e.memoizedState=m}}function Po(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Us.transition;Us.transition={};try{e(!1),t()}finally{ie=n,Us.transition=r}}function Vc(){return it().memoizedState}function Ip(e,t,n){var r=Ht(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Qc(e))Kc(t,n);else if(n=Ec(e,t,n,r),n!==null){var l=Fe();ft(n,e,r,l),Xc(n,t,r)}}function Op(e,t,n){var r=Ht(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Qc(e))Kc(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,pt(o,a)){var u=t.interleaved;u===null?(l.next=l,xa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Ec(e,t,l,r),n!==null&&(l=Fe(),ft(n,e,r,l),Xc(n,t,r))}}function Qc(e){var t=e.alternate;return e===ge||t!==null&&t===ge}function Kc(e,t){xr=Hl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Xc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,sa(e,n)}}var Wl={readContext:st,useCallback:Re,useContext:Re,useEffect:Re,useImperativeHandle:Re,useInsertionEffect:Re,useLayoutEffect:Re,useMemo:Re,useReducer:Re,useRef:Re,useState:Re,useDebugValue:Re,useDeferredValue:Re,useTransition:Re,useMutableSource:Re,useSyncExternalStore:Re,useId:Re,unstable_isNewReconciler:!1},Fp={readContext:st,useCallback:function(e,t){return mt().memoizedState=[e,t===void 0?null:t],e},useContext:st,useEffect:zo,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,wl(4194308,4,Ac.bind(null,t,e),n)},useLayoutEffect:function(e,t){return wl(4194308,4,e,t)},useInsertionEffect:function(e,t){return wl(4,2,e,t)},useMemo:function(e,t){var n=mt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=mt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Ip.bind(null,ge,e),[r.memoizedState,e]},useRef:function(e){var t=mt();return e={current:e},t.memoizedState=e},useState:Lo,useDebugValue:Ta,useDeferredValue:function(e){return mt().memoizedState=e},useTransition:function(){var e=Lo(!1),t=e[0];return e=$p.bind(null,e[1]),mt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=ge,l=mt();if(he){if(n===void 0)throw Error(z(407));n=n()}else{if(n=t(),Te===null)throw Error(z(349));un&30||zc(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,zo(Dc.bind(null,r,i,e),[e]),r.flags|=2048,Fr(9,Rc.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=mt(),t=Te.identifierPrefix;if(he){var n=jt,r=kt;n=(r&~(1<<32-dt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ir++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[gt]=t,e[Rr]=r,ld(e,t,!1,!1),t.stateNode=e;e:{switch(a=ci(n,r),n){case"dialog":ue("cancel",e),ue("close",e),l=r;break;case"iframe":case"object":case"embed":ue("load",e),l=r;break;case"video":case"audio":for(l=0;lWn&&(t.flags|=128,r=!0,sr(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ul(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),sr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!he)return De(t),null}else 2*xe()-i.renderingStartTime>Wn&&n!==1073741824&&(t.flags|=128,r=!0,sr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=xe(),t.sibling=null,n=me.current,oe(me,r?n&1|2:n&1),t):(De(t),null);case 22:case 23:return Da(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ke&1073741824&&(De(t),t.subtreeFlags&6&&(t.flags|=8192)):De(t),null;case 24:return null;case 25:return null}throw Error(z(156,t.tag))}function Qp(e,t){switch(ha(t),t.tag){case 1:return We(t.type)&&$l(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Un(),ce(He),ce(Ie),Sa(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ja(t),null;case 13:if(ce(me),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(z(340));An()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ce(me),null;case 4:return Un(),null;case 10:return ya(t.type._context),null;case 22:case 23:return Da(),null;case 24:return null;default:return null}}var ol=!1,$e=!1,Kp=typeof WeakSet=="function"?WeakSet:Set,O=null;function bn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ye(e,t,r)}else n.current=null}function Oi(e,t,n){try{n()}catch(r){ye(e,t,r)}}var Ho=!1;function Xp(e,t){if(wi=Ll,e=dc(),fa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,g=0,m=e,h=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(o=a+l),m!==i||r!==0&&m.nodeType!==3||(u=a+r),m.nodeType===3&&(a+=m.nodeValue.length),(y=m.firstChild)!==null;)h=m,m=y;for(;;){if(m===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++g===r&&(u=a),(y=m.nextSibling)!==null)break;m=h,h=m.parentNode}m=y}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(ki={focusedElem:e,selectionRange:n},Ll=!1,O=t;O!==null;)if(t=O,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,O=e;else for(;O!==null;){t=O;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var k=x.memoizedProps,j=x.memoizedState,p=t.stateNode,d=p.getSnapshotBeforeUpdate(t.elementType===t.type?k:ot(t.type,k),j);p.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(z(163))}}catch(w){ye(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,O=e;break}O=t.return}return x=Ho,Ho=!1,x}function wr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Oi(t,n,i)}l=l.next}while(l!==r)}}function as(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Fi(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function ad(e){var t=e.alternate;t!==null&&(e.alternate=null,ad(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[gt],delete t[Rr],delete t[Ni],delete t[Pp],delete t[Lp])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function od(e){return e.tag===5||e.tag===3||e.tag===4}function Wo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||od(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Mi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Dl));else if(r!==4&&(e=e.child,e!==null))for(Mi(e,t,n),e=e.sibling;e!==null;)Mi(e,t,n),e=e.sibling}function Ai(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ai(e,t,n),e=e.sibling;e!==null;)Ai(e,t,n),e=e.sibling}var be=null,ut=!1;function Pt(e,t,n){for(n=n.child;n!==null;)ud(e,t,n),n=n.sibling}function ud(e,t,n){if(vt&&typeof vt.onCommitFiberUnmount=="function")try{vt.onCommitFiberUnmount(Zl,n)}catch{}switch(n.tag){case 5:$e||bn(n,t);case 6:var r=be,l=ut;be=null,Pt(e,t,n),be=r,ut=l,be!==null&&(ut?(e=be,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):be.removeChild(n.stateNode));break;case 18:be!==null&&(ut?(e=be,n=n.stateNode,e.nodeType===8?Ms(e.parentNode,n):e.nodeType===1&&Ms(e,n),Tr(e)):Ms(be,n.stateNode));break;case 4:r=be,l=ut,be=n.stateNode.containerInfo,ut=!0,Pt(e,t,n),be=r,ut=l;break;case 0:case 11:case 14:case 15:if(!$e&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&Oi(n,t,a),l=l.next}while(l!==r)}Pt(e,t,n);break;case 1:if(!$e&&(bn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ye(n,t,o)}Pt(e,t,n);break;case 21:Pt(e,t,n);break;case 22:n.mode&1?($e=(r=$e)||n.memoizedState!==null,Pt(e,t,n),$e=r):Pt(e,t,n);break;default:Pt(e,t,n)}}function Vo(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Kp),t.forEach(function(r){var l=rh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function at(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=xe()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*qp(r/1960))-r,10e?16:e,It===null)var r=!1;else{if(e=It,It=null,Kl=0,te&6)throw Error(z(331));var l=te;for(te|=4,O=e.current;O!==null;){var i=O,a=i.child;if(O.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uxe()-za?ln(e,0):La|=n),Ve(e,t)}function vd(e,t){t===0&&(e.mode&1?(t=Zr,Zr<<=1,!(Zr&130023424)&&(Zr=4194304)):t=1);var n=Fe();e=Ct(e,t),e!==null&&(Br(e,t,n),Ve(e,n))}function nh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),vd(e,n)}function rh(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(z(314))}r!==null&&r.delete(t),vd(e,n)}var yd;yd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||He.current)Ue=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ue=!1,Wp(e,t,n);Ue=!!(e.flags&131072)}else Ue=!1,he&&t.flags&1048576&&jc(t,Fl,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;kl(e,t),e=t.pendingProps;var l=Mn(t,Ie.current);$n(t,n),l=_a(null,t,r,e,l,n);var i=Ca();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,We(r)?(i=!0,Il(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,wa(t),l.updater=is,t.stateNode=l,l._reactInternals=t,Pi(t,r,e,n),t=Ri(null,t,r,!0,i,n)):(t.tag=0,he&&i&&pa(t),Oe(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(kl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=sh(r),e=ot(r,e),l){case 0:t=zi(null,t,r,e,n);break e;case 1:t=Ao(null,t,r,e,n);break e;case 11:t=Fo(null,t,r,e,n);break e;case 14:t=Mo(null,t,r,ot(r.type,e),n);break e}throw Error(z(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ot(r,l),zi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ot(r,l),Ao(e,t,r,l,n);case 3:e:{if(td(t),e===null)throw Error(z(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Tc(e,t),Bl(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=Hn(Error(z(423)),t),t=Bo(e,t,r,n,l);break e}else if(r!==l){l=Hn(Error(z(424)),t),t=Bo(e,t,r,n,l);break e}else for(Xe=At(t.stateNode.containerInfo.firstChild),Je=t,he=!0,ct=null,n=Cc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(An(),r===l){t=Et(e,t,n);break e}Oe(e,t,r,n)}t=t.child}return t;case 5:return bc(t),e===null&&Ei(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,ji(r,l)?a=null:i!==null&&ji(r,i)&&(t.flags|=32),ed(e,t),Oe(e,t,a,n),t.child;case 6:return e===null&&Ei(t),null;case 13:return nd(e,t,n);case 4:return ka(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Bn(t,null,r,n):Oe(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ot(r,l),Fo(e,t,r,l,n);case 7:return Oe(e,t,t.pendingProps,n),t.child;case 8:return Oe(e,t,t.pendingProps.children,n),t.child;case 12:return Oe(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,oe(Ml,r._currentValue),r._currentValue=a,i!==null)if(pt(i.value,a)){if(i.children===l.children&&!He.current){t=Et(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=St(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var g=c.pending;g===null?u.next=u:(u.next=g.next,g.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Ti(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(z(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Ti(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Oe(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,$n(t,n),l=st(l),r=r(l),t.flags|=1,Oe(e,t,r,n),t.child;case 14:return r=t.type,l=ot(r,t.pendingProps),l=ot(r.type,l),Mo(e,t,r,l,n);case 15:return Gc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:ot(r,l),kl(e,t),t.tag=1,We(r)?(e=!0,Il(t)):e=!1,$n(t,n),Jc(t,r,l),Pi(t,r,l,n),Ri(null,t,r,!0,e,n);case 19:return rd(e,t,n);case 22:return Zc(e,t,n)}throw Error(z(156,t.tag))};function xd(e,t){return Qu(e,t)}function lh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function rt(e,t,n,r){return new lh(e,t,n,r)}function Ia(e){return e=e.prototype,!(!e||!e.isReactComponent)}function sh(e){if(typeof e=="function")return Ia(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ta)return 11;if(e===na)return 14}return 2}function Wt(e,t){var n=e.alternate;return n===null?(n=rt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Nl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")Ia(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case wn:return sn(n.children,l,i,t);case ea:a=8,l|=8;break;case ei:return e=rt(12,n,t,l|2),e.elementType=ei,e.lanes=i,e;case ti:return e=rt(13,n,t,l),e.elementType=ti,e.lanes=i,e;case ni:return e=rt(19,n,t,l),e.elementType=ni,e.lanes=i,e;case bu:return us(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Eu:a=10;break e;case Tu:a=9;break e;case ta:a=11;break e;case na:a=14;break e;case Lt:a=16,r=null;break e}throw Error(z(130,e==null?e:typeof e,""))}return t=rt(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function sn(e,t,n,r){return e=rt(7,e,r,t),e.lanes=n,e}function us(e,t,n,r){return e=rt(22,e,r,t),e.elementType=bu,e.lanes=n,e.stateNode={isHidden:!1},e}function Ks(e,t,n){return e=rt(6,e,null,t),e.lanes=n,e}function Xs(e,t,n){return t=rt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function ih(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ts(0),this.expirationTimes=Ts(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ts(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Oa(e,t,n,r,l,i,a,o,u){return e=new ih(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=rt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wa(i),e}function ah(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Sd)}catch(e){console.error(e)}}Sd(),Su.exports=Ye;var fh=Su.exports,Nd,Zo=fh;Nd=Zo.createRoot,Zo.hydrateRoot;async function _e(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ph(){return _e("/api/archives")}async function hh(e){return _e(`/api/archives/${e}/entries`)}async function mh(e,t,n){const r=new URLSearchParams;return t&&r.set("q",t),n&&r.set("tag",n),_e(`/api/archives/${e}/entries/search?${r}`)}async function Vi(e,t){return _e(`/api/archives/${e}/entries/${t}`)}function gh(e,t,n){return Promise.all(n.map(r=>_e(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function vh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function yh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function dl(e,t){return _e(`/api/archives/${e}/entries/${t}/tags`)}async function eu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function xh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function tu(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function wh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function kh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function jh(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function Sh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function Js(e){return _e(`/api/archives/${e}/runs`)}async function fl(e){return _e(`/api/archives/${e}/tags`)}async function Nh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled),typeof r.via_freedium=="boolean"&&(l.via_freedium=r.via_freedium));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({}));throw new Error(a.error||`HTTP ${i.status}`)}return i.json()}async function _h(e,t){return _e(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function _d(e,t){return _e(`/api/archives/${e}/capture_jobs/${t}`)}async function Ch(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Eh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Th(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function bh(){await fetch("/api/auth/logout",{method:"POST"})}async function Ph(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function Lh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function zh(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Rh(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function Dh(){return _e("/api/auth/tokens")}async function $h(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function Ih(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function Ba(){return _e("/api/admin/instance-settings")}async function _l(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Oh(){return _e("/api/admin/users")}async function Fh(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function Mh(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Ah(){return _e("/api/admin/roles")}async function Bh(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Cd(e){return _e(`/api/archives/${e}/collections`)}async function Uh(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}return l.json()}async function Hh(e,t){return _e(`/api/archives/${e}/collections/${t}`)}async function Ed(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Wh(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function Vh(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Qh(e,t){return _e(`/api/archives/${e}/entries/${t}/collections`)}async function nu(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function Kh(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function Xh(e){return _e(`/api/archives/${e}/blob-cleanup`)}async function Jh(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function qh(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function Yh(){return _e("/api/admin/cookie-rules")}async function Gh(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function Zh(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function em(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}const tm=window.fetch;window.fetch=async(...e)=>{var n;const t=await tm(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function nm({onLogin:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(null),[o,u]=f.useState(!1);async function c(g){g.preventDefault(),a(null),u(!0);try{const m=await Th(t,r);e(m)}catch(m){a(m.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:g=>n(g.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:g=>l(g.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function rm({onComplete:e}){const[t,n]=f.useState(""),[r,l]=f.useState(""),[i,a]=f.useState(""),[o,u]=f.useState(null),[c,g]=f.useState(!1);async function m(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),g(!0);try{await Eh(t,r),e()}catch(y){u(y.message)}finally{g(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function lm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i}){const{currentUser:a,setCurrentUser:o}=f.useContext(hs)??{},[u,c]=f.useState(!1);async function g(){c(!0),await bh(),o(null),window.location.reload()}return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),a&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:a.display_name||a.username}),s.jsx("button",{className:"logout-btn",onClick:g,disabled:u,children:u?"Logging out…":"Log out"})]})]})}let Qi=1;function Td(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function ar(e=""){return{id:Qi++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null}}function ru(e){return e.some(t=>t.status==="submitting"||t.status==="running")}function sm({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l}){const i=f.useRef(null),a=f.useRef(!0),o=f.useRef(new Map),u=f.useRef(new Map),c=f.useRef(new Map),g=f.useRef(t);f.useEffect(()=>{g.current=t},[t]);const m=f.useRef(r),h=f.useRef(l);f.useEffect(()=>{m.current=r},[r]),f.useEffect(()=>{h.current=l},[l]);const[y,x]=f.useState(()=>{try{const N=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(N)&&N.length>0)return N.forEach(F=>{F.id>=Qi&&(Qi=F.id+1)}),N}catch{}return[ar()]});f.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(y))},[y]);const[k,j]=f.useState(!1),[p,d]=f.useState(null),[v,w]=f.useState(null),[_,P]=f.useState(!0),[C,S]=f.useState(!0),[$,L]=f.useState(!0);f.useEffect(()=>{Ba().then(N=>{w(N),P(N.cookie_ext_enabled??!0),S(N.modal_closer_enabled??!0)}).catch(()=>w({}))},[]);const W=p!==null?p:(v==null?void 0:v.ublock_enabled)??!0,[A,Q]=f.useState(!1);f.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(N=>sessionStorage.removeItem(N)),x(N=>N.map(F=>F.status==="submitting"?{...F,status:"idle",error:null}:F)),y.forEach(N=>{N.status==="running"&&N.jobUid&&N.archiveId&&!o.current.has(N.jobUid)&&ee(N.id,N.jobUid,N.locator,N.archiveId)})},[]),f.useEffect(()=>{const N=i.current;if(!N)return;const F=()=>{u.current.forEach(H=>clearTimeout(H)),u.current.clear(),n()};return N.addEventListener("close",F),()=>N.removeEventListener("close",F)},[n]),f.useEffect(()=>{const N=i.current;N&&(e?(!a.current&&!ru(y)&&x([ar()]),a.current=!1,N.open||N.showModal()):(u.current.forEach(F=>clearTimeout(F)),u.current.clear(),N.open&&N.close()))},[e]),f.useEffect(()=>()=>{o.current.forEach(N=>clearInterval(N)),u.current.forEach(N=>clearTimeout(N))},[]);function ee(N,F,H,X,K=null){if(o.current.has(F))return;const pe=setInterval(async()=>{try{const G=await _d(X,F);if(G.status==="completed"){clearInterval(o.current.get(F)),o.current.delete(F),x(q=>q.map(T=>T.id===N?{...T,status:"completed"}:T)),setTimeout(()=>{x(q=>{const T=q.filter(B=>B.id!==N);return T.length===0?[ar()]:T})},1400),m.current();try{const q=G.notes_json?JSON.parse(G.notes_json):null;if(q!=null&&q.ublock_skipped||q!=null&&q.cookie_ext_skipped){const B=q.ublock_skipped&&q.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":q.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";h.current(B,H,"warning"),le(K,"warning",H)}else K||h.current(null,H,"success"),le(K,"archived")}catch{K||h.current(null,H,"success"),le(K,"archived")}}else if(G.status==="failed"){clearInterval(o.current.get(F)),o.current.delete(F);const q=G.error_text||"Capture failed.";x(T=>T.map(B=>B.id===N?{...B,status:"failed",error:q}:B)),h.current(q,H),le(K,"failed",H)}}catch(G){clearInterval(o.current.get(F)),o.current.delete(F);const q=G.message||"Network error";x(T=>T.map(B=>B.id===N?{...B,status:"failed",error:q}:B)),h.current(q,H),le(K,"failed",H)}},500);o.current.set(F,pe)}function le(N,F,H=null){if(!N)return;const X=c.current.get(N);if(!X||(F==="archived"||F==="warning"?(X.archived++,F==="warning"&&(X.warnings++,H&&X.warningLocators.push(H))):(X.failed++,H&&X.failedLocators.push(H)),X.archived+X.failed0?`${K} archived (${pe} with warnings)`:`${K} archived`;B=G>0?`${Ze}, ${G} failed`:Ze}const Ce=K===0?"error":G>0||pe>0?"warning":"success",ke=[];q.length>0&&ke.push(`Failed: +${q.map(Ze=>` ${Ze}`).join(` +`)}`),T.length>0&&ke.push(`With warnings: +${T.map(Ze=>` ${Ze}`).join(` +`)}`);const Xn=ke.length>0?ke.join(` +`):null;h.current(Xn,null,Ce,B)}async function de(N,F=null){if(!N.locator.trim())return;const H=t,X=N.locator.trim(),K=N.quality||"best";x(pe=>pe.map(G=>G.id===N.id?{...G,status:"submitting",error:null}:G));try{const G=await Nh(H,X,K,{ublock_enabled:W,reader_mode:A,cookie_ext_enabled:_,modal_closer_enabled:C,via_freedium:$});x(q=>q.map(T=>T.id===N.id?{...T,status:"running",jobUid:G.job_uid,archiveId:H}:T)),ee(N.id,G.job_uid,X,H,F)}catch(pe){const G=pe.message||"Submission failed.";x(q=>q.map(T=>T.id===N.id?{...T,status:"failed",error:G}:T)),h.current(G,X),le(F,"failed",X)}}function ne(){var H,X;const N=y.filter(K=>K.status==="idle"&&K.locator.trim());if(N.length===0)return;const F=N.length>1?((H=crypto.randomUUID)==null?void 0:H.call(crypto))??`batch-${Date.now()}`:null;F&&c.current.set(F,{total:N.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]}),N.forEach(K=>de(K,F)),(X=i.current)==null||X.close()}function D(){x(N=>[...N,ar()])}function b(N){clearTimeout(u.current.get(N)),u.current.delete(N),x(F=>{const H=F.filter(X=>X.id!==N);return H.length===0?[ar()]:H})}function M(N){x(F=>F.map(H=>H.id===N?{...H,status:"idle",error:null}:H))}function Y(N,F){if(clearTimeout(u.current.get(N)),x(X=>X.map(K=>K.id===N?{...K,locator:F,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best"}:K)),!Td(F))return;const H=setTimeout(async()=>{u.current.delete(N),x(X=>X.map(K=>K.id===N?{...K,probeState:"probing"}:K));try{const X=await _h(g.current,F.trim());x(K=>K.map(pe=>{if(pe.id!==N||pe.locator!==F)return pe;const G=X.qualities??[],q=X.has_audio??!1,T=G.length===0&&q?"audio":"best";return{...pe,probeState:"done",probeQualities:G,probeHasAudio:q,quality:T}}))}catch{x(X=>X.map(K=>K.id===N?{...K,probeState:"idle",probeQualities:null}:K))}},600);u.current.set(N,H)}function U(N,F){x(H=>H.map(X=>X.id===N?{...X,quality:F}:X))}const fe=y.filter(N=>N.status==="idle"&&N.locator.trim()).length,ae=ru(y);return s.jsx("dialog",{ref:i,className:"capture-dialog",children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:y.map((N,F)=>s.jsx(im,{item:N,autoFocus:F===y.length-1&&N.status==="idle",onLocatorChange:H=>Y(N.id,H),onQualityChange:H=>U(N.id,H),onRemove:()=>b(N.id),onReset:()=>M(N.id),onSubmit:ne},N.id))}),s.jsxs("button",{type:"button",className:"capture-add-row",onClick:D,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add another"]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>j(N=>!N),"aria-expanded":k,children:[s.jsx("svg",{className:`capture-chevron${k?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),k&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":W,className:`ext-toggle ext-toggle--sm${W?" ext-toggle--on":""}`,onClick:()=>d(N=>N===null?!W:!N),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(v!=null&&v.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":_,className:`ext-toggle ext-toggle--sm${_?" ext-toggle--on":""}`,onClick:()=>P(N=>!N),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":A,className:`ext-toggle ext-toggle--sm${A?" ext-toggle--on":""}`,onClick:()=>Q(N=>!N),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":C,className:`ext-toggle ext-toggle--sm${C?" ext-toggle--on":""}`,onClick:()=>S(N=>!N),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Freedium mirror"}),s.jsx("span",{className:"capture-ext-desc",children:"Route paywalled articles through a Freedium mirror (Medium, NYT, WaPo, etc.)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":$,className:`ext-toggle ext-toggle--sm${$?" ext-toggle--on":""}`,onClick:()=>L(N=>!N),"aria-label":"Toggle Freedium mirror for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:ne,disabled:fe===0,children:fe>1?`Archive ${fe}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var N;return(N=i.current)==null?void 0:N.close()},children:ae?"Close":"Cancel"})]})]})})}function im({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onReset:i,onSubmit:a}){const o=f.useRef(null),u=e.status==="submitting"||e.status==="running";f.useEffect(()=>{var g;t&&e.status==="idle"&&((g=o.current)==null||g.focus())},[t]);const c=(()=>{if(e.status==="completed"||u||!Td(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const g=e.probeQualities??[],m=e.probeHasAudio??!1;return g.length===0&&!m?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):g.length===0&&m?s.jsx("select",{className:"capture-quality",value:"audio",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:h=>r(h.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),g.map(h=>s.jsx("option",{value:h,children:h},h)),m&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})();return s.jsxs("div",{className:`capture-row capture-row--${e.status}`,children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx(am,{status:e.status}),s.jsx("input",{ref:o,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"&&a()},disabled:u||e.status==="completed",autoComplete:"off",spellCheck:!1}),c,e.status==="failed"&&s.jsx("button",{type:"button",className:"capture-row-action",onClick:i,title:"Retry",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M13 2.5A7 7 0 1 1 6.5 1"}),s.jsx("polyline",{points:"6.5 1 4 3.5 6.5 6"})]})}),!u&&e.status!=="completed"&&e.status!=="failed"&&s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error})]})}function am({status:e}){return e==="submitting"||e==="running"?s.jsx("span",{className:"cap-dot cap-dot--running","aria-label":"Running",children:s.jsx("span",{className:"cap-spinner"})}):e==="completed"?s.jsx("span",{className:"cap-dot cap-dot--ok","aria-label":"Done",children:"✓"}):e==="failed"?s.jsx("span",{className:"cap-dot cap-dot--err","aria-label":"Failed",children:"✕"}):s.jsx("span",{className:"cap-dot cap-dot--idle","aria-hidden":"true"})}function ql(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function rn(e){return om(e)??""}function bd(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const lu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Ua(e){return lu[e]??lu.other}function Pd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function um({entry:e,archiveId:t,isSelected:n,isMultiSelected:r,onRowClick:l}){const[i,a]=f.useState(!1),u=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!i?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>a(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Ua(e.source_kind)}}),c=n||r;function g(m){m.stopPropagation(),l(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}return s.jsxs("div",{className:[n&&"is-selected",r&&"is-multi-selected"].filter(Boolean).join(" ")||void 0,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:m=>{m.shiftKey&&m.preventDefault()},onClick:m=>l(e,m),onKeyDown:m=>{m.key==="Enter"&&l(e,m)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${c?" is-checked":""}`,"aria-pressed":c,"aria-label":c?"Deselect entry":"Select entry",onClick:g,onKeyDown:m=>m.stopPropagation()})}),s.jsx("div",{className:"col-added",children:bd(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:u}),s.jsx("span",{className:"entry-title",children:rn(e.title)||rn(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:rn(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:ql(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${ql(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:rn(e.original_url)})]})}function cm({entries:e,selectedUids:t,onRowClick:n,archiveId:r}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsx("div",{id:"entries-body",children:e.map(l=>s.jsx(um,{entry:l,archiveId:r,isSelected:t.size===1&&t.has(l.entry_uid),isMultiSelected:t.size>=2&&t.has(l.entry_uid),onRowClick:n},l.entry_uid))})]})})}function dm(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function fm({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function pm({runs:e}){const[t,n]=f.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:dm(l.started_at)}),s.jsxs("td",{children:[s.jsx(fm,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const hm=4;function mm({archives:e}){const{currentUser:t}=f.useContext(hs)??{},n=t&&(t.role_bits&hm)!==0,[r,l]=f.useState("users"),[i,a]=f.useState([]),[o,u]=f.useState([]),[c,g]=f.useState(!1),[m,h]=f.useState(null),[y,x]=f.useState(""),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(null),[_,P]=f.useState(!1),[C,S]=f.useState(""),[$,L]=f.useState(""),[W,A]=f.useState(null),[Q,ee]=f.useState(!1),le=f.useCallback(async()=>{if(n){g(!0),h(null);try{const[b,M]=await Promise.all([Oh(),Ah()]);a(b),u(M)}catch(b){h(b.message)}finally{g(!1)}}},[n]);f.useEffect(()=>{le()},[le]);async function de(b){const M=b.status==="active"?"disabled":"active";try{await Mh(b.user_uid,M),a(Y=>Y.map(U=>U.user_uid===b.user_uid?{...U,status:M}:U))}catch(Y){h(Y.message)}}async function ne(b){if(b.preventDefault(),!y.trim()||!k){w("Username and password required");return}P(!0),w(null);try{await Fh(y.trim(),k,p.trim()||void 0),x(""),j(""),d(""),await le()}catch(M){w(M.message)}finally{P(!1)}}async function D(b){if(b.preventDefault(),!C.trim()||!$.trim()){A("Slug and name required");return}ee(!0),A(null);try{await Bh(C.trim(),$.trim()),S(""),L(""),await le()}catch(M){A(M.message)}finally{ee(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(b=>s.jsxs("tr",{className:b.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:b.username}),s.jsx("td",{className:"muted",children:b.email||"—"}),s.jsx("td",{children:b.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${b.status}`,children:b.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>de(b),children:b.status==="active"?"Ban":"Unban"})})]},b.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ne,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:y,onChange:b=>x(b.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:k,onChange:b=>j(b.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:b=>d(b.target.value)}),v&&s.jsx("div",{className:"form-msg form-msg--err",children:v}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(b=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:b.slug})}),s.jsx("td",{children:b.name}),s.jsx("td",{children:b.level}),s.jsx("td",{children:b.bit_position}),s.jsx("td",{children:b.is_builtin?"✓":""})]},b.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:D,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:C,onChange:b=>S(b.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:$,onChange:b=>L(b.target.value),required:!0}),W&&s.jsx("div",{className:"form-msg form-msg--err",children:W}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:Q,children:Q?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(b=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:b.label}),s.jsx("div",{className:"muted",children:b.archive_path})]},b.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(b=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:b.label}),s.jsx("div",{className:"muted",children:b.archive_path})]},b.id))})]})}function Ld({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(Ld,{node:r,onPick:t},r.tag.tag_uid))})})]})}function su({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){f.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(Ld,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function zd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=f.useState(""),a=f.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await jh(t,c),n()}catch(g){alert(g.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function Rd({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:g,pendingCreateParentUid:m,onCreateDone:h,onCreateCancel:y}){var W;const x=n===e.tag.full_path,[k,j]=f.useState(!1),[p,d]=f.useState(""),v=f.useRef(!1);function w(){if(k)return;if(c){g(e);return}const A=x?null:e.tag.full_path;r(A),l("archive")}function _(A){A.stopPropagation(),!c&&(d(e.tag.slug),j(!0))}async function P(){const A=p.trim();if(!A||A===e.tag.slug){j(!1);return}try{const Q=await wh(t,e.tag.tag_uid,A);i(e.tag.full_path,Q.full_path),o()}catch{}finally{j(!1)}}async function C(A){var ee;A.stopPropagation();const Q=((ee=e.children)==null?void 0:ee.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(Q))try{await kh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const S={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:g,pendingCreateParentUid:m,onCreateDone:h,onCreateCancel:y},$=m===e.tag.tag_uid,L=((W=e.children)==null?void 0:W.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${c?" tag-node-row--move-select":""}`,children:[k?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:A=>d(A.target.value),onKeyDown:A=>{A.key==="Enter"&&A.currentTarget.blur(),A.key==="Escape"&&(v.current=!0,A.currentTarget.blur())},onBlur:()=>{v.current?(v.current=!1,j(!1)):P()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${c?" tag-node-btn--move-select":""}`,title:c?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:w,onDoubleClick:c?void 0:_,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!c&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:A=>{A.stopPropagation(),_(A)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!k&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:C,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||$)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(A=>s.jsx(Rd,{node:A,...S},A.tag.tag_uid)),$&&s.jsx("li",{children:s.jsx(zd,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:y})})]})})]})}function gm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,g]=f.useState(null),[m,h]=f.useState(null);function y(){g("select-source"),h(null)}function x(){g(null),h(null)}f.useEffect(()=>{if(c!=="select-source")return;function Q(ee){ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),x())}return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[c]);function k(Q){h(Q),g("select-dest")}async function j(Q){const ee=m.tag.full_path,le=m.tag.tag_uid,de=(Q==null?void 0:Q.tag_uid)??null;x();try{const ne=await Sh(e,le,de);i(ee,ne.full_path),o()}catch(ne){alert(ne.message||"Move failed")}}const[p,d]=f.useState(null),[v,w]=f.useState(void 0);function _(){d("select-parent"),w(void 0)}function P(){d(null),w(void 0)}function C(Q){w(Q??null),d("input")}function S(){d(null),w(void 0),o()}const $=c==="select-source",L=p==="input"?v?v.tag_uid:"__root__":void 0,W={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:$,onMoveSourceSelect:k,pendingCreateParentUid:L,onCreateDone:S,onCreateCancel:P},A=L==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:$?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:_,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:y,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!A?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(Q=>s.jsx(Rd,{node:Q,...W},Q.tag.tag_uid)),A&&s.jsx("li",{children:s.jsx(zd,{parentPath:null,archiveId:e,onDone:S,onCancel:P})})]})]}),p==="select-parent"&&s.jsx(su,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:C,onCancel:P}),c==="select-dest"&&m&&s.jsx(su,{title:`Move "${m.tag.slug}" under…`,tagNodes:t,excludeUid:m.tag.tag_uid,onPick:j,onCancel:x})]})}const pr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],vm=e=>{var t;return((t=pr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function ym({archiveId:e}){const[t,n]=f.useState([]),[r,l]=f.useState(!1),[i,a]=f.useState(null),[o,u]=f.useState(null),[c,g]=f.useState(null),[m,h]=f.useState(!1),[y,x]=f.useState(null),[k,j]=f.useState(""),[p,d]=f.useState(""),[v,w]=f.useState(2),[_,P]=f.useState(!1),[C,S]=f.useState(null),[$,L]=f.useState(""),[W,A]=f.useState(2),[Q,ee]=f.useState(!1),[le,de]=f.useState(null),[ne,D]=f.useState(!1),[b,M]=f.useState(""),Y=f.useRef(null),U=t.find(T=>T.collection_uid===o)??null,fe=(U==null?void 0:U.slug)==="_default_",ae=f.useCallback(async()=>{if(e){l(!0),a(null);try{const T=await Cd(e);n(T)}catch(T){a(T.message)}finally{l(!1)}}},[e]),N=f.useCallback(async T=>{if(!T){g(null);return}h(!0),x(null);try{const B=await Hh(e,T);g(B)}catch(B){x(B.message)}finally{h(!1)}},[e]);f.useEffect(()=>{ae()},[ae]),f.useEffect(()=>{N(o)},[o,N]),f.useEffect(()=>{ne&&Y.current&&Y.current.focus()},[ne]);async function F(T){T.preventDefault();const B=k.trim(),Ce=p.trim();if(!(!B||!Ce)){P(!0),S(null);try{const ke=await Uh(e,B,Ce,v);j(""),d(""),w(2),await ae(),u(ke.collection_uid)}catch(ke){S(ke.message)}finally{P(!1)}}}async function H(){const T=b.trim();if(!T||!U){D(!1);return}try{await nu(e,U.collection_uid,{name:T}),await ae(),g(B=>B&&{...B,name:T})}catch(B){a(B.message)}finally{D(!1)}}async function X(T){if(U)try{await nu(e,U.collection_uid,{default_visibility_bits:T}),await ae(),g(B=>B&&{...B,default_visibility_bits:T})}catch(B){a(B.message)}}async function K(){if(U&&window.confirm(`Delete collection "${U.name}"? Entries will not be deleted.`))try{await Kh(e,U.collection_uid),u(null),g(null),await ae()}catch(T){a(T.message)}}async function pe(T){T.preventDefault();const B=$.trim();if(!(!B||!U)){ee(!0),de(null);try{await Ed(e,U.collection_uid,B,W),L(""),await N(U.collection_uid)}catch(Ce){de(Ce.message)}finally{ee(!1)}}}async function G(T){if(U)try{await Wh(e,U.collection_uid,T),await N(U.collection_uid)}catch(B){x(B.message)}}async function q(T,B){if(U)try{await Vh(e,U.collection_uid,T,B),g(Ce=>Ce&&{...Ce,entries:Ce.entries.map(ke=>ke.entry_uid===T?{...ke,collection_visibility_bits:B}:ke)})}catch(Ce){x(Ce.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(T=>s.jsxs("button",{className:`coll-sidebar-row${o===T.collection_uid?" is-active":""}`,onClick:()=>u(T.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:T.name}),s.jsx("span",{className:"coll-row-meta",children:vm(T.default_visibility_bits)})]},T.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),U?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[ne?s.jsx("input",{ref:Y,className:"coll-rename-input",value:b,onChange:T=>M(T.target.value),onBlur:H,onKeyDown:T=>{T.key==="Enter"&&H(),T.key==="Escape"&&D(!1)}}):s.jsxs("h3",{className:`coll-detail-name${fe?"":" coll-detail-name--editable"}`,title:fe?void 0:"Click to rename",onClick:()=>{fe||(M(U.name),D(!0))},children:[(c==null?void 0:c.name)??U.name,!fe&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!fe&&s.jsx("button",{className:"coll-delete-btn",onClick:K,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??U.default_visibility_bits,onChange:T=>X(Number(T.target.value)),disabled:fe,children:pr.map(T=>s.jsx("option",{value:T.value,children:T.label},T.value))})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),m&&s.jsx("div",{className:"muted",children:"Loading…"}),y&&s.jsx("div",{className:"collections-error",children:y}),!m&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(T=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:T.title||T.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:T.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:T.collection_visibility_bits,onChange:B=>q(T.entry_uid,Number(B.target.value)),children:pr.map(B=>s.jsx("option",{value:B.value,children:B.label},B.value))}),!fe&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>G(T.entry_uid),title:"Remove from collection",children:"×"})]})]},T.entry_uid))}))]}),!fe&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:pe,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:$,onChange:T=>L(T.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:W,onChange:T=>A(Number(T.target.value)),children:pr.map(T=>s.jsx("option",{value:T.value,children:T.label},T.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:Q,children:Q?"…":"Add"})]}),le&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:le})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:F,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:k,onChange:T=>{j(T.target.value),p||d(T.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:T=>d(T.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:v,onChange:T=>w(Number(T.target.value)),children:pr.map(T=>s.jsx("option",{value:T.value,children:T.label},T.value))})]}),C&&s.jsx("div",{className:"collections-error",children:C}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const xm=4;function wm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=f.useContext(hs)??{},i=r&&(r.role_bits&xm)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(km,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(jm,{}),e==="instance"&&i&&s.jsx(Sm,{}),e==="cookies"&&i&&s.jsx(_m,{}),e==="extensions"&&i&&s.jsx(Cm,{}),e==="storage"&&i&&s.jsx(Nm,{archiveId:n})]})}function km({currentUser:e,setCurrentUser:t}){const[n,r]=f.useState((e==null?void 0:e.display_name)??""),[l,i]=f.useState(!1),[a,o]=f.useState(null),[u,c]=f.useState(""),[g,m]=f.useState(""),[h,y]=f.useState(""),[x,k]=f.useState(!1),[j,p]=f.useState(null);async function d(w){w.preventDefault(),i(!0),o(null);try{await Lh(n),t(_=>({..._,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(_){o({ok:!1,text:_.message})}finally{i(!1)}}async function v(w){if(w.preventDefault(),g!==h){p({ok:!1,text:"Passwords do not match."});return}k(!0),p(null);try{await Rh(u,g),c(""),m(""),y(""),p({ok:!0,text:"Password changed."})}catch(_){p({ok:!1,text:_.message})}finally{k(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:d,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const _=w.target.checked;try{await zh({humanize_slugs:_}),t(P=>({...P,humanize_slugs:_}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:g,onChange:w=>m(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:w=>y(w.target.value),required:!0})]}),j&&s.jsx("div",{className:`form-msg form-msg--${j.ok?"ok":"err"}`,children:j.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function jm(){const[e,t]=f.useState([]),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(""),[u,c]=f.useState(!1),[g,m]=f.useState(null),h=f.useCallback(async()=>{r(!0),i(null);try{t(await Dh())}catch(k){i(k.message)}finally{r(!1)}},[]);f.useEffect(()=>{h()},[h]);async function y(k){if(k.preventDefault(),!!a.trim()){c(!0);try{const j=await $h(a.trim());m(j),o(""),h()}catch(j){i(j.message)}finally{c(!1)}}}async function x(k){try{await Ih(k),t(j=>j.filter(p=>p.token_uid!==k))}catch(j){i(j.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),g&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:g.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>m(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:y,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:k=>o(k.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(k=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:k.name}),s.jsxs("div",{className:"muted",children:["Created ",k.created_at.slice(0,10),k.last_used_at&&` · Last used ${k.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(k.token_uid),children:"Revoke"})]},k.token_uid))]})]})})}function Sm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState(!1),[u,c]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(m){i(m.message)}finally{r(!1)}})()},[]);async function g(m){m.preventDefault(),o(!0),c(null);try{await _l(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:g,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([m,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[m],onChange:y=>t(x=>({...x,[m]:y.target.checked}))}),h]},m)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:m=>t(h=>({...h,default_entry_visibility:Number(m.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function qs(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function Nm({archiveId:e}){const[t,n]=f.useState("idle"),[r,l]=f.useState(null),[i,a]=f.useState(null),[o,u]=f.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function g(){n("scanning"),u(null),l(null);try{const y=await Xh(e);l(y),n("scanned")}catch(y){u(y.message),n("error")}}async function m(){n("deleting"),u(null);try{const y=await Jh(e);a(y),n("done")}catch(y){u(y.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:g,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:qs(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:m,children:["Delete (",qs(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:qs(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function _m(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(null),[a,o]=f.useState("global"),[u,c]=f.useState(""),[g,m]=f.useState("{}"),[h,y]=f.useState(null),[x,k]=f.useState(!1),[j,p]=f.useState({});f.useEffect(()=>{d()},[]);async function d(){r(!0),i(null);try{t(await Yh())}catch(S){i(S.message)}finally{r(!1)}}async function v(S){S.preventDefault();try{JSON.parse(g)}catch{y({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}k(!0),y(null);try{await Gh(a==="global"?null:u.trim(),a,g),c(""),m("{}"),o("global"),y({ok:!0,text:"Rule added."}),await d()}catch($){y({ok:!1,text:$.message})}finally{k(!1)}}async function w(S){try{await em(S),await d()}catch($){i($.message)}}function _(S){p($=>({...$,[S.rule_uid]:{cookiesInput:S.cookies_json,saving:!1,msg:null}}))}function P(S){p($=>{const L={...$};return delete L[S],L})}async function C(S){const $=j[S.rule_uid];try{JSON.parse($.cookiesInput)}catch{p(L=>({...L,[S.rule_uid]:{...L[S.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[S.rule_uid]:{...L[S.rule_uid],saving:!0,msg:null}}));try{await Zh(S.rule_uid,{cookies_json:$.cookiesInput}),P(S.rule_uid),await d()}catch(L){p(W=>({...W,[S.rule_uid]:{...W[S.rule_uid],saving:!1,msg:{ok:!1,text:L.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(S=>{const $=j[S.rule_uid],L=S.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[S.pattern_kind,":"]})," ",s.jsx("code",{children:S.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:L}),s.jsx("td",{children:$?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:$.cookiesInput,onChange:W=>p(A=>({...A,[S.rule_uid]:{...A[S.rule_uid],cookiesInput:W.target.value}}))}),$.msg&&s.jsx("div",{className:`form-msg form-msg--${$.msg.ok?"ok":"err"}`,children:$.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:$.saving,onClick:()=>C(S),children:$.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(S.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:S.cookies_json})}),s.jsx("td",{children:!$&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>_(S),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(S.rule_uid),children:"Del"})]})})]},S.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:v,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:S=>o(S.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:S=>c(S.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:g,onChange:S=>m(S.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function Cm(){const[e,t]=f.useState(null),[n,r]=f.useState(!0),[l,i]=f.useState(!1),[a,o]=f.useState(null);f.useEffect(()=>{(async()=>{try{t(await Ba())}catch(j){o({ok:!1,text:j.message})}finally{r(!1)}})()},[]);async function u(j){i(!0),o(null);try{await _l({ublock_enabled:j}),t(p=>({...p,ublock_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(j){i(!0),o(null);try{await _l({cookie_ext_enabled:j}),t(p=>({...p,cookie_ext_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function g(j){i(!0),o(null);try{await _l({modal_closer_enabled:j}),t(p=>({...p,modal_closer_enabled:j})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const m=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,y=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,k=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!m&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!y&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":k,className:`ext-toggle${k?" ext-toggle--on":""}`,onClick:()=>g(!k),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const iu={0:"Private",1:"Public",2:"Users only",3:"Public"},Em=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Tm({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:g,humanizeTags:m,onDetailRefresh:h,onOpenPreview:y,onPlay:x}){var bt;const[k,j]=f.useState([]),[p,d]=f.useState(""),[v,w]=f.useState([]),[_,P]=f.useState(""),C=f.useRef(0),S=f.useRef(!1),[$,L]=f.useState(!1),[W,A]=f.useState(""),[Q,ee]=f.useState("idle"),[le,de]=f.useState(""),ne=f.useRef(null),[D,b]=f.useState(!1);f.useEffect(()=>{b(!1)},[(bt=l==null?void 0:l.summary)==null?void 0:bt.entry_uid]);const M=(n==null?void 0:n.size)>=2,[Y,U]=f.useState(""),[fe,ae]=f.useState("idle"),[N,F]=f.useState(""),[H,X]=f.useState([]),[K,pe]=f.useState(""),[G,q]=f.useState("idle"),[T,B]=f.useState(""),[Ce,ke]=f.useState("idle");f.useEffect(()=>{const I=++C.current;if(ne.current&&(clearInterval(ne.current),ne.current=null),ee("idle"),de(""),!t||!e){j([]),w([]);return}L(!1),A(""),S.current=!1,j([]),Promise.all([dl(e,t.entry_uid),Qh(e,t.entry_uid)]).then(([se,Qe])=>{I===C.current&&(j(se),w(Qe))}).catch(()=>{})},[t,e]),f.useEffect(()=>()=>{clearInterval(ne.current)},[]),f.useEffect(()=>{if(!M||!e){X([]);return}Cd(e).then(X).catch(()=>X([]))},[M,e]),f.useEffect(()=>{U(""),ae("idle"),F(""),pe(""),q("idle"),B(""),ke("idle")},[n]);async function Xn(){const I=n.size;if(!window.confirm(`Delete ${I} entr${I===1?"y":"ies"}? This cannot be undone.`))return;ke("running");const se=new Set;for(const Qe of n)try{await tu(e,Qe),se.add(Qe)}catch{}ke("idle"),g==null||g(se)}async function Ze(){const I=Y.trim();if(I){ae("running"),F("");try{for(const se of n)await eu(e,se,I);U(""),ae("done"),o==null||o(),setTimeout(()=>ae("idle"),1800)}catch(se){F(se.message),ae("error")}}}async function ms(){if(!K)return;q("running"),B("");const I=[];for(const se of n)try{await Ed(e,K,se)}catch{I.push(se)}I.length>0?(B(`Failed for ${I.length} entr${I.length===1?"y":"ies"}.`),q("error")):(q("done"),setTimeout(()=>q("idle"),1800))}async function gs(){const I=W.trim()||null;try{await yh(e,t.entry_uid,I),u==null||u(t.entry_uid,I)}catch{}finally{L(!1)}}async function Vr(){const I=p.trim();if(!(!I||!t))try{await eu(e,t.entry_uid,I),d(""),P("");const se=await dl(e,t.entry_uid);j(se),o()}catch(se){P(se.message)}}async function vs(I){try{await xh(e,t.entry_uid,I);const se=await dl(e,t.entry_uid);j(se),o()}catch{}}async function ys(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await tu(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function xs(){if(!t||!e||Q==="running")return;const I=C.current,se=t.entry_uid;ee("running"),de("");try{const{job_uid:Qe}=await qh(e,se);if(C.current!==I)return;ne.current=setInterval(async()=>{try{const qt=await _d(e,Qe);if(qt.status==="completed"){if(clearInterval(ne.current),ne.current=null,C.current!==I)return;ee("done");const qn=await dl(e,se);if(C.current!==I)return;j(qn),h==null||h()}else if(qt.status==="failed"){if(clearInterval(ne.current),ne.current=null,C.current!==I)return;ee("error"),de(qt.error_text||"Re-archive failed.")}}catch{if(clearInterval(ne.current),ne.current=null,C.current!==I)return;ee("error"),de("Network error while polling.")}},500)}catch(Qe){if(C.current!==I)return;ee("error"),de(Qe.message||"Failed to start re-archive.")}}const ws=l?[["Added",bd(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",iu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],ks=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),js=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),hn=l?l.artifacts.findIndex(I=>I.artifact_role==="primary_media"):-1,mn=hn>=0?l.artifacts[hn]:null,Qr=mn?mn.relpath.split(".").pop().toLowerCase():"",Kr=mn&&ks.has(Qr),gn=hn>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${hn}`:null,Jn=l&&!Kr&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||mn&&js.has(Qr));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),M?s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),N&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:N}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:Y,onChange:I=>U(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Ze()}}),s.jsx("button",{className:"tag-add-btn",onClick:Ze,disabled:fe==="running"||!Y.trim(),children:fe==="running"?"…":fe==="done"?"✓":"Add"})]})]}),H.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:K,onChange:I=>pe(I.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),H.map(I=>s.jsx("option",{value:I.collection_uid,children:I.name},I.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:ms,disabled:!K||G==="running",children:G==="running"?"…":G==="done"?"✓":G==="error"?"!":"Add"})]}),T&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:T})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:Xn,disabled:Ce==="running",children:Ce==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[$?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:W,onChange:I=>A(I.target.value),onKeyDown:I=>{I.key==="Enter"&&I.currentTarget.blur(),I.key==="Escape"&&(S.current=!0,I.currentTarget.blur())},onBlur:()=>{S.current?L(!1):gs(),S.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{A(l.summary.title??""),L(!0)},children:[rn(l.summary.title)||rn(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Ua(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Em,{})})]}),Kr&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(gn,t),children:"▶ Play"}),Jn&&y&&s.jsx("button",{className:"rail-preview-btn",onClick:y,children:"Preview"}),s.jsx("div",{className:"meta-list",children:ws.filter(([,I])=>I!=null&&I!=="").map(([I,se])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:I}),s.jsx("span",{className:`meta-v${I==="Root"?" mono":""}`,children:rn(se)})]},I))}),l.artifacts.length>0&&(()=>{const I=l.artifacts.map((R,V)=>({...R,_idx:V})),se=I.filter(R=>R.artifact_role==="font"),Qe=I.filter(R=>R.artifact_role!=="font"),qt=se.reduce((R,V)=>R+(V.byte_size||0),0),qn=l.summary.entry_uid,E=R=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${qn}/artifacts/${R._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:R.artifact_role==="font"?R.relpath.split("/").pop():R.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:R.byte_size!=null?ql(R.byte_size):"—"})]})},R._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[Qe.map(E),se.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":D,onClick:()=>b(R=>!R),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${D?" open":""}`,children:"›"}),` fonts (${se.length})`]}),s.jsx("span",{className:"artifact-size",children:ql(qt)})]}),D&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:se.map(E)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!M&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),k.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:k.map(I=>s.jsxs("span",{className:"tag-pill",title:I.full_path,children:[m?Pd(I.full_path):I.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${I.full_path}`,onClick:()=>vs(I.tag_uid),children:"×"})]},I.tag_uid))}),_&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:_}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:p,onChange:I=>d(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Vr()}}),s.jsx("button",{className:"tag-add-btn",onClick:Vr,children:"Add"})]})]}),v.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),v.map(I=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:I.collection_uid}),s.jsx("span",{className:"vis-badge",children:iu[I.visibility_bits]??`bits:${I.visibility_bits}`})]},I.collection_uid))]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:xs,disabled:Q==="running",children:Q==="running"?"Re-archiving…":"Re-archive"}),Q==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),Q==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:le})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:ys,children:"Delete entry"})})]})]})}function bm({src:e}){const t=f.useRef(null);return f.useEffect(()=>{t.current&&t.current.load()},[e]),s.jsx("div",{className:"preview-video-wrap",style:{background:"#111",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",minHeight:"240px"},children:e?s.jsxs("video",{ref:t,controls:!0,autoPlay:!1,style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:e}),"Your browser does not support the video element."]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function au({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function Pm({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function Dd(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function ou(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const J={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},je={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Ys={article:{background:je.bg,color:je.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:je.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:je.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:je.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:je.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${je.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:je.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${je.border}`,padding:"2px 14px",margin:"14px 0",color:je.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${je.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:je.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${je.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:je.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:je.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:je.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:je.accent,textDecoration:"none"}};function Lm(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function On(e,t,n){return e&&n[e]?n[e]:t||null}function $d(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function Ha(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function Id(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=Ha(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function Od(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=Ha(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const uu=/https?:\/\/[^\s<>"'\])]+/g,zm=/[.,;:!?)()]+$/;function Yl(e,t){const n=[];let r=0,l;for(uu.lastIndex=0;(l=uu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(zm,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rId(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>Od(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return Yl(ou(e),J.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,g])=>c<=o&&g>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const g=e.slice(o,c),m=r.filter(x=>x.s<=o&&x.e>=c),h=m.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:J.link,children:h.display||g},u);const y=m.find(x=>x.kind==="mention");return y?s.jsx("a",{href:`https://x.com/${y.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:J.link,children:g},u):s.jsx("span",{children:Yl(ou(g),J.link)},u)}).filter(o=>o!==null)}function Dm(e,t,n,r,l=J){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=Id(u,e);c&&i.push(c)}for(const u of r){const c=Od(u,e);c&&i.push(c)}if(i.length===0)return Yl(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const g=o[c+1],m=i.filter(j=>j.s<=u&&j.e>=g),h=e.slice(u,g);let y;if(h.includes(` +`)){const j=h.split(` +`);y=j.flatMap((p,d)=>dj.kind==="style"&&j.style==="Code")&&(y=s.jsx("code",{style:l.iCode,children:y})),m.some(j=>j.kind==="style"&&j.style==="Bold")&&(y=s.jsx("strong",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Italic")&&(y=s.jsx("em",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Underline")&&(y=s.jsx("u",{children:y})),m.some(j=>j.kind==="style"&&j.style==="Strikethrough")&&(y=s.jsx("s",{children:y}));const x=m.find(j=>j.kind==="url");if(x){const j=/^https?:\/\/t\.co\//i.test(y);y=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:j?x.display:y})}const k=m.find(j=>j.kind==="mention");return k&&(y=s.jsx("a",{href:`https://x.com/${k.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:y})),s.jsx("span",{children:typeof y=="string"?Yl(y,l.link):y},c)})}function $m(e,t,n){const r=(n==null?void 0:n.st)||J,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=On(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var g;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(g=n==null?void 0:n.onImgClick)==null||g.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx($d,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function Gs(e,t,n,r){const l=(r==null?void 0:r.st)||J,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=Dm(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const g=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return g?s.jsxs("a",{href:`https://x.com/i/status/${g[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx($d,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:$m(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function Im(e,t,n){const r=(n==null?void 0:n.st)||J,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Ys:J,u=e.cover_media||{},c=e.author||t||{},g=e.first_published_at_secs?Dd(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",g].filter(Boolean).join(" · "),y=On(u.local_path,u.url,n),x=On(c.avatar_local_path,c.avatar_url,n),k=s.jsxs(s.Fragment,{children:[i&&s.jsx(Fd,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),y&&s.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:j=>{!j.metaKey&&!j.ctrlKey&&(j.preventDefault(),a(y))},children:s.jsx("img",{src:y,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Im(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:Ys.article,children:s.jsx("div",{style:Ys.articleInner,children:k})}):s.jsx("div",{style:J.article,children:k})}function Fm({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:J.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function Fd({items:e,startIndex:t,onClose:n}){const[r,l]=f.useState(t);f.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:J.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:J.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:J.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:J.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:J.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:J.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:J.lightboxImg}),e.length>1&&s.jsxs("div",{style:J.lightboxNav,children:[s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:J.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function cu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var d,v;const[l,i]=f.useState(null),a=e.author||{},o=e.created_at_secs?Dd(e.created_at_secs):"",u=e.entities||{},c=On(a.avatar_local_path,a.avatar_url,r),g=t&&!n,m=e.is_quote_status===!0,h=t?J.tweetRowThread:J.tweetRow,y=e.full_text||"",x=((v=(d=e.extended_entities)==null?void 0:d.media)!=null&&v.length?e.extended_entities.media:u.media)||[],k=[],j=[];for(const w of x)if(w.type==="photo"){const _=On(w.local_path,w.media_url_https,r);_&&k.push({kind:"photo",src:_,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const _=w.local_path&&r[w.local_path]||(()=>{var C,S;return(S=(((C=w.video_info)==null?void 0:C.variants)||[]).filter($=>$.content_type==="video/mp4").sort(($,L)=>(L.bitrate||0)-($.bitrate||0))[0])==null?void 0:S.url})();_&&j.push({kind:w.type==="animated_gif"?"gif":"video",src:_})}const p=[];for(const w of x){if(!w.url||!(w.type==="photo"?k.some(C=>C.src===On(w.local_path,w.media_url_https,r)):j.length>0))continue;const P=Ha(w,y,w.url);P&&p.push([P.s,P.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Fd,{items:k,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:J.leftCol,children:[c?s.jsx("img",{src:c,style:J.avatar,alt:a.name||""}):s.jsx("div",{style:J.avatarPh}),g&&s.jsx("div",{style:J.threadLine})]}),s.jsxs("div",{style:J.rightCol,children:[s.jsxs("div",{style:J.authorRow,children:[s.jsx("span",{style:J.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:J.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:J.datePart,children:["· ",o]}),m&&s.jsx("span",{style:J.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:J.tweetText,children:Rm(y,u,p)}),k.length>0&&s.jsx("div",{style:J.mediaGrid,children:s.jsx(Fm,{photos:k,onOpen:w=>i(w)})}),j.map((w,_)=>s.jsx("div",{style:J.mediaGrid,children:s.jsx("video",{src:w.src,style:J.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},_)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:J.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function Mm({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=f.useState(!0),[u,c]=f.useState(null),[g,m]=f.useState([]);if(f.useEffect(()=>{if(o(!0),c(null),m([]),!n||!e||!t){o(!1);return}const x=n.map((j,p)=>({...j,index:p})).filter(j=>j.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let k=!1;return gh(e,t,x.map(j=>j.index)).then(async j=>{if(k)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,d=C=>{var $;const S=C.full_text||"";return((($=C.entities)==null?void 0:$.urls)||[]).map(L=>{var W;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((W=L.indices)==null?void 0:W.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const A=S.indexOf(L.url);if(A!==-1)return[A,A+L.url.length]}return null}).filter(Boolean)},v=(C,S,$)=>C.some(([L,W])=>L<=S&&W>=$),w=new Set;for(const C of j){const S=C.full_text||"",$=d(C);let L;for(p.lastIndex=0;(L=p.exec(S))!==null;)v($,L.index,L.index+L[0].length)||w.add(L[0])}const _=w.size>0?await vh([...w]).catch(()=>({})):{},P=j.map(C=>{var A;const S=C.full_text||"",$=d(C),L=[];let W;for(p.lastIndex=0;(W=p.exec(S))!==null;){const Q=W[0],ee=_[Q];ee&&ee!==Q&&!v($,W.index,W.index+Q.length)&&L.push({url:Q,expanded_url:ee,display_url:(()=>{try{const le=new URL(ee);return le.hostname+(le.pathname.length>1?"/…":"")}catch{return ee}})(),fromIndex:W.index,toIndex:W.index+Q.length})}return L.length===0?C:{...C,entities:{...C.entities||{},urls:[...((A=C.entities)==null?void 0:A.urls)||[],...L]}}});k||m(P)}).catch(j=>{k||c(j.message||"Failed to load tweet.")}).finally(()=>{k||o(!1)}),()=>{k=!0}},[e,t,n]),a)return s.jsx("div",{style:J.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:J.error,children:["Error: ",u]});if(g.length===0)return null;const h=Lm(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:J.threadOuter,children:g.map((x,k)=>s.jsx(cu,{tweet:x,isInThread:!0,isLast:k===g.length-1,artifactMap:h},x.id||k))});const y=g[0];return y.is_article&&y.article?s.jsx(Om,{article:y.article,tweetAuthor:y.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:J.card,children:s.jsx(cu,{tweet:y,isInThread:!1,isLast:!0,artifactMap:h})})}const Am=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Bm=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Um=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]);function Md({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const y=s.jsx(Mm,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?y:s.jsx("div",{className:"preview-tweet-wrap",children:y})}const c=a.findIndex(y=>y.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]});const g=a[c],m=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=g.relpath.split(".").pop().toLowerCase();return Am.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(bm,{src:m})}):Bm.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:m,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(au,{src:m,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(au,{src:m,type:"page",title:i.title,originalUrl:i.original_url})}):Um.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Pm,{src:m,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((y,x)=>s.jsxs("li",{children:[y.artifact_role,": ",y.relpath]},x))})]})}function Hm({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return f.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(Md,{archiveId:e,entry:t,detail:n})})]})})}function du(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function Wm({entry:e,src:t,archiveId:n,onClose:r}){const l=f.useRef(null),[i,a]=f.useState(!1),[o,u]=f.useState(0),[c,g]=f.useState(NaN),[m,h]=f.useState(1);f.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),g(NaN),a(!1))},[t]),f.useEffect(()=>{l.current&&(l.current.volume=m)},[m]);function y(){const d=l.current;d&&(i?d.pause():d.play().catch(()=>{}))}function x(d){const v=l.current;if(!v||!isFinite(c))return;const w=Number(d.target.value);v.currentTime=w,u(w)}function k(d){h(Number(d.target.value))}const j=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var d;return u(((d=l.current)==null?void 0:d.currentTime)??0)},onLoadedMetadata:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},onDurationChange:()=>{var d;return g(((d=l.current)==null?void 0:d.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Ua(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:j,children:j})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:y,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:du(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:du(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:m,onChange:k,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function Vm({archiveId:e,entryUid:t}){var h,y;const[n,r]=f.useState(null),[l,i]=f.useState(!0),[a,o]=f.useState(null),[u,c]=f.useState(!1);f.useEffect(()=>{if(!u)return;const x=document.documentElement,k=document.body,j=x.style.colorScheme,p=k.style.background;return x.style.colorScheme="dark",k.style.background="#000",()=>{x.style.colorScheme=j,k.style.background=p}},[u]),f.useEffect(()=>{c(!1),Vi(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const g=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,m=(y=n==null?void 0:n.summary)==null?void 0:y.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g}),m&&s.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(Md,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Qm=7e3;function Km({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Jm,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Xm(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Jm({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=f.useState(!1),i=e.type==="warning",a=e.type==="success";f.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Qm);return()=>clearTimeout(u)},[r,e.id,t]);const o=Xm(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const hs=f.createContext(null),or=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})(),qm=["archive","tags","collections","runs","admin","settings"],Ym=["profile","tokens","instance","cookies","extensions","storage"];function Yt(){const e=window.location.pathname.split("/").filter(Boolean),t=qm.includes(e[0])?e[0]:"archive",n=t==="settings"&&Ym.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null;return{view:t,settingsTab:n,q:l,tag:i,entry:a}}function Gm(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Zm(){const[e,t]=f.useState("loading"),[n,r]=f.useState(null);f.useEffect(()=>{(async()=>{if(await Ch()){t("setup");return}const R=await Ph();if(!R){t("login");return}r(R),t("authenticated")})()},[]),f.useEffect(()=>{const E=()=>{r(null),t("login")};return window.addEventListener("auth:expired",E),()=>window.removeEventListener("auth:expired",E)},[]),f.useEffect(()=>{const E=()=>{const{view:R,settingsTab:V,q:re,tag:ze,entry:et}=Yt();v(R),_(V),C(re),p(ze),m(et),y(null),k(et?new Set([et]):new Set)};return window.addEventListener("popstate",E),()=>window.removeEventListener("popstate",E)},[]);const[l,i]=f.useState([]),[a,o]=f.useState(null),[u,c]=f.useState([]),[g,m]=f.useState(()=>Yt().entry),[h,y]=f.useState(null),[x,k]=f.useState(()=>{const E=Yt().entry;return E?new Set([E]):new Set}),[j,p]=f.useState(()=>Yt().tag),[d,v]=f.useState(()=>Yt().view),[w,_]=f.useState(()=>Yt().settingsTab),[P,C]=f.useState(()=>Yt().q),[S,$]=f.useState(""),[L,W]=f.useState(!1),[A,Q]=f.useState([]),[ee,le]=f.useState([]),[de,ne]=f.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[D,b]=f.useState([]),M=f.useRef(0),[Y,U]=f.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[fe,ae]=f.useState(null),N=f.useRef(0),F=f.useRef(null),H=f.useRef(!1),X=f.useRef(!0),K=f.useRef(null),pe=(n==null?void 0:n.humanize_slugs)??!1;f.useEffect(()=>{const E=++N.current;ae(null),!(!h||!a)&&Vi(a,h.entry_uid).then(R=>{E===N.current&&ae(R)}).catch(()=>{})},[h,a]),f.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",de)},[de]);const G=f.useCallback(async(E,R,V)=>{if(E){W(!0);try{let re;R||V?re=await mh(E,R,V):re=await hh(E),c(re),k(ze=>{if(ze.size<2)return ze;const et=new Set(re.map(vn=>vn.entry_uid)),Yn=new Set([...ze].filter(vn=>et.has(vn)));return Yn.size===ze.size?ze:Yn}),$(re.length===0?"No results":`${re.length} result${re.length===1?"":"s"}`)}catch{c([]),$("Search failed. Try again.")}finally{W(!1)}}},[]);f.useEffect(()=>{e==="authenticated"&&ph().then(E=>{if(i(E),E.length>0){const R=E[0].id;o(R)}})},[e]),f.useEffect(()=>{if(a){if(X.current){X.current=!1,Promise.all([Js(a).then(Q),fl(a).then(le)]);return}p(null),y(null),m(null),k(new Set),Promise.all([G(a,"",null),Js(a).then(Q),fl(a).then(le)])}},[a]),f.useEffect(()=>{if(a===null)return;const E=setTimeout(()=>{G(a,P,j)},300);return()=>clearTimeout(E)},[P,a]),f.useEffect(()=>{a!==null&&(j!==null&&v("archive"),G(a,P,j))},[j,a]);const q=f.useCallback(E=>{o(E)},[]),T=f.useCallback(E=>{v(E),E==="tags"&&a&&fl(a).then(le)},[a]);f.useEffect(()=>{if(or)return;const E=Gm(d,w);window.location.pathname!==E&&history.pushState(null,"",E+window.location.search)},[d,w]);const B=f.useCallback(E=>{m(E?E.entry_uid:null),y(E)},[]),Ce=f.useCallback((E,R)=>{if(R.shiftKey&&K.current!==null){R.preventDefault();const V=u.findIndex(Gn=>Gn.entry_uid===K.current),re=u.findIndex(Gn=>Gn.entry_uid===E.entry_uid);if(V===-1||re===-1){K.current=E.entry_uid,k(new Set([E.entry_uid])),B(E);return}const ze=Math.min(V,re),et=Math.max(V,re),Yn=u.slice(ze,et+1),vn=new Set(Yn.map(Gn=>Gn.entry_uid));k(vn),vn.size===1&&B(Yn[0])}else R.ctrlKey||R.metaKey?(K.current=E.entry_uid,k(V=>{const re=new Set(V);return re.has(E.entry_uid)?re.delete(E.entry_uid):re.add(E.entry_uid),re})):(K.current=E.entry_uid,k(new Set([E.entry_uid])),B(E))},[u,B]),ke=f.useCallback(E=>{p(E)},[]),Xn=f.useCallback(()=>{p(null)},[]),Ze=f.useCallback(()=>{a&&fl(a).then(le)},[a]),ms=f.useCallback((E,R)=>{j===E?p(R):j!=null&&j.startsWith(E+"/")&&p(R+j.slice(E.length))},[j]),gs=f.useCallback(E=>{(j===E||j!=null&&j.startsWith(E+"/"))&&p(null)},[j]),Vr=f.useCallback((E,R)=>{c(V=>V.map(re=>re.entry_uid===E?{...re,title:R}:re)),y(V=>V&&V.entry_uid===E?{...V,title:R}:V),ae(V=>V&&V.summary.entry_uid===E?{...V,summary:{...V.summary,title:R}}:V)},[]),vs=f.useCallback(()=>{if(!a||!h)return;const E=++N.current;Vi(a,h.entry_uid).then(R=>{E===N.current&&ae(R)}).catch(()=>{})},[a,h]),ys=f.useCallback(E=>{c(R=>R.filter(V=>V.entry_uid!==E)),y(R=>(R==null?void 0:R.entry_uid)===E?null:R),m(R=>R===E?null:R),k(R=>{const V=new Set(R);return V.delete(E),V})},[]),xs=f.useCallback(E=>{c(R=>R.filter(V=>!E.has(V.entry_uid))),k(new Set),y(null),m(null)},[]);f.useEffect(()=>{if(x.size>=2)m(null),y(null);else if(x.size===1){const[E]=x;m(E)}else m(null),y(null)},[x]);const ws=f.useMemo(()=>u.filter(E=>x.has(E.entry_uid)),[u,x]);f.useEffect(()=>{if(!g||h)return;const E=u.find(R=>R.entry_uid===g);E&&y(E)},[u,g,h]),f.useEffect(()=>{if(or)return;const E=new URLSearchParams;P&&E.set("q",P),d==="archive"&&j&&E.set("tag",j),d==="archive"&&g&&E.set("entry",g);const R=E.toString(),V=window.location.pathname+(R?"?"+R:"");window.location.pathname+window.location.search!==V&&history.replaceState(null,"",V)},[P,j,g,d]),f.useEffect(()=>{const E=R=>{var V,re;(R.metaKey||R.ctrlKey)&&R.key==="k"&&(R.preventDefault(),d==="archive"?((V=F.current)==null||V.focus(),(re=F.current)==null||re.select()):(H.current=!0,v("archive")))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[d]),f.useEffect(()=>{d==="archive"&&H.current&&(H.current=!1,requestAnimationFrame(()=>{var E,R;(E=F.current)==null||E.focus(),(R=F.current)==null||R.select()}))},[d]);const ks=f.useCallback(()=>{ne(!0)},[]),js=f.useCallback(()=>{ne(!1)},[]),hn=f.useCallback(()=>{a&&Promise.all([G(a,P,j),Js(a).then(Q)])},[a,P,j,G]),mn=f.useCallback((E,R,V="error",re=null)=>{if(V==="warning"&&Y&&R)return;const ze=++M.current;b(et=>[...et,{id:ze,text:E,locator:R,type:V,headline:re}])},[Y]),Qr=f.useCallback(E=>{b(R=>R.filter(V=>V.id!==E))},[]),Kr=f.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),U(!0),b(E=>E.filter(R=>!(R.type==="warning"&&R.locator)))},[]),[gn,Jn]=f.useState(null),[bt,I]=f.useState(null),se=f.useCallback(()=>{h&&Jn(h.entry_uid)},[h]),Qe=f.useCallback(()=>Jn(null),[]),qt=f.useCallback((E,R)=>{I({src:E,entry:R})},[]),qn=f.useCallback(()=>I(null),[]);return f.useEffect(()=>{Jn(null)},[h]),f.useEffect(()=>{const E=R=>{var re,ze,et;if(R.key!=="Escape"||de||gn)return;const V=(re=document.activeElement)==null?void 0:re.tagName;V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||x.size>0&&(R.preventDefault(),k(new Set),(et=(ze=document.activeElement)==null?void 0:ze.blur)==null||et.call(ze))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[de,gn,x]),f.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!bt),()=>document.body.classList.remove("has-audio-bar")),[bt]),e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(rm,{onComplete:()=>t("login")}):e==="login"?s.jsx(nm,{onLogin:E=>{r(E),t("authenticated")}}):or?s.jsx(Vm,{archiveId:or.archiveId,entryUid:or.entryUid}):s.jsx(hs.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(lm,{archives:l,archiveId:a,onArchiveChange:q,view:d,onViewChange:T,onCaptureClick:ks}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[d==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:F,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":L,placeholder:"Search titles, URLs, types, tags…",value:P,onChange:E=>C(E.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[S&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:S.split(" ")[0]})," ",S.split(" ").slice(1).join(" ")]}),j&&s.jsxs("button",{className:"tag-filter-badge",onClick:Xn,children:["× ",pe?Pd(j):j]})]})]}),d==="archive"&&s.jsx(cm,{entries:u,selectedUids:x,onRowClick:Ce,archiveId:a}),d==="runs"&&s.jsx(pm,{runs:A}),d==="admin"&&s.jsx(mm,{archives:l}),d==="tags"&&s.jsx(gm,{archiveId:a,tagNodes:ee,tagFilter:j,onTagFilterSet:ke,onViewChange:T,onTagRenamed:ms,onTagDeleted:gs,onTagsRefresh:Ze,humanizeTags:pe}),d==="collections"&&s.jsx(ym,{archiveId:a}),d==="settings"&&s.jsx(wm,{tab:w,onTabChange:_,archiveId:a})]}),s.jsx(Tm,{archiveId:a,selectedEntry:h,selectedUids:x,selectedEntries:ws,detail:fe,onTagFilterSet:ke,tagNodes:ee,onTagsRefresh:Ze,onEntryTitleChange:Vr,onEntryDeleted:ys,onBulkDeleted:xs,humanizeTags:pe,onDetailRefresh:vs,onOpenPreview:se,onPlay:qt})]}),gn&&h&&h.entry_uid===gn&&s.jsx(Hm,{archiveId:a,entry:h,detail:fe,onClose:Qe}),bt&&s.jsx(Wm,{entry:bt.entry,src:bt.src,archiveId:a,onClose:qn}),s.jsx(sm,{open:de,archiveId:a,onClose:js,onCaptured:hn,onToast:mn}),s.jsx(Km,{toasts:D,onDismiss:Qr,onIgnoreUblock:Kr})]})})}Nd(document.getElementById("root")).render(s.jsx(f.StrictMode,{children:s.jsx(Zm,{})})); diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index b71782c..395784e 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -4,7 +4,7 @@ Archivr - + diff --git a/frontend/src/api.js b/frontend/src/api.js index 1d235e1..d9fd243 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -142,12 +142,13 @@ export async function fetchTags(archiveId) { export async function submitCapture(archiveId, locator, quality = null, extensions = null) { const payload = { locator } if (quality && quality !== 'best') payload.quality = quality - // extensions: { ublock_enabled?: bool, reader_mode?: bool, cookie_ext_enabled?: bool, modal_closer_enabled?: bool } + // extensions: { ublock_enabled?: bool, reader_mode?: bool, cookie_ext_enabled?: bool, modal_closer_enabled?: bool, via_freedium?: bool } if (extensions) { if (typeof extensions.ublock_enabled === 'boolean') payload.ublock_enabled = extensions.ublock_enabled if (typeof extensions.reader_mode === 'boolean') payload.reader_mode = extensions.reader_mode if (typeof extensions.cookie_ext_enabled === 'boolean') payload.cookie_ext_enabled = extensions.cookie_ext_enabled if (typeof extensions.modal_closer_enabled === 'boolean') payload.modal_closer_enabled = extensions.modal_closer_enabled + if (typeof extensions.via_freedium === 'boolean') payload.via_freedium = extensions.via_freedium } const res = await fetch(`/api/archives/${archiveId}/captures`, { method: "POST", diff --git a/frontend/src/components/CaptureDialog.jsx b/frontend/src/components/CaptureDialog.jsx index c4b326d..1099c3f 100644 --- a/frontend/src/components/CaptureDialog.jsx +++ b/frontend/src/components/CaptureDialog.jsx @@ -123,6 +123,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on // Cookie consent: session-level only, initialized from server default const [cookieExtEnabled, setCookieExtEnabled] = useState(true) const [modalCloserEnabled, setModalCloserEnabled] = useState(true) + const [freediumEnabled, setFreediumEnabled] = useState(true) // Load global settings from server once on mount useEffect(() => { @@ -301,7 +302,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on const qual = item.quality || 'best' setItems(prev => prev.map(it => it.id === item.id ? { ...it, status: 'submitting', error: null } : it)) try { - const extensions = { ublock_enabled: ublockEnabled, reader_mode: readerMode, cookie_ext_enabled: cookieExtEnabled, modal_closer_enabled: modalCloserEnabled } + const extensions = { ublock_enabled: ublockEnabled, reader_mode: readerMode, cookie_ext_enabled: cookieExtEnabled, modal_closer_enabled: modalCloserEnabled, via_freedium: freediumEnabled } const job = await submitCapture(aid, loc, qual, extensions) setItems(prev => prev.map(it => it.id === item.id ? { ...it, status: 'running', jobUid: job.job_uid, archiveId: aid } : it @@ -517,6 +518,22 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on +
    )} From f9759c08a364639fa6cd6926aa21b8cad8c8c1dd Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sun, 19 Jul 2026 12:34:49 +0200 Subject: [PATCH 05/12] =?UTF-8?q?fix(core):=20Freedium=20capture=20fixes?= =?UTF-8?q?=20=E2=80=94=20title,=20notifications,=20reader=20images?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - extract_html_title: take().read_to_end() up to 256 KiB (single read() can short-read, leaving title at byte ~106 K undiscovered); regression test added - Strip " - Freedium" suffix before storing entry title - is_freedium_fetch keys off actual fetch_url host - Remove Freedium toast overlay ([data-sonner-toaster]) before capture - Resolve lazy images (data-zoom-src etc.) before Readability in reader mode --- crates/archivr-core/src/capture.rs | 18 ++++++- .../archivr-core/src/downloader/singlefile.rs | 51 +++++++++++++++++-- 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index 1f02d58..345cb18 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -1051,7 +1051,10 @@ pub fn perform_capture( } else { (locator.to_string(), cookies.clone()) }; - match downloader::singlefile::save(&fetch_url, store_path, ×tamp, &fetch_cookies, config.ublock_enabled, config.cookie_ext_enabled, config.reader_mode, config.modal_closer_enabled) { + // Key cleanup/title-stripping off the actual fetch host so that + // user-supplied freedium-mirror.cfd URLs are also handled correctly. + let is_freedium_fetch = fetch_url.starts_with("https://freedium-mirror.cfd/"); + match downloader::singlefile::save(&fetch_url, store_path, ×tamp, &fetch_cookies, config.ublock_enabled, config.cookie_ext_enabled, config.reader_mode, config.modal_closer_enabled, is_freedium_fetch) { Ok(result) => { let file_extension = ".html".to_string(); let temp_html = store_path @@ -1115,6 +1118,17 @@ pub fn perform_capture( let _ = fs::remove_dir_all(store_path.join("temp").join(×tamp)); // 4. Create the entry + primary_media artifact. + // Strip mirror branding from title when fetched via Freedium. + let entry_title = if is_freedium_fetch { + result.title.as_deref().map(|t| { + t.trim_end_matches(" - Freedium") + .trim_end_matches(" \u{2014} Freedium") + .trim() + .to_string() + }) + } else { + result.title + }; let entry = record_media_entry( &conn, store_path, @@ -1127,7 +1141,7 @@ pub fn perform_capture( &html_hash, &file_extension, byte_size, - result.title, + entry_title, )?; // 5. Add favicon artifact if we captured one. diff --git a/crates/archivr-core/src/downloader/singlefile.rs b/crates/archivr-core/src/downloader/singlefile.rs index 78c80b7..420e235 100644 --- a/crates/archivr-core/src/downloader/singlefile.rs +++ b/crates/archivr-core/src/downloader/singlefile.rs @@ -47,6 +47,18 @@ const READER_MODE_SCRIPT: &str = concat!( _archivrReaderMark('failed:no-readability'); return; } + // Resolve lazy-loaded images (src="data:," placeholders) before Readability + // clones the document so figures/photos are preserved in the article output. + document.querySelectorAll('img').forEach(function(img) { + var lazySrc = img.getAttribute('data-src') || img.getAttribute('data-lazy-src') || + img.getAttribute('data-zoom-src') || img.getAttribute('data-original') || + img.getAttribute('data-lazy'); + var curSrc = img.getAttribute('src') || ''; + if (lazySrc && (!curSrc || curSrc === 'data:,' || curSrc.startsWith('data:,'))) { + img.setAttribute('src', lazySrc); + img.removeAttribute('loading'); + } + }); var article = new Readability(document.cloneNode(true)).parse(); if (!article || !article.content || article.content.length < 100) { _archivrReaderMark('failed:no-article'); @@ -236,6 +248,7 @@ pub fn save( cookie_ext_enabled: Option, reader_mode: bool, modal_closer_enabled: Option, + freedium_cleanup: bool, ) -> Result { let single_file = env::var("ARCHIVR_SINGLE_FILE").unwrap_or_else(|_| "single-file".to_string()); @@ -254,6 +267,7 @@ pub fn save( cookie_ext.as_deref(), reader_mode, modal_closer, + freedium_cleanup, )?; result.ublock_skipped = ublock_skipped; result.cookie_ext_skipped = cookie_ext_skipped; @@ -378,6 +392,7 @@ fn save_with( cookie_ext: Option<&Path>, reader_mode: bool, modal_closer: bool, + freedium_cleanup: bool, ) -> Result { let temp_dir = store_path.join("temp").join(timestamp); std::fs::create_dir_all(&temp_dir).context("failed to create temp dir")?; @@ -464,6 +479,16 @@ fn save_with( _archivr_mc_run();" ); } + if freedium_cleanup { + // Remove Freedium's notification/toast overlay (Sonner library) before + // SingleFile serialises the DOM. Target the data attribute, not class + // names, to stay stable across Freedium updates. + strip_scripts.push_str( + "document.querySelectorAll('[data-sonner-toaster]').forEach(function(el){\ + var s=el.closest('section')||el;s.remove();\ + });", + ); + } strip_scripts.push_str("});"); std::fs::write(&strip_scripts_path, &strip_scripts) .context("failed to write single-file user script")?; @@ -653,18 +678,20 @@ fn base_single_file_cmd( // ── HTML helpers ────────────────────────────────────────────────────────────── -/// Reads the first 8 KiB of `path` and extracts the content of the first +/// Reads up to 256 KiB of `path` and extracts the content of the first /// `` element. Returns `None` if absent or empty. /// /// Uses `to_ascii_lowercase` for case-insensitive tag matching. ASCII-only /// lowercasing is byte-length-preserving, so byte offsets derived from the /// lowercased buffer are valid indices into the original buffer. +/// +/// Uses `take().read_to_end()` rather than a single `read()` call so the +/// full 256 KiB is always consumed even when the OS short-reads. fn extract_html_title(path: &Path) -> Option { let mut f = std::fs::File::open(path).ok()?; - let mut buf = vec![0u8; 8192]; - let n = f.read(&mut buf).ok()?; - let buf = &buf[..n]; - let lower = String::from_utf8_lossy(buf).to_ascii_lowercase(); + let mut buf = Vec::new(); + f.take(256 * 1024).read_to_end(&mut buf).ok()?; + let lower = String::from_utf8_lossy(&buf).to_ascii_lowercase(); let start = lower.find("")? + "<title>".len(); let end = lower[start..].find("")? + start; let title = String::from_utf8_lossy(&buf[start..end]) @@ -774,6 +801,19 @@ mod tests { assert_eq!(extract_html_title(f.path()), None); } + #[test] + fn extract_html_title_after_100kb_preamble() { + // Freedium / SingleFile pages can embed large CSS blocks before . + // Verify take().read_to_end() reads the full 256 KiB window. + let mut f = NamedTempFile::new().unwrap(); + let padding = " ".repeat(100 * 1024); // 100 KiB of whitespace + write!(f, "{}<html><head><title>Deep Title", padding).unwrap(); + assert_eq!( + extract_html_title(f.path()), + Some("Deep Title".to_string()) + ); + } + #[test] fn save_with_missing_binary_returns_clear_error() { // Calls save_with directly — no env mutation, safe in parallel test runs. @@ -789,6 +829,7 @@ mod tests { None, // no cookie ext false, // reader mode off false, // modal closer off + false, // freedium cleanup off ); let err = result.unwrap_err(); let msg = format!("{err:#}"); From 331fe7fd611796c78f6224f80c95a6b8d2a8f697 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Sun, 19 Jul 2026 13:15:35 +0200 Subject: [PATCH 06/12] fix(core): extract HTML title after font stripping, not before MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SingleFile embeds fonts as base64 data URIs in