@joelincc/mailroom 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +47 -5
  2. package/SECURITY.md +1 -1
  3. package/bin/mailroom.mjs +26 -0
  4. package/dist/broadcast/config.js +79 -0
  5. package/dist/broadcast/explain.js +50 -0
  6. package/dist/cli/args.js +29 -0
  7. package/dist/cli/errors.js +31 -0
  8. package/dist/cli/main.js +475 -0
  9. package/dist/compose/clicks.js +29 -0
  10. package/dist/compose/compose.js +224 -0
  11. package/dist/compose/index.js +8 -0
  12. package/dist/compose/markdown.js +637 -0
  13. package/dist/compose/personalize.js +123 -0
  14. package/dist/compose/preflight.js +251 -0
  15. package/dist/compose/preview.js +41 -0
  16. package/dist/compose/render.js +136 -0
  17. package/dist/compose/template.js +118 -0
  18. package/docs/broadcast.md +199 -0
  19. package/docs/composing.md +135 -0
  20. package/docs/desk-commands.md +52 -0
  21. package/docs/export.md +51 -0
  22. package/docs/lists.md +66 -0
  23. package/docs/security-model.md +4 -4
  24. package/docs/ses.md +116 -0
  25. package/docs/unsubscribe.md +117 -0
  26. package/migrations/0004_last_error.sql +2 -0
  27. package/migrations/0005_lists.sql +41 -0
  28. package/migrations/0006_broadcast.sql +154 -0
  29. package/migrations/0007_unsubscribe.sql +12 -0
  30. package/package.json +19 -3
  31. package/src/alert.ts +123 -0
  32. package/src/aws-sigv4.ts +100 -0
  33. package/src/broadcast/audience.ts +96 -0
  34. package/src/broadcast/campaigns.ts +339 -0
  35. package/src/broadcast/config.ts +136 -0
  36. package/src/broadcast/dispatch.ts +766 -0
  37. package/src/broadcast/events.ts +107 -0
  38. package/src/broadcast/explain.ts +73 -0
  39. package/src/broadcast/freeze.ts +93 -0
  40. package/src/broadcast/index.ts +21 -0
  41. package/src/broadcast/postman.ts +229 -0
  42. package/src/broadcast/reconcile.ts +120 -0
  43. package/src/broadcast/routes.ts +181 -0
  44. package/src/broadcast/ses.ts +181 -0
  45. package/src/broadcast/stats.ts +59 -0
  46. package/src/broadcast/status.ts +60 -0
  47. package/src/broadcast/test-send.ts +88 -0
  48. package/src/broadcast/warmup.ts +150 -0
  49. package/src/broadcast/worker.ts +177 -0
  50. package/src/cf-events.ts +4 -3
  51. package/src/cli/args.ts +27 -0
  52. package/src/cli/errors.ts +33 -0
  53. package/src/cli/main.ts +466 -0
  54. package/src/compose/clicks.ts +45 -0
  55. package/src/compose/compose.ts +257 -0
  56. package/src/compose/index.ts +8 -0
  57. package/src/compose/markdown.ts +624 -0
  58. package/src/compose/personalize.ts +130 -0
  59. package/src/compose/preflight.ts +250 -0
  60. package/src/compose/preview.ts +58 -0
  61. package/src/compose/render.ts +153 -0
  62. package/src/compose/template.ts +197 -0
  63. package/src/core.ts +42 -1
  64. package/src/export.ts +184 -0
  65. package/src/feedback.ts +111 -0
  66. package/src/http.ts +17 -0
  67. package/src/index.ts +120 -31
  68. package/src/list-routes.ts +42 -0
  69. package/src/lists.ts +370 -0
  70. package/src/ses-events.ts +426 -0
  71. package/src/unsub-wiring.ts +64 -0
  72. package/src/unsub.ts +499 -0
  73. package/src/webhook.ts +5 -3
  74. package/wrangler.example.jsonc +16 -2
