@joelincc/mailroom 0.1.0 → 0.3.1
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.
- package/README.md +54 -8
- package/SECURITY.md +1 -1
- package/bin/mailroom.mjs +26 -0
- package/dist/broadcast/config.js +79 -0
- package/dist/broadcast/explain.js +50 -0
- package/dist/cli/args.js +29 -0
- package/dist/cli/errors.js +37 -0
- package/dist/cli/main.js +533 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +275 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +1197 -0
- package/dist/compose/personalize.js +123 -0
- package/dist/compose/preflight.js +251 -0
- package/dist/compose/preview.js +41 -0
- package/dist/compose/render.js +141 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +156 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +52 -0
- package/docs/lists.md +68 -0
- package/docs/security-model.md +6 -4
- package/docs/ses.md +116 -0
- package/docs/tracking.md +102 -0
- package/docs/unsubscribe.md +124 -0
- package/docs/welcome.md +72 -0
- package/migrations/0004_last_error.sql +2 -0
- package/migrations/0005_lists.sql +41 -0
- package/migrations/0006_broadcast.sql +154 -0
- package/migrations/0007_unsubscribe.sql +12 -0
- package/migrations/0008_tracking.sql +5 -0
- package/migrations/0009_welcome.sql +17 -0
- package/package.json +21 -3
- package/src/alert.ts +123 -0
- package/src/aws-sigv4.ts +100 -0
- package/src/broadcast/audience.ts +96 -0
- package/src/broadcast/campaigns.ts +352 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +779 -0
- package/src/broadcast/events.ts +110 -0
- package/src/broadcast/explain.ts +73 -0
- package/src/broadcast/freeze.ts +93 -0
- package/src/broadcast/index.ts +21 -0
- package/src/broadcast/postman.ts +229 -0
- package/src/broadcast/reconcile.ts +120 -0
- package/src/broadcast/routes.ts +181 -0
- package/src/broadcast/ses.ts +181 -0
- package/src/broadcast/stats.ts +59 -0
- package/src/broadcast/status.ts +60 -0
- package/src/broadcast/test-send.ts +88 -0
- package/src/broadcast/warmup.ts +150 -0
- package/src/broadcast/worker.ts +218 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +39 -0
- package/src/cli/main.ts +515 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +297 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +1173 -0
- package/src/compose/personalize.ts +130 -0
- package/src/compose/preflight.ts +250 -0
- package/src/compose/preview.ts +58 -0
- package/src/compose/render.ts +158 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +45 -2
- package/src/export.ts +184 -0
- package/src/feedback.ts +128 -0
- package/src/http.ts +17 -0
- package/src/index.ts +146 -32
- package/src/list-routes.ts +55 -0
- package/src/lists.ts +381 -0
- package/src/ses-events.ts +426 -0
- package/src/track.ts +409 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/src/welcome.ts +257 -0
- package/wrangler.example.jsonc +16 -2
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// 暖機梯子:每一步寫「這期寄給哪幾群(分波)、最多幾人、過關條件」。
|
|
2
|
+
// 目前這一步=已放行的最高一步(第一步不用放行)。上一期過關才放行下一步;不過關=下一期維持同一步;
|
|
3
|
+
// 連續 gateMaxFails 期不過關=這條梯子鎖住,開寄時直接擋下,要明確解鎖(寫原因)才繼續。
|
|
4
|
+
// 過關比的是「同一批人」在換郵差前的開信率基準(由分析端算好傳進來),不比全名單。
|
|
5
|
+
|
|
6
|
+
import type { Db } from '../core.ts';
|
|
7
|
+
import { checkWaves, CAMPAIGN_ID, getCampaign } from './campaigns.ts';
|
|
8
|
+
import type { BroadcastConfig } from './config.ts';
|
|
9
|
+
import { campaignRates } from './stats.ts';
|
|
10
|
+
|
|
11
|
+
export interface WarmupStepRow {
|
|
12
|
+
plan_id: string; step: number; segments: string; max_count: number | null; gate: string | null;
|
|
13
|
+
released_at: string | null; blocked_reason: string | null; fails: number; last_eval: string | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface GateOverrides { bounceRate?: number; complaintRate?: number; openDrop?: number; waitHours?: number }
|
|
17
|
+
|
|
18
|
+
export interface StepInput { plan: string; step: number; waves: string[][]; maxCount?: number | null; gate?: GateOverrides }
|
|
19
|
+
|
|
20
|
+
const nowIso = (now?: () => Date) => (now ?? (() => new Date()))().toISOString();
|
|
21
|
+
|
|
22
|
+
export async function upsertWarmupStep(db: Db, input: StepInput): Promise<{ ok: true } | { ok: false; reason: string }> {
|
|
23
|
+
if (!input || typeof input.plan !== 'string' || !CAMPAIGN_ID.test(input.plan)) return { ok: false, reason: 'bad_plan' };
|
|
24
|
+
if (!Number.isInteger(input.step) || input.step < 1 || input.step > 100) return { ok: false, reason: 'bad_step' };
|
|
25
|
+
const waves = checkWaves(input.waves);
|
|
26
|
+
if (!waves) return { ok: false, reason: 'bad_waves' };
|
|
27
|
+
if (input.maxCount !== undefined && input.maxCount !== null && !(Number.isInteger(input.maxCount) && input.maxCount > 0)) return { ok: false, reason: 'bad_max_count' };
|
|
28
|
+
let gate: string | null = null;
|
|
29
|
+
if (input.gate !== undefined) {
|
|
30
|
+
const g: GateOverrides = {};
|
|
31
|
+
for (const k of ['bounceRate', 'complaintRate', 'openDrop'] as const) {
|
|
32
|
+
const v = input.gate[k];
|
|
33
|
+
if (v === undefined) continue;
|
|
34
|
+
if (typeof v !== 'number' || !(v >= 0 && v <= 1)) return { ok: false, reason: 'bad_gate' };
|
|
35
|
+
g[k] = v;
|
|
36
|
+
}
|
|
37
|
+
if (input.gate.waitHours !== undefined) {
|
|
38
|
+
if (typeof input.gate.waitHours !== 'number' || !(input.gate.waitHours > 0)) return { ok: false, reason: 'bad_gate' };
|
|
39
|
+
g.waitHours = input.gate.waitHours;
|
|
40
|
+
}
|
|
41
|
+
gate = JSON.stringify(g);
|
|
42
|
+
}
|
|
43
|
+
// 已放行/已鎖住的狀態不因改設定而清掉。
|
|
44
|
+
await db
|
|
45
|
+
.prepare(
|
|
46
|
+
`INSERT INTO warmup_steps (plan_id, step, segments, max_count, gate) VALUES (?, ?, ?, ?, ?)
|
|
47
|
+
ON CONFLICT (plan_id, step) DO UPDATE SET segments = excluded.segments, max_count = excluded.max_count, gate = excluded.gate`,
|
|
48
|
+
)
|
|
49
|
+
.bind(input.plan, input.step, JSON.stringify(waves), input.maxCount ?? null, gate)
|
|
50
|
+
.run();
|
|
51
|
+
return { ok: true };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function planSteps(db: Db, plan: string): Promise<WarmupStepRow[]> {
|
|
55
|
+
return (await db.prepare('SELECT * FROM warmup_steps WHERE plan_id = ? ORDER BY step').bind(plan).all<WarmupStepRow>()).results;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 目前這一步:已放行的最高一步;都沒放行就是最低那一步。 */
|
|
59
|
+
export async function currentStep(db: Db, plan: string): Promise<WarmupStepRow | null> {
|
|
60
|
+
const steps = await planSteps(db, plan);
|
|
61
|
+
if (steps.length === 0) return null;
|
|
62
|
+
const released = steps.filter((s) => s.released_at !== null);
|
|
63
|
+
return released.length ? released[released.length - 1] : steps[0];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 這條梯子有沒有被鎖住(任何一步有 blocked_reason)。 */
|
|
67
|
+
export async function planBlocked(db: Db, plan: string): Promise<string | null> {
|
|
68
|
+
const row = await db.prepare('SELECT blocked_reason FROM warmup_steps WHERE plan_id = ? AND blocked_reason IS NOT NULL LIMIT 1').bind(plan).first<{ blocked_reason: string }>();
|
|
69
|
+
return row?.blocked_reason ?? null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type GateResult =
|
|
73
|
+
| { result: 'pass'; step: number; advancedTo: number | null; rates: Record<string, number> }
|
|
74
|
+
| { result: 'fail'; step: number; reasons: string[]; fails: number; blocked: boolean; rates: Record<string, number> }
|
|
75
|
+
| { result: 'not_ready'; reasons: string[] }
|
|
76
|
+
| { result: 'already_evaluated'; last: unknown };
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 評一期信能不能讓梯子往上一步(上一期滿 waitHours 小時後評)。
|
|
80
|
+
* baselineOpenRate=這期收件的那幾群,在換郵差前 4 期的平均開信率(0~1,由分析端提供);沒給=不評(不放量)。
|
|
81
|
+
* 同一期只算一次(重複呼叫回 already_evaluated,不會重複累計不過關次數)。
|
|
82
|
+
*/
|
|
83
|
+
export async function evaluateWarmup(
|
|
84
|
+
db: Db,
|
|
85
|
+
plan: string,
|
|
86
|
+
campaignId: string,
|
|
87
|
+
baselineOpenRate: number | null | undefined,
|
|
88
|
+
cfg: BroadcastConfig,
|
|
89
|
+
now?: () => Date,
|
|
90
|
+
): Promise<GateResult> {
|
|
91
|
+
const step = await currentStep(db, plan);
|
|
92
|
+
if (!step) return { result: 'not_ready', reasons: ['unknown_plan'] };
|
|
93
|
+
if (step.last_eval) {
|
|
94
|
+
try {
|
|
95
|
+
const last = JSON.parse(step.last_eval) as { campaign?: string };
|
|
96
|
+
if (last.campaign === campaignId) return { result: 'already_evaluated', last };
|
|
97
|
+
} catch {
|
|
98
|
+
/* 壞掉的紀錄當沒評過 */
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const c = await getCampaign(db, campaignId);
|
|
102
|
+
if (!c) return { result: 'not_ready', reasons: ['unknown_campaign'] };
|
|
103
|
+
let resolved: { plan?: string; step?: number } = {};
|
|
104
|
+
try {
|
|
105
|
+
resolved = JSON.parse(c.audience_resolved ?? '{}');
|
|
106
|
+
} catch {
|
|
107
|
+
/* 下面擋 */
|
|
108
|
+
}
|
|
109
|
+
if (resolved.plan !== plan || resolved.step !== step.step) return { result: 'not_ready', reasons: ['campaign_not_on_current_step'] };
|
|
110
|
+
if (c.status !== 'done' || !c.finished_at) return { result: 'not_ready', reasons: ['campaign_not_done'] };
|
|
111
|
+
const gate: GateOverrides = step.gate ? JSON.parse(step.gate) : {};
|
|
112
|
+
const waitHours = gate.waitHours ?? cfg.gateWaitHours;
|
|
113
|
+
const t = (now ?? (() => new Date()))();
|
|
114
|
+
if (t.getTime() - Date.parse(c.finished_at) < waitHours * 3_600_000) return { result: 'not_ready', reasons: [`wait_${waitHours}h`] };
|
|
115
|
+
if (typeof baselineOpenRate !== 'number' || !(baselineOpenRate >= 0 && baselineOpenRate <= 1)) return { result: 'not_ready', reasons: ['baseline_missing'] };
|
|
116
|
+
|
|
117
|
+
const r = await campaignRates(db, campaignId);
|
|
118
|
+
const rates = { sent: r.sent, hardBounceRate: r.hardBounceRate, complaintRate: r.complaintRate, openRate: r.openRate, baselineOpenRate };
|
|
119
|
+
const reasons: string[] = [];
|
|
120
|
+
if (r.sent === 0) reasons.push('nothing_sent');
|
|
121
|
+
if (r.hardBounceRate > (gate.bounceRate ?? cfg.gateBounceRate)) reasons.push('bounce_rate');
|
|
122
|
+
if (r.complaintRate > (gate.complaintRate ?? cfg.gateComplaintRate)) reasons.push('complaint_rate');
|
|
123
|
+
if (r.openRate < baselineOpenRate - (gate.openDrop ?? cfg.gateOpenDrop)) reasons.push('open_rate_below_baseline');
|
|
124
|
+
// 對帳對不上也不放下一步。
|
|
125
|
+
const counts = c.counts ? (JSON.parse(c.counts) as { reconcileOk?: boolean }) : {};
|
|
126
|
+
if (counts.reconcileOk !== true) reasons.push('reconcile_not_ok');
|
|
127
|
+
|
|
128
|
+
const at = nowIso(now);
|
|
129
|
+
if (reasons.length === 0) {
|
|
130
|
+
const steps = await planSteps(db, plan);
|
|
131
|
+
const next = steps.find((s) => s.step > step.step) ?? null;
|
|
132
|
+
await db.prepare('UPDATE warmup_steps SET fails = 0, last_eval = ? WHERE plan_id = ? AND step = ?').bind(JSON.stringify({ campaign: campaignId, result: 'pass', at, rates }), plan, step.step).run();
|
|
133
|
+
if (next) await db.prepare('UPDATE warmup_steps SET released_at = ? WHERE plan_id = ? AND step = ? AND released_at IS NULL').bind(at, plan, next.step).run();
|
|
134
|
+
return { result: 'pass', step: step.step, advancedTo: next?.step ?? null, rates };
|
|
135
|
+
}
|
|
136
|
+
const fails = step.fails + 1;
|
|
137
|
+
const blocked = fails >= cfg.gateMaxFails;
|
|
138
|
+
await db
|
|
139
|
+
.prepare('UPDATE warmup_steps SET fails = ?, last_eval = ?, blocked_reason = CASE WHEN ? THEN COALESCE(blocked_reason, ?) ELSE blocked_reason END WHERE plan_id = ? AND step = ?')
|
|
140
|
+
.bind(fails, JSON.stringify({ campaign: campaignId, result: 'fail', at, reasons, rates }), blocked ? 1 : 0, `failed ${fails} gates in a row: ${reasons.join(',')}`, plan, step.step)
|
|
141
|
+
.run();
|
|
142
|
+
return { result: 'fail', step: step.step, reasons, fails, blocked, rates };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 解鎖:要寫查過什麼。清掉鎖與連續不過關次數,梯子停在原本那一步。 */
|
|
146
|
+
export async function unblockWarmup(db: Db, plan: string, note: string): Promise<{ ok: true; cleared: number } | { ok: false; reason: string }> {
|
|
147
|
+
if (typeof note !== 'string' || !note.trim()) return { ok: false, reason: 'note_required' };
|
|
148
|
+
const r = await db.prepare('UPDATE warmup_steps SET blocked_reason = NULL, fails = 0, last_eval = json_set(COALESCE(last_eval, \'{}\'), \'$.unblockNote\', ?) WHERE plan_id = ? AND blocked_reason IS NOT NULL').bind(note.trim().slice(0, 300), plan).run();
|
|
149
|
+
return { ok: true, cleared: r.meta.changes ?? 0 };
|
|
150
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// Worker 端的接線:從環境變數組出群發要的東西(郵差、Queue、設定、個人化)。index.ts 只呼叫這裡的三個函式。
|
|
2
|
+
|
|
3
|
+
import { personalize } from '../compose/personalize.ts';
|
|
4
|
+
import { unsubscribeLinks, unsubSecrets } from '../unsub.ts';
|
|
5
|
+
import type { ListDb } from '../lists.ts';
|
|
6
|
+
import type { CampaignRow } from './campaigns.ts';
|
|
7
|
+
import { consumeBatch, tick, type BroadcastDeps, type BroadcastMessage, type QueueMessageLike, type RecipientRow, type RenderResult } from './dispatch.ts';
|
|
8
|
+
import type { IngestOptions } from './events.ts';
|
|
9
|
+
import { FakePostman, type FakeRule, type Postman } from './postman.ts';
|
|
10
|
+
import { parseAllowed, type TestSendDeps } from './test-send.ts';
|
|
11
|
+
import { SesPostman } from './ses.ts';
|
|
12
|
+
import { trackHost, trackSecrets, trackSigner } from '../track.ts';
|
|
13
|
+
|
|
14
|
+
export interface BroadcastEnv {
|
|
15
|
+
DB: D1Database;
|
|
16
|
+
/** 電子報的寄件網域(例 mail.example.com)。沒設=群發整個關閉。 */
|
|
17
|
+
MARKETING_DOMAIN?: string;
|
|
18
|
+
/** 群發 Queue 的 producer 綁定。 */
|
|
19
|
+
BROADCAST?: Queue<BroadcastMessage>;
|
|
20
|
+
/** 群發 Queue 的名字(consumer 收到的 batch.queue),預設 mailroom-broadcast。 */
|
|
21
|
+
BROADCAST_QUEUE_NAME?: string;
|
|
22
|
+
/** 群發設定(JSON,只寫想改的欄位,見 docs/broadcast.md)。 */
|
|
23
|
+
BROADCAST_CONFIG?: string | Record<string, unknown>;
|
|
24
|
+
/** 自己的每日上限(覆寫 BROADCAST_CONFIG 的 maxPerDay)。 */
|
|
25
|
+
NEWSLETTER_MAX_PER_DAY?: string | number;
|
|
26
|
+
/** 電子報的郵差:"ses"(Amazon SES)或 "fake"(開發與演習用,不真的寄)。沒設=群發關閉。 */
|
|
27
|
+
NEWSLETTER_POSTMAN?: string;
|
|
28
|
+
/** SES 地區(例 us-east-1)。郵差與事件入口共用。 */
|
|
29
|
+
SES_REGION?: string;
|
|
30
|
+
/** SES 寄信鑰匙(Secret):IAM 只給 ses:SendEmail 與 ses:GetAccount。 */
|
|
31
|
+
SES_ACCESS_KEY_ID?: string;
|
|
32
|
+
SES_SECRET_ACCESS_KEY?: string;
|
|
33
|
+
/** SES 設定組(事件發布到 SNS)。 */
|
|
34
|
+
SES_CONFIGURATION_SET?: string;
|
|
35
|
+
/** 假郵差設定(JSON):{ "rules": [{ "match": "bounce", "outcome": "hard_bounce" }], "limits": { "perSecond": 1, "perDay": 200 } }。 */
|
|
36
|
+
FAKE_POSTMAN?: string | Record<string, unknown>;
|
|
37
|
+
/** 退訂券(與退訂模組共用):每封信的退訂連結與一鍵退訂標頭靠它們產生;沒設=每期都會因 render_error 暫停。 */
|
|
38
|
+
UNSUB_TOKEN_SECRET?: string;
|
|
39
|
+
UNSUB_TOKEN_SECRET_PREVIOUS?: string;
|
|
40
|
+
UNSUB_BASE_URL?: string;
|
|
41
|
+
UNSUB_MAILTO?: string;
|
|
42
|
+
/** 允許收測試信的內部信箱(JSON 陣列或逗號分隔)。沒設=測試信功能關閉。 */
|
|
43
|
+
TEST_RECIPIENTS?: string | string[];
|
|
44
|
+
/** 追蹤網址的根(https,例 https://t.example.com)。要同時有 TRACK_TOKEN_SECRET 才開追蹤端點。 */
|
|
45
|
+
TRACK_BASE_URL?: string;
|
|
46
|
+
/** 追蹤券簽章鑰匙(Secret,至少 16 字元)。內容用到追蹤佔位卻沒設=那期因 render_error 暫停(不寄出點了會壞的信)。 */
|
|
47
|
+
TRACK_TOKEN_SECRET?: string;
|
|
48
|
+
/** 換鑰匙過渡期:舊鑰匙(逗號分隔),只驗證不簽新券。 */
|
|
49
|
+
TRACK_TOKEN_SECRET_PREVIOUS?: string;
|
|
50
|
+
/** 追蹤設定(JSON,只寫想改的欄位,見 docs/tracking.md)。 */
|
|
51
|
+
TRACK_CONFIG?: string | Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const DEFAULT_BROADCAST_QUEUE = 'mailroom-broadcast';
|
|
55
|
+
|
|
56
|
+
function jsonObject(v: unknown): Record<string, unknown> {
|
|
57
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) return v as Record<string, unknown>;
|
|
58
|
+
if (typeof v !== 'string' || !v.trim()) return {};
|
|
59
|
+
try {
|
|
60
|
+
const p = JSON.parse(v);
|
|
61
|
+
return p && typeof p === 'object' && !Array.isArray(p) ? p : {};
|
|
62
|
+
} catch {
|
|
63
|
+
console.error('bad broadcast json var');
|
|
64
|
+
return {};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function postmanFor(env: BroadcastEnv): Postman | null {
|
|
69
|
+
if (env.NEWSLETTER_POSTMAN === 'fake') {
|
|
70
|
+
const cfg = jsonObject(env.FAKE_POSTMAN);
|
|
71
|
+
const rules = Array.isArray(cfg.rules) ? (cfg.rules as FakeRule[]).filter((r) => r && typeof r.match === 'string' && typeof r.outcome === 'string') : [];
|
|
72
|
+
return new FakePostman({
|
|
73
|
+
rules,
|
|
74
|
+
limits: jsonObject(cfg.limits) as never,
|
|
75
|
+
// 假事件丟回同一個 Queue,延遲幾秒回來(模擬郵差的事後回報)。
|
|
76
|
+
emit: async (event, delayMs) => {
|
|
77
|
+
await env.BROADCAST?.send({ kind: 'event', event }, { delaySeconds: Math.max(1, Math.min(43_200, Math.ceil(delayMs / 1000))) });
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (env.NEWSLETTER_POSTMAN === 'ses') {
|
|
82
|
+
if (!env.SES_REGION || !env.SES_ACCESS_KEY_ID || !env.SES_SECRET_ACCESS_KEY || !env.SES_CONFIGURATION_SET) {
|
|
83
|
+
console.error('ses postman needs SES_REGION, SES_ACCESS_KEY_ID, SES_SECRET_ACCESS_KEY, SES_CONFIGURATION_SET; broadcasting disabled');
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
return new SesPostman({
|
|
88
|
+
region: env.SES_REGION,
|
|
89
|
+
credentials: { accessKeyId: env.SES_ACCESS_KEY_ID, secretAccessKey: env.SES_SECRET_ACCESS_KEY },
|
|
90
|
+
configurationSet: env.SES_CONFIGURATION_SET,
|
|
91
|
+
});
|
|
92
|
+
} catch (e) {
|
|
93
|
+
console.error('ses postman config error, broadcasting disabled', e instanceof Error ? e.message : 'unknown');
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (env.NEWSLETTER_POSTMAN) console.error('unknown NEWSLETTER_POSTMAN, broadcasting disabled');
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
type Links = { unsubscribe_url: string; unsubscribe_mailto?: string | null };
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 預設的個人化:compose 的 personalize({{name}} {{email}} {{unsubscribe_url}} {{unsubscribe_mailto}} {{web_url}},標頭一起填)。
|
|
105
|
+
* 退訂連結由 links 提供;拿不到=丟例外(這期會被暫停,不寄出沒有退訂連結的信)。
|
|
106
|
+
*/
|
|
107
|
+
export type TrackFor = (c: CampaignRow, r: RecipientRow, contents: string[]) => Promise<NonNullable<Parameters<typeof personalize>[2]>['track']>;
|
|
108
|
+
|
|
109
|
+
export function personalizeRender(links?: (c: CampaignRow, r: RecipientRow) => Links | null | Promise<Links | null>, track?: Parameters<typeof personalize>[2] | TrackFor) {
|
|
110
|
+
return async (c: CampaignRow, r: RecipientRow & { name: string | null }): Promise<RenderResult> => {
|
|
111
|
+
const l = await links?.(c, r);
|
|
112
|
+
if (!l) throw new Error('unsubscribe links not configured');
|
|
113
|
+
if (!c.web_url) throw new Error('campaign has no web_url');
|
|
114
|
+
let headers: Record<string, string> = {};
|
|
115
|
+
try {
|
|
116
|
+
headers = c.headers ? (JSON.parse(c.headers) as Record<string, string>) : {};
|
|
117
|
+
} catch {
|
|
118
|
+
throw new Error('bad campaign headers');
|
|
119
|
+
}
|
|
120
|
+
const opts = typeof track === 'function' ? { track: await track(c, r, [c.html, c.text, ...Object.values(headers)]) } : track;
|
|
121
|
+
return personalize({ html: c.html, text: c.text, headers }, { name: r.name, email: r.email, web_url: c.web_url, ...l }, opts);
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 退訂券產生的連結(每位收件人一張券,綁名單、聯絡人、期別)。 */
|
|
126
|
+
export function unsubLinksFromEnv(env: BroadcastEnv) {
|
|
127
|
+
return async (c: CampaignRow, r: RecipientRow): Promise<Links | null> => {
|
|
128
|
+
const secrets = unsubSecrets(env.UNSUB_TOKEN_SECRET, env.UNSUB_TOKEN_SECRET_PREVIOUS);
|
|
129
|
+
if (!secrets.length || !env.UNSUB_BASE_URL) return null;
|
|
130
|
+
const l = await unsubscribeLinks(secrets, { baseUrl: env.UNSUB_BASE_URL, mailtoAddress: env.UNSUB_MAILTO }, { list: c.list_id, contactId: r.contact_id, campaign: c.id });
|
|
131
|
+
return { unsubscribe_url: l.url, unsubscribe_mailto: l.mailto };
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 追蹤券(每位收件人、每個連結一張)。沒設鑰匙=undefined:內容沒用到追蹤佔位就照常寄;用到了 personalize 會丟例外、這期暫停。 */
|
|
136
|
+
export function trackFromEnv(env: BroadcastEnv): TrackFor | undefined {
|
|
137
|
+
const secrets = trackSecrets(env.TRACK_TOKEN_SECRET, env.TRACK_TOKEN_SECRET_PREVIOUS);
|
|
138
|
+
const host = trackHost(env.TRACK_BASE_URL);
|
|
139
|
+
// 鑰匙、追蹤網址缺一=追蹤端點不存在:不簽(內容有追蹤佔位就會 render_error 暫停,不寄出點了 404 的信)。
|
|
140
|
+
if (!secrets.length || !host) return undefined;
|
|
141
|
+
const origin = `https://${host}`;
|
|
142
|
+
return async (c, r, contents) => {
|
|
143
|
+
// 內容裡的追蹤佔位必須掛在這個部署的追蹤網址下(compose 的 trackBase 跟 TRACK_BASE_URL 不一致=連結會壞)。
|
|
144
|
+
for (const s of contents) {
|
|
145
|
+
for (const m of s.matchAll(/\{\{\s*(c:\d+|o)\s*\}\}/g)) {
|
|
146
|
+
const want = m[1] === 'o' ? `${origin}/o/` : `${origin}/c/`;
|
|
147
|
+
if (s.slice(Math.max(0, m.index - want.length), m.index).toLowerCase() !== want) throw new Error('tracking placeholder is not under TRACK_BASE_URL');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
let count: number | null = 0;
|
|
151
|
+
if (c.links) {
|
|
152
|
+
try {
|
|
153
|
+
const parsed = JSON.parse(c.links);
|
|
154
|
+
count = Array.isArray(parsed) ? parsed.length : 0;
|
|
155
|
+
} catch {
|
|
156
|
+
count = 0;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return trackSigner(secrets[0], c.id, r.contact_id, contents, count);
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export interface BroadcastWiring {
|
|
164
|
+
render?: BroadcastDeps['render'];
|
|
165
|
+
feedback?: IngestOptions['feedback'];
|
|
166
|
+
alert?: BroadcastDeps['alert'];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function broadcastDeps(env: BroadcastEnv, wiring: BroadcastWiring = {}): BroadcastDeps | null {
|
|
170
|
+
if (!env.MARKETING_DOMAIN || !env.BROADCAST) return null;
|
|
171
|
+
const postman = postmanFor(env);
|
|
172
|
+
if (!postman) return null;
|
|
173
|
+
const config = jsonObject(env.BROADCAST_CONFIG);
|
|
174
|
+
if (env.NEWSLETTER_MAX_PER_DAY !== undefined && env.NEWSLETTER_MAX_PER_DAY !== '') config.maxPerDay = env.NEWSLETTER_MAX_PER_DAY;
|
|
175
|
+
return {
|
|
176
|
+
db: env.DB as unknown as ListDb,
|
|
177
|
+
postman,
|
|
178
|
+
domain: env.MARKETING_DOMAIN.toLowerCase(),
|
|
179
|
+
queue: env.BROADCAST as unknown as BroadcastDeps['queue'],
|
|
180
|
+
config,
|
|
181
|
+
render: wiring.render ?? personalizeRender(unsubLinksFromEnv(env), trackFromEnv(env)),
|
|
182
|
+
feedback: wiring.feedback,
|
|
183
|
+
unsub: { secrets: unsubSecrets(env.UNSUB_TOKEN_SECRET, env.UNSUB_TOKEN_SECRET_PREVIOUS), baseUrl: env.UNSUB_BASE_URL, mailto: env.UNSUB_MAILTO },
|
|
184
|
+
alert: wiring.alert ?? ((a) => (a.level === 'info' ? console.log : console.warn)('broadcast', a.level, a.code, a.campaign ?? '-', a.message)),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 管理入口的測試信設定(郵差、個人化、白名單)。群發沒開=undefined。 */
|
|
189
|
+
export function testSendDeps(env: BroadcastEnv, wiring: BroadcastWiring = {}): Omit<TestSendDeps, 'domain' | 'now'> | undefined {
|
|
190
|
+
const d = broadcastDeps(env, wiring);
|
|
191
|
+
return d ? { postman: d.postman, render: d.render, allowed: parseAllowed(env.TEST_RECIPIENTS) } : undefined;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 排程每分鐘呼叫。沒設定群發就什麼都不做。 */
|
|
195
|
+
export async function broadcastTick(env: BroadcastEnv, wiring?: BroadcastWiring): Promise<void> {
|
|
196
|
+
const deps = broadcastDeps(env, wiring);
|
|
197
|
+
if (!deps) return;
|
|
198
|
+
const r = await tick(deps);
|
|
199
|
+
const released = Object.values(r.released).reduce((a, b) => a + b, 0);
|
|
200
|
+
if (released || r.started.length || r.paused.length || r.finished.length) {
|
|
201
|
+
console.log('broadcast tick', JSON.stringify({ started: r.started, released, paused: r.paused, finished: r.finished }));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 這一批是不是群發 Queue 的。 */
|
|
206
|
+
export function isBroadcastBatch(env: BroadcastEnv, queueName: string): boolean {
|
|
207
|
+
return queueName === (env.BROADCAST_QUEUE_NAME || DEFAULT_BROADCAST_QUEUE);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export async function broadcastQueue(env: BroadcastEnv, messages: readonly QueueMessageLike[], wiring?: BroadcastWiring): Promise<void> {
|
|
211
|
+
const deps = broadcastDeps(env, wiring);
|
|
212
|
+
if (!deps) {
|
|
213
|
+
// 群發關掉了:訊息留著(重送),不要默默丟掉。
|
|
214
|
+
for (const m of messages) m.retry({ delaySeconds: 300 });
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
await consumeBatch(deps, messages);
|
|
218
|
+
}
|
package/src/cf-events.ts
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// 跟 Resend 的 webhook 進同一份拒收名單、同一張帳本(messages.provider_id=Cloudflare 回的 messageId)。
|
|
4
4
|
// 文件:https://developers.cloudflare.com/email-service/reference/event-subscriptions/(2026-11-04 查)
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { type Db } from './core.ts';
|
|
7
|
+
import { applyFeedback } from './feedback.ts';
|
|
7
8
|
|
|
8
9
|
interface CfEmailEvent {
|
|
9
10
|
type?: string;
|
|
@@ -63,12 +64,12 @@ async function applyEvent(db: Db, ev: CfEmailEvent, name: string, now: Date): Pr
|
|
|
63
64
|
// 只有硬退信(信箱不存在、網域收不到)才進拒收名單;暫時性重試用完的 soft 不擋。
|
|
64
65
|
if (p.bounce?.type !== 'hard' || !email) return `bounce_${String(p.bounce?.type ?? 'unknown').toLowerCase()}`;
|
|
65
66
|
const detail = [p.bounce.classification, p.bounce.reason, p.delivery?.smtpStatusCode].filter(Boolean).join(': ');
|
|
66
|
-
await
|
|
67
|
+
await applyFeedback(db, { type: 'bounce', kind: 'permanent', email, source: 'cloudflare-event', detail: detail || null }, { now: () => now });
|
|
67
68
|
return 'hard_bounce:1';
|
|
68
69
|
}
|
|
69
70
|
if (name === 'complained') {
|
|
70
71
|
if (!email) return 'complaint:0';
|
|
71
|
-
await
|
|
72
|
+
await applyFeedback(db, { type: 'complaint', email, source: 'cloudflare-event', detail: p.complaint?.type ?? null }, { now: () => now });
|
|
72
73
|
return 'complaint:1';
|
|
73
74
|
}
|
|
74
75
|
return last ? `event:${last}` : 'ignored';
|
package/src/cli/args.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// 指令列參數:--key value、--key=value、--flag。不收未知旗標(打錯字不能被默默吞掉)。
|
|
2
|
+
|
|
3
|
+
export interface ParsedArgs { positional: string[]; flags: Record<string, string | true> }
|
|
4
|
+
|
|
5
|
+
export function parseArgs(argv: readonly string[], spec: { values: readonly string[]; booleans: readonly string[] }): ParsedArgs | { error: string } {
|
|
6
|
+
const values = new Set(spec.values);
|
|
7
|
+
const booleans = new Set(spec.booleans);
|
|
8
|
+
const out: ParsedArgs = { positional: [], flags: {} };
|
|
9
|
+
for (let i = 0; i < argv.length; i++) {
|
|
10
|
+
const a = argv[i];
|
|
11
|
+
if (!a.startsWith('--')) {
|
|
12
|
+
out.positional.push(a);
|
|
13
|
+
continue;
|
|
14
|
+
}
|
|
15
|
+
const eq = a.indexOf('=');
|
|
16
|
+
const key = a.slice(2, eq === -1 ? undefined : eq);
|
|
17
|
+
if (booleans.has(key)) {
|
|
18
|
+
if (eq !== -1) return { error: `--${key} does not take a value` };
|
|
19
|
+
out.flags[key] = true;
|
|
20
|
+
} else if (values.has(key)) {
|
|
21
|
+
const v = eq !== -1 ? a.slice(eq + 1) : argv[++i];
|
|
22
|
+
if (v === undefined || (eq === -1 && v.startsWith('--'))) return { error: `--${key} needs a value` };
|
|
23
|
+
out.flags[key] = v;
|
|
24
|
+
} else return { error: `unknown option --${key}` };
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// 引擎回的失敗原因 → 人看得懂的一句話+下一步。找不到對照的,照實印原因代碼。
|
|
2
|
+
|
|
3
|
+
const TABLE: Record<string, [string, string]> = {
|
|
4
|
+
links_missing: ['The content uses a tracked link that is not in the link table.', 'Run `campaign create` again with the current engine (it stores the link table), or compose without trackBase.'],
|
|
5
|
+
bad_links: ['The link table is malformed (numbers must be 1..N, http(s) URLs only).', 'Compose the issue again with `campaign create`.'],
|
|
6
|
+
marketing_domain_not_set: ['Newsletters are not configured on this deployment (no sender domain), so the welcome mail cannot be checked or stored.', 'Set MARKETING_DOMAIN first; the welcome mail can be stored switched off (--disable).'],
|
|
7
|
+
enabled_required: ['Say explicitly whether the welcome mail is on.', 'Add --enable or --disable.'],
|
|
8
|
+
unsubscribe_link_missing: ['The welcome mail has no {{unsubscribe_url}} link in the HTML or the text.', 'Use a template whose footer contains the unsubscribe link.'],
|
|
9
|
+
tracking_not_supported: ['The welcome mail contains tracking placeholders.', 'Compose it without trackBase (the `welcome` command does this).'],
|
|
10
|
+
not_found: ['No such issue.', 'Check the issue id with `campaign status <id>`; create it with `campaign create` first.'],
|
|
11
|
+
illegal_transition: ['The issue is not in a state where this is allowed.', 'Run `campaign status <id>` to see the current state and what comes next.'],
|
|
12
|
+
illegal_state: ['The issue is not in a state where this is allowed (retry-failed works only while it is sending or paused; a finished (done) issue is closed for good: recipients that failed are recorded with their reason).', 'Run `campaign status <id>` to see the current state.'],
|
|
13
|
+
locked: ['The content is locked: sending has started.', 'Pause the issue first if it must change; a sent issue cannot be edited.'],
|
|
14
|
+
changed_meanwhile: ['The issue changed while the command ran.', 'Run `campaign status <id>` and try again.'],
|
|
15
|
+
conflict: ['An issue with this id already exists.', 'Use a different id or look at the existing one.'],
|
|
16
|
+
domain_held: ['The sender domain is on hold: every newsletter is stopped.', 'Read `campaign status <id>`, then release it with `hold release --note "..." --yes` (or, when this issue paused because of the hold: `campaign release <id> --release-domain`).'],
|
|
17
|
+
preview_required: ['This content has not been previewed yet (or it changed after the preview).', 'Run `campaign preview <id> --yes`, let the owner look at it, then approve.'],
|
|
18
|
+
duplicate_content: ['The same content already exists under another id.', 'Use the existing issue (or see the line above for what to change).'],
|
|
19
|
+
note_required: ['A note is required: who said yes, when, where.', 'Add --note "..."'],
|
|
20
|
+
reason_required: ['A reason is required.', 'Add --reason "..."'],
|
|
21
|
+
not_approved: ['The approval does not match the current content.', 'Preview and approve the current content again.'],
|
|
22
|
+
preflight_not_passed: ['The pre-send check has not passed for the current content.', 'Run `campaign create` again (or fix the source) until the check passes.'],
|
|
23
|
+
web_url_required: ['The issue has no web version URL.', 'Recreate it with --web-url.'],
|
|
24
|
+
bad_time: ['The time could not be understood.', 'Use "YYYY-MM-DD HH:MM" (local time) or a full ISO time.'],
|
|
25
|
+
unknown_plan: ['The warm-up plan does not exist.', 'Define it with the warm-up API before scheduling.'],
|
|
26
|
+
unknown_list: ['The list does not exist.', 'Check the list id.'],
|
|
27
|
+
recipient_not_allowed: ['That address is not on the test recipient list.', 'Test mail only goes to the addresses configured as TEST_RECIPIENTS.'],
|
|
28
|
+
test_recipients_not_configured: ['Test mail is not enabled on this deployment.', 'Set TEST_RECIPIENTS on the Worker.'],
|
|
29
|
+
bad_recipients: ['Give 1 to 10 test addresses.', 'Use --to a@example.com,b@example.com'],
|
|
30
|
+
bad_prefix: ['The subject prefix is not valid.', 'At most 20 characters, no line breaks.'],
|
|
31
|
+
not_uncertain: ['That recipient is not in the "uncertain" state.', 'Run `campaign status <id>` to see who is.'],
|
|
32
|
+
bad_json: ['The request body was not valid JSON.', 'This is a bug in the command: report it.'],
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function friendly(reason: string, extra?: string): string {
|
|
36
|
+
const t = TABLE[reason];
|
|
37
|
+
const head = t ? `${t[0]} (${reason})` : `Refused: ${reason}`;
|
|
38
|
+
return [head, extra, t ? `Next: ${t[1]}` : 'Next: read the reason above; `campaign status <id>` shows the current state.'].filter(Boolean).join('\n');
|
|
39
|
+
}
|