Cotton code
229 lines · 9.9 KB · TypeScriptRaw
/** * MAIL PREDICATE (the coordinator, 26 and 27 Nov 2026; the eight rules of * NEXT-PHASE2-RULES): the Worker's mirror of cotton-rules * `mail::predicate::cuts` (crates/cotton-rules/src/mail/cuts.rs). The phone * asks that file in SQL; the Worker's tools read stored rows in TypeScript and * ask here. Both run the same cases (crates/cotton-rules/src/mail/cut_cases.json: * the Rust test against SQLite, test/mail-predicate.test.ts here) and read the * same public domains (public_domains.json), so the two cannot drift. * * A cut covers a mail when ALL hold: * - the cut row is not deleted and its `state` is not `undone` (an Undo of a *   Delete is a write of its state; of an Archive or a Mark read, its row goes); * - the mail is not from one of his own addresses (`MailCuts.own`); * - its key is the mail's address normalised (`normaliseKey`), `@` and the *   mail's domain, or (a read cut only) `*`. A key is stored normalised by its *   writer; a key stored any other way covers nothing. `+tag` is not folded; * - the mail was sent at or before the cut's `before`; * - the mail LANDED on the server at or before the cut's `at`: the stored row's *   `landed_at`, stamped by the object's clock alone (src/store.ts `landing`), *   taken here as the row's own field, never from its data. A mail with no *   landing time is never covered; * - its id is not in the cut's `except`. * Every time compared passes `normaliseTime`, the cut's own too. A Delete's * Bin date and its 30 days are its `made_at`, when he tapped, never `at`. * * No Worker reader calls this yet (PHASE 2 PHONE 2, item 4): an assistant sees a * mail a cut covers as live until a phone erases it. * * Precedence: a newer act on one mail (its id in every covering cut's except) * > bin cut > archive cut > read cut. A conversation is live when any of its * mails is live; waiting when none is opened. A row still sealed waits. * Times compared here are all in one shape (`normaliseTime`). */import domains from "../../../../crates/cotton-rules/src/mail/public_domains.json";type Data = Record<string, unknown>;/** A mail as stored: its data (sealed or opened), and the row's own landing time. */export interface MailRow {  id: string;  data: Data;  landed_at?: string | null;  /** Set by a reader that knows the row is not yet opened, whatever its data says. */  sealed?: boolean;}/** A cut row's opened data, with its row's `deleted_at` where the row is gone. */export interface MailCut {  key: unknown;  before: unknown;  at: unknown;  except?: unknown;  deleted_at?: unknown;  /** When he tapped (a Delete's Bin date and its 30 days). */  made_at?: unknown;  /** live, undone, erasing or erased (a Delete's); absent is live. */  state?: unknown;}export interface MailCuts {  bin: MailCut[];  read: MailCut[];  archive: MailCut[];  /** His own addresses, normalised: never covered by any cut. */  own?: string[];}export const NO_CUTS: MailCuts = { bin: [], read: [], archive: [] };export type MailState = "live" | "binned" | "waiting";/** What a key's ends are trimmed of: the same set as cuts.rs `TRIM`. */const TRIM = new Set([" ", "\t", "\n", "\r", "\u000B", "\u000C", " ", "", "
", "
", " "]);/** One normaliser for an address and a cut's key: the ends trimmed of TRIM, then lower case by full Unicode. */export function normaliseKey(key: string): string {  const chars = Array.from(key);  let start = 0;  let end = chars.length;  while (start < end && TRIM.has(chars[start]!)) start++;  while (end > start && TRIM.has(chars[end - 1]!)) end--;  return chars.slice(start, end).join("").toLowerCase();}export const PUBLIC_DOMAINS: readonly string[] = domains.domains;/** A public mail service's domain or any name under it (`mail.yahoo.co.uk` is yahoo.co.uk's): cuts.rs `is_public_domain`. */export function isPublicDomain(domain: string): boolean {  return PUBLIC_DOMAINS.some((p) => domain === p || domain.endsWith("." + p));}/** Why a cut's key cannot be written, or null (cuts.rs `refused_key`). */export function refusedKey(key: string): "not_normal" | "empty" | "not_a_domain" | "public_domain" | null {  const normal = normaliseKey(key);  if (normal !== key) return "not_normal";  if (normal === "" || normal === "@") return "empty";  if (normal.startsWith("@")) {    const domain = normal.slice(1);    if (domain.includes("@") || !domain.includes(".")) return "not_a_domain";    if (isPublicDomain(domain)) return "public_domain";  }  return null;}const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;/** A time in the one shape, `YYYY-MM-DDTHH:MM:SS.mmmZ` UTC, from RFC 3339 with any offset and fraction (cut, never rounded); null otherwise. */export function normaliseTime(value: string): string | null {  const m = RFC3339.exec(value);  if (!m) return null;  const [y, mo, d, h, mi, s] = [m[1], m[2], m[3], m[4], m[5], m[6]].map(Number) as [number, number, number, number, number, number];  const ms = Number(((m[7] ?? "") + "000").slice(0, 3));  if (mo < 1 || mo > 12 || h > 23 || mi > 59 || s > 59) return null;  const local = Date.UTC(y, mo - 1, d, h, mi, s, ms);  const check = new Date(local);  if (check.getUTCFullYear() !== y || check.getUTCMonth() !== mo - 1 || check.getUTCDate() !== d) return null;  let offset = 0;  if (m[8] !== "Z") {    const [oh, om] = m[8]!.slice(1).split(":").map(Number) as [number, number];    if (oh > 23 || om > 59) return null;    offset = (m[8]!.startsWith("-") ? -1 : 1) * (oh * 60 + om);  }  return new Date(local - offset * 60_000).toISOString();}export function isPinned(value: string): boolean {  return normaliseTime(value) === value;}/** A cut's `at`: the newest server landing time among the mails the screen showed. */export function cutAt(shownLanded: Iterable<string | null | undefined>): string | null {  let newest: string | null = null;  for (const v of shownLanded) {    const t = typeof v === "string" ? normaliseTime(v) : null;    if (t !== null && (newest === null || t > newest)) newest = t;  }  return newest;}/** Why a cut's `at` cannot be written, or null: pinned, and no later than the newest landing the copy knows. */export function checkCutAt(at: string, newestKnown: string | null | undefined): "not_pinned" | "later_than_known" | null {  if (!isPinned(at)) return "not_pinned";  const newest = typeof newestKnown === "string" ? normaliseTime(newestKnown) : null;  return newest !== null && at <= newest ? null : "later_than_known";}const text = (v: unknown): string | null => (typeof v === "string" ? v : null);function exceptOf(v: unknown): unknown[] {  if (typeof v !== "string") return [];  try {    const parsed: unknown = JSON.parse(v);    return Array.isArray(parsed) ? parsed : [];  } catch {    return [];  }}/** A stored row is opened unless a reader says otherwise or its data still carries its sealed body. */function opened(row: MailRow): boolean {  return row.sealed !== true && typeof row.data.sealed_enc !== "string";}const timeOf = (v: unknown): string | null => (typeof v === "string" ? normaliseTime(v) : null);function covers(cut: MailCut, row: MailRow, star: boolean, own: readonly string[] = []): boolean {  if (cut.deleted_at != null) return false;  if (cut.state === "undone") return false;  const key = text(cut.key);  const before = timeOf(cut.before);  const at = timeOf(cut.at);  const sent = timeOf(row.data.sent_at);  const landed = timeOf(row.landed_at);  if (timeOf(cut.made_at) === null) return false;  if (key === null || before === null || at === null || sent === null || landed === null) return false;  const from = text(row.data.from_email);  if (from === null) return false;  const address = normaliseKey(from);  const atSign = address.indexOf("@");  // SQLite's substr(x, instr(x, '@')) is the whole address when it holds no '@'.  const domain = atSign < 0 ? address : address.slice(atSign);  if (own.includes(address)) return false;  if (!(key === address || key === domain || (star && key === "*"))) return false;  if (!(sent <= before)) return false;  if (!(landed <= at)) return false;  return !exceptOf(cut.except).includes(row.id);}/** When a mail went to the Bin: its own `trashed_at`, else the earliest covering bin cut's `made_at`; null when live or waiting. */export function binnedAt(row: MailRow, cuts: MailCuts = NO_CUTS): string | null {  if (!opened(row)) return null;  if (row.data.trashed_at != null) return String(row.data.trashed_at);  let earliest: string | null = null;  for (const cut of cuts.bin) {    if (!covers(cut, row, false, cuts.own)) continue;    const at = timeOf(cut.made_at)!;    if (earliest === null || at < earliest) earliest = at;  }  return earliest;}/** Live, binned, or waiting (not yet opened). */export function mailState(row: MailRow, cuts: MailCuts = NO_CUTS): MailState {  if (!opened(row)) return "waiting";  return binnedAt(row, cuts) === null ? "live" : "binned";}/** A live mail an archive cut covers (a bin cut wins over it). */export function archivedMail(row: MailRow, cuts: MailCuts = NO_CUTS): boolean {  return mailState(row, cuts) === "live" && cuts.archive.some((cut) => covers(cut, row, false, cuts.own));}/** Unread: its own `unread` (1 or true) and no read cut. Null while waiting. */export function unreadMail(row: MailRow, cuts: MailCuts = NO_CUTS): boolean | null {  if (!opened(row)) return null;  const own = row.data.unread === 1 || row.data.unread === true;  return own && !cuts.read.some((cut) => covers(cut, row, true, cuts.own));}/** A conversation by its mails: live when any is live; binned when some is opened and none live; else waiting. Never its stored trashed_at. */export function threadState(mails: readonly MailRow[], cuts: MailCuts = NO_CUTS): MailState {  let opened_any = false;  for (const m of mails) {    const state = mailState(m, cuts);    if (state === "live") return "live";    if (state === "binned") opened_any = true;  }  return opened_any ? "binned" : "waiting";}