Repository Public
1// SP Mail Next — tests unitaires du langage de recherche (analyse et traduction JMAP, sans réseau ni base).2import assert from "node:assert/strict"3import { test } from "node:test"4import { compileFilter, fold, foldersFor, parseQuery, resolveDate, resolveSize, zonedMidnight, type Term } from "./query"5import { parseSearch } from "../../../web/src/mail/search"67const NOW = new Date("2026-11-20T15:30:00Z")8const p = (q: unknown, tz?: string) => parseQuery(q, { now: NOW, tz })9const brief = (q: string) => p(q).terms.map((t) => `${t.negated ? "-" : ""}${t.op}:${t.value}${t.phrase ? "~" : ""}@${t.group}`)10const FOLDERS = [11 { id: "a", name: "Inbox", role: "inbox" }, { id: "b", name: "Deleted Items", role: "trash" }, { id: "c", name: "Junk Mail", role: "junk" },12 { id: "d", name: "Sent Items", role: "sent" }, { id: "e", name: "Projets Été", role: null }, { id: "f", name: "Snoozed", role: null },13]14const CTX = { folders: FOLDERS, labels: new Map([[fold("Clients"), "lbl_0a1b2c3d"], [fold("À Faire"), "lbl_ffffffff"]]) }15const jm = (q: string) => compileFilter(p(q).terms, CTX)16const SCOPE = { inMailboxOtherThan: ["b", "c"] }1718test("opérateurs simples, guillemets et texte libre", () => {19 assert.deepEqual(brief('from:alice to:bob cc:carl bcc:dan subject:"rapport final" body:budget filename:devis.pdf mots libres "phrase exacte"'), [20 "from:alice@0", "to:bob@1", "cc:carl@2", "bcc:dan@3", "subject:rapport final@4", "body:budget@5", "filename:devis.pdf@6", "text:mots@7", "text:libres@8", "text:phrase exacte~@9",21 ])22 const t = p('subject:"rapport final"').terms[0]23 assert.deepEqual([t.raw, t.start, t.end], ['subject:"rapport final"', 0, 23])24 assert.deepEqual(p("").terms, [])25 assert.deepEqual(p(" ").errors, [])26})2728test("synonymes français du client web et sur-ensemble de son analyseur", () => {29 assert.deepEqual(brief("de:alice à:bob a:carl sujet:x objet:y avec:pj has:pièce avec:fichier"), ["from:alice@0", "to:bob@1", "to:carl@2", "subject:x@3", "subject:y@4", "has:attachment@5", "has:attachment@6", "has:attachment@7"])30 assert.deepEqual(p("après:2026-01-02 depuis:2026-01-03 since:2026-01-04 apres:2026-01-05 avant:2026-02-01").terms.map((t) => t.op), ["after", "after", "after", "after", "before"])31 assert.deepEqual(brief("cci:x corps:y est:non-lu étiquette:Clients dans:corbeille fichier:a.pdf"), ["bcc:x@0", "body:y@1", "is:unread@2", "label:Clients@3", "in:trash@4", "filename:a.pdf@5"])32 // tout ce que le client web comprend est compris de la même façon ici33 for (const q of ['from:alice subject:"rapport final" has:attachment after:2026-01-01 mots libres', "de:bob à:carl sujet:devis avant:2026-03-04 avec:pj", 'objet:"a b" since:2026-05-06 "phrase libre" x']) {34 const web = parseSearch(q), srv = p(q)35 assert.deepEqual(srv.errors, [])36 const vals = (op: string) => srv.terms.filter((t) => t.op === op).map((t) => t.value).join(" ")37 assert.equal(vals("from"), web.from)38 assert.equal(vals("to"), web.to)39 assert.equal(vals("subject"), web.subject)40 assert.equal(srv.terms.some((t) => t.op === "has"), web.hasAttachment)41 assert.equal(vals("after"), web.after)42 assert.equal(vals("before"), web.before)43 assert.equal(srv.terms.filter((t) => t.op === "text").map((t) => (t.phrase ? `"${t.value}"` : t.value)).join(" "), web.text)44 }45})4647test("clé inconnue = texte libre ; URL et heures ne sont pas des opérateurs", () => {48 assert.deepEqual(brief("note:abc https://example.org/a 12:30"), ["text:note:abc@0", "text:https://example.org/a@1", "text:12:30@2"])49 assert.deepEqual(brief("-note:abc"), ["-text:note:abc@0"])50})5152test("négation", () => {53 assert.deepEqual(brief('-from:alice -facture -"mot à mot" -has:attachment -is:unread - x'), ["-from:alice@0", "-text:facture@1", "-text:mot à mot~@2", "-has:attachment@3", "-is:unread@4", "text:x@5"])54 assert.deepEqual(jm("-from:alice").filter, { operator: "AND", conditions: [{ operator: "NOT", conditions: [{ from: "alice" }] }, SCOPE] })55 assert.deepEqual(jm("-has:attachment -is:unread -is:starred").filter, { operator: "AND", conditions: [{ hasAttachment: false }, { hasKeyword: "$seen" }, { notKeyword: "$flagged" }, SCOPE] })56})5758test("OR relie deux termes voisins et lie plus fort que le ET implicite", () => {59 assert.deepEqual(brief("from:alice OR from:bob devis"), ["from:alice@0", "from:bob@0", "text:devis@1"])60 assert.deepEqual(brief("a OR b OR c d"), ["text:a@0", "text:b@0", "text:c@0", "text:d@1"])61 assert.deepEqual(brief("a OU b"), ["text:a@0", "text:b@0"])62 assert.deepEqual(brief("a or b"), ["text:a@0", "text:or@1", "text:b@2"], "seul OR en majuscules est un opérateur")63 assert.deepEqual(jm("from:alice OR -from:bob devis").filter, { operator: "AND", conditions: [{ operator: "OR", conditions: [{ from: "alice" }, { operator: "NOT", conditions: [{ from: "bob" }] }] }, { text: "devis" }, SCOPE] })64 for (const q of ["OR a", "a OR", "a OR OR b"]) assert.ok(p(q).errors.some((e) => e.code === "dangling_or"), q)65 assert.deepEqual(brief("a OR OR b"), ["text:a@0", "text:b@0"])66 // le terme après OR est invalide : le OR ne relie pas le terme suivant67 assert.deepEqual(brief("a OR before:nope c"), ["text:a@0", "text:c@1"])68})6970test("is: et has:", () => {71 assert.deepEqual(brief("is:unread is:read is:starred is:flagged is:pinned is:snoozed is:followup est:lu est:épinglé is:answered"), ["is:unread@0", "is:read@1", "is:starred@2", "is:starred@3", "is:pinned@4", "is:snoozed@5", "is:followup@6", "is:read@7", "is:pinned@8", "is:answered@9"])72 assert.deepEqual(jm("is:unread is:read is:starred is:pinned is:snoozed is:followup").filter, { operator: "AND", conditions: [{ notKeyword: "$seen" }, { hasKeyword: "$seen" }, { hasKeyword: "$flagged" }, { hasKeyword: "$pinned" }, { hasKeyword: "$snoozed" }, { hasKeyword: "$followup" }, SCOPE] })73 const bad = p("is:purple has:wings from:")74 assert.deepEqual(bad.terms, [])75 assert.deepEqual(bad.errors.map((e) => [e.token, e.code]), [["is:purple", "invalid_value"], ["has:wings", "invalid_value"], ["from:", "empty_value"]])76 assert.deepEqual([bad.errors[1].start, bad.errors[1].end], [10, 19])77})7879test("dates absolues (jour inclus pour before), relatives, fuseau", () => {80 assert.equal(p("after:2026-01-15").terms[0].date, "2026-01-15T00:00:00Z")81 assert.equal(p("before:2026-01-15").terms[0].date, "2026-01-16T00:00:00Z", "before inclut la journée indiquée")82 assert.equal(p("after:2026-01-15", "America/Toronto").terms[0].date, "2026-01-15T05:00:00Z")83 assert.equal(p("after:2026-07-15", "America/Toronto").terms[0].date, "2026-07-15T04:00:00Z", "heure d'été")84 assert.equal(p("before:2026-07-15", "America/Toronto").terms[0].date, "2026-07-16T04:00:00Z")85 assert.equal(p("after:2026-01-15", "Mars/Olympus").terms[0].date, "2026-01-15T00:00:00Z", "fuseau inconnu = UTC")86 assert.equal(p("after:today").terms[0].date, "2026-11-20T00:00:00Z")87 assert.equal(p("before:today").terms[0].date, "2026-11-21T00:00:00Z")88 assert.equal(p("after:yesterday").terms[0].date, "2026-11-19T00:00:00Z")89 assert.equal(p("after:hier before:aujourd'hui").terms.length, 2)90 // 15:30 UTC le 20 = 00:30 le 21 à Tokyo91 assert.equal(p("after:today", "Asia/Tokyo").terms[0].date, "2026-11-20T15:00:00Z")92 assert.equal(p("after:7d").terms[0].date, "2026-11-13T15:30:00Z")93 assert.equal(p("before:7d").terms[0].date, "2026-11-13T15:30:00Z")94 assert.equal(p("after:2w").terms[0].date, "2026-11-06T15:30:00Z")95 assert.equal(p("after:3m").terms[0].date, "2026-08-20T15:30:00Z")96 assert.equal(p("after:1y").terms[0].date, "2025-11-20T15:30:00Z")97 assert.equal(p("after:12h").terms[0].date, "2026-11-20T03:30:00Z")98 assert.equal(p("newer_than:2d").terms[0].op, "after")99 for (const q of ["after:2026-02-30", "after:demain", "before:2026-13-01", "after:7x", "after:20260115"]) {100 const r = p(q)101 assert.deepEqual([r.terms.length, r.errors[0]?.code], [0, "invalid_date"], q)102 }103 assert.equal(zonedMidnight(2026, 3, 8, "America/Toronto"), Date.parse("2026-03-08T05:00:00Z"))104 assert.equal(resolveDate("after", "2026-01-01", NOW, "UTC"), Date.parse("2026-01-01T00:00:00Z"))105 assert.deepEqual(jm("after:2026-01-01 before:2026-01-31").filter, { operator: "AND", conditions: [{ after: "2026-01-01T00:00:00Z" }, { before: "2026-02-01T00:00:00Z" }, SCOPE] })106})107108test("tailles", () => {109 assert.deepEqual([resolveSize("300"), resolveSize("10k"), resolveSize("10kb"), resolveSize("5m"), resolveSize("5Mo"), resolveSize("1g"), resolveSize("1,5m")], [300, 10240, 10240, 5242880, 5242880, 1073741824, 1572864])110 assert.deepEqual([resolveSize("big"), resolveSize("5x"), resolveSize("-5")], [null, null, null])111 assert.deepEqual(jm("larger:10k smaller:5m").filter, { operator: "AND", conditions: [{ minSize: 10240 }, { maxSize: 5242880 }, SCOPE] })112 assert.equal(p("larger:enorme").errors[0].code, "invalid_size")113})114115test("label: résolu par la table des étiquettes ; inconnu = aucun résultat et une erreur", () => {116 assert.deepEqual(jm("label:clients").filter, { operator: "AND", conditions: [{ hasKeyword: "lbl_0a1b2c3d" }, SCOPE] })117 assert.deepEqual(jm('label:"à faire"').filter, { operator: "AND", conditions: [{ hasKeyword: "lbl_ffffffff" }, SCOPE] })118 assert.deepEqual(jm("label:a faire").filter, null)119 assert.deepEqual(jm("-label:Clients").filter, { operator: "AND", conditions: [{ notKeyword: "lbl_0a1b2c3d" }, SCOPE] })120 assert.deepEqual(jm("label:lbl_12345678").filter, { operator: "AND", conditions: [{ hasKeyword: "lbl_12345678" }, SCOPE] }, "le mot-clé brut est accepté")121 const unknown = jm("label:inconnue")122 assert.equal(unknown.filter, null)123 assert.deepEqual(unknown.errors.map((e) => [e.token, e.code]), [["label:inconnue", "unknown_label"]])124 // dans un OR, l'étiquette inconnue ne retire que sa branche ; niée, elle ne restreint rien125 assert.deepEqual(jm("label:inconnue OR from:a").filter, { operator: "AND", conditions: [{ from: "a" }, SCOPE] })126 assert.deepEqual(jm("-label:inconnue").filter, SCOPE)127})128129test("in: rôle, nom de dossier, tout ; portée par défaut sans corbeille ni indésirables", () => {130 assert.deepEqual(jm("devis").filter, { operator: "AND", conditions: [{ text: "devis" }, SCOPE] })131 assert.deepEqual(jm("").filter, SCOPE)132 assert.deepEqual(jm("in:inbox").filter, { inMailbox: "a" })133 assert.deepEqual(jm("in:trash x").filter, { operator: "AND", conditions: [{ inMailbox: "b" }, { text: "x" }] })134 assert.deepEqual(jm("in:spam").filter, { inMailbox: "c" })135 assert.deepEqual(jm("dans:envoyés").filter, { inMailbox: "d" })136 assert.deepEqual(jm('in:"projets ete"').filter, { inMailbox: "e" })137 assert.deepEqual(jm("in:snoozed").filter, { inMailbox: "f" })138 assert.deepEqual(jm("in:all x").filter, { text: "x" }, "in:all lève la portée par défaut")139 assert.deepEqual(jm("in:inbox OR in:sent").filter, { operator: "OR", conditions: [{ inMailbox: "a" }, { inMailbox: "d" }] })140 assert.deepEqual(jm("-in:inbox").filter, { operator: "AND", conditions: [{ operator: "NOT", conditions: [{ inMailbox: "a" }] }, SCOPE] })141 const none = jm("in:archive")142 assert.equal(none.filter, null, "dossier absent de cette boîte")143 assert.equal(none.errors[0].code, "unknown_folder")144 assert.deepEqual(foldersFor("inbox", FOLDERS), ["a"])145 assert.deepEqual(compileFilter(p("x").terms, { folders: [], labels: new Map() }).filter, { text: "x" })146})147148test("filename: vérifié sur les noms des pièces jointes", () => {149 const c = jm("filename:Été.pdf")150 assert.deepEqual(c.filter, { operator: "AND", conditions: [{ hasAttachment: true }, SCOPE] })151 assert.equal(c.post!({ attachments: [{ name: "Rapport ÉTÉ.PDF" }] }), true)152 assert.equal(c.post!({ attachments: [{ name: "hiver.pdf" }, { name: null }] }), false)153 assert.equal(c.post!({}), false)154 const n = jm("-filename:pdf")155 assert.deepEqual(n.filter, SCOPE)156 assert.equal(n.post!({ attachments: [{ name: "a.pdf" }] }), false)157 assert.equal(n.post!({ attachments: [{ name: "a.png" }] }), true)158 assert.equal(jm("from:a").post, null)159 const or = p("filename:a.pdf OR from:bob")160 assert.equal(or.errors[0].code, "filename_in_or")161 assert.deepEqual(compileFilter(or.terms, CTX).filter, { operator: "AND", conditions: [{ operator: "OR", conditions: [{ hasAttachment: true }, { from: "bob" }] }, SCOPE] })162})163164test("forme symbolique rendue aux clients (indépendante de la boîte)", () => {165 assert.deepEqual(p('label:Clients in:inbox "a b" -filename:x').filters, { operator: "AND", conditions: [{ label: "Clients" }, { in: "inbox" }, { text: '"a b"' }, { operator: "NOT", conditions: [{ filename: "x" }] }] })166 assert.deepEqual(p("x").filters, { operator: "AND", conditions: [{ text: "x" }, { notIn: ["trash", "junk"] }] })167})168169test("entrées hostiles : jamais d'exception, bornes respectées", () => {170 for (const q of [undefined, null, 42, {}, [], "\u0000", '"', '""', '"""', ":", "::", "-", "--", "-:", "from:\"", "a:b:c", "OR", "OR OR", "🙂:🙂", "(a OR b)", "\\", "from:a\nto:b\tcc:c"]) assert.doesNotThrow(() => p(q), String(q))171 assert.deepEqual(brief("from:a\nto:b\tcc:c"), ["from:a@0", "to:b@1", "cc:c@2"])172 assert.deepEqual(brief('from:"alice'), ["from:alice@0"])173 assert.deepEqual(brief('"non fermée'), ["text:non fermée~@0"])174 const long = p("x".repeat(1500))175 assert.equal(long.errors[0].code, "query_too_long")176 assert.equal(long.terms[0].value.length, 1000)177 const many = p(Array.from({ length: 80 }, (_, i) => `w${i}`).join(" "))178 assert.equal(many.terms.length, 50)179 assert.deepEqual(many.errors.map((e) => e.code), ["too_many_terms"])180 const terms: Term[] = p('"a"b" x').terms181 assert.ok(terms.every((t) => !String(compileFilter([t], CTX).filter && JSON.stringify(compileFilter([t], CTX).filter)).includes('\\"a\\"b')))182})183184// ------------------------------------------------------------------ vCard, ZIP, contacts : fonctions pures des modules voisins185import { parseVcards, writeVcards, decodeVcf } from "./vcard"186187test("vCard : dépliage, échappements, quoted-printable, jeux de caractères, entrées abîmées", () => {188 const { cards, skipped } = parseVcards(["BEGIN:VCARD", "VERSION:3.0", "FN:Élo", " die Dupré", "N:Dupré;Élodie;;;", "EMAIL;TYPE=INTERNET,WORK:Elodie@Exemple.Test", "EMAIL:pas-une-adresse", "EMAIL:elodie@exemple.test",189 "TEL;TYPE=CELL:+1 819 555-0101", "ORG:A\\, B;C", "NOTE:l1\\nl2\; fin\\\\", "END:VCARD", "begin:vcard", "n:Nom;Prénom;;Dr;", "tel;work;voice:555", "end:vcard", "BEGIN:VCARD", "END:VCARD", "FN:hors fiche"].join("\r\n"))190 assert.deepEqual(cards, [191 { name: "Élodie Dupré", emails: [{ email: "elodie@exemple.test", label: "work" }], phones: [{ number: "+1 819 555-0101", label: "mobile" }], organization: "A, B, C", title: null, notes: "l1\nl2; fin\\" },192 { name: "Dr Prénom Nom", emails: [], phones: [{ number: "555", label: "work" }], organization: null, title: null, notes: null },193 ])194 assert.equal(skipped, 1)195 const qp = parseVcards("BEGIN:VCARD\nVERSION:2.1\nFN;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:Ren=E9e\nNOTE;ENCODING=QUOTED-PRINTABLE:a=\nb=C3=A9\nEND:VCARD").cards[0]196 assert.deepEqual([qp.name, qp.notes], ["Renée", "abé"])197 assert.equal(decodeVcf(Buffer.from("Zo\xe9", "latin1")), "Zoé")198 assert.equal(decodeVcf(Buffer.from("Zoé", "utf8")), "Zoé")199 for (const junk of ["", ":", "BEGIN:VCARD", "END:VCARD", "BEGIN:VCARD\n:::\n;;;:\nEMAIL\nEND:VCARD", "\u0000".repeat(50), "FN;ENCODING=QUOTED-PRINTABLE:=ZZ=\n"]) assert.doesNotThrow(() => parseVcards(junk))200})201202test("vCard : écriture 3.0 pliée à 75 octets, relue à l'identique", () => {203 const cards = [204 { name: "Élodie Dupré-Lévesque", emails: [{ email: "elodie@exemple.test", label: "work" }, { email: "e2@exemple.test", label: null }], phones: [{ number: "+1 819 555-0101", label: "mobile" }], organization: "Société, Division; Été", title: "Directrice", notes: `Ligne 1\nLigne 2 ${"très longue é ".repeat(20)}fin` },205 { name: "", emails: [{ email: "seul@exemple.test", label: null }], phones: [], organization: null, title: null, notes: null },206 ]207 const text = writeVcards(cards)208 assert.ok(text.split("\r\n").every((l) => Buffer.byteLength(l, "utf8") <= 75))209 assert.ok(text.startsWith("BEGIN:VCARD\r\nVERSION:3.0\r\n") && text.endsWith("END:VCARD\r\n"))210 const back = parseVcards(text).cards211 assert.deepEqual(back[0], cards[0])212 assert.deepEqual(back[1], { ...cards[1], name: "seul@exemple.test" })213 assert.equal(writeVcards([]), "")214})215