@@ -0,0 +1,118 @@
1
+ // 信件樣板:把「正文」包進頁首/頁尾,變成完整信件。
2
+ // 樣板是設定,不是程式:引擎只給一個通用的樣板工廠 createTemplate(),品牌樣板(名稱、頁尾、地址、文案)放私有設定。
3
+ // 表格排版+內嵌 CSS(Outlook 看得到)、深色模式用 class 覆寫(不把底色反白)。
4
+ export const DEFAULT_THEME = {
5
+ font: "-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang TC','Noto Sans TC','Microsoft JhengHei',Helvetica,Arial,sans-serif",
6
+ text: '#222222',
7
+ muted: '#6b6b6b',
8
+ link: '#1a56c4',
9
+ bg: '#f3f3f3',
10
+ card: '#ffffff',
11
+ border: '#dddddd',
12
+ accent: '#333333',
13
+ codeBg: '#f5f5f5',
14
+ width: 600,
15
+ dark: { bg: '#111111', card: '#1c1c1c', text: '#e8e8e8', muted: '#a0a0a0', link: '#8ab4f8', border: '#3a3a3a', codeBg: '#262626' },
16
+ };
17
+ export const DEFAULT_LABELS = {
18
+ viewInBrowser: 'View in browser',
19
+ unsubscribe: 'Unsubscribe',
20
+ sentTo: 'This email was sent to {email}',
21
+ embedCard: 'This content is best viewed on the website →',
22
+ image: (alt) => (alt ? `[Image: ${alt}]` : '[Image]'),
23
+ };
24
+ export function escapeHtml(s) {
25
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/\uE000/g, '&#123;');
26
+ }
27
+ function mergeTheme(t) {
28
+ return { ...DEFAULT_THEME, ...t, dark: { ...DEFAULT_THEME.dark, ...(t?.dark ?? {}) } };
29
+ }
30
+ export function createTemplate(cfg) {
31
+ const theme = mergeTheme(cfg.theme);
32
+ const labels = { ...DEFAULT_LABELS, ...cfg.labels };
33
+ const lang = cfg.lang ?? 'en';
34
+ const w = theme.width;
35
+ const d = theme.dark;
36
+ const footer = cfg.footerLines ?? [];
37
+ const css = `
38
+ body,table,td,a{-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}
39
+ table{border-collapse:collapse;mso-table-lspace:0;mso-table-rspace:0}
40
+ img{border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic}
41
+ a{word-break:break-word}
42
+ @media only screen and (max-width:${w + 20}px){.mr-wrap{width:100%!important}.mr-pad{padding-left:16px!important;padding-right:16px!important}}
43
+ @media (prefers-color-scheme:dark){
44
+ .mr-bg{background:${d.bg}!important}
45
+ .mr-card{background:${d.card}!important}
46
+ .mr-text{color:${d.text}!important}
47
+ .mr-muted{color:${d.muted}!important}
48
+ .mr-link{color:${d.link}!important}
49
+ .mr-bd{border-color:${d.border}!important}
50
+ .mr-code{background:${d.codeBg}!important}
51
+ }`;
52
+ const renderHtml = (p) => {
53
+ const pre = escapeHtml(p.preheader);
54
+ const header = cfg.logoUrl
55
+ ? `<img src="${escapeHtml(cfg.logoUrl)}" alt="${escapeHtml(cfg.brandName)}" height="36" style="display:block;border:0;height:36px;width:auto">`
56
+ : `<span class="mr-text" style="font-size:20px;font-weight:700;color:${theme.accent}">${escapeHtml(cfg.brandName)}</span>`;
57
+ const tagline = cfg.tagline ? `<div class="mr-muted" style="font-size:13px;color:${theme.muted};margin-top:2px">${escapeHtml(cfg.tagline)}</div>` : '';
58
+ const greeting = cfg.greeting ? `{{#name}}<p class="mr-text" style="margin:0 0 18px;font-size:16px;line-height:1.8;color:${theme.text}">${escapeHtml(cfg.greeting)}</p>{{/name}}` : '';
59
+ const footLines = footer
60
+ .map((l) => typeof l === 'string'
61
+ ? `<p class="mr-muted" style="margin:0 0 6px;font-size:12px;line-height:1.7;color:${theme.muted}">${escapeHtml(l)}</p>`
62
+ : `<p style="margin:0 0 6px;font-size:12px;line-height:1.7"><a class="mr-link" href="${escapeHtml(l.href)}" style="color:${theme.link}">${escapeHtml(l.text)}</a></p>`)
63
+ .join('');
64
+ const sentTo = labels.sentTo.replace('{email}', '{{email}}');
65
+ const lead = cfg.unsubscribeLead ? `${escapeHtml(cfg.unsubscribeLead)} ` : '';
66
+ return `<!doctype html>
67
+ <html lang="${escapeHtml(lang)}" xmlns="http://www.w3.org/1999/xhtml">
68
+ <head>
69
+ <meta charset="utf-8">
70
+ <meta name="viewport" content="width=device-width,initial-scale=1">
71
+ <meta name="color-scheme" content="light dark">
72
+ <meta name="supported-color-schemes" content="light dark">
73
+ <title>${escapeHtml(p.subject)}</title>
74
+ <style>${css}</style>
75
+ </head>
76
+ <body class="mr-bg" style="margin:0;padding:0;background:${theme.bg};word-break:break-word">
77
+ <div style="display:none;max-height:0;overflow:hidden;opacity:0;mso-hide:all;font-size:1px;line-height:1px;color:${theme.bg}">${pre}${'&#8204;&nbsp;'.repeat(40)}</div>
78
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="mr-bg" style="background:${theme.bg}"><tr><td align="center" style="padding:20px 10px">
79
+ <!--[if mso]><table role="presentation" width="${w}" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
80
+ <table role="presentation" class="mr-wrap" width="${w}" cellpadding="0" cellspacing="0" border="0" style="width:${w}px;max-width:100%">
81
+ <tr><td class="mr-pad" style="padding:0 4px 12px;font-family:${theme.font}">
82
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="font-family:${theme.font}">${header}${tagline}</td>
83
+ <td align="right" style="font-family:${theme.font};font-size:12px"><a class="mr-link" href="{{web_url}}" style="color:${theme.link}">${escapeHtml(labels.viewInBrowser)}</a></td></tr></table>
84
+ </td></tr>
85
+ <tr><td class="mr-card mr-bd mr-pad" style="background:${theme.card};border:1px solid ${theme.border};padding:28px 32px;font-family:${theme.font};color:${theme.text}">
86
+ ${greeting}${p.bodyHtml}
87
+ </td></tr>
88
+ <tr><td class="mr-pad" style="padding:16px 4px;font-family:${theme.font}">
89
+ ${cfg.footerHtml ?? ''}${footLines}<p class="mr-muted" style="margin:0 0 6px;font-size:12px;line-height:1.7;color:${theme.muted}">${escapeHtml(cfg.postalAddress)}</p>
90
+ {{#email}}<p class="mr-muted" style="margin:0 0 6px;font-size:12px;line-height:1.7;color:${theme.muted}">${escapeHtml(sentTo)}</p>{{/email}}
91
+ <p class="mr-muted" style="margin:0;font-size:12px;line-height:1.7;color:${theme.muted}">${lead}<a class="mr-link" href="{{unsubscribe_url}}" style="color:${theme.link}">${escapeHtml(labels.unsubscribe)}</a></p>
92
+ ${p.pixelUrl ? `<img src="${escapeHtml(p.pixelUrl)}" width="1" height="1" alt="" style="display:block;border:0;width:1px;height:1px">` : ''}
93
+ </td></tr>
94
+ </table>
95
+ <!--[if mso]></td></tr></table><![endif]-->
96
+ </td></tr></table>
97
+ </body>
98
+ </html>`;
99
+ };
100
+ const renderText = (p) => {
101
+ const lines = [];
102
+ lines.push(cfg.brandName + (cfg.tagline ? ` — ${cfg.tagline}` : ''));
103
+ lines.push(`${labels.viewInBrowser}: {{web_url}}`);
104
+ lines.push('');
105
+ if (cfg.greeting)
106
+ lines.push(`{{#name}}${cfg.greeting}{{/name}}`, '');
107
+ lines.push(p.bodyText.trim(), '', '--');
108
+ if (cfg.footerText)
109
+ lines.push(cfg.footerText.trim());
110
+ for (const l of footer)
111
+ lines.push(typeof l === 'string' ? l : `${l.text}: ${l.href}`);
112
+ lines.push(cfg.postalAddress);
113
+ lines.push(`{{#email}}${labels.sentTo.replace('{email}', '{{email}}')}{{/email}}`);
114
+ lines.push(`${cfg.unsubscribeLead ? `${cfg.unsubscribeLead} ` : ''}${labels.unsubscribe}: {{unsubscribe_url}}`);
115
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n{{#email}}{{\/email}}/g, '') + '\n';
116
+ };
117
+ return { theme, labels, postalAddress: cfg.postalAddress, renderHtml, renderText };
118
+ }
@@ -0,0 +1,199 @@
1
+ # Newsletter broadcasting (preview)
2
+
3
+ Sends one newsletter issue to a frozen list, in waves, at a steady pace, with automatic brakes. Code: `src/broadcast/`
4
+ (exported as `@joelincc/mailroom/broadcast`), tables: migration `0006_broadcast.sql`. Status: **preview** — built-in newsletter
5
+ postmans: Amazon SES (see [docs/ses.md](ses.md)) and a fake one for development; another provider plugs in through the
6
+ `Postman` interface.
7
+
8
+ Everything below uses example values (`mail.example.com`, a 2,000-person list). Your real numbers belong in your private config.
9
+
10
+ ## One issue, start to finish
11
+
12
+ ```
13
+ draft ──approve──▶ approved ──schedule──▶ scheduled ──(cron, at time)──▶ sending ⇄ paused ──▶ done
14
+ ▲ │ ▲ │ │
15
+ └── content edited ─┘ └──── unschedule ────┘ cancelled ◀── (draft / approved / scheduled / paused)
16
+ ```
17
+
18
+ 1. **Draft** — `PUT /v1/campaigns/{id}` with subject, sender (must be on `MARKETING_DOMAIN`), HTML, text, the web version
19
+ URL (`webUrl`, required before scheduling), extra headers (only `List-Unsubscribe`, `List-Unsubscribe-Post`, `List-Id`
20
+ and `X-…`) and the audience. Editing a draft,
21
+ an approved or a scheduled issue sends it back to `draft` and clears approval and the pre-send check.
22
+ After `sending` the content is locked.
23
+ 2. **Pre-send check** — run the compose module's `preflight()` (it needs the network to check links), then
24
+ `POST /v1/campaigns/{id}/preflight` with the result. It is tied to a hash of the content; any edit invalidates it.
25
+ 3. **Approve** — `POST /v1/campaigns/{id}/approve { note }`. The note is required ("who said yes, when, where").
26
+ 4. **Schedule** — `POST /v1/campaigns/{id}/schedule { at }`. Refused unless the approval and a passing pre-send check
27
+ match the current content.
28
+ 5. **Start** (cron, once `scheduled_at` has passed) — the issue moves to `sending` and the list is **frozen** into
29
+ `campaign_recipients`: every member who is `subscribed` at that moment. Members on the global suppression list are
30
+ written as `skipped/suppressed`; members outside this issue's audience as `skipped/warmup`. People who subscribe later
31
+ are not part of this issue. People who unsubscribe or get suppressed later are checked again right before their mail
32
+ is handed over, and skipped (`skipped/unsubscribed`, `skipped/suppressed`).
33
+ 6. **Waves and pacing** (cron, every minute) — recipients are released into the `mailroom-broadcast` queue, wave by wave,
34
+ in audience order. Per minute the engine releases the smallest of:
35
+ - provider speed: `perSecond × 60 × rateFactor` (default 0.8), halved for one minute after a throttling reply;
36
+ - what is left today: your own daily cap (`maxPerDay`, local day, default UTC+8) and the provider's 24-hour quota,
37
+ minus mails already handed over;
38
+ - the pace: `ceil(people to send ÷ paceMinutes)` (default 150 → a 2,000-person issue takes about 2½ hours);
39
+ - what is left in the current wave.
40
+ A new wave starts no earlier than `waveGapMinutes` (60) after the previous one started and `waveGateWaitMinutes` (30)
41
+ after its last mail, and only if the previous wave's hard-bounce rate is below `waveGateBounceRate` (2%).
42
+ 7. **Hand-over** (queue consumer, one at a time, spaced to the provider's per-second limit) — each recipient is one ledger
43
+ row in `messages` (`stream='marketing'`, `tier='marketing'`, key `c:{issue}:{contact}`).
44
+ 8. **Reconcile** — when nobody is left to send, the engine checks
45
+ `frozen = sent + skipped (per reason) + failed + uncertain + pending`, that every sent recipient has a `sent` ledger
46
+ row and the ledger has no extra ones, and that provider events show no second mail to anyone. Only then is the issue
47
+ `done`. Any mismatch pauses it (`reconcile_mismatch:…`) for a person to look at. Events that simply have not arrived
48
+ yet (deliveries, late complaints) are listed as `awaiting`, not as a mismatch. Run `POST /v1/campaigns/{id}/reconcile`
49
+ again later (for example after 72 hours) for the final numbers.
50
+
51
+ ## Never twice
52
+
53
+ - One idempotency key per person per issue. A ledger row that is already `sent` only ever answers `duplicate`.
54
+ - The ledger row is created **before** the mail is handed to the provider. Unlike transactional mail, a newsletter row
55
+ stuck in `sending` is never re-claimed: if the Worker died mid-hand-over, or the provider threw (we cannot know whether
56
+ it accepted the mail), that recipient becomes `uncertain`. A provider event for that mail settles it as sent; otherwise
57
+ a person decides with `POST /v1/campaigns/{id}/resolve { contact, as: 'sent' | 'failed', note }`. An issue with
58
+ `uncertain` recipients cannot reach `done`.
59
+ - Queue redelivery, the same person released twice, or a stuck release re-sent after `stuckMinutes` (10): the consumer
60
+ only hands over recipients whose state is `enqueued`, and the ledger key catches the rest.
61
+ - Nothing is handed over while the issue is not `sending` or the sender domain is on hold.
62
+
63
+ ## Brakes
64
+
65
+ | Level | Condition (defaults) | What happens |
66
+ |---|---|---|
67
+ | Wave gate | previous wave's hard bounces ≥ 2% | issue paused before the next wave |
68
+ | Issue brake | ≥ 200 sent in this issue and hard bounces ≥ 4%; or ≥ 3 complaints and ≥ 0.1% (no sent minimum: the 3 complaints are the floor) | issue paused |
69
+ | Provider | provider reports the account as not `HEALTHY`, or answers "account paused" | sending issues paused, scheduled issues do not start, queued mails are not handed over |
70
+ | Queue stalled | work handed to the queue but no result for 30 minutes | issue paused |
71
+ | Domain stop | among newsletter mails sent in the last 30 days (and since the last release): ≥ 200 sent and hard bounces ≥ 4% or complaints ≥ 0.08% | **all** newsletters on the domain stop; scheduled issues do not start |
72
+ | Warm-up gate | see below | the ladder does not move up; after 2 failures in a row it locks |
73
+
74
+ Every brake waits for a person: `POST /v1/campaigns/{id}/resume { note }` (refused while the domain is on hold) and
75
+ `POST /v1/broadcast/release-hold { note }`. After a resume, **only the brake that paused the issue** (bounce rate,
76
+ complaint rate or wave gate) restarts counting from the resume; every other rate keeps counting the whole issue. After a
77
+ release, the domain rate counts only mails sent after the release. An issue that finishes with failed recipients is
78
+ `done` (they were tried `maxAttempts` times) and raises a yellow alert. Newsletter ledger rows are kept at least 400
79
+ days even if `LEDGER_RETENTION_DAYS` is shorter (de-duplication and the domain rate depend on them). Transactional mail (the "must
80
+ deliver" desk) is not affected by any of this: it uses another sender domain and its own providers.
81
+
82
+ Alerts (started, paused, finished, blocked) go to the `alert` hook you pass in; the engine does not send them itself.
83
+
84
+ ## Warm-up ladder
85
+
86
+ ```http
87
+ PUT /v1/warmup/ramp/1 { "waves": [["core"], ["steady", "returning"], ["new"]] }
88
+ PUT /v1/warmup/ramp/2 { "waves": [["core"], ["steady", "returning"], ["new"], ["quiet"]] }
89
+ PUT /v1/warmup/ramp/3 { "waves": [["core"], ["steady", "returning"], ["new"], ["quiet"], ["*"]], "maxCount": 1800 }
90
+ ```
91
+
92
+ An issue with `"audience": { "plan": "ramp" }` is sent to the **current step** (the highest released step; step 1 needs
93
+ no release). Segment names come from `list_members.segment`; `"*"` means everyone not matched earlier (it must be last).
94
+ `maxCount` caps the step; the people beyond it (last waves first) are `skipped/warmup`.
95
+
96
+ After an issue has been `done` for 72 hours:
97
+
98
+ ```http
99
+ POST /v1/warmup/ramp/evaluate { "campaign": "weekly-12", "baselineOpenRate": 0.52 }
100
+ ```
101
+
102
+ `baselineOpenRate` is **the same people's** average open rate before the switch (computed by your analytics, not by the
103
+ engine; comparing with the whole list would make a step that only mails the most engaged readers look better than it
104
+ is). Pass: hard bounces ≤ 2%, complaints ≤ 0.1%, open rate not more than 5 points below the baseline, and the issue
105
+ reconciled cleanly → the next step is released. Fail → the next issue stays on the same step. Two failures in a row lock
106
+ the ladder: scheduled issues on it do not start until `POST /v1/warmup/ramp/unblock { note }`. Each issue is evaluated
107
+ once. Open rate = people with an open event ÷ (sent − hard bounces).
108
+
109
+ ## Status
110
+
111
+ - `GET /v1/campaigns/{id}` — state, approval, pre-send check, recipients by state/reason/wave, rates (no content, no addresses).
112
+ - `GET /v1/campaigns/{id}/audience` — who would receive it if it started now: per wave and segment, and how many are skipped (suppressed, not in this warm-up step). Read-only.
113
+ - `GET /v1/campaigns/{id}/preview` — the issue filled in for a sample reader (and a reader without a name), the pre-send check detail. `POST` does the same and marks this exact content as previewed; **approval over HTTP is refused (`preview_required`) until it has been**, and any edit invalidates it.
114
+ - `POST /v1/campaigns/{id}/test { to: [...], subjectPrefix? }` — real postman, real headers, one mail per address, **only to addresses listed in `TEST_RECIPIENTS`** (at most 10 per call), subject prefixed. Not in the frozen list, not in the ledger, not counted anywhere. The provider's events for a test mail (tag `contact=test`) are recorded but never suppress an address or unsubscribe anyone, so a test mailbox that bounces or marks the mail as spam changes nothing on the list; still, send test mail only to mailboxes you own and have confirmed receive mail. Refused while the domain is on hold. A postman error that leaves the outcome unknown is reported as `unknown_outcome` and never retried.
115
+ - The status answer includes `pauseExplain` for a paused issue: the code, a one-line summary, the numerator and denominator at the time, the threshold, whether the domain hold must be released first, whether a plain resume makes sense, and the suggested next step.
116
+ - `GET /v1/throttle` — today's cap and usage, provider speed and health, domain hold, issues in flight.
117
+
118
+ ## Postmen
119
+
120
+ ```ts
121
+ interface Postman {
122
+ name: string;
123
+ send(mail: PostmanMail): Promise<{ ok: true; providerId: string } | { ok: false; kind: 'temporary' | 'permanent' | 'throttled' | 'account_paused'; error: string }>;
124
+ limits(): Promise<{ perSecond: number; perDay: number; sentLast24h?: number; enforcement: string }>;
125
+ }
126
+ ```
127
+
128
+ Return a failure **only when you are sure the provider did not accept the mail**; throw when you do not know. One postman
129
+ per deployment; switching is a config change and a deploy, never automatic.
130
+
131
+ Provider feedback enters through one function, whatever the provider:
132
+
133
+ ```ts
134
+ await ingestEvent(db, { provider, providerEventId, providerMessageId, type, subtype, at, email, campaign, contact }, { feedback })
135
+ ```
136
+
137
+ `type` is one of `send`, `delivery`, `bounce` (`subtype` `Permanent…` / `Transient` / `Undetermined`; a transient
138
+ bounce may carry `cause: "mailbox"` or `"content"` — only `mailbox` counts toward the transient-bounce streak), `complaint`,
139
+ `reject`, `delay`, `open`, `click`, `unsubscribe`. Re-deliveries of the same `providerEventId` are ignored. Without a
140
+ `feedback` hook, bounces, complaints and deliveries go through `applyFeedback` (see [docs/unsubscribe.md](unsubscribe.md)).
141
+ An `unsubscribe` event that names an issue unsubscribes the person from that issue's list.
142
+
143
+ ### The fake postman
144
+
145
+ `FakePostman` sends nothing. Addresses whose local part is `success`, `bounce`, `complaint`, `ooto` or
146
+ `suppressionlist` (optionally `+tag`) behave like a provider's mailbox simulator and produce the matching events after a
147
+ short delay. `rules` can make any address answer `temporary`, `permanent`, `throttle`, `account_paused`, `delay`,
148
+ `daily_quota`, `soft_bounce` (a mailbox-full transient bounce) or `crash` (throw), optionally only the first `times` calls. In the Worker, set
149
+ `NEWSLETTER_POSTMAN = "fake"`; its events come back through the broadcast queue.
150
+
151
+ ## Worker setup
152
+
153
+ ```jsonc
154
+ "vars": {
155
+ "MARKETING_DOMAIN": "mail.example.com",
156
+ "NEWSLETTER_POSTMAN": "fake",
157
+ "NEWSLETTER_MAX_PER_DAY": 3000,
158
+ "BROADCAST_CONFIG": { "paceMinutes": 150 }
159
+ },
160
+ "queues": {
161
+ "producers": [{ "binding": "BROADCAST", "queue": "mailroom-broadcast" }],
162
+ "consumers": [{ "queue": "mailroom-broadcast", "max_batch_size": 10, "max_concurrency": 1, "max_retries": 10, "dead_letter_queue": "mailroom-broadcast-dlq" }]
163
+ },
164
+ "triggers": { "crons": ["* * * * *"] }
165
+ ```
166
+
167
+ Keep `max_concurrency: 1`: the per-second spacing is applied inside one consumer. Keep a dead-letter queue: send
168
+ messages lost there are re-released after `stuckMinutes`, but provider events (bounces, complaints) are not, and the
169
+ brakes would undercount them. Do not give an HTTP client the same site name as `BROADCAST_CONFIG.site`.
170
+
171
+ Personalisation per recipient goes through `render(campaign, recipient)`. The Worker default fills the compose
172
+ placeholders (`{{name}}`, `{{email}}`, `{{web_url}}`, `{{unsubscribe_url}}`, `{{unsubscribe_mailto}}`, also inside the
173
+ headers) with a signed unsubscribe token per recipient (`UNSUB_TOKEN_SECRET`, `UNSUB_BASE_URL`, optional `UNSUB_MAILTO`;
174
+ see [docs/unsubscribe.md](unsubscribe.md)). Without them every issue pauses with `render_error` instead of sending mail
175
+ without an unsubscribe link. Headers produced by a custom `render` are checked against the same allowlist.
176
+
177
+ ### All settings (`BROADCAST_CONFIG`)
178
+
179
+ | Key | Default | Meaning |
180
+ |---|---|---|
181
+ | `site` | `newsletter` | ledger `site` for newsletter rows |
182
+ | `maxPerDay` | 3000 | your own daily cap (also `NEWSLETTER_MAX_PER_DAY`) |
183
+ | `rateFactor` | 0.8 | share of the provider's speed to use |
184
+ | `paceMinutes` | 150 | spread one issue over this many minutes |
185
+ | `waveGapMinutes` / `waveGateWaitMinutes` / `waveGateBounceRate` | 60 / 30 / 0.02 | wave timing and gate |
186
+ | `brakeMinSent` / `brakeHardBounceRate` / `brakeComplaintCount` / `brakeComplaintRate` | 200 / 0.04 / 3 / 0.001 | issue brake |
187
+ | `domainWindowDays` / `domainMinSent` / `domainBounceRate` / `domainComplaintRate` | 30 / 200 / 0.04 / 0.0008 | domain stop |
188
+ | `domainMinComplaints` | 1 (max 10) | complaints in the window needed (besides the rate) to stop the domain. 1 = no extra floor: with a small sample a single complaint can cross 0.08% (1 of 220 is 0.45%). Decide before the first real send whether to raise it |
189
+ | `waveGateMinSent` | 1 (max 100) | mails the previous wave must have sent before its bounce rate is judged. With 30-person waves one bounce is 3.3%, over the 2% gate |
190
+ | `startGraceMinutes` | 360 (max 2880) | a scheduled issue more than this many minutes past its time (provider unhealthy or unreachable, domain on hold, Worker down) goes back to **`draft`** (approval and preview are cleared) with a yellow alert `start_stale` instead of starting late: look at it again, approve it again, schedule it again. An issue that did start but handed **no mail at all** to the provider for this long is paused (`brake:start_stale`) |
191
+ | `stuckMinutes` / `stallMinutes` | 10 / 30 | re-release / queue-stalled brake |
192
+ | `maxAttempts` / `throttleRetrySeconds` | 3 / 30 | temporary failures / throttling |
193
+ | `utcOffsetHours` | 8 | which local day the daily cap uses |
194
+ | `limitsRefreshMinutes` | 60 | how often provider limits and health are read |
195
+ | `gateWaitHours` / `gateBounceRate` / `gateComplaintRate` / `gateOpenDrop` / `gateMaxFails` | 72 / 0.02 / 0.001 / 0.05 / 2 | warm-up gate |
196
+
197
+ Invalid values fall back to the default; they never switch a check off. The three settings above also have a ceiling (a floor set absurdly high would switch the brake off): a larger value is ignored and the default is used, with a line in the log.
198
+
199
+ When the provider's limits cannot be read (bad key, API down) the engine does **not** start scheduled issues (`start_blocked_provider_unreachable`): they stay `scheduled` until the limits can be read again, or until `startGraceMinutes` passes and they go back to `draft`.
@@ -0,0 +1,135 @@
1
+ # Composing an issue
2
+
3
+ This is the "compose" side of the newsletter desk: it turns one markdown source into an email — HTML and plain text — and
4
+ refuses to let a broken issue be scheduled. It only **produces** content. Click redirects, open pixels and event logging
5
+ are separate parts; this module just emits the placeholders they will fill in.
6
+
7
+ Import from the `./compose` entry point. It has no Cloudflare-specific imports, so it runs in Node, in a Worker and in tests:
8
+
9
+ ```ts
10
+ import { compose, createTemplate, preflight, personalize, buildPreview } from '@joelincc/mailroom/compose';
11
+ ```
12
+
13
+ ## What goes in, what comes out
14
+
15
+ ```ts
16
+ const template = createTemplate({
17
+ brandName: 'Example Weekly',
18
+ greeting: 'Hi {{name}},', // omitted for readers without a name
19
+ footerLines: ['You get this because you subscribed.'],
20
+ postalAddress: '1 Example Street, Sample City 00000',
21
+ });
22
+
23
+ const issue = compose({
24
+ source, // markdown, optional frontmatter (title, description)
25
+ template,
26
+ issue: '2026-01-05', // becomes utm_campaign
27
+ trackBase: 'https://t.example.com', // omit to skip link rewriting and the open pixel
28
+ siteBase: 'https://example.com', // resolves relative links
29
+ assetBase: 'https://cdn.example.com', // resolves relative image URLs
30
+ });
31
+ ```
32
+
33
+ `compose()` returns `subject`, `preheader`, `html`, `text`, `headers` (the two unsubscribe headers), `links`
34
+ (every rewritten link: index, final URL, original URL, text), `images`, `problems` and `htmlBytes`.
35
+ The HTML is stored once per issue — it is never rendered per recipient until send time.
36
+
37
+ ### Markdown that works
38
+
39
+ Headings, paragraphs (a single newline becomes a line break), bold, italic, inline code, links, bare URLs (trailing
40
+ punctuation is not part of the URL), images, lists (nested, ordered), block quotes, tables (with alignment), fenced code, rules.
41
+ Also understood: `<https://…>` autolinks, `<a href="…">text</a>` (only the `href` and the text are kept — every other
42
+ attribute is dropped and the link goes through the normal checks and tracking), and paired `<b>` / `<strong>` / `<i>` / `<em>`.
43
+ HTML character references (`&nbsp;`, `&amp;`, `&#39;` …) are decoded once and escaped once.
44
+
45
+ HTML comments (`<!-- … -->`) are removed wherever they appear — on their own line, right under a paragraph, inside a list item, inline, or across lines — except inside a code fence. As a last safety net, parsing ends with a check: if any `<!--` is still present in the text outside code, the issue gets a `comment_leaked` error (so a future mismatch between the comment stripper and the parser cannot expose an internal note). Comments inside inline code (`` `<!--` ``, including spans that run over several lines) and inside code fences — including fences indented in lists or block quotes — are not comments and are left alone; the parser and the stripper share one definition of an inline code span. A backslash-escaped backtick does not open code, and a backslash-escaped `<` does not open a comment. A line that holds only `<div>`, `<div lang="…">` or `</div>` (a language wrapper) is dropped and its content converted normally; a `div` with any other attribute (`hidden`, `style`, `class` …) is an error, so text meant to be hidden can never reach readers. Angle-bracket words that only look like tags (`<Research.example>`, `</p/100110>`) are reported with a hint to rewrite them or put them in backticks.
46
+
47
+ Everything else is **not** passed through: an unknown tag or an unknown block syntax (for example `:::note`) is recorded
48
+ as an `error` problem and the pre-send check fails, so nothing half-converted can be sent. So are an unclosed `<!--` comment
49
+ (`unclosed_comment`, wherever it starts) and an unclosed code fence (`unclosed_fence`) — both would silently swallow the rest of the issue; the text after them is kept in the output.
50
+ The exception is content that cannot work in an email — `<iframe>`, `<video>`, `<audio>`, `<embed>`, `<object>`, `<canvas>`
51
+ and a ```` ```mermaid ```` fence: it becomes a "view on the website" link card and an `info` problem.
52
+
53
+ To write a literal `{{` in an article, escape it as `\{\{` (a code span or fence containing `{{` is escaped for you).
54
+ An unescaped `{{…}}` that is not one of the placeholders below fails the check.
55
+
56
+ ### Links, tracking and personalisation
57
+
58
+ | Placeholder | Filled by `personalize()` with |
59
+ |---|---|
60
+ | `{{name}}` | the reader's name; wrap a whole element in `{{#name}}…{{/name}}` to drop it when there is no name |
61
+ | `{{email}}` | the address (use `{{#email}}…{{/email}}` the same way) |
62
+ | `{{unsubscribe_url}}` | the unsubscribe page URL (never rewritten) |
63
+ | `{{unsubscribe_mailto}}` | a `mailto:` unsubscribe link (e.g. `mailto:unsub@example.com?subject=<token>`); only used in the `List-Unsubscribe` header, and only when `compose({ unsubscribeMailto: true })`. Then `personalize()` requires `unsubscribe_mailto` in the recipient data and throws if it is missing or not a plain `mailto:` link |
64
+ | `{{web_url}}` | the web version of the issue (never rewritten) |
65
+ | `{{c:N}}` | the signature for link N (inside `https://t.example.com/c/{{c:N}}`) |
66
+ | `{{o}}` | the signature for the open pixel (`https://t.example.com/o/{{o}}.gif`) |
67
+
68
+ Only these are accepted. Two shapes of `List-Unsubscribe` pass the check: `<{{unsubscribe_url}}>` and
69
+ `<{{unsubscribe_url}}>, <{{unsubscribe_mailto}}>`; `List-Unsubscribe-Post: List-Unsubscribe=One-Click` is always required.
70
+ The interface for whoever builds the unsubscribe flow: put the per-recipient URL in `unsubscribe_url` and, if you accept
71
+ unsubscribe-by-mail, the per-recipient mailto in `unsubscribe_mailto`; both must be free of CR/LF.
72
+
73
+ Only the links written in the article body are tracked and get `utm_*`. The links the template adds (the "view in browser"
74
+ link, footer links, the unsubscribe link) are left as they are: no tracking redirect, no `utm_*`.
75
+ Every body link (except placeholders, `mailto:` and `tel:`) (except placeholders, `mailto:` and `tel:`) is rewritten to the tracking URL and its
76
+ destination gets `utm_source=newsletter`, `utm_medium=email`, `utm_campaign=<issue>` appended to the original query string
77
+ (which is otherwise left byte-for-byte as written; an existing `utm_*` is not overwritten). `javascript:` and
78
+ `data:` links are refused. `personalize()` escapes values for HTML, flattens the name to one line (max 60 characters),
79
+ expands everything in a single pass (a name containing `{{email}}` stays literal), and **throws** if `email`,
80
+ `unsubscribe_url` or `web_url` is missing or not `https`, or if any placeholder is left over.
81
+
82
+ ## Pre-send check
83
+
84
+ ```ts
85
+ const check = await preflight(issue, { template, webUrl }); // schedule only if check.ok && check.linksChecked && check.webChecked
86
+ ```
87
+
88
+ Every `error` blocks scheduling. `warn` and `info` are recorded only. The result also carries `linksChecked` and `webChecked`:
89
+ scheduling a real send requires `ok && linksChecked && webChecked` — offline mode (`checkLinks: false`) and a missing `webUrl`
90
+ are errors (`links_unchecked`, `web_url_unchecked`), not warnings. Links and images are taken from the **final HTML**, so
91
+ the template's footer is checked too, not only the article.
92
+
93
+ | Code | Blocks when |
94
+ |---|---|
95
+ | `html_too_large` | HTML (plus an allowance for signatures and personalisation) is 90,000 bytes or more (`maxHtmlBytes`) |
96
+ | `text_missing` | no plain-text version |
97
+ | `unsubscribe_link_missing`, `unsubscribe_text_missing` | the HTML or the text has no unsubscribe link |
98
+ | `unsubscribe_header_missing`, `unsubscribe_post_header_missing` | `List-Unsubscribe` or `List-Unsubscribe-Post` is missing |
99
+ | `address_missing`, `address_todo`, `address_not_in_html`, `address_not_in_text` | the template has no postal address, it is still a TODO marker, or it did not make it into the mail |
100
+ | `todo_marker` | `[[TODO: …]]` / `【待補:…】` is still present anywhere in the mail, including inside an `href` or `src` |
101
+ | `links_unchecked`, `web_url_unchecked` | offline mode, or no web-version URL was given |
102
+ | `image_alt_missing` | an image has no alt text |
103
+ | `subject_missing`, `subject_too_long`, `subject_invalid` | no subject, more than 80 characters (counted as characters, not bytes), or a control character / newline in it |
104
+ | `preheader_missing` | no preview text |
105
+ | `unknown_placeholder`, `unbalanced_section` | any `{{…}}` that is not on the list above, or an unmatched `{{#name}}` |
106
+ | `link_broken`, `image_broken` | HTTP 404 or 410 (only these two; a HEAD that returns 404/410/405/501 is retried once with GET before judging) |
107
+ | `link_invalid`, `link_private_host` | a malformed URL, or one pointing at localhost / a private or reserved address (IPv4, IPv6, IPv4-mapped IPv6, 100.64/10…) |
108
+ | `link_redirect_private`, `link_redirect_bad` | a redirect leads to a private address, a non-http(s) URL, or loops past 5 hops |
109
+ | `unsupported_html`, `unsupported_syntax`, `unsafe_link`, `link_not_absolute`, `image_not_absolute`, `issue_invalid`, `track_base_invalid` | reported by `compose()` itself |
110
+
111
+ Redirects are followed by hand, one hop at a time, and every hop goes through the private-address check again. The check looks at the host as written; it does not resolve DNS, so run `preflight` from a network that cannot reach your internal services if the content is not written by you.
112
+
113
+ Timeouts, network errors and other status codes (403, 429, 5xx…) are recorded as `warn` (`link_unverified`,
114
+ `link_status`) and do not block. Pass your own `fetch` to test, or `checkLinks: false` to run offline.
115
+
116
+ ## Scanner clicks
117
+
118
+ Security scanners click every link in a message right after it is delivered. `detectScannerClicks(clicks, sentAt)` is the rule
119
+ for spotting that (pure function; recording events belongs to the redirect side): when one message gets clicks on **3 or more
120
+ different links within 60 seconds of being sent**, every click of that message inside the window is returned for marking as
121
+ `detail.suspect = 'scanner'`. Mark, don't delete; exclude the marked ones when counting clicks. Window and threshold are
122
+ adjustable (`windowMs`, `minDistinctLinks`). Opens are kept as they are (mail-client preloading cannot be told apart reliably).
123
+
124
+ ## Preview
125
+
126
+ `buildPreview(issue, check)` returns a map of file name → content: `email.html` and `email.txt` (rendered for a sample
127
+ reader), `check.json`, `links.json`, and `index.html` — one page with the check results, the mail at phone and desktop
128
+ width, and the plain text. With `withoutName: true` it also renders the no-name version. Writing the files is up to the caller.
129
+
130
+ ## Templates
131
+
132
+ A template is configuration, not code: `createTemplate()` takes a brand name, optional logo, greeting, footer lines or a
133
+ trusted `footerHtml` / `footerText` block, labels, a theme and the postal address. The layout is table-based with inline CSS
134
+ (Outlook-safe), 600 px wide, with a dark-mode override. Keep brand templates in your own configuration; the engine ships
135
+ none. The compose module is tested against a made-up issue in `tests/fixtures/`.
@@ -0,0 +1,52 @@
1
+ # Newsletter desk commands
2
+
3
+ `bin/mailroom.mjs` (also `@joelincc/mailroom/cli` as `runCli`) is the one set of commands for a whole newsletter issue. It talks to the
4
+ admin endpoints of the deployed Worker (see [broadcast.md](broadcast.md)); it never touches the database itself.
5
+
6
+ ```sh
7
+ export MAILROOM_URL=https://mailroom.example.com # the Worker's admin address
8
+ export MAILROOM_ADMIN_TOKEN=... # the admin token (never put it in a file in the repo)
9
+ node bin/mailroom.mjs campaign status weekly-12
10
+ node bin/mailroom.mjs --config ./my-defaults.mjs campaign create --issue weekly-12 --post my-post --yes
11
+ ```
12
+
13
+ Requires Node 22.18+. Installed from npm it runs the compiled JavaScript in `dist/` (built by `prepack`; Node does not strip types inside `node_modules`); in a source checkout it loads the TypeScript directly. Your own defaults (list, sender, template, test addresses…) live in a module
14
+ whose default export is a `CliDefaults` (`--config <path>` or `MAILROOM_CONFIG`), or call `runCli(argv, { defaults, env })` from your own script.
15
+ Nothing specific to one deployment is built in.
16
+
17
+ ## Rules every command follows
18
+
19
+ - **Dry run unless `--yes`.** A command that changes anything (including test mail and "mark as previewed") only prints what it *would* do until
20
+ you add `--yes`. Read-only commands (`status`, `audience`, `throttle`, `reconcile`) never need it.
21
+ - **Two outputs.** A short summary for people; with `--json` exactly one JSON object on stdout (`{ ok, command, … }`, or `{ ok: false, error }`).
22
+ - **Errors say what to do next.** Exit code 1 = refused or failed (nothing half-done is hidden), 2 = wrong usage.
23
+ - **Nothing is retried silently.** Failed test mail and unknown outcomes are reported, not resent.
24
+
25
+ ## The flow of one issue
26
+
27
+ | Step | Command | Notes |
28
+ |---|---|---|
29
+ | 1 | `campaign create --issue ID (--source file.md \| --post NAME) [--web-url URL] --yes` | Composes the email, runs the pre-send check (it opens the links), saves a **draft**. Same id again updates the draft. Refused if the same web-version URL, source or body already belongs to another non-cancelled issue |
30
+ | 2 | `campaign preview ID --yes [--out DIR]` | Marks this exact content as previewed. `--out` also writes `email.html`, `email.txt`, `email-no-name.html`, `check.json`. Approval is refused until this has been done for the current content |
31
+ | 3 | `campaign test ID (--to a@x,b@x \| --to-defaults) --yes` | Real postman, real headers, subject prefix; only to the Worker's `TEST_RECIPIENTS` |
32
+ | 4 | `campaign approve ID --note "who, when, where" --yes` | Only after the owner has seen the preview and said yes |
33
+ | 5 | `campaign schedule ID --at "2027-03-01 09:00" --yes` | Local time (default `+08:00`, `--tz`); a past time is refused. The dry run prints who would receive it per wave. `unschedule` takes it back. `start ID --yes` = schedule for now |
34
+ | 6 | `campaign status ID` | State, brake light (green / yellow = a rate is at half its brake / red), counts, rates, why it paused and what to do |
35
+ | 7 | `campaign pause ID --reason "…" --yes` | Emergency stop; mail already handed to the provider still goes out |
36
+ | 8 | `campaign resume ID --note "what was checked" [--release-domain] [--force] --yes` (alias `release`) | Shows which brake fired, the numerator and denominator and the suggestion. `--release-domain` is accepted only when this issue paused *because of* the sender-domain hold (it then releases the hold with the same note and resumes). If the hold exists but is not why this issue paused, release it separately with `hold release` (its dry run prints the threshold and the numbers). A pause whose cause must be fixed first (render error, reconciliation mismatch, a run of permanent failures…) needs `--force` |
37
+ | 9 | `campaign reconcile ID` | frozen = sent + skipped + failed + uncertain + pending, ledger rows, and provider events (sends vs sent; delivered + bounced + not-yet-reported vs sends). A mismatch prints the problem list and every number and exits 1. Run again 72 hours after it finished |
38
+ | — | `campaign retry-failed ID --yes` | Only while the issue is sending or paused; a finished issue is closed |
39
+ | — | `campaign resolve ID --contact N --as sent\|failed --note "…" --yes` | For a recipient left "uncertain" |
40
+ | — | `campaign cancel ID --reason "…" --yes` | Not undoable |
41
+ | — | `campaign hold release --note "…" --yes` | Release the sender-domain hold on its own; paused issues stay paused |
42
+ | — | `campaign audience ID`, `campaign throttle` | Read-only |
43
+
44
+ ## Settings you will want to decide before the first real send
45
+
46
+ All in `BROADCAST_CONFIG` (see [broadcast.md](broadcast.md#all-settings-broadcast_config)):
47
+
48
+ - `domainMinComplaints` (default 1): the sender-domain stop needs this many complaints besides the 0.08% rate. With ~220 mails sent a single
49
+ complaint is 0.45%, so with the default one complaint stops every newsletter on the domain. That errs on the safe side; raise it if you would
50
+ rather have a person look first. `campaign resume … --release-domain` is the one-step way out.
51
+ - `waveGateMinSent` (default 1): with small waves one bounce can cross the 2% wave gate.
52
+ - `startGraceMinutes` (default 360): how late a scheduled issue may start before it goes back to `draft` (and must be approved again).
package/docs/export.md ADDED
@@ -0,0 +1,51 @@
1
+ # Analytics export
2
+
3
+ Hand the delivery events, issues, frozen recipient lists and list members to an outside analytics pipeline as paged NDJSON.
4
+ All endpoints need the admin bearer token (a wrong or missing token gets `404`, so the endpoints do not reveal themselves)
5
+ and have their own rate bucket (`_export`: 60 per minute, 1000 per day), separate from the other admin endpoints.
6
+
7
+ | Endpoint | Cursor | Rows |
8
+ |---|---|---|
9
+ | `GET /v1/export/events?cursor=&limit=` | event `id` | every row of `events` (provider feedback plus open/click/unsubscribe), oldest first |
10
+ | `POST /v1/export/events/ack` `{ "through": id }` | | sets `exported_at` on events with `id <= through` |
11
+ | `GET /v1/export/campaigns?cursor=&limit=` | row number | one row per issue (state, timestamps) |
12
+ | `GET /v1/export/recipients?campaign=&cursor=&limit=` | `contact_id` | the frozen list of one issue: who it was for and their segment **at send time** |
13
+ | `GET /v1/export/members?list=&cursor=&limit=` | `contact_id` | everyone on one list now, with address and segment (for the weekly snapshot) |
14
+
15
+ `limit` defaults to 2000, at most 5000. Each response is one JSON object per line. Paging state is in response headers:
16
+ `x-export-count`, `x-export-has-more` (`1`/`0`) and `x-export-next-cursor` (pass it back as `cursor`; empty when done).
17
+
18
+ ## Guarantees
19
+
20
+ - **Reads change nothing.** Pulling the same cursor again returns the same rows (plus anything newer at the end). A consumer that
21
+ fails half way restarts from the last cursor it durably stored: nothing is skipped and nothing is stored twice as long as the
22
+ consumer de-duplicates on `id` / `provider_event_id`.
23
+ - **`ack` is a marker, not a position.** The consumer keeps its own cursor; it calls `ack` only after the pulled rows are safely
24
+ stored. `ack` can be repeated, never marks beyond the current highest id, and can be used later to decide which events are old
25
+ enough to purge.
26
+ - **Order.** D1 commits writes one at a time, so when `id` N+1 is visible N is too; paging by `id` never skips a row.
27
+ - **No addresses in events, campaigns or recipients.** Events carry `contact_id`; join to the members export for the address.
28
+ Only the members export contains addresses, so keep its output as private as the list itself.
29
+
30
+ ## Event shape
31
+
32
+ ```json
33
+ { "id": 812, "provider": "self", "provider_event_id": "…", "message_id": 77, "provider_message_id": "…",
34
+ "campaign_id": "weekly-163", "contact_id": 12, "type": "click", "subtype": null,
35
+ "at": "2027-03-01T01:07:00.000Z", "detail": { "url": "https://…", "linkIndex": 1, "suspect": "scanner" }, "exported_at": null }
36
+ ```
37
+
38
+ `detail` is the stored JSON (or `null`). Anything shaped like an email address is replaced with `[email]` when the event is recorded and again on export (`@channel`-style handles are not addresses and stay). Contract the analytics side relies on:
39
+
40
+ - `detail.suspect = "scanner"` marks a click that a security scanner made (see `docs/composing.md`). Keep these rows, do not count them.
41
+ - **`detail.prefetch = true` must be written explicitly by the tracking service** for opens that mail-privacy prefetching made. The user-agent string (`detail.ua`) is only a fallback hint and is not reliable; check a real message end to end once the tracker exists.
42
+ - `detail.linkIndex` / `detail.url` identify the link of a click.
43
+ - Unsubscribes are recorded by the engine itself when someone goes from subscribed to unsubscribed through the unsubscribe page, the one-click endpoint or an unsubscribe mail: `type = "unsubscribe"`, `detail = { via: "link" | "one_click" | "mailto", list, reason? }`. Repeating the request records nothing more. Unsubscribes made through the list API or a member-centre sync record no event, so a per-issue unsubscribe count only counts people who left from a mail of that issue.
44
+
45
+ Known limits of the address scrub: version-like strings such as `pkg@1.2.3` are masked too, and addresses written percent-encoded (`%40`) are not. Revisit when links start carrying recipient parameters.
46
+
47
+ ## Test data
48
+
49
+ `tests/export-fixture.ts` builds two complete issues with the fake postman (bounces, a complaint, opens, prefetch opens, clicks,
50
+ scanner clicks, unsubscribes) using only `@example.com` addresses. Run
51
+ `node --experimental-strip-types tests/export-fixture.ts <dir>` to write the same data as NDJSON files for an outside pipeline's tests.