//! Chat rows as the relay writes them, and the pure rules that read them.//!//! Moved from `cotton-core::messages` (which re-exports all of it) so the//! Worker runs the same shapes and the same preview line as WASM.//!//! `packages/core/src/messages/*`.//!//! Eleven small modules and one rule between them: **a message row is written//! once and read in N files**. Everything here follows from that. The preview//! line, the group-event sentence, the tick a bubble draws, the id a reaction//! gets — each has exactly ONE implementation, because the relay writes the//! same row into every member's file and two spellings of any of them would//! show up as one member's copy of a conversation quietly disagreeing with//! another's.//!//! Pure, like the rest of the crate: no clock, no locale, no store. The English//! strings are English by DESIGN and not by locale — the server imports these//! rules and has no catalog — and every instant arrives as an argument.//!//! ## Where the shared row shapes live//!//! The TypeScript keeps [`MessageMedia`], [`MessageMeta`] and [`GroupEvent`] in//! `packages/core/src/models/message/types.ts`, one file over from the rules//! that read them. Several modules here read them ([`preview`] the media and//! the poll, [`group_event`] the system field, [`apply_message_write`] both), so//! they are declared HERE rather than inside whichever module happened to need//! them first — the same reason the TypeScript gave them their own file.//!//! ## Two things a reader of this tree must know//!//! * **Every cap and every index is in UTF-16 code units.**//! `String.prototype.length` and `.slice` count them, so a 140-character//! preview cut at a code point would be a different string the moment an emoji//! is in it. Ports here use `encode_utf16`, never bytes and never `chars()`,//! and say so at the cap.//! * **Every trim is ECMAScript's whitespace class**//! ([`crate::js::is_js_whitespace`]), which trims U+FEFF and//! does NOT trim U+0085 — Rust's `str::trim` has it exactly the other way//! round.use serde::{Deserialize, Serialize};use serde_json::{Map, Value};/// One media attachment. Stored as a JSON array on the message so a picture/// message is one row, not a row plus a join.////// `key` names bytes in this device's media store. Remote URL attachments are refused.////// An optional display kind must be a current kind; otherwise the MIME type names the medium.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pubstructMessageMedia {/// The media-store object key — `{workspaceId}/messages/{threadId}/{sha}.{ext}`.pub key: String,/// MIME type as uploaded; the renderer branches on the `image/` prefix.pub content_type: String,/// The original filename, when the importer knew it — a chip's label. #[serde(default, skip_serializing_if = "Option::is_none")]pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub width: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")]pub height: Option<f64>,/// Bytes, when the uploader knew — drives the "still loading" placeholder. #[serde(default, skip_serializing_if = "Option::is_none")]pub size_bytes: Option<f64>,/// Optional display kind; when absent, the renderer uses the MIME type. #[serde(default, skip_serializing_if = "Option::is_none")]pub kind: Option<MessageMediaKind>,/// Playback length for video / audio / voice. #[serde(default, skip_serializing_if = "Option::is_none")]pub duration_ms: Option<f64>,/// The same recording in a container the phone plays — a voice note's/// AAC m4a beside its Ogg original. #[serde(default, skip_serializing_if = "Option::is_none")]pub playback_key: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub playback_content_type: Option<String>,/// Voice notes: 64 samples in 0..1, drawn as bars. #[serde(default, skip_serializing_if = "Option::is_none")]pub waveform: Option<Vec<f64>>,/// A base64 JPEG (≤ 4 KB) shown blurred until the real bytes are local. #[serde(default, skip_serializing_if = "Option::is_none")]pub preview: Option<String>,/// What a shared `.vcf` SAYS, read at import so the app can draw a name and/// a number without opening the bytes. #[serde(default, skip_serializing_if = "Option::is_none")]pub contact: Option<MessageMediaContact>,/// A sealed message's file (sealing plan L8): the per-file key its bytes/// open with (`cotton_core::seal::file`), base64url, inside the sealed blob. #[serde(default, skip_serializing_if = "Option::is_none")]pub file_key: Option<String>,}implMessageMedia {/// The two-field shape most call sites want, so a test does not spell ten/// `None`s to say "a photo".pubfn new(key: &str, content_type: &str) -> Self {MessageMedia { key: key.to_string(), content_type: content_type.to_string(), ..MessageMedia::default() } }}/// The readable part of a shared `.vcf`.////// Deliberately four fields and no more: a vCard can carry a photo, an address,/// a birthday and thirty other properties, and every one we copy into a message/// row is a copy of somebody's details living somewhere nobody expects to find/// them. The name and the numbers are what a bubble shows; the file keeps the/// rest, where the person who was sent it can still open it.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessageMediaContact {/// `FN`, or the assembled `N`, or the first phone — never empty.pub name: String, #[serde(default)]pub phones: Vec<String>, #[serde(default)]pub emails: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub org: Option<String>,}/// WHAT happened to a group, as data rather than as a sentence.////// A group event row is written ONCE, by the person who acted, and mirrored/// verbatim into every member's file — so its words cannot be baked in at write/// time: "You created the group" is true in exactly one of those files and a lie/// in all the others (seen 2026-08-26 on the two-simulator rig, where every/// member read that they had created a group somebody else made). The row/// therefore carries the FACTS and each reader's app says them in its own second/// person.////// The English sentence still travels, in the message BODY/// ([`group_event::group_event_sentence`]), because search, the chat-list/// preview, an assistant reading over MCP and any client older than this change/// all read that column and must find something true in it.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructGroupEvent {pub kind: GroupEventKind,/// Who did it — a phone as digits.////// `None` means "the owner of the file this row is written in". A file does/// not reliably know its own number (it lives in the session's credential,/// not in the file), so the author may have nothing better to write — and in/// their own file `null` is exactly right. The SERVER fills it with the/// envelope's author before the row reaches anybody else, so a null actor/// never survives a mirror. #[serde(default)]pub actor: Option<String>,/// Who it was done TO — phones, digits. Set for `added` and `removed`. #[serde(default, skip_serializing_if = "Option::is_none")]pub subjects: Option<Vec<String>>,/// The new name, on `renamed`. #[serde(default, skip_serializing_if = "Option::is_none")]pub title: Option<String>,}/// `meta.system` — a group event line rather than something somebody said.////// `true` is the ORIGINAL shape and still arrives: every imported WhatsApp/// archive writes it, and so did every Cotton group event before 2026-08-26./// Those rows have only their body, which is why every reader treats `system` as/// a truthiness test and reaches for the structure separately/// ([`group_event::group_event_of`]).#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(untagged)]pubenumMessageSystem {/// The bare flag. `false` is a system field that says "no".Flag(bool),Event(GroupEvent),}implMessageSystem {/// JavaScript truthiness of `meta.system` — an object is always truthy, a/// boolean is itself. Every renderer branches on this FIRST.pubfn is_truthy(&self) -> bool {matchself {MessageSystem::Flag(flag) => *flag,MessageSystem::Event(_) => true, } }}/// Descriptive flags ABOUT a message — never flags that change what the app/// DOES. Anything behaviour-bearing earns a real column and a CHECK, because a/// JSON key that quietly gates behaviour is a constraint nobody can see.////// `extra` is `#[serde(flatten)]` so a key written by a build this one has never/// heard of survives a read/write round trip. It is not decoration: `meta`/// travels verbatim into every member's file, and a writer that silently dropped/// what it did not understand would strip provenance off other people's rows.////// `source` is read leniently (`MessageMeta`'s own `Deserialize`): the WhatsApp/// importer names its rows' source with a word (`"whatsapp-chat-txt"`), not the/// provenance object, and every imported row in every archive carries it. Read/// strictly, that word failed the whole meta, so an imported group's "created/// group" line lost its `system` and was drawn as a message from "(unknown)"./// The word is kept verbatim among `extra`, as JavaScript reads it.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", remote = "Self")]pubstructMessageMeta { #[serde(default, skip_serializing_if = "Option::is_none")]pub edited: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")]pub forwarded: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")]pub starred: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")]pub system: Option<MessageSystem>,/// The importer's record of an attachment it could NOT upload — the textual/// trace that a file existed, kept so nothing about an archive is silently/// lost. #[serde(default, skip_serializing_if = "Option::is_none")]pub attachment: Option<MessageMetaAttachment>,/// The link card for the first URL in the body, when the server fetched one. #[serde(default, skip_serializing_if = "Option::is_none")]pub preview: Option<MessageLinkPreview>,/// A poll, read out of the body a WhatsApp export wrote for one. #[serde(default, skip_serializing_if = "Option::is_none")]pub poll: Option<MessagePoll>,/// Where this row came from, when it did not come from Cotton. #[serde(default, skip_serializing_if = "Option::is_none")]pub source: Option<MessageSource>,/// Every key this build does not know, kept verbatim. #[serde(flatten)]pub extra: Map<String, Value>,}implSerializeforMessageMeta {fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {MessageMeta::serialize(self, serializer) }}impl<'de> Deserialize<'de> forMessageMeta {fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {letmut map = Map::<String, Value>::deserialize(deserializer)?;// A source that is not the provenance object (the importer's word) stands aside, kept verbatim.let named = match map.get("source") {Some(Value::Object(_)) | Some(Value::Null) | None => None,Some(_) => map.remove("source"), };letmut meta = MessageMeta::deserialize(Value::Object(map)).map_err(serde::de::Error::custom)?;ifletSome(named) = named { meta.extra.insert("source".to_string(), named); }Ok(meta) }}/// The described-but-not-uploaded attachment on `MessageMeta.attachment`.////// `name` is OPTIONAL because an omitted attachment has none: WhatsApp writes/// "image omitted" when it trims media from an export. An archive is forever, so/// the reader accepts both that shape and the clean one the importer writes now.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessageMetaAttachment { #[serde(default, skip_serializing_if = "Option::is_none")]pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub mime: Option<String>,/// True when the export itself omitted the file (`<Media omitted>`). #[serde(default, skip_serializing_if = "Option::is_none")]pub omitted: Option<bool>,}/// A link card the server fetched. `thumb` is a base64 JPEG ≤ 8 KB.////// Descriptive, like everything else in `meta`: it changes how a bubble LOOKS/// and never what the app does, so it earns a JSON key rather than a column.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessageLinkPreview {pub url: String, #[serde(default, skip_serializing_if = "Option::is_none")]pub title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub site_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub thumb: Option<String>,}/// Provenance for an imported row — what the app's Source block reads.////// Every field is optional: source names are strings and an ambiguous reply/// binding is an explicit flag. No reader knows all of them. A field the/// ingestor could not fill is ABSENT rather than guessed: "read by Mac" with no/// machine behind it would be a sentence the file cannot support.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessageSource {/// Live GET snapshots: absent is unknown; an explicit empty list is observed. #[serde(default, skip_serializing_if = "Option::is_none")]pub reactions: Option<Vec<SiteReaction>>, #[serde(default, skip_serializing_if = "Option::is_none")]pub story_reaction: Option<StoryReaction>,/// The source's reply binding, written by a live reader, never a display name. #[serde(default, skip_serializing_if = "Option::is_none")]pub site: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub account: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub chat: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub reply_account_conflict: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")]pub client_context: Option<String>,/// Confirmed by the owner-send worker, never inferred from an imported row. #[serde(default, skip_serializing_if = "Option::is_none")]pub sent_from_cotton: Option<bool>,/// Stable serving-device key; readers resolve its name in this database. #[serde(default, skip_serializing_if = "Option::is_none")]pub sent_by_device: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")]pub send_started_at: Option<String>,/// The source's own label, verbatim — `iMessage`, `SMS`, `WhatsApp backup`. #[serde(default, skip_serializing_if = "Option::is_none")]pub service: Option<String>,/// The ingesting machine's label. Who READ it. #[serde(default, skip_serializing_if = "Option::is_none")]pub device: Option<String>,/// Whose copy it was read out of. Where it LIVED. #[serde(default, skip_serializing_if = "Option::is_none")]pub file: Option<String>,/// The source's own stable id, kept so a re-read is free. Never shown. #[serde(default, skip_serializing_if = "Option::is_none")]pub external_id: Option<String>,}implMessageSource {/// An observed snapshot replaces legacy name-only reactions, including an empty one.pubfn instagram_reactions(&self) -> Option<&[SiteReaction]> {ifself.site.as_deref() != Some("instagram") || self.origin.as_deref() != Some("live") || self.reply_account_conflict == Some(true) { returnNone; }self.account.as_deref().and_then(|raw| crate::handles::normalize_contact_handle(crate::handles::HandleKind::Instagram, raw))?;let chat = self.chat.as_deref()?;if chat.is_empty() || !chat.bytes().all(|b| b.is_ascii_digit()) { returnNone; }let reactions = self.reactions.as_deref()?; reactions.iter().all(|r| !r.user_id.is_empty() && r.user_id.bytes().all(|b| b.is_ascii_digit()) && !r.emoji.trim().is_empty()).then_some(reactions) }}/// One choice on an imported poll, and how many people picked it.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessagePollOption {pub text: String,pub votes: f64,}/// A poll.////// From a WhatsApp export: totals only, there is no "who voted for what" and a/// named voter here would be invented. From the Mac's WhatsApp link (CONTRACT/// "Polls shown"): how many may be chosen, and each voter's latest choice;/// `options[].votes` is then the count of `voters` holding it.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessagePoll {pub question: String, #[serde(default)]pub options: Vec<MessagePollOption>,/// WhatsApp's `selectableOptionsCount`: 0 any number, 1 one. Link polls only. #[serde(default, skip_serializing_if = "Option::is_none")]pub selectable: Option<u32>,/// One entry a voter, their latest choice. Link polls only. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub voters: Vec<MessagePollVoter>,}implMessagePoll {/// Whether it came by the Mac's link (who voted is known), not from an export (totals only).pubfn live(&self) -> bool {self.selectable.is_some() || !self.voters.is_empty() }}/// One voter on a link poll and what they chose now.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructMessagePollVoter {/// Their number, digits only (as contacts hold numbers), or `"me"` for the owner.pub who: String,/// The options they chose, by place in `options`. #[serde(default)]pub options: Vec<u32>, #[serde(default, skip_serializing_if = "Option::is_none")]pub at: Option<String>,}/// A JavaScript-truthy number: neither `0`, `-0` nor `NaN`.////// `wordFor` writes `if (kind === "voice" && entry.durationMs)`, so a voice note/// stamped `durationMs: 0` says "Voice message" and not "Voice message · 0:00"./// Rust has no truthiness, and `Option::is_some` is NOT the same predicate.pubfn truthy_number(value: Option<f64>) -> Option<f64> {match value {Some(number) if number != 0.0 && !number.is_nan() => Some(number), _ => None, }}pubusecrate::js::truthy_str;/// `String.prototype.trim()` — the ECMAScript whitespace class, which trims/// U+FEFF and does NOT trim U+0085. Rust's `str::trim` is the other way round.////// PUBLIC since 4m, because the chat WRITE verbs are outside this crate and/// trim exactly what the composer that produced the string trimmed. A handler/// reaching for `str::trim` instead would refuse a message a phone accepted, or/// accept one it did not — for a body whose only difference is one invisible/// character.pubusecrate::js::js_trim;/// `String.prototype.length` — UTF-16 code units, not bytes and not code points.pubfn utf16_len(input: &str) -> usize { input.encode_utf16().count()}/// `text.slice(0, max)` — a cut at a UTF-16 code-unit index.////// Every cap in this tree runs through here. A 140-unit preview cut at a code/// POINT would be a different string the moment somebody sends an emoji, and a/// cut at a BYTE would be a different one for any non-ASCII text at all.////// A cut that would land inside a surrogate pair keeps the whole pair out: Rust/// has no string that can hold half of one, and half a code point is not a/// character anybody meant to read either.pubfn slice_utf16(input: &str, max: usize) -> String {if utf16_len(input) <= max {return input.to_string(); }letmut out = String::with_capacity(input.len());letmut units = 0usize;for ch in input.chars() {let width = ch.len_utf16();if units + width > max {break; } out.push(ch); units += width; } out}/// A string as JavaScript holds it: a vector of UTF-16 code units.////// Every index this tree hands out or takes in — a mention range, a link's start/// and end, a text field's cursor — is an index INTO THIS: UTF-16 units are/// what the stored ranges count and what a text field reports its selection/// in. A byte offset would be a different number for any non-ASCII text, and a/// `char` index a different one again for any emoji.pubfn utf16_units(input: &str) -> Vec<u16> { input.encode_utf16().collect()}/// Back to a `String`.////// Lossy in signature only: every slice this tree takes is cut at a range/// boundary produced by matching whole substrings, so no cut can land inside a/// surrogate pair. A Rust `String` cannot hold half of one in any case, and half/// a code point is not a character anybody meant to read.pubfn units_to_string(units: &[u16]) -> String {String::from_utf16_lossy(units)}string_enum! {/// `MEDIA_KINDS` — how a bubble renders an attachment.////// Named `MessageMediaKind`, not `MediaKind`: `media/keys.ts` already owns/// that name for a different question — which PREFIX an object key belongs/// under. This one answers how a bubble draws the thing.////// `voice` is separate from `audio` deliberately: a voice note renders as a/// waveform you hold to record, an audio file as a chip you tap. One value/// could not tell a renderer which. `contact` also follows from vCard MIME types.MessageMediaKind {Image => "image",Video => "video",Audio => "audio",Voice => "voice",File => "file",Contact => "contact", }}string_enum! {/// `GROUP_EVENT_KINDS` — the things that can HAPPEN to a group, as opposed/// to be said in one.////// This list IS the constraint: a group event lives inside `meta`, which is/// a JSON object with no CHECK past `json_type`, so refusing an unknown/// kind is the only thing standing between a typo and a timeline row that/// renders as nothing.////// One entry per verb in `groupVerbs`, and no more. `setRole` is/// deliberately absent: promoting somebody changes what they may do, not/// what the group is, and WhatsApp says nothing about it either.GroupEventKind {Created => "created",Added => "added",Removed => "removed",Left => "left",Renamed => "renamed",Photo => "photo",Description => "description", }}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructSiteReaction {pub user_id: String,pub emoji: String,pub from_me: bool, #[serde(default, skip_serializing_if = "Option::is_none")]pub handle: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructStoryReaction {pub story_external_id: String,pub actor: SiteReaction,}pubmod media_only;pubmod preview;pubmod resolve_contact;