Cotton code
884 lines · 34.3 KB · RustRaw
//! FALLBACK ADAPTER — WhatsApp's official per-chat export (`_chat.txt`). The//! port of `packages/import-core/src/adapters/chatTxt.ts`.//!//! Spec §2.3 makes this the fallback, not the primary, and the reasons are all//! visible in this file: the format has no message ids, no reply relations and//! no reactions, so a `.txt` import is permanently poorer than a device-backup//! one. It exists because a counterparty can veto nothing about it — the user//! exports their own chat from the share sheet with no tooling at all.//!//! ## What makes this format hostile//!//! * Two dialects (iOS bracketed, Android dashed) plus locale variants in the//!   date order, the clock (12h/24h), and the space before AM/PM.//! * **No timezone.** Every timestamp is device-local wall clock.//! * Ambiguous dates: `03/04/2025` is March 4th or April 3rd depending on the//!   exporting phone's locale, and the file does not say which. We INFER from//!   the corpus and say so in the report rather than guessing silently.//! * Invisible bidi scaffolding on every line (see `super::super::text`).//! * System lines that look like messages, and messages that look like system//!   lines. See [`classify_remainder`].//!//! Everything this parser is unsure about becomes a counted, reported number —//! never a silent drop.//!//! ## The zone is an ARGUMENT, and it always was//!//! The TypeScript never reads the process time zone either: `tzOffset` is an//! operator input carried in [`ChatTxtOptions`], and the whole conversion is//! `Date.UTC(…)` minus that offset. So the crate's "the zone is explicit" rule//! costs nothing here — [`local_to_instant`] takes the offset in MINUTES and//! [`ChatTxtOptions::tz_offset`] carries it as the `"+HH:MM"` / `"-HH:MM"` ///! `"Z"` string the CLI and the app both hand over. A wrong one lands the whole//! archive in the wrong hour, which is why the report prints it back.//!//! The parse result types themselves live in [`crate::import::normalize`],//! which is the one module that reads all of them; this adapter PRODUCES them//! rather than declaring its own, so the two halves of the import cannot drift//! in the one place a drift is invisible.use std::sync::OnceLock;use cotton_store::protocol::js;use regex::Regex;use serde::{Deserialize, Serialize};use serde_json::Value;use thiserror::Error;use crate::transforms::zoned_clock::{civil_from_days, date_utc};use crate::import::normalize::{    ChatTxtParseResult, DateOrder, SenderCount, TxtAttachment, TxtMessage, TxtSystemLine,};use crate::import::text::{js_trim, normalize_export_text, utf16_len, JS_WHITESPACE_CLASS};/// `dateOrder: DateOrder | "auto"` — the operator's setting, before the corpus/// has had its say.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum DateOrderSetting {    /// Infer from the corpus, falling back to `fallback_date_order`.    Auto,    Dmy,    Mdy,    Ymd,}impl DateOrderSetting {    /// `None` for `"auto"` — the one value the corpus is allowed to decide.    pub const fn fixed(self) -> Option<DateOrder> {        match self {            DateOrderSetting::Auto => None,            DateOrderSetting::Dmy => Some(DateOrder::Dmy),            DateOrderSetting::Mdy => Some(DateOrder::Mdy),            DateOrderSetting::Ymd => Some(DateOrder::Ymd),        }    }}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ChatTxtOptions {    /// Wall-clock offset the export was written in, e.g. `"+05:30"`. There is    /// no timezone in the file, so this is an operator input with an IST    /// default — the CLI prints it in the report so a wrong one is visible    /// before writing.    pub tz_offset: String,    /// `Auto` infers from the corpus and falls back to `fallback_date_order`.    pub date_order: DateOrderSetting,    /// Used only when the corpus is ambiguous (every day ≤ 12).    pub fallback_date_order: DateOrder,}/// `DEFAULT_CHAT_TXT_OPTIONS`.impl Default for ChatTxtOptions {    fn default() -> Self {        Self {            tz_offset: "+05:30".to_string(),            date_order: DateOrderSetting::Auto,            fallback_date_order: DateOrder::Dmy,        }    }}/// The one refusal this adapter raises. `Display` is the TypeScript's sentence/// VERBATIM, down to the `JSON.stringify` around the offending value, so a CLI/// or a route that already prints it keeps printing the same line.#[derive(Debug, Clone, PartialEq, Eq, Error)]pub enum ChatTxtError {    #[error(        "Bad --tz-offset {} — expected \"+HH:MM\", \"-HH:MM\" or \"Z\".",        js::json_stringify(&Value::String(.0.clone()))    )]    BadTzOffset(String),}/// What a header line's remainder turned out to be.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(tag = "kind", rename_all = "camelCase")]pub enum Classified {    Message { sender: String, body: String },    System { text: String },}/// The date components of one header line — the TypeScript's/// `Pick<Header, "a" | "b" | "c">`, which is all [`infer_date_order`] reads.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct HeaderDate {    pub a: i64,    pub b: i64,    pub c: i64,}/// What [`decorate_body`] read out of a message body.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DecoratedBody {    pub body: String,    pub attachment: Option<TxtAttachment>,    pub edited: bool,    pub deleted: bool,}/// The local wall-clock components a header line carries, before a zone.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct LocalParts {    pub y: i64,    pub m: i64,    pub d: i64,    pub hh: i64,    pub mm: i64,    pub ss: i64,}// ─────────────────────────────────────────────────────────────────────────────// Line grammar// ─────────────────────────────────────────────────────────────────────────────//// Built by `format!` from ASCII source so the exotic dash characters are named// by code point rather than pasted in invisibly, exactly as the TypeScript// builds its patterns with `new RegExp` (see `super::super::text`).//// Two classes are spelled out rather than taken from Rust's own shorthands://   * `\d` is `[0-9]`, because JavaScript's `\d` without the `u` flag is ASCII//     only and Rust's is every Unicode decimal digit — an Arabic-Indic numeral//     must not parse as an hour on one side and not the other.//   * `\s` is `JS_WHITESPACE_CLASS`, the ECMAScript class (U+FEFF in, U+0085//     out), which Rust's `\s` has the other way round in both directions./// `-`, U+2013 EN DASH, U+2014 EM DASH — the three separators Android writes.const DASHES: &str = "[-\u{2013}\u{2014}]";const DIGITS: &str = "[0-9]";fn date_pattern() -> String {    format!(r"({DIGITS}{{1,4}})[/.\-]({DIGITS}{{1,2}})[/.\-]({DIGITS}{{2,4}})")}fn time_pattern() -> String {    format!(r"({DIGITS}{{1,2}}):({DIGITS}{{2}})(?::({DIGITS}{{2}}))?")}fn meridiem_pattern() -> String {    format!(r"(?:[{JS_WHITESPACE_CLASS}]*([AaPp])\.?[{JS_WHITESPACE_CLASS}]*[Mm]\.?)?")}/// `[26/07/2025, 10:12:45 AM] Sender: body`fn ios_header_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(            r"^\[[{JS_WHITESPACE_CLASS}]*{},?[{JS_WHITESPACE_CLASS}]+{}{}[{JS_WHITESPACE_CLASS}]*\][{JS_WHITESPACE_CLASS}]?((?s:.*))$",            date_pattern(),            time_pattern(),            meridiem_pattern(),        ))        .expect("ios header")    })}/// `26/07/2025, 10:12 - Sender: body`fn android_header_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(            r"^{},?[{JS_WHITESPACE_CLASS}]+{}{}[{JS_WHITESPACE_CLASS}]+{DASHES}[{JS_WHITESPACE_CLASS}]+((?s:.*))$",            date_pattern(),            time_pattern(),            meridiem_pattern(),        ))        .expect("android header")    })}/// A profile name longer than this is not a name.const MAX_PLAUSIBLE_SENDER_LENGTH: usize = 60;/// The TypeScript's `SENDER_SPLIT` bound, `^([^:]{1,100}):`.const MAX_SENDER_SPLIT_LENGTH: usize = 100;/// Words that do not appear in a WhatsApp profile name but do appear in every/// group-event line. Their job is to catch the one case the sender split gets/// wrong: a system line that happens to contain ": ", e.g./// `Asha created group "Trip: Goa"` → candidate sender/// `Asha created group "Trip`.////// `(?-u:\b)` is the JavaScript word boundary: JS without the `u` flag uses the/// ASCII one, and Rust's `\b` is Unicode — the two disagree next to an accented/// letter, which is exactly where a localized group event puts one.fn sender_looks_systemic_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(            r"(?i)(?-u:\b)(created|added|removed|left|joined|changed|deleted|turned on|turned off|blocked|unblocked|pinned|encrypted)(?-u:\b)",        )        .expect("systemic sender")    })}fn encryption_notice_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"(?i)end-to-end encrypted").expect("encryption notice"))}/// NOT anchored: photos put the marker first (`<attached: …jpg>`), but document/// lines put a caption before it (`Quotation.pdf • 1 page <attached: …pdf>`) —/// the marker can sit anywhere in the line.fn ios_attached_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(r"<attached:[{JS_WHITESPACE_CLASS}]*([^>]+)>")).expect("ios attached")    })}/// Android puts the marker on its OWN line and the caption on the lines after/// it, so the pattern anchors to the first line and captures the rest:////// ```text/// 26/07/2025, 10:15 - Anita: IMG-20250726-WA0001.jpg (file attached)/// Look at the loading pattern/// ```////// Anchored at `^` and `$` with the caption group optional, so a caption-less/// attachment still matches exactly as before. Until 2026-09-05 the pattern/// ended at `$` with no caption group at all, which meant a CAPTIONED Android/// attachment matched nothing: the message kept `… (file attached)\n<caption>`/// as its body and carried no attachment, so its file never even entered the/// media plan.fn android_attached_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(            r"^([^{JS_WHITESPACE_CLASS}][^\n]*?)[{JS_WHITESPACE_CLASS}]+\(file attached\)(?:\n((?s:.*)))?$"        ))        .expect("android attached")    })}fn media_omitted_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(            r"(?i)^(?:<Media omitted>|image omitted|video omitted|audio omitted|sticker omitted|GIF omitted|document omitted|Contact card omitted|This message was deleted|You deleted this message\.?)[{JS_WHITESPACE_CLASS}]*$"        ))        .expect("media omitted")    })}fn edited_suffix_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(            r"[{JS_WHITESPACE_CLASS}]*<This message was edited>[{JS_WHITESPACE_CLASS}]*$"        ))        .expect("edited suffix")    })}fn deleted_body_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(&format!(            r"(?i)^(?:This message was deleted|You deleted this message\.?)[{JS_WHITESPACE_CLASS}]*$"        ))        .expect("deleted body")    })}/// JS `String.prototype.replace(/\s+/g, " ")` — the ECMAScript whitespace/// class, not Rust's. Kept separate from the store's/// `collapse_whitespace_and_trim` at the call sites that trim afterwards/// anyway, so the two operations stay legible as the TypeScript's two.fn collapse_js_whitespace(input: &str) -> String {    js::collapse_whitespace_and_trim(input)}/// One parsed header line.#[derive(Debug, Clone, PartialEq, Eq)]struct Header {    date: HeaderDate,    hh: i64,    mm: i64,    ss: i64,    /// `'a'` or `'p'`, lower-cased; `None` on a 24-hour clock.    meridiem: Option<char>,    remainder: String,}fn match_header(line: &str) -> Option<Header> {    let captures = ios_header_re()        .captures(line)        .or_else(|| android_header_re().captures(line))?;    // Every group is `[0-9]{1,4}` at most, so a parse cannot overflow and a    // failure here would mean the pattern and this reader disagree.    let number = |index: usize| -> i64 {        captures            .get(index)            .map(|m| m.as_str().parse::<i64>().expect("digits"))            .unwrap_or(0)    };    Some(Header {        date: HeaderDate {            a: number(1),            b: number(2),            c: number(3),        },        hh: number(4),        mm: number(5),        // `match[6] === undefined ? 0 : Number(match[6])` — a header with no        // seconds is the whole Android dialect.        ss: number(6),        meridiem: captures            .get(7)            .and_then(|m| m.as_str().chars().next())            .map(|ch| ch.to_ascii_lowercase()),        remainder: captures            .get(8)            .map(|m| m.as_str().to_string())            .unwrap_or_default(),    })}/// `^([^:]{1,100}):(?: ([\s\S]*))?$`, written out rather than compiled.////// The `{1,100}` counts UTF-16 code units in JavaScript and would count/// characters in a Rust regex, so a name written in astral characters would/// split on one side and not the other. `[^:]` cannot cross a colon, so the/// split is always at the FIRST colon; after it the line must either END or/// continue with a literal space — which is what keeps a bare URL in a body/// (`https://…`) from being read as a sender boundary.fn split_sender(remainder: &str) -> Option<(&str, &str)> {    let colon = remainder.find(':')?;    let prefix = &remainder[..colon];    let units = utf16_len(prefix);    if units == 0 || units > MAX_SENDER_SPLIT_LENGTH {        return None;    }    let rest = &remainder[colon + 1..];    if rest.is_empty() {        return Some((prefix, ""));    }    Some((prefix, rest.strip_prefix(' ')?))}/// A message line is `Sender: body`. A system line has no sender at all.pub fn classify_remainder(remainder: &str) -> Classified {    let system = || Classified::System {        text: remainder.to_string(),    };    let Some((raw_sender, body)) = split_sender(remainder) else {        return system();    };    let sender = js_trim(raw_sender);    if sender.is_empty()        || utf16_len(sender) > MAX_PLAUSIBLE_SENDER_LENGTH        || sender_looks_systemic_re().is_match(sender)    {        return system();    }    Classified::Message {        sender: sender.to_string(),        body: body.to_string(),    }}// ─────────────────────────────────────────────────────────────────────────────// Dates// ─────────────────────────────────────────────────────────────────────────────/// Which component is the day, decided by the corpus itself: a value above 12/// can only be a day, and a 4-digit or >31 leading value can only be a year./// Returns `None` when every date in the file fits all readings — genuinely/// ambiguous, and the caller says so out loud rather than pretending.pub fn infer_date_order(headers: &[HeaderDate]) -> Option<DateOrder> {    let mut saw_year_first = false;    let mut saw_day_first = false;    let mut saw_month_first = false;    for header in headers {        if header.a > 31 {            saw_year_first = true;        } else if header.a > 12 {            saw_day_first = true;        }        if header.b > 12 {            saw_month_first = true;        }    }    if saw_year_first {        return Some(DateOrder::Ymd);    }    if saw_day_first && !saw_month_first {        return Some(DateOrder::Dmy);    }    if saw_month_first && !saw_day_first {        return Some(DateOrder::Mdy);    }    None}/// WhatsApp shipped in 2009; every 2-digit year in an export is 20xx.fn expand_year(year: i64) -> i64 {    if year < 100 {        2000 + year    } else {        year    }}/// The reading in words, for a warning a person (not a flag parser) reads.fn describe_date_order(order: DateOrder) -> &'static str {    match order {        DateOrder::Dmy => "day-first (dmy)",        DateOrder::Mdy => "month-first (mdy)",        DateOrder::Ymd => "year-first (ymd)",    }}fn apply_date_order(date: HeaderDate, order: DateOrder) -> (i64, i64, i64) {    match order {        DateOrder::Ymd => (expand_year(date.a), date.b, date.c),        DateOrder::Mdy => (expand_year(date.c), date.a, date.b),        DateOrder::Dmy => (expand_year(date.c), date.b, date.a),    }}fn apply_meridiem(hh: i64, meridiem: Option<char>) -> i64 {    match meridiem {        None => hh,        Some('p') => {            if hh == 12 {                12            } else {                hh + 12            }        }        Some(_) => {            if hh == 12 {                0            } else {                hh            }        }    }}fn offset_pattern_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^(?:Z|([+-])([0-9]{2}):([0-9]{2}))$").expect("offset"))}/// `"+05:30"` → 330. The operator's stated wall-clock offset, in minutes.////// Deliberately no range check: `"+99:99"` is 6039 minutes on both sides. The/// grammar is the whole validation, and a malformed offset is REFUSED rather/// than silently read as UTC — landing a whole archive five and a half hours/// out is the failure this sentence exists to prevent.pub fn offset_minutes(tz_offset: &str) -> Result<i64, ChatTxtError> {    let Some(captures) = offset_pattern_re().captures(js_trim(tz_offset)) else {        return Err(ChatTxtError::BadTzOffset(tz_offset.to_string()));    };    let Some(sign) = captures.get(1) else {        return Ok(0);    };    let magnitude = captures[2].parse::<i64>().expect("digits") * 60        + captures[3].parse::<i64>().expect("digits");    Ok(if sign.as_str() == "-" {        -magnitude    } else {        magnitude    })}/// Local wall clock → UTC instant, with an explicit calendar round-trip so an/// impossible date (31 February, from a misread date order) is REJECTED rather/// than silently rolling into March.////// `tz_offset_minutes` is the EXPLICIT zone: this crate reads no clock and no/// environment, and the TypeScript reads none either — the offset is the/// operator's input all the way down.////// `None` where the TypeScript returns `null`, and also for a time value so far/// out that `new Date(…).toISOString()` would throw a `RangeError` — a year/// coming out of the header grammar cannot reach it (four digits at most), so/// the difference is only visible to a caller passing components by hand.pub fn local_to_instant(parts: LocalParts, tz_offset_minutes: i64) -> Option<String> {    let LocalParts {        y,        m,        d,        hh,        mm,        ss,    } = parts;    if !(1..=12).contains(&m) || !(1..=31).contains(&d) || hh > 23 || mm > 59 || ss > 59 {        return None;    }    let probe = date_utc(y, m - 1, d, hh, mm, ss, 0);    // `getUTCFullYear` / `getUTCMonth` / `getUTCDate` on the probe: out-of-range    // components NORMALISE in `Date.UTC` (31 February becomes 3 March), so the    // only way to reject one is to read the date back out.    let (probe_y, probe_m, probe_d) = civil_from_days(probe.div_euclid(86_400_000));    if probe_y != y || probe_m != m || probe_d != d {        return None;    }    js::to_iso_string(probe - tz_offset_minutes * 60_000)}/// `YYYY-MM-DDTHH:mm:ss`, zero-padded, with no zone applied.////// `String(value).padStart(width, "0")` on values that are always non-negative/// here (every component comes out of a `[0-9]+` group), which is exactly/// Rust's `{:0width$}`.pub fn local_wall_clock(parts: LocalParts) -> String {    let LocalParts {        y,        m,        d,        hh,        mm,        ss,    } = parts;    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}")}// ─────────────────────────────────────────────────────────────────────────────// Body decoration// ─────────────────────────────────────────────────────────────────────────────/// Pull the attachment marker, the edited suffix and the deleted tombstone out/// of a raw body.////// The order is the TypeScript's and it matters: the edited suffix is stripped/// FIRST, so `sticker omitted <This message was edited>` is still recognised as/// omitted media; and `deleted` is read off the trimmed body at the END, so a/// deleted tombstone keeps its words (the normalizer shows them) while never/// being mistaken for an omitted-media marker.pub fn decorate_body(raw: &str) -> DecoratedBody {    let mut body = raw.to_string();    let mut edited = false;    let mut attachment: Option<TxtAttachment> = None;    if edited_suffix_re().is_match(&body) {        // JS `replace` without `/g` replaces the first match only; the pattern        // is `$`-anchored, so there is at most one.        body = edited_suffix_re().replace(&body, "").into_owned();        edited = true;    }    let trimmed = js_trim(&body).to_string();    let ios_attached = ios_attached_re().captures(&trimmed);    let android_attached = android_attached_re().captures(&trimmed);    if let Some(captures) = ios_attached {        let whole = captures.get(0).expect("whole match");        attachment = Some(TxtAttachment {            filename: Some(js_trim(&captures[1]).to_string()),            omitted: false,            label: js_trim(whole.as_str()).to_string(),        });        // The caption is whatever surrounds the marker — documents put it        // before, photos (when captioned at all) after.        body = collapse_js_whitespace(&format!(            "{} {}",            &trimmed[..whole.start()],            &trimmed[whole.end()..]        ));    } else if let Some(captures) = android_attached {        let filename = js_trim(&captures[1]).to_string();        attachment = Some(TxtAttachment {            filename: Some(filename.clone()),            omitted: false,            // The marker LINE, not the whole body — the caption is the            // message's, not the marker's.            label: format!("{filename} (file attached)"),        });        body = collapse_js_whitespace(captures.get(2).map_or("", |m| m.as_str()));    } else if media_omitted_re().is_match(&trimmed) && !deleted_body_re().is_match(&trimmed) {        attachment = Some(TxtAttachment {            filename: None,            omitted: true,            label: trimmed.clone(),        });        body = String::new();    }    let deleted = deleted_body_re().is_match(&trimmed);    DecoratedBody {        body,        attachment,        edited,        deleted,    }}// ─────────────────────────────────────────────────────────────────────────────// Albums// ─────────────────────────────────────────────────────────────────────────────/// How far after the container line its first attachment may sit.////// WhatsApp stamps the container and the photos of one album within a second or/// two of each other — measured across eight real iOS exports (34 blank sender/// lines, 29 of them containers): every first attachment landed 0, 1 or 2/// seconds after its container. Android writes no seconds at all, so every line/// of the same minute reads as the same instant and the delta is always 0.////// Five seconds is that spread plus margin, and it is deliberately NOT the/// fingerprint's minute: the window's whole job is to keep a genuinely blank/// line (a sticker, a location pin, a view-once photo) from being swallowed/// because the same person happened to send a photo later in the same minute.const ALBUM_CONTAINER_WINDOW_MS: i64 = 5_000;/// Mark the empty sender lines that are album scaffolding.////// Before a multi-photo album, WhatsApp writes a header with a sender and then/// NOTHING — no text, no attachment marker — followed immediately by the/// album's `<attached: …>` lines from the same sender at the same instant. That/// blank is not a message anybody sent: kept, it becomes a row whose body is/// `[unsupported message]` sitting above the photos it was scaffolding for,/// which is exactly what the owner saw in an imported chat (2026-09-05).////// A blank line that is NOT followed by that sender's attachment stays a/// message: those are the real unsupported shapes — stickers, location pins,/// view-once media, a poll the exporter did not render — and losing them would/// lose the fact that something was said at all.////// Marks rather than removes: the normalizer still walks the container so it/// keeps its place in the content-fingerprint occurrence sequence, and only/// then declines to emit it.pub fn mark_album_containers(messages: &mut [TxtMessage]) -> i64 {    let mut marks: Vec<usize> = Vec::new();    // `windows(2)` is the TypeScript's `messages[index + 1] === undefined`    // guard made structural: the last row can never be a container.    for (index, pair) in messages.windows(2).enumerate() {        let (candidate, next) = (&pair[0], &pair[1]);        if !candidate.body.is_empty() || candidate.attachment.is_some() {            continue;        }        if next.attachment.is_none() || next.sender != candidate.sender {            continue;        }        // `Date.parse` on a value the adapter itself wrote; an unparsable one        // is JS `NaN`, and every comparison against it is false, so the        // candidate is stepped over rather than marked.        let (Some(next_ms), Some(candidate_ms)) = (            js::parse_date_ms(&next.sent_at),            js::parse_date_ms(&candidate.sent_at),        ) else {            continue;        };        // The TypeScript's `delta < 0 || delta > ALBUM_CONTAINER_WINDOW_MS`:        // the attachment may not precede its container, and five seconds is        // the far edge INCLUSIVE.        let delta = next_ms - candidate_ms;        if !(0..=ALBUM_CONTAINER_WINDOW_MS).contains(&delta) {            continue;        }        marks.push(index);    }    for index in &marks {        messages[*index].album_container = true;    }    marks.len() as i64}// ─────────────────────────────────────────────────────────────────────────────// The parse// ─────────────────────────────────────────────────────────────────────────────struct Block {    header: Header,    lines: Vec<String>,    line: i64,}/// Read a WhatsApp `_chat.txt` export.////// Three passes, and the order is the point: split into header + continuation/// blocks FIRST, so the date order can be inferred from the WHOLE corpus before/// any single timestamp is interpreted. A file whose first ten dates are all/// ambiguous and whose eleventh says `26/07` must read the first ten the same/// way as the eleventh.pub fn parse_chat_txt(    input: &str,    options: &ChatTxtOptions,) -> Result<ChatTxtParseResult, ChatTxtError> {    let mut warnings: Vec<String> = Vec::new();    let text = normalize_export_text(input);    // Pass 1 — blocks.    let mut blocks: Vec<Block> = Vec::new();    let mut unparsed_lines: i64 = 0;    for (index, line) in text.split('\n').enumerate() {        if line.is_empty() && blocks.is_empty() {            continue;        }        if let Some(header) = match_header(line) {            blocks.push(Block {                header,                lines: Vec::new(),                line: index as i64 + 1,            });            continue;        }        if let Some(current) = blocks.last_mut() {            current.lines.push(line.to_string());            continue;        }        if !js_trim(line).is_empty() {            unparsed_lines += 1;        }    }    if unparsed_lines > 0 {        warnings.push(format!(            "{unparsed_lines} line(s) before the first timestamp were ignored — if this number is large the file is probably not a WhatsApp export."        ));    }    // Pass 2 — date order.    let dates: Vec<HeaderDate> = blocks.iter().map(|block| block.header.date).collect();    let inferred = infer_date_order(&dates);    let fixed = options.date_order.fixed();    let date_order = fixed.unwrap_or_else(|| inferred.unwrap_or(options.fallback_date_order));    let date_order_inferred = if fixed.is_some() {        true    } else {        inferred.is_some()    };    if fixed.is_none() && inferred.is_none() && !blocks.is_empty() {        // Platform-neutral wording: the app shows this line as-is, and a phone        // has no flag to pass — the CLI documents `--date-order` in its usage.        warnings.push(format!(            "Every date in this export fits both day-first and month-first readings, so the order could not be inferred; dates were read as {}.",            describe_date_order(options.fallback_date_order)        ));    }    let tz_minutes = offset_minutes(&options.tz_offset)?;    // Pass 3 — interpret.    let mut messages: Vec<TxtMessage> = Vec::new();    let mut system_messages: Vec<TxtSystemLine> = Vec::new();    let mut sender_counts: Vec<SenderCount> = Vec::new();    let mut system_lines: i64 = 0;    let mut starts_with_encryption_notice = false;    let mut bad_timestamps: i64 = 0;    for (index, block) in blocks.iter().enumerate() {        let mut joined = String::from(&block.header.remainder);        for line in &block.lines {            joined.push('\n');            joined.push_str(line);        }        // `.replace(/\n+$/, "")` — a block's trailing blank lines are the file's        // formatting, not the message's.        let remainder = joined.trim_end_matches('\n');        let classified = classify_remainder(remainder);        let (y, m, d) = apply_date_order(block.header.date, date_order);        let hh = apply_meridiem(block.header.hh, block.header.meridiem);        let parts = LocalParts {            y,            m,            d,            hh,            mm: block.header.mm,            ss: block.header.ss,        };        let sent_at = local_to_instant(parts, tz_minutes);        // Tested on the RAW remainder: a GROUP export attributes the notice to        // the group name (`AQ <> TinFactory: Messages and calls are        // end-to-end…`), which classifies as a message — but it is still the        // not-truncated signal.        if index == 0 && encryption_notice_re().is_match(remainder) {            starts_with_encryption_notice = true;        }        match classified {            Classified::System { text } => {                system_lines += 1;                if let Some(sent_at) = sent_at {                    system_messages.push(TxtSystemLine {                        text: js_trim(&text).to_string(),                        sent_at,                        sent_at_local: local_wall_clock(parts),                        line: block.line,                    });                }            }            Classified::Message { sender, body } => {                let Some(sent_at) = sent_at else {                    bad_timestamps += 1;                    continue;                };                let decorated = decorate_body(&body);                messages.push(TxtMessage {                    sender: sender.clone(),                    sent_at_local: local_wall_clock(parts),                    sent_at,                    body: decorated.body,                    attachment: decorated.attachment,                    edited: decorated.edited,                    deleted: decorated.deleted,                    album_container: false,                    line: block.line,                });                // A `Map` on the TypeScript side, and its INSERTION ORDER is                // observable downstream, so the port is an ordered list filled                // in first-appearance order.                match sender_counts.iter_mut().find(|entry| entry.name == sender) {                    Some(entry) => entry.count += 1,                    None => sender_counts.push(SenderCount {                        name: sender,                        count: 1,                    }),                }            }        }    }    if bad_timestamps > 0 {        warnings.push(format!(            "{bad_timestamps} message(s) had an impossible date when read as {} and were skipped — the date order is probably wrong.",            describe_date_order(date_order)        ));    }    let album_containers = mark_album_containers(&mut messages);    Ok(ChatTxtParseResult {        messages,        album_containers,        system_lines,        system_messages,        unparsed_lines,        date_order,        date_order_inferred,        starts_with_encryption_notice,        sender_counts,        warnings,    })}#[cfg(test)]#[path = "chat_txt_tests.rs"]mod tests;