Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/TemplateTests.swift3// Description: Unit tests of the template studio, unified inbox and sender identities that need no server: SSE generation stream replayed from a4// recording (fuzzed over chunk boundaries, through a stubbed URLProtocol), variable extraction, forced dark transform, preview document, id decoding, signature swap.5import Foundation6import Testing7@testable import SPMailCore89/// The stream of a real generation, recorded from the development backend (Resources/generation-stream.sse).10enum Recording {11 static let data: Data = {12 let url = Bundle.module.url(forResource: "generation-stream", withExtension: "sse", subdirectory: "Resources")!13 return try! Data(contentsOf: url)14 }()15}1617struct Chunks: AsyncSequence, Sendable {18 typealias Element = UInt819 let chunks: [[UInt8]]20 struct Iterator: AsyncIteratorProtocol {21 var chunks: [[UInt8]]22 var c = 0, i = 023 mutating func next() async -> UInt8? {24 while c < chunks.count, i >= chunks[c].count { c += 1; i = 0; await Task.yield() }25 guard c < chunks.count else { return nil }26 defer { i += 1 }27 return chunks[c][i]28 }29 }30 func makeAsyncIterator() -> Iterator { Iterator(chunks: chunks) }31}3233struct SplitMix: RandomNumberGenerator {34 var state: UInt6435 mutating func next() -> UInt64 {36 state &+= 0x9E3779B97F4A7C1537 var z = state38 z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B939 z = (z ^ (z >> 27)) &* 0x94D049BB133111EB40 return z ^ (z >> 31)41 }42}4344func split(_ bytes: [UInt8], using rng: inout SplitMix, maxChunk: Int) -> [[UInt8]] {45 var out: [[UInt8]] = [], i = 046 while i < bytes.count {47 let n = Int.random(in: 1...maxChunk, using: &rng)48 out.append(Array(bytes[i..<min(bytes.count, i + n)]))49 i += n50 }51 return out52}5354func collect(_ stream: AsyncThrowingStream<GenerationEvent, Error>) async throws -> [GenerationEvent] {55 var out: [GenerationEvent] = []56 for try await e in stream { out.append(e) }57 return out58}5960final class StubProtocol: URLProtocol, @unchecked Sendable {61 struct Answer: Sendable { var status = 200; var headers = ["Content-Type": "text/event-stream; charset=utf-8"]; var chunks: [Data] = []; var failAfter = false; var delay: UInt64 = 0 }62 nonisolated(unsafe) static var answer = Answer()63 nonisolated(unsafe) static var lastRequest: URLRequest?64 nonisolated(unsafe) static var lastBody: Data?65 nonisolated(unsafe) static var stopped = 066 final class Flag: @unchecked Sendable { private let lock = NSLock(); private var v = false; var isSet: Bool { lock.withLock { v } }; func set() { lock.withLock { v = true } } }67 private let cancelled = Flag()68 override class func canInit(with request: URLRequest) -> Bool { true }69 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }70 override func startLoading() {71 Self.lastRequest = request72 if let s = request.httpBodyStream {73 s.open(); var d = Data(); var buf = [UInt8](repeating: 0, count: 4096)74 while s.hasBytesAvailable { let n = s.read(&buf, maxLength: buf.count); if n <= 0 { break }; d.append(buf, count: n) }75 Self.lastBody = d76 } else { Self.lastBody = request.httpBody }77 let a = Self.answer78 nonisolated(unsafe) let me = self79 let flag = cancelled80 DispatchQueue.global().async {81 guard let client = me.client else { return }82 client.urlProtocol(me, didReceive: HTTPURLResponse(url: me.request.url!, statusCode: a.status, httpVersion: "HTTP/1.1", headerFields: a.headers)!, cacheStoragePolicy: .notAllowed)83 for c in a.chunks {84 if a.delay > 0 { usleep(UInt32(a.delay / 1000)) }85 if flag.isSet { return }86 client.urlProtocol(me, didLoad: c)87 }88 if flag.isSet { return }89 if a.failAfter { client.urlProtocol(me, didFailWithError: URLError(.networkConnectionLost)) } else { client.urlProtocolDidFinishLoading(me) }90 }91 }92 override func stopLoading() { Self.stopped += 1; cancelled.set() }93}9495@Suite(.serialized) struct GenerationStreamTests {96 @Test func recordedStreamDecodesToStartProgressDone() async throws {97 let events = try await collect(TemplateGenerationStream.events(bytes: Chunks(chunks: [Array(Recording.data)])))98 guard case .start(let model, let revising) = events.first else { Issue.record("no start"); return }99 #expect(!model.isEmpty && !revising)100 let progress = events.compactMap { e -> Int? in if case .progress(let c) = e { return c } else { return nil } }101 #expect(progress.count >= 5 && progress == progress.sorted() && progress.first! >= 400)102 guard case .done(let template, let usage) = events.last else { Issue.record("no done"); return }103 #expect(template.isAI && template.version == 1 && template.html?.lowercased().contains("<!doctype html") == true && !template.variables.isEmpty)104 #expect(TemplateText.variables(in: template.subject, template.preheader, template.html ?? "", template.text ?? "") == template.variables.map(\.name).sorted())105 #expect(usage.outputTokens > 1000 && usage.seconds > 10 && usage.model == model)106 #expect(template.aiBrief?.contains("bienvenue") == true && template.brand.accent == "#4f46e5")107 }108109 @Test func parserIsStableOverEveryKindOfChunking() async throws {110 let reference = try await collect(TemplateGenerationStream.events(bytes: Chunks(chunks: [Array(Recording.data)]))).filter { $0 != .alive }111 let lf = Array(Recording.data)112 // the same stream with CRLF line ends, comments / pings between events, a byte-order mark and an unknown event type113 var crlf: [UInt8] = [0xEF, 0xBB, 0xBF]114 var n = 0115 for b in lf {116 if b == 0x0A { crlf += [0x0D, 0x0A] } else { crlf.append(b) }117 if b == 0x0A, crlf.suffix(4) == [0x0D, 0x0A, 0x0D, 0x0A] {118 n += 1119 if n % 3 == 0 { crlf += Array(": ping\r\n\r\n".utf8) }120 if n % 7 == 0 { crlf += Array("event: future\r\ndata: {\"x\":1}\r\nretry: 500\r\n\r\n".utf8) }121 }122 }123 var rng = SplitMix(state: 20261119)124 for round in 0..<60 {125 let source = round % 2 == 0 ? lf : crlf126 let chunks = split(source, using: &rng, maxChunk: [1, 2, 3, 7, 64, 1024, 9000][round % 7])127 let got = try await collect(TemplateGenerationStream.events(bytes: Chunks(chunks: chunks))).filter { $0 != .alive }128 #expect(got == reference, "round \(round)")129 }130 // every single split point around the multi-byte characters of the final event131 let tail = lf.count - 400132 for cut in stride(from: tail, to: lf.count - 1, by: 1) {133 let got = try await collect(TemplateGenerationStream.events(bytes: Chunks(chunks: [Array(lf[..<cut]), Array(lf[cut...])]))).filter { $0 != .alive }134 #expect(got.count == reference.count && got.last == reference.last, "cut \(cut)")135 }136 }137138 @Test func multiLineDataAndCommentsFollowTheSpecification() {139 var p = SSEParser()140 let events = p.feed(": hello\n\nevent: progress\ndata: {\"chars\":\ndata: 12}\n\ndata\n\nevent: x\rdata: two spaces\r\r\nid: 7\ndata: last\n\n")141 #expect(events.map(\.event) == ["progress", "message", "x", "message"])142 #expect(events[0].data == "{\"chars\":\n12}" && events[1].data == "" && events[2].data == " two spaces" && events[3].id == "7")143 #expect(try! TemplateGenerationStream.event(from: events[0]) == .progress(chars: 12))144 }145146 @Test func errorEventAndCutStream() async throws {147 let failing = "event: start\ndata: {\"model\":\"m\",\"revising\":true}\n\n: ping\n\nevent: error\ndata: {\"code\":\"ai_refused\",\"message\":\"The model declined this request\"}\n\n"148 var seen: [GenerationEvent] = []149 do {150 for try await e in TemplateGenerationStream.events(bytes: Chunks(chunks: [Array(failing.utf8)])) { seen.append(e) }151 Issue.record("should have thrown")152 } catch let e as GenerationError { #expect(e.code == "ai_refused" && e.message.contains("declined")) }153 #expect(seen == [.start(model: "m", revising: true), .alive])154 // the connection dies after a few progress events: neither done nor error155 let cut = Array(Recording.data.prefix(600))156 do { _ = try await collect(TemplateGenerationStream.events(bytes: Chunks(chunks: [cut]))); Issue.record("should have thrown") } catch let e as GenerationError { #expect(e == .streamCut) }157 }158159 func client() -> APIClient { APIClient(baseURL: URL(string: "http://stub.invalid")!, token: "tok-test", userAgent: "t", protocolClasses: [StubProtocol.self]) }160161 @Test func requestAndReplayThroughURLSession() async throws {162 var rng = SplitMix(state: 7)163 StubProtocol.answer = .init(chunks: split(Array(Recording.data), using: &rng, maxChunk: 700).map { Data($0) })164 var brand = TemplateBrand(); brand.name = " SP Mail "; brand.accent = "#4F46E5"; brand.logoURL = "http://insecure.example/logo.png"; brand.website = "javascript:alert(1)"165 let req = GenerationRequest(brief: "Un courriel de bienvenue chaleureux", language: "fr", category: "transactional", brand: brand)166 let events = try await collect(TemplateGenerationStream.events(api: client(), request: req))167 guard case .done(let t, _) = events.last else { Issue.record("no done"); return }168 #expect(t.name.isEmpty == false && events.contains { if case .progress = $0 { return true } else { return false } })169 let sent = try #require(StubProtocol.lastRequest)170 #expect(sent.httpMethod == "POST" && sent.url?.path == "/api/templates/generate" && sent.value(forHTTPHeaderField: "Authorization") == "Bearer tok-test")171 #expect(sent.value(forHTTPHeaderField: "Accept") == "text/event-stream" && sent.value(forHTTPHeaderField: "Origin") == nil)172 let body = try JSONValue.parse(try #require(StubProtocol.lastBody))173 #expect(body["brief"].stringValue == req.brief && body["language"].stringValue == "fr" && body["category"].stringValue == "transactional" && body["base_template_id"].isNull)174 // the brand only carries what the server accepts: an http logo and a javascript: site are left out175 #expect(body["brand"] == ["name": "SP Mail", "accent": "#4F46E5"])176 }177178 @Test func refusalsBeforeTheStreamCarryTheServerCode() async throws {179 for (status, payload, code) in [(503, "{\"error\":\"ai_not_configured\",\"message\":\"No Anthropic credential is configured on this server\"}", "ai_not_configured"),180 (429, "{\"error\":\"rate_limited\",\"message\":\"Too many requests\"}", "rate_limited"), (400, "{\"error\":\"invalid_request\"}", "invalid_request")] {181 StubProtocol.answer = .init(status: status, headers: ["Content-Type": "application/json"], chunks: [Data(payload.utf8)])182 do { _ = try await collect(TemplateGenerationStream.events(api: client(), request: GenerationRequest(brief: "Un brief assez long"))); Issue.record("should throw") }183 catch let e as GenerationError { #expect(e.code == code) }184 }185 StubProtocol.answer = .init(status: 401, headers: ["Content-Type": "application/json"], chunks: [Data("{\"error\":\"unauthenticated\"}".utf8)])186 do { _ = try await collect(TemplateGenerationStream.events(api: client(), request: GenerationRequest(brief: "Un brief assez long"))); Issue.record("should throw") }187 catch let e as APIError { #expect(e.isUnauthorized) }188 // transport failure in the middle of the stream189 StubProtocol.answer = .init(chunks: [Recording.data.prefix(500)], failAfter: true)190 do { _ = try await collect(TemplateGenerationStream.events(api: client(), request: GenerationRequest(brief: "Un brief assez long"))); Issue.record("should throw") }191 catch let e as GenerationError { #expect(e.code == "stream_cut") }192 }193194 @Test func cancellingTheTaskClosesTheConnection() async throws {195 let all = Array(Recording.data)196 // 80 ms between chunks: the 41 events of the recording sit in its first 2 kB (ten chunks, 800 ms), well after the cancellation below.197 // (At 30 ms they could all arrive within the 250 ms before the cancellation — the test failed about one run in three.)198 StubProtocol.answer = .init(chunks: stride(from: 0, to: all.count, by: 200).map { Data(all[$0..<min(all.count, $0 + 200)]) }, delay: 80_000_000)199 let before = StubProtocol.stopped200 let api = client()201 let task = Task { () -> Int in202 var n = 0203 for try await _ in TemplateGenerationStream.events(api: api, request: GenerationRequest(brief: "Un brief assez long")) { n += 1 }204 return n205 }206 try await Task.sleep(for: .milliseconds(250))207 task.cancel()208 let result = await task.result209 switch result {210 case .success(let n): #expect(n < 40, "the stream should have stopped early (\(n) events)")211 case .failure(let e): #expect(e is CancellationError, "\(e)")212 }213 try await Task.sleep(for: .milliseconds(200))214 #expect(StubProtocol.stopped > before)215 }216}217218@Suite struct TemplateHelperTests {219 @Test func variableExtractionMatchesTheServerRule() {220 let html = "<a href=\"{{ action_url }}\">{{first_name}}</a> {{first_name}} {{ Bad }} {{9x}} {{a}} {{toolong_\(String(repeating: "x", count: 40))}} { {no} } {{amount_2}}"221 #expect(TemplateText.variables(in: "Bonjour {{first_name}}", html) == ["a", "action_url", "amount_2", "first_name"])222 #expect(TemplateText.isValidName("first_name") && !TemplateText.isValidName("First") && !TemplateText.isValidName("1a") && !TemplateText.isValidName(""))223 let declared = [TemplateVariable(name: "first_name", description: "Prénom", example: "Zoé", required: true), TemplateVariable(name: "ghost")]224 let r = TemplateText.reconcile(declared, texts: ["{{first_name}} {{code}}"])225 #expect(r.map(\.name) == ["code", "first_name"] && r[1].example == "Zoé" && r[1].required && r[0].example.isEmpty)226 #expect(TemplateText.isClipped(bytes: 102_001) && !TemplateText.isClipped(bytes: 80_000))227 }228229 let sample = """230 <!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark">231 <style>232 body{background:#fff}233 @media (max-width:600px){.c{width:100%!important}}234 @media (prefers-color-scheme: dark){body{background:#111!important}.card{color:#eee!important}}235 @media screen and (PREFERS-COLOR-SCHEME:dark) and (max-width:600px){.x{color:red}}236 @media (prefers-color-scheme:light){.l{color:blue}}237 </style></head><body><p>(prefers-color-scheme: dark) in prose stays</p>238 <img src="https://cdn.example.org/logo.png?a=1&b=2" srcset="https://cdn.example.org/logo@2x.png 2x" width="120">239 <td background="https://cdn.example.org/bg.jpg" style="background-image:url('https://cdn.example.org/bg.jpg')">x</td>240 <img src="http://insecure.example/x.png"><a href="https://example.org/go">go</a></body></html>241 """242243 @Test func forcedDarkRewritesOnlyMediaFeaturesInsideStyleBlocks() {244 let dark = TemplatePreview.forced(sample, scheme: .dark)245 #expect(dark.contains("@media (min-width:0){body{background:#111!important}"))246 #expect(dark.contains("@media screen and (min-width:0) and (max-width:600px){.x{color:red}}"))247 #expect(dark.contains("@media (max-width:0){.l{color:blue}}"))248 #expect(dark.contains("@media (max-width:600px){.c{width:100%!important}}"))249 #expect(dark.contains("<p>(prefers-color-scheme: dark) in prose stays</p>"))250 #expect(dark.contains("name=\"color-scheme\" content=\"dark\"") && dark.contains("name=\"supported-color-schemes\" content=\"dark\""))251 let light = TemplatePreview.forced(sample, scheme: .light)252 #expect(light.contains("@media (max-width:0){body{background:#111!important}") && light.contains("@media (min-width:0){.l{color:blue}}") && light.contains("content=\"light\""))253 #expect(!light.contains("prefers-color-scheme:") || light.contains("in prose"))254 // idempotent, and a document without style is returned as is255 #expect(TemplatePreview.forced(dark, scheme: .dark) == dark)256 #expect(TemplatePreview.forced("<p>plain</p>", scheme: .dark) == "<p>plain</p>")257 #expect(TemplatePreview.forced("<style>@media (prefers-color-scheme:dark){a{}}", scheme: .dark) == "<style>@media (min-width:0){a{}}")258 }259260 @Test func previewDocumentProxiesImagesAndCarriesTheCSP() {261 let doc = TemplatePreview.document(html: sample, scheme: .dark)262 #expect(doc.contains("<head><meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; img-src data: spmail-img:;"))263 #expect(doc.contains("src=\"spmail-img://proxy/?u=https%3A%2F%2Fcdn.example.org%2Flogo.png%3Fa%3D1%26b%3D2\""))264 #expect(doc.contains("background=\"spmail-img://proxy/?u=https%3A%2F%2Fcdn.example.org%2Fbg.jpg\"") && doc.contains("url('spmail-img://proxy/?u=https%3A%2F%2Fcdn.example.org%2Fbg.jpg')"))265 #expect(!doc.contains("srcset") && !doc.contains("src=\"https://") && doc.contains("src=\"http://insecure.example/x.png\"")) // plain http is left alone: the renderer blocks it266 #expect(doc.contains("href=\"https://example.org/go\""))267 #expect(TemplatePreview.remoteImages(in: sample) == ["https://cdn.example.org/logo.png?a=1&b=2", "https://cdn.example.org/bg.jpg"])268 #expect(TemplatePreview.document(html: "<p>frag</p>", scheme: .light).hasPrefix("<!doctype html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"Content-Security-Policy\""))269 #expect(TemplatePreview.document(html: "<html><body>x</body></html>", scheme: .light).contains("<html><head><meta http-equiv"))270 }271272 @Test func recordedTemplateSurvivesTheTransforms() async throws {273 let events = try await collect(TemplateGenerationStream.events(bytes: Chunks(chunks: [Array(Recording.data)])))274 guard case .done(let t, _) = events.last, let html = t.html else { Issue.record("no template"); return }275 let dark = TemplatePreview.document(html: html, scheme: .dark), light = TemplatePreview.document(html: html, scheme: .light)276 #expect(html.contains("prefers-color-scheme") && !dark.replacingOccurrences(of: "color-scheme\" content", with: "").contains("prefers-color-scheme"))277 #expect(dark.contains("(min-width:0)") && light.contains("(max-width:0)") && dark.count >= html.count)278 #expect(TemplatePreview.remoteImages(in: html).isEmpty)279 }280281 @Test func brandAndContentEncoding() throws {282 var b = TemplateBrand(json: ["name": "ACME", "accent": "#ff0000", "logo_url": "https://a.example/l.png", "tone": "calme", "footer": "f", "website": "https://a.example", "unknown": 1])283 #expect(b.json == ["name": "ACME", "accent": "#ff0000", "logo_url": "https://a.example/l.png", "tone": "calme", "footer": "f", "website": "https://a.example"])284 b.accent = "red"; b.logoURL = ""; b.name = String(repeating: "n", count: 200)285 #expect(b.json["accent"].isNull && b.json["logo_url"].isNull && b.json["name"].stringValue?.count == 80)286 #expect(TemplateBrand().isEmpty && TemplateBrand().json == [:])287 let c = TemplateContent(name: "N", subject: "S", variables: [TemplateVariable(name: "a", example: "x", required: true)], note: "n")288 #expect(c.json == ["name": "N", "subject": "S", "variables": [["name": "a", "description": "", "example": "x", "required": true]], "note": "n"])289 let t = try #require(MailTemplate(json: ["id": "i", "name": "n", "source": "ai", "version": 3, "updated_at": "2026-11-19T07:46:42.999Z", "size_bytes": 12, "variables": [["name": "v"]]]))290 #expect(t.isAI && t.version == 3 && t.updatedAt != nil && t.html == nil && t.variables.first?.name == "v" && t.category == "other")291 }292}293294@Suite struct UnifiedAndIdentityTests {295 let mbA = "1b922af5-93ff-41a8-b44b-6c355d069f67", mbB = "fc87370d-dd2d-40a5-abfb-0bdb8e104fe5"296297 @Test func messageIdRoundTripAndRejection() {298 let id = V1MessageID.encode(mailboxId: mbA, emailId: "eaaaab")!299 #expect(id.hasPrefix("msg_") && V1MessageID.decode(id)! == (mbA, "eaaaab"))300 #expect(V1MessageID.decode("msg_") == nil && V1MessageID.decode("thr_" + id.dropFirst(4)) == nil && V1MessageID.decode("msg_!!!") == nil && V1MessageID.decode("msg_AAAA") == nil)301 #expect(V1MessageID.decode("thr_" + id.dropFirst(4), prefix: "thr")?.emailId == "eaaaab")302 }303304 func row(_ mailbox: String, _ account: String, _ jmap: String, at t: TimeInterval, folders: [(String, String?)] = [("f", "inbox")], extra: JSONValue = [:]) -> JSONValue {305 var j: JSONValue = ["id": .string(V1MessageID.encode(mailboxId: account, emailId: jmap)!), "thread_id": .string(V1MessageID.encode(mailboxId: account, emailId: "t\(jmap)", prefix: "thr")!),306 "mailbox": .string(mailbox), "delivered_to": ["alias@stg.spboucher.ai"], "folders": .array(folders.map { ["id": .string($0.0), "role": JSONValue($0.1), "name": "x"] }),307 "from": [["email": "x@example.org", "name": "X"]], "to": [["email": "alias@stg.spboucher.ai", "name": nil]], "cc": [], "subject": "S", "preview": "p",308 "received_at": .string(ISODate.string(Date(timeIntervalSince1970: t))), "sent_at": nil, "size": 10, "unread": true, "starred": true, "draft": false, "answered": false,309 "forwarded": false, "has_attachment": true, "labels": ["projet"]]310 for (k, v) in extra.objectValue ?? [:] { j[k] = v }311 return j312 }313314 @Test func unifiedRowsResolveTheirEngineOnlyWhenTheIdAgreesWithTheMailbox() throws {315 let accounts = ["a@stg.spboucher.ai": mbA, "b@stg.spboucher.ai": mbB]316 let m = try #require(UnifiedMessage(json: row("A@stg.spboucher.ai", mbA, "e1", at: 1000), accounts: accounts))317 #expect(m.account == mbA && m.email.id == "e1" && m.email.threadId == "te1" && !m.email.isSeen && m.email.isFlagged && m.email.hasAttachment && m.email.keywords.contains("projet"))318 #expect(m.receivingAddress == "alias@stg.spboucher.ai" && m.roles == ["inbox"])319 // an id that names another mailbox than the row says is not trusted: the row keeps its API id and has no engine320 let odd = try #require(UnifiedMessage(json: row("b@stg.spboucher.ai", mbA, "e2", at: 1000), accounts: accounts))321 #expect(odd.account == nil && odd.email.id == odd.id)322 let unknown = try #require(UnifiedMessage(json: row("z@stg.spboucher.ai", mbA, "e3", at: 1000, extra: ["delivered_to": []]), accounts: accounts))323 #expect(unknown.account == nil && unknown.receivingAddress == "z@stg.spboucher.ai")324 // virtual views leave out the same folders as the per-mailbox ones325 let trash = try #require(UnifiedMessage(json: row("a@stg.spboucher.ai", mbA, "e4", at: 1, folders: [("t", "trash")]), accounts: accounts))326 let custom = try #require(UnifiedMessage(json: row("a@stg.spboucher.ai", mbA, "e5", at: 1, folders: [("c", nil)]), accounts: accounts))327 let sent = try #require(UnifiedMessage(json: row("a@stg.spboucher.ai", mbA, "e6", at: 1, folders: [("s", "sent")]), accounts: accounts))328 #expect(!UnifiedView.unread.keeps(trash) && UnifiedView.unread.keeps(custom) && !UnifiedView.unread.keeps(sent) && UnifiedView.unread.keeps(m))329 #expect(!UnifiedView.flagged.keeps(trash) && UnifiedView.flagged.keeps(sent) && UnifiedView.inbox.keeps(trash))330 }331332 @Test func offlineMergeOrdersTheLocalCachesByDate() async throws {333 let (store, _, dir) = try tempStore()334 defer { try? FileManager.default.removeItem(at: dir) }335 try await store.upsertMailboxes("A", [Mailbox(id: "in", name: "Inbox", role: "inbox"), Mailbox(id: "tr", name: "Trash", role: "trash"), Mailbox(id: "se", name: "Sent", role: "sent")])336 try await store.upsertMailboxes("B", [Mailbox(id: "in", name: "Inbox", role: "inbox"), Mailbox(id: "dr", name: "Drafts", role: "drafts")])337 try await store.upsertEmails("A", [sample("1", date: 100), sample("2", date: 300, seen: true, flagged: true), sample("3", box: "tr", date: 400), sample("4", box: "se", date: 500, seen: true)])338 try await store.upsertEmails("B", [sample("1", date: 200), sample("9", box: "dr", date: 50, flagged: true)])339 let accounts = [(id: "A", address: "a@x"), (id: "B", address: "b@x")]340 let inbox = try await store.unified(.inbox, accounts: accounts)341 #expect(inbox.map { "\($0.account!)\($0.email.id)" } == ["A2", "B1", "A1"] && Set(inbox.map(\.id)).count == 3 && inbox[1].mailbox == "b@x" && inbox[0].roles == ["inbox"])342 #expect(try await store.unified(.unread, accounts: accounts).map { "\($0.account!)\($0.email.id)" } == ["B1", "A1"])343 #expect(try await store.unified(.flagged, accounts: accounts).map { "\($0.account!)\($0.email.id)" } == ["A2", "B9"])344 let sent = try await store.unified(.sent, accounts: accounts), drafts = try await store.unified(.drafts, accounts: accounts)345 #expect(sent.map(\.email.id) == ["4"] && drafts.map(\.email.id) == ["9"])346 }347348 @Test func outboundAndTemplateSendEncoding() throws {349 var s = TemplateSend(from: "alias@stg.spboucher.ai", to: [EmailAddress(name: "B", email: "b@stg.spboucher.ai"), EmailAddress(email: "c@stg.spboucher.ai")], templateId: "t1", variables: ["first_name": "Zoé"], subject: " ")350 #expect(s.json == ["from": "alias@stg.spboucher.ai", "to": [["email": "b@stg.spboucher.ai", "name": "B"], ["email": "c@stg.spboucher.ai"]], "template_id": "t1", "variables": ["first_name": "Zoé"]])351 s.subject = "Objet"; s.sendAt = Date(timeIntervalSince1970: 1_800_000_000)352 #expect(s.json["subject"] == "Objet" && s.json["send_at"].stringValue == "2027-01-15T08:00:00Z" && s.json["html"].isNull && s.json["text"].isNull)353 let vars = [TemplateVariable(name: "a", required: true), TemplateVariable(name: "b", required: true), TemplateVariable(name: "c")]354 #expect(TemplateSend.missing(vars, values: ["a": "1", "b": ""]) == ["b"])355 let o = try #require(OutboundStatus(json: ["id": "msg_out_x", "status": "sent", "from": "a@x", "recipients": [["address": "b@x", "status": "delivered", "smtp_reply": "250 OK"]], "send_at": nil]))356 #expect(!o.isFinal && o.recipients.first?.smtpReply == "250 OK" && !o.isScheduled)357 let e = APIClient.error(from: Data("{\"error\":{\"code\":\"missing_variables\",\"message\":\"Required template variables are missing\",\"details\":{\"variables\":[\"code\"]}}}".utf8), status: 400)358 #expect(e.code == "missing_variables" && e.message.contains("code"))359 #expect(APIClient.error(from: Data("{\"error\":\"not_found\",\"message\":\"m\"}".utf8), status: 404) == APIError(status: 404, code: "not_found", message: "m"))360 }361362 @Test func senderIdentitiesGroupMailboxesAndSendableAliases() throws {363 func addr(_ a: String, _ kind: String, _ mb: String, name: String = "", sig: String = "", send: Bool = true, status: String = "active") -> MailAddress {364 MailAddress(json: ["id": .string(a), "address": .string(a), "kind": .string(kind), "mailbox": "m", "mailbox_id": .string(mb), "display_name": .string(name), "signature_text": .string(sig),365 "can_send": .bool(send), "can_receive": true, "status": .string(status), "expired": false])!366 }367 let rows = [addr("a@x", "mailbox", "A", name: "Alice"), addr("ventes@x", "alias", "A", name: "Ventes", sig: "Équipe des ventes"), addr("lecture@x", "receive_only", "A", send: false),368 addr("vieux@x", "alias", "A", status: "suspended"), addr("b@x", "mailbox", "B"), addr("autre@x", "alias", "Z", name: "Pas à moi")]369 let ids = ["A": [Identity(id: "i1", name: "Alice JMAP", email: "a@x", textSignature: "Sig JMAP"), Identity(id: "i2", name: "", email: "ventes@x")], "B": [Identity(id: "i9", name: "Bob", email: "b@x")]]370 let list = SenderIdentity.list(addresses: rows, identities: ids, accounts: [(id: "A", address: "a@x", name: "Boîte A"), (id: "B", address: "b@x", name: "Boîte B")])371 #expect(list.map(\.email) == ["a@x", "ventes@x", "b@x"] && list.map(\.isAlias) == [false, true, false])372 #expect(list[0].name == "Alice" && list[0].signature == "Sig JMAP" && list[0].jmapIdentityId == "i1")373 #expect(list[1].name == "Ventes" && list[1].signature == "Équipe des ventes" && list[1].account == "A" && list[1].jmapIdentityId == "i2")374 #expect(list[2].name == "Bob" && list[2].identity.email == "b@x")375 // without the address list (offline, older server): the mailboxes alone376 #expect(SenderIdentity.list(addresses: [], identities: [:], accounts: [(id: "A", address: "a@x", name: "Boîte A")]).map(\.name) == ["Boîte A"])377 // a reply starts from the address the message was sent to378 let mail = EmailSummary(id: "1", threadId: "t", mailboxIds: [], receivedAt: Date(), from: [EmailAddress(email: "ext@example.org")], to: [EmailAddress(email: "Ventes@x")], cc: [EmailAddress(email: "a@x")])379 #expect(SenderIdentity.forReply(to: mail, among: list, fallback: list[0])?.email == "ventes@x")380 #expect(SenderIdentity.forReply(to: mail, among: list, deliveredTo: ["b@x"], fallback: nil)?.email == "b@x")381 let other = EmailSummary(id: "2", threadId: "t", mailboxIds: [], receivedAt: Date(), to: [EmailAddress(email: "liste@example.org")])382 #expect(SenderIdentity.forReply(to: other, among: list, fallback: list[0])?.email == "a@x")383 }384385 @Test func signatureSwapNeverDuplicatesNorTouchesTypedText() {386 let a = "Alice\nDirectrice", b = "Équipe des ventes"387 let typed = "Bonjour,\n\nVoici le devis."388 let start = typed + SignatureBlock.block(a)389 let swapped = SignatureBlock.swapped(start, from: a, to: b)390 #expect(swapped == typed + "\n\n-- \nÉquipe des ventes")391 #expect(SignatureBlock.swapped(swapped, from: b, to: a) == start) // and back392 #expect(SignatureBlock.swapped(swapped, from: b, to: b) == swapped) // same signature: nothing393 #expect(SignatureBlock.swapped(start, from: a, to: "") == typed) // to an identity without signature394 #expect(SignatureBlock.swapped(typed, from: "", to: b) == typed + "\n\n-- \n" + b) // from none: appended once395 #expect(SignatureBlock.swapped(typed + SignatureBlock.block(b), from: "", to: b) == typed + SignatureBlock.block(b))396 // the person rewrote the signature by hand: the text is kept as typed, the new block is appended, and a second switch replaces it cleanly397 let edited = typed + "\n\n-- \nAlice (en congé)"398 let once = SignatureBlock.swapped(edited, from: a, to: b)399 #expect(once == edited + SignatureBlock.block(b) && SignatureBlock.swapped(once, from: b, to: "") == edited)400 // text typed after the signature stays where it is401 let after = typed + SignatureBlock.block(a) + "\n\nPS : à lundi"402 #expect(SignatureBlock.swapped(after, from: a, to: b) == typed + SignatureBlock.block(b) + "\n\nPS : à lundi")403 #expect(SignatureBlock.swap(in: "", from: "", to: "") == nil)404 }405}406