@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.
- package/README.md +47 -5
- 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 +31 -0
- package/dist/cli/main.js +475 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +224 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +637 -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 +136 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +135 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +51 -0
- package/docs/lists.md +66 -0
- package/docs/security-model.md +4 -4
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -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/package.json +19 -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 +339 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +766 -0
- package/src/broadcast/events.ts +107 -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 +177 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +33 -0
- package/src/cli/main.ts +466 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +257 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +624 -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 +153 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +42 -1
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +120 -31
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/wrangler.example.jsonc +16 -2
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
// 電子報櫃台的指令(AI 用):建一期、預覽、寄測試信、核准、排程、開寄、看進度、暫停、放行、取消、重試、對帳、解除網域停寄。
|
|
2
|
+
// 每個會改狀態的指令:沒有 --yes 就只演練(dry-run),印出「會做什麼」;有 --yes 才真的做。
|
|
3
|
+
// 輸出:給人看的摘要;加 --json 改成一個 JSON 物件(給程式讀)。錯誤講清楚下一步,結束碼 1(用法錯誤 2)。
|
|
4
|
+
// 預設值(名單代號、寄件人、樣板、測試信箱…)由部署端傳入 runCli 的 defaults,引擎本身不帶任何自家資訊。
|
|
5
|
+
import { compose, createTemplate, preflight } from "../compose/index.js";
|
|
6
|
+
import { parseArgs } from "./args.js";
|
|
7
|
+
import { explainPause } from "../broadcast/explain.js";
|
|
8
|
+
import { resolveConfig } from "../broadcast/config.js";
|
|
9
|
+
import { friendly } from "./errors.js";
|
|
10
|
+
const VALUES = ['issue', 'source', 'post', 'web-url', 'list', 'from', 'subject', 'audience', 'source-ref', 'to', 'note', 'reason', 'at', 'out', 'contact', 'as', 'tz', 'base-url'];
|
|
11
|
+
const BOOLEANS = ['yes', 'json', 'offline', 'force', 'release-domain', 'to-defaults', 'help'];
|
|
12
|
+
class CliError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(message, code = 1) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const HELP = `mailroom campaign <command> [options]
|
|
20
|
+
|
|
21
|
+
Read-only:
|
|
22
|
+
status <id> progress, brake light, why it paused, what to do next
|
|
23
|
+
audience <id> who would receive it if it started now
|
|
24
|
+
reconcile <id> check frozen = sent + skipped + failed (safe to repeat)
|
|
25
|
+
throttle today's budget, provider health, domain hold
|
|
26
|
+
Changes state (dry-run unless --yes is given):
|
|
27
|
+
create --issue <id> (--source <file.md> | --post <name>) [--web-url U] [--list L] [--subject S] [--audience JSON|plan] [--offline] --yes
|
|
28
|
+
preview <id> [--out DIR] --yes mark the current content as previewed (needed before approve)
|
|
29
|
+
test <id> (--to a@x,b@x | --to-defaults) --yes
|
|
30
|
+
approve <id> --note "who, when, where" --yes
|
|
31
|
+
schedule <id> --at "2027-03-01 09:00" --yes unschedule <id> --yes
|
|
32
|
+
start <id> --yes schedule for right now
|
|
33
|
+
pause <id> --reason "..." --yes
|
|
34
|
+
resume <id> --note "what was checked" [--release-domain] [--force] --yes (alias: release)
|
|
35
|
+
cancel <id> --reason "..." --yes
|
|
36
|
+
retry-failed <id> --yes resolve <id> --contact N --as sent|failed --note "..." --yes
|
|
37
|
+
hold release --note "..." --yes release the sender-domain hold
|
|
38
|
+
Options: --json (machine-readable output), --base-url, --tz +08:00
|
|
39
|
+
Environment: MAILROOM_URL, MAILROOM_ADMIN_TOKEN`;
|
|
40
|
+
const ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
41
|
+
/** 重複建期的說明:撞到誰、用什麼撞到、下一步(寄完的期取消不了,不建議取消)。 */
|
|
42
|
+
function twinText(b) {
|
|
43
|
+
const by = b.twinBy === 'web_url' ? 'the same web version URL' : b.twinBy === 'source_ref' ? 'the same source reference' : 'the same list and body';
|
|
44
|
+
const done = b.twinStatus === 'done';
|
|
45
|
+
return `Issue "${b.twin}" (${b.twinStatus}) already has ${by}.${done ? ' It was already sent and cannot be cancelled.' : ''}\n${b.twinBy === 'source_ref' ? 'If this is a different issue that reuses the file path, pass --source-ref with something unique (for example the post id and date).' : done ? 'If this is really a new issue, its web version URL and body must differ from the sent one.' : `If it was created by mistake, cancel it first: campaign cancel ${b.twin} --reason "..." --yes.`}`;
|
|
46
|
+
}
|
|
47
|
+
function offsetOf(s) {
|
|
48
|
+
const v = s ?? '+08:00';
|
|
49
|
+
if (!/^[+-]\d{2}:\d{2}$/.test(v))
|
|
50
|
+
throw new CliError(`bad time zone "${v}": use +08:00 style`, 2);
|
|
51
|
+
return v;
|
|
52
|
+
}
|
|
53
|
+
/** 「2027-03-01 09:00」(本地時間)或完整 ISO → ISO(UTC)。 */
|
|
54
|
+
export function parseAt(input, offset) {
|
|
55
|
+
const s = input.trim();
|
|
56
|
+
const local = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})(?::(\d{2}))?$/.exec(s);
|
|
57
|
+
const iso = local ? `${local[1]}T${local[2]}:${local[3] ?? '00'}${offset}` : /^\d{4}-\d{2}-\d{2}T[\d:.]+(?:Z|[+-]\d{2}:\d{2})$/.test(s) ? s : null;
|
|
58
|
+
if (!iso)
|
|
59
|
+
return null;
|
|
60
|
+
const t = Date.parse(iso);
|
|
61
|
+
return Number.isNaN(t) ? null : new Date(t).toISOString();
|
|
62
|
+
}
|
|
63
|
+
export async function runCli(argv, opts = {}) {
|
|
64
|
+
const d = opts.defaults ?? {};
|
|
65
|
+
const env = opts.env ?? {};
|
|
66
|
+
const io = {
|
|
67
|
+
out: opts.io?.out ?? ((s) => console.log(s)),
|
|
68
|
+
err: opts.io?.err ?? ((s) => console.error(s)),
|
|
69
|
+
fetch: opts.io?.fetch ?? fetch,
|
|
70
|
+
// 檔案讀寫由入口(bin/mailroom.mjs)注入:這支不碰 node 內建模組,型別檢查與 Worker 打包都乾淨。
|
|
71
|
+
readFile: opts.io?.readFile ?? (async () => { throw new Error('file access not provided'); }),
|
|
72
|
+
writeFile: opts.io?.writeFile ?? (async () => { throw new Error('file access not provided'); }),
|
|
73
|
+
now: opts.io?.now ?? (() => new Date()),
|
|
74
|
+
};
|
|
75
|
+
const words = [...argv];
|
|
76
|
+
if (words[0] === 'campaign')
|
|
77
|
+
words.shift();
|
|
78
|
+
const parsed = parseArgs(words, { values: VALUES, booleans: BOOLEANS });
|
|
79
|
+
let json = false;
|
|
80
|
+
try {
|
|
81
|
+
if ('error' in parsed)
|
|
82
|
+
throw new CliError(`${parsed.error}\n\n${HELP}`, 2);
|
|
83
|
+
const { positional, flags } = parsed;
|
|
84
|
+
json = flags.json === true;
|
|
85
|
+
if (flags.help === true || positional.length === 0) {
|
|
86
|
+
io.out(HELP);
|
|
87
|
+
return positional.length === 0 && flags.help !== true ? 2 : 0;
|
|
88
|
+
}
|
|
89
|
+
const cmd = positional[0];
|
|
90
|
+
const baseUrl = String(flags['base-url'] ?? d.baseUrl ?? env.MAILROOM_URL ?? '').replace(/\/+$/, '');
|
|
91
|
+
const token = env.MAILROOM_ADMIN_TOKEN ?? '';
|
|
92
|
+
const yes = flags.yes === true;
|
|
93
|
+
const idArg = () => {
|
|
94
|
+
const id = positional[1];
|
|
95
|
+
if (!id || !ID.test(id))
|
|
96
|
+
throw new CliError(`${cmd} needs an issue id (lowercase letters, digits, hyphens).`, 2);
|
|
97
|
+
return id;
|
|
98
|
+
};
|
|
99
|
+
const need = (name) => {
|
|
100
|
+
const v = flags[name];
|
|
101
|
+
if (typeof v !== 'string' || !v.trim())
|
|
102
|
+
throw new CliError(`--${name} is required for ${cmd}.`, 2);
|
|
103
|
+
return v.trim();
|
|
104
|
+
};
|
|
105
|
+
async function api(method, path, body) {
|
|
106
|
+
if (!baseUrl || !token)
|
|
107
|
+
throw new CliError('Missing connection settings.\nNext: set MAILROOM_URL and MAILROOM_ADMIN_TOKEN (or pass --base-url), then run again.');
|
|
108
|
+
let res;
|
|
109
|
+
try {
|
|
110
|
+
res = await io.fetch(`${baseUrl}${path}`, { method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
throw new CliError(`Could not reach the mailroom (${e instanceof Error ? e.message.slice(0, 100) : 'network error'}).\nNext: check MAILROOM_URL and the network, then run again. Nothing was changed.`);
|
|
114
|
+
}
|
|
115
|
+
const text = await res.text();
|
|
116
|
+
let b = {};
|
|
117
|
+
try {
|
|
118
|
+
b = text ? JSON.parse(text) : {};
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
if (res.status === 404 || res.status === 401)
|
|
122
|
+
throw new CliError(`The mailroom answered ${res.status} without details.\nNext: check MAILROOM_ADMIN_TOKEN, and that the newsletter desk is enabled on this deployment.`);
|
|
123
|
+
if (res.status === 429)
|
|
124
|
+
throw new CliError('Rate limited by the mailroom (admin calls are limited per minute).\nNext: wait a minute and run again.');
|
|
125
|
+
throw new CliError(`Unexpected answer (${res.status}) from the mailroom.\nNext: try again; if it repeats, look at the Worker logs.`);
|
|
126
|
+
}
|
|
127
|
+
return { status: res.status, body: b };
|
|
128
|
+
}
|
|
129
|
+
/** 呼叫並把失敗翻成人話。 */
|
|
130
|
+
async function call(method, path, body) {
|
|
131
|
+
const r = await api(method, path, body);
|
|
132
|
+
if (r.status >= 400 || r.body.ok === false) {
|
|
133
|
+
const extra = r.body.twin ? twinText(r.body) : r.body.status ? `Current state: ${r.body.status}.` : r.body.error ? String(r.body.error) : undefined;
|
|
134
|
+
throw new CliError(friendly(String(r.body.reason ?? `http_${r.status}`), extra));
|
|
135
|
+
}
|
|
136
|
+
return r.body;
|
|
137
|
+
}
|
|
138
|
+
const emit = (human, data) => io.out(json ? JSON.stringify({ ok: true, command: cmd, ...data }) : human.join('\n'));
|
|
139
|
+
const dry = (what, data) => {
|
|
140
|
+
emit([...what, '', 'DRY RUN: nothing was changed. Add --yes to do it.'], { dryRun: true, ...data });
|
|
141
|
+
return 0;
|
|
142
|
+
};
|
|
143
|
+
switch (cmd) {
|
|
144
|
+
case 'throttle': {
|
|
145
|
+
const t = await call('GET', '/v1/throttle');
|
|
146
|
+
emit([`domain ${t.domain} day ${t.day}`, t.hold ? `DOMAIN ON HOLD: ${t.hold.reason} (since ${t.hold.created_at})` : 'domain: not on hold', `issues in flight: ${t.campaigns.map((c) => `${c.id}(${c.status})`).join(', ') || 'none'}`], { throttle: t });
|
|
147
|
+
return 0;
|
|
148
|
+
}
|
|
149
|
+
case 'status': {
|
|
150
|
+
const id = idArg();
|
|
151
|
+
const [s, t] = await Promise.all([call('GET', `/v1/campaigns/${id}`), call('GET', '/v1/throttle')]);
|
|
152
|
+
const light = brakeLight(s, t);
|
|
153
|
+
const lines = [`${id}: ${s.status}${s.pauseReason ? ` (${s.pauseReason})` : ''} brake light: ${light.icon} ${light.text}`, `subject: ${s.subject}`];
|
|
154
|
+
if (s.scheduledAt && s.status === 'scheduled')
|
|
155
|
+
lines.push(`scheduled for ${s.scheduledAt}`);
|
|
156
|
+
if (s.status === 'draft' || s.status === 'approved')
|
|
157
|
+
lines.push(`pre-send check: ${s.preflight ? (s.preflight.ok ? 'passed' : `FAILED (${(s.preflight.errors ?? []).join(', ')})`) : 'not run'} previewed: ${s.previewed ? 'yes' : 'no'} approved: ${s.approved ? `yes (${s.approvedNote})` : 'no'}`);
|
|
158
|
+
const byState = new Map();
|
|
159
|
+
for (const r of s.recipients)
|
|
160
|
+
byState.set(r.skip_reason ? `${r.state}/${r.skip_reason}` : r.state, (byState.get(r.skip_reason ? `${r.state}/${r.skip_reason}` : r.state) ?? 0) + Number(r.n));
|
|
161
|
+
if (byState.size)
|
|
162
|
+
lines.push(`recipients: ${[...byState.entries()].map(([k, n]) => `${k} ${n}`).join(', ')}`);
|
|
163
|
+
const r = s.rates;
|
|
164
|
+
if (r && r.sent > 0)
|
|
165
|
+
lines.push(`so far: ${r.sent} sent, hard bounces ${r.hardBounces} (${pct(r.hardBounceRate)}), complaints ${r.complaints} (${pct(r.complaintRate)}), opens ${r.opens} (${pct(r.openRate)})`);
|
|
166
|
+
if (t.hold)
|
|
167
|
+
lines.push(`SENDER DOMAIN ON HOLD: ${t.hold.reason}`);
|
|
168
|
+
if (s.pauseExplain)
|
|
169
|
+
lines.push('', `why: ${s.pauseExplain.summary}`, ...(s.pauseExplain.threshold ? [`threshold: ${JSON.stringify(s.pauseExplain.threshold)}`] : []), `next: ${s.pauseExplain.suggestion}`, s.pauseExplain.needsDomainRelease ? `then: campaign resume ${id} --note "..." --release-domain --yes` : s.pauseExplain.resumable ? `then: campaign resume ${id} --note "..." --yes` : 'this one cannot simply be resumed: fix the cause first');
|
|
170
|
+
else
|
|
171
|
+
lines.push('', nextStep(s));
|
|
172
|
+
emit(lines, { status: s, throttle: { hold: t.hold, day: t.day, today: t.today }, brakeLight: light });
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
case 'audience': {
|
|
176
|
+
const a = await call('GET', `/v1/campaigns/${idArg()}/audience`);
|
|
177
|
+
emit(audienceLines(a), { audience: a });
|
|
178
|
+
return 0;
|
|
179
|
+
}
|
|
180
|
+
case 'reconcile': {
|
|
181
|
+
// 對不上時引擎回 200+ok:false(附問題清單與各項數字):這不是「被拒絕」,要把證據印出來,所以不走 call()。
|
|
182
|
+
const res = await api('POST', `/v1/campaigns/${idArg()}/reconcile`, {});
|
|
183
|
+
if (res.status >= 400)
|
|
184
|
+
throw new CliError(friendly(String(res.body.reason ?? `http_${res.status}`)));
|
|
185
|
+
const r = res.body;
|
|
186
|
+
const ev = r.events ?? {};
|
|
187
|
+
const evSum = Number(ev.delivered ?? 0) + Number(ev.hardBounced ?? 0) + Number(ev.softBounced ?? 0) + Number(ev.awaiting ?? 0);
|
|
188
|
+
const lines = [
|
|
189
|
+
`reconcile: ${r.ok ? 'all numbers add up' : 'MISMATCH'}`,
|
|
190
|
+
`frozen ${r.frozen} = sent ${r.sent} + skipped ${r.skippedTotal} ${JSON.stringify(r.skipped)} + failed ${r.failed} + uncertain ${r.uncertain} + pending ${r.pending}`,
|
|
191
|
+
`ledger: ${r.ledger?.sent} sent rows, ${r.ledger?.doneWithoutLedger} recipients marked sent without a ledger row`,
|
|
192
|
+
`provider events: ${ev.sends} sends vs ${r.sent} sent${ev.sends === r.sent ? '' : ' (DIFFERENT)'}; delivered ${ev.delivered} + bounced ${Number(ev.hardBounced ?? 0) + Number(ev.softBounced ?? 0)} + not reported yet ${ev.awaiting} = ${evSum} vs ${ev.sends} sends${evSum === ev.sends ? '' : ' (DIFFERENT)'}; duplicate sends ${ev.duplicateSends}`,
|
|
193
|
+
...(r.problems?.length ? [`problems: ${r.problems.join(', ')}`, 'Next: do not release the next warm-up step until a person has explained the differences.'] : []),
|
|
194
|
+
...(Number(ev.awaiting) > 0 ? [`${ev.awaiting} provider event(s) have not arrived yet (not a mismatch): run again after 72 hours.`] : []),
|
|
195
|
+
];
|
|
196
|
+
io.out(json ? JSON.stringify({ ok: !!r.ok, command: cmd, reconcile: r }) : lines.join('\n'));
|
|
197
|
+
return r.ok ? 0 : 1;
|
|
198
|
+
}
|
|
199
|
+
case 'create': return await create();
|
|
200
|
+
case 'preview': {
|
|
201
|
+
const id = idArg();
|
|
202
|
+
if (!yes) {
|
|
203
|
+
const p = await call('GET', `/v1/campaigns/${id}/preview`);
|
|
204
|
+
await writePreview(id, p);
|
|
205
|
+
return dry(previewLines(id, p, false), { preview: slim(p) });
|
|
206
|
+
}
|
|
207
|
+
const p = await call('POST', `/v1/campaigns/${id}/preview`, {});
|
|
208
|
+
await writePreview(id, p);
|
|
209
|
+
emit(previewLines(id, p, true), { preview: slim(p), previewUrl: d.previewUrl?.(id) ?? null });
|
|
210
|
+
return 0;
|
|
211
|
+
}
|
|
212
|
+
case 'test': {
|
|
213
|
+
const id = idArg();
|
|
214
|
+
const to = flags['to-defaults'] === true ? d.testRecipients ?? [] : typeof flags.to === 'string' ? flags.to.split(',').map((x) => x.trim()).filter(Boolean) : [];
|
|
215
|
+
if (!to.length)
|
|
216
|
+
throw new CliError('Give test addresses with --to a@x,b@x, or use --to-defaults (needs testRecipients in the defaults).', 2);
|
|
217
|
+
if (!yes)
|
|
218
|
+
return dry([`Would send a test copy of ${id} to: ${to.join(', ')} (subject prefix "${d.subjectPrefix ?? '[Test] '}", real headers, not counted in any statistics).`], { to });
|
|
219
|
+
const r = await call('POST', `/v1/campaigns/${id}/test`, { to, ...(d.subjectPrefix !== undefined ? { subjectPrefix: d.subjectPrefix } : {}) });
|
|
220
|
+
const bad = r.results.filter((x) => !x.ok).length;
|
|
221
|
+
emit([...r.results.map((x) => `${x.ok ? 'sent ' : 'FAILED '} ${x.to}${x.error ? ` ${x.error}` : ''}`), bad ? 'Next: failed addresses were NOT retried automatically; check the reason, then run test again for them.' : 'Next: open the test mails in each mailbox (light and dark mode), then ask the owner to look at the preview.'], { results: r.results });
|
|
222
|
+
return bad ? 1 : 0;
|
|
223
|
+
}
|
|
224
|
+
case 'approve': {
|
|
225
|
+
const id = idArg();
|
|
226
|
+
const note = need('note');
|
|
227
|
+
const s = await call('GET', `/v1/campaigns/${id}`);
|
|
228
|
+
const problems = [s.status !== 'draft' ? `state is ${s.status}, approve only works on a draft` : '', s.preflight?.ok !== true ? 'the pre-send check has not passed' : '', s.previewed ? '' : 'the current content has not been previewed (run preview --yes)'].filter(Boolean);
|
|
229
|
+
if (problems.length)
|
|
230
|
+
throw new CliError(`Cannot approve ${id}: ${problems.join('; ')}.\nNext: ${s.status !== 'draft' ? `campaign status ${id}` : s.preflight?.ok !== true ? 'fix the issues and run create again' : `campaign preview ${id} --yes`}`);
|
|
231
|
+
if (!yes)
|
|
232
|
+
return dry([`Would approve ${id} ("${s.subject}") with note: ${note}`, 'Only do this after the owner has looked at the preview and said yes.'], { note });
|
|
233
|
+
const r = await call('POST', `/v1/campaigns/${id}/approve`, { note });
|
|
234
|
+
emit([`${id}: ${r.status}`, `Next: campaign schedule ${id} --at "YYYY-MM-DD HH:MM" --yes`], { result: r });
|
|
235
|
+
return 0;
|
|
236
|
+
}
|
|
237
|
+
case 'schedule':
|
|
238
|
+
case 'start': {
|
|
239
|
+
const id = idArg();
|
|
240
|
+
const offset = offsetOf(typeof flags.tz === 'string' ? flags.tz : d.utcOffset);
|
|
241
|
+
let at;
|
|
242
|
+
if (cmd === 'start')
|
|
243
|
+
at = new Date(io.now().getTime() + 1000).toISOString();
|
|
244
|
+
else {
|
|
245
|
+
const parsedAt = parseAt(need('at'), offset);
|
|
246
|
+
if (!parsedAt)
|
|
247
|
+
throw new CliError(friendly('bad_time'), 2);
|
|
248
|
+
if (Date.parse(parsedAt) < io.now().getTime() - 60_000)
|
|
249
|
+
throw new CliError(`${parsedAt} is in the past: scheduling it would start sending immediately.\nNext: pick a future time, or use \`campaign start ${id} --yes\` if you really mean now.`);
|
|
250
|
+
at = parsedAt;
|
|
251
|
+
}
|
|
252
|
+
const a = await call('GET', `/v1/campaigns/${id}/audience`);
|
|
253
|
+
const what = [cmd === 'start' ? `Would START ${id} NOW.` : `Would schedule ${id} for ${at}.`, '', ...audienceLines(a)];
|
|
254
|
+
if (a.blocked)
|
|
255
|
+
what.push('', `WARNING: this issue cannot start right now: ${a.blocked}`);
|
|
256
|
+
if (!yes)
|
|
257
|
+
return dry(what, { at, audience: a });
|
|
258
|
+
const r = await call('POST', `/v1/campaigns/${id}/schedule`, { at });
|
|
259
|
+
emit([...what, '', `${id}: ${r.status} at ${r.scheduledAt}`, 'Next: the per-minute job starts it at that time; watch it with `campaign status`.'], { result: r, audience: a });
|
|
260
|
+
return 0;
|
|
261
|
+
}
|
|
262
|
+
case 'unschedule': {
|
|
263
|
+
const id = idArg();
|
|
264
|
+
if (!yes)
|
|
265
|
+
return dry([`Would take ${id} off the schedule (back to approved).`], {});
|
|
266
|
+
emit([`${id}: ${(await call('POST', `/v1/campaigns/${id}/unschedule`, {})).status}`], {});
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
case 'pause': {
|
|
270
|
+
const id = idArg();
|
|
271
|
+
const reason = need('reason');
|
|
272
|
+
if (!yes)
|
|
273
|
+
return dry([`Would pause ${id}: ${reason}. Mails already handed to the provider still go out; nothing new is handed over.`], { reason });
|
|
274
|
+
emit([`${id}: ${(await call('POST', `/v1/campaigns/${id}/pause`, { reason })).status}`, `Next: when ready, campaign resume ${id} --note "..." --yes`], {});
|
|
275
|
+
return 0;
|
|
276
|
+
}
|
|
277
|
+
case 'resume':
|
|
278
|
+
case 'release': {
|
|
279
|
+
const id = idArg();
|
|
280
|
+
const note = need('note');
|
|
281
|
+
const [s, t] = await Promise.all([call('GET', `/v1/campaigns/${id}`), call('GET', '/v1/throttle')]);
|
|
282
|
+
if (s.status !== 'paused')
|
|
283
|
+
throw new CliError(`${id} is ${s.status}, not paused: nothing to release.\nNext: campaign status ${id}`);
|
|
284
|
+
const ex = s.pauseExplain;
|
|
285
|
+
const lines = [`${id} is paused: ${s.pauseReason}`, ...(ex ? [`why: ${ex.summary}`, ...(ex.threshold ? [`threshold: ${JSON.stringify(ex.threshold)}`] : []), `suggestion: ${ex.suggestion}`] : [])];
|
|
286
|
+
if (ex && !ex.resumable && flags.force !== true)
|
|
287
|
+
throw new CliError(`${lines.join('\n')}\n\nThis pause is about a cause that must be fixed first; resuming would just stop again or send something wrong.\nNext: fix the cause, then run again with --force.`);
|
|
288
|
+
const held = !!t.hold;
|
|
289
|
+
// 網域停寄影響所有電子報:只有「這期就是因為它才暫停」時,才准一起解除;其他情況要另外看過數字再單獨解除。
|
|
290
|
+
const releaseHere = held && ex?.code === 'domain_hold';
|
|
291
|
+
if (held && !releaseHere)
|
|
292
|
+
throw new CliError(`${lines.join('\n')}\n\nThe sender domain is on hold (${t.hold.reason}), but that is not why this issue paused. Releasing it affects every newsletter, so it is a separate decision.\nNext: run \`campaign hold release --note "..."\` (the dry run shows the threshold and the numbers), decide, then resume this issue.`);
|
|
293
|
+
if (releaseHere && flags['release-domain'] !== true)
|
|
294
|
+
throw new CliError(`${lines.join('\n')}\n\nThis issue paused because the sender domain is on hold, and that stops every newsletter.\nNext: read the numbers above. If they are explained, \`--release-domain\` releases the hold with your note and resumes this issue in one step.`);
|
|
295
|
+
const plan = [...lines, '', ...(releaseHere ? [`Would release the sender-domain hold (${t.hold.reason}).`] : []), `Would resume ${id} with note: ${note}`, ...(ex?.code === 'hard_bounce_rate' || ex?.code === 'complaint_rate' || ex?.code === 'wave_gate' ? ['That brake restarts counting from the resume.'] : [])];
|
|
296
|
+
if (!yes)
|
|
297
|
+
return dry(plan, { pauseExplain: ex ?? null, domainHold: t.hold ?? null });
|
|
298
|
+
if (releaseHere)
|
|
299
|
+
await call('POST', '/v1/broadcast/release-hold', { note });
|
|
300
|
+
let r;
|
|
301
|
+
try {
|
|
302
|
+
r = await call('POST', `/v1/campaigns/${id}/resume`, { note });
|
|
303
|
+
}
|
|
304
|
+
catch (e) {
|
|
305
|
+
throw new CliError(`${releaseHere ? 'The domain hold WAS released, but resuming failed:\n' : ''}${e instanceof Error ? e.message : String(e)}`);
|
|
306
|
+
}
|
|
307
|
+
emit([...plan, '', `${id}: ${r.status}`], { result: r, domainReleased: releaseHere });
|
|
308
|
+
return 0;
|
|
309
|
+
}
|
|
310
|
+
case 'cancel': {
|
|
311
|
+
const id = idArg();
|
|
312
|
+
const reason = need('reason');
|
|
313
|
+
if (!yes)
|
|
314
|
+
return dry([`Would cancel ${id}: ${reason}. This cannot be undone; people not yet mailed are marked skipped/cancelled.`], { reason });
|
|
315
|
+
emit([`${id}: ${(await call('POST', `/v1/campaigns/${id}/cancel`, { reason })).status}`], {});
|
|
316
|
+
return 0;
|
|
317
|
+
}
|
|
318
|
+
case 'retry-failed': {
|
|
319
|
+
const id = idArg();
|
|
320
|
+
if (!yes)
|
|
321
|
+
return dry([`Would retry the failed recipients of ${id} with the same de-duplication key (nobody gets two copies). Only works while the issue is sending or paused.`], {});
|
|
322
|
+
const r = await call('POST', `/v1/campaigns/${id}/retry-failed`, {});
|
|
323
|
+
emit([`${id}: ${r.requeued} recipient(s) queued again`, 'Next: if they fail again the reason is recorded; leave them.'], { result: r });
|
|
324
|
+
return 0;
|
|
325
|
+
}
|
|
326
|
+
case 'resolve': {
|
|
327
|
+
const id = idArg();
|
|
328
|
+
const contact = Number(need('contact'));
|
|
329
|
+
const as = need('as');
|
|
330
|
+
if (!Number.isInteger(contact) || (as !== 'sent' && as !== 'failed'))
|
|
331
|
+
throw new CliError('--contact must be a number and --as must be sent or failed.', 2);
|
|
332
|
+
const note = need('note');
|
|
333
|
+
if (!yes)
|
|
334
|
+
return dry([`Would mark recipient ${contact} of ${id} as ${as} (they were "uncertain": the provider may or may not have accepted the mail). Note: ${note}`], {});
|
|
335
|
+
emit([`${id}: recipient ${contact} marked ${as}`], { result: await call('POST', `/v1/campaigns/${id}/resolve`, { contact, as, note }) });
|
|
336
|
+
return 0;
|
|
337
|
+
}
|
|
338
|
+
case 'hold': {
|
|
339
|
+
if (positional[1] !== 'release')
|
|
340
|
+
throw new CliError('Usage: hold release --note "..." --yes', 2);
|
|
341
|
+
const note = need('note');
|
|
342
|
+
const t = await call('GET', '/v1/throttle');
|
|
343
|
+
if (!t.hold)
|
|
344
|
+
throw new CliError('The sender domain is not on hold: nothing to release.');
|
|
345
|
+
const hx = explainPause(`brake:domain_hold:${t.hold.reason}`, resolveConfig(t.config));
|
|
346
|
+
const hlines = [`sender domain on hold since ${t.hold.created_at}: ${t.hold.reason}`, ...(hx ? [`why: ${hx.summary}`, `threshold: ${JSON.stringify(hx.threshold)}`, `suggestion: ${hx.suggestion}`] : [])];
|
|
347
|
+
if (!yes)
|
|
348
|
+
return dry([...hlines, '', 'Would release the hold. Paused issues stay paused until resumed one by one.'], { hold: t.hold, explain: hx });
|
|
349
|
+
emit([...hlines, `released ${(await call('POST', '/v1/broadcast/release-hold', { note })).released} hold(s)`, 'Next: resume each paused issue with `campaign resume <id> --note "..." --yes`.'], {});
|
|
350
|
+
return 0;
|
|
351
|
+
}
|
|
352
|
+
default:
|
|
353
|
+
throw new CliError(`unknown command "${cmd}"\n\n${HELP}`, 2);
|
|
354
|
+
}
|
|
355
|
+
async function create() {
|
|
356
|
+
const issue = need('issue');
|
|
357
|
+
if (!ID.test(issue))
|
|
358
|
+
throw new CliError('--issue: lowercase letters, digits and hyphens only (max 40).', 2);
|
|
359
|
+
if (!d.template)
|
|
360
|
+
throw new CliError('No email template is configured.\nNext: pass `template` in the defaults (see docs/composing.md).');
|
|
361
|
+
const post = typeof flags.post === 'string' ? d.sourceFor?.(flags.post) : undefined;
|
|
362
|
+
if (typeof flags.post === 'string' && !post)
|
|
363
|
+
throw new CliError('--post needs `sourceFor` in the defaults; use --source <file.md> instead.', 2);
|
|
364
|
+
const sourcePath = post?.path ?? (typeof flags.source === 'string' ? flags.source : '');
|
|
365
|
+
if (!sourcePath)
|
|
366
|
+
throw new CliError('Give the source with --source <file.md> (or --post <name>).', 2);
|
|
367
|
+
let source;
|
|
368
|
+
try {
|
|
369
|
+
source = await io.readFile(sourcePath);
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
throw new CliError(`Could not read the source file "${sourcePath}".\nNext: check the path.`);
|
|
373
|
+
}
|
|
374
|
+
const list = (typeof flags.list === 'string' ? flags.list : d.list) ?? '';
|
|
375
|
+
const from = (typeof flags.from === 'string' ? flags.from : d.from) ?? '';
|
|
376
|
+
if (!list || !from)
|
|
377
|
+
throw new CliError('The list and the sender are required: pass --list/--from or set them in the defaults.', 2);
|
|
378
|
+
let audience = d.audience;
|
|
379
|
+
if (typeof flags.audience === 'string') {
|
|
380
|
+
try {
|
|
381
|
+
audience = flags.audience.trim().startsWith('{') ? JSON.parse(flags.audience) : { plan: flags.audience.trim() };
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
throw new CliError('--audience must be a plan name or a JSON object like {"waves":[["*"]]}.', 2);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (!audience)
|
|
388
|
+
throw new CliError('No audience: pass --audience or set it in the defaults.', 2);
|
|
389
|
+
const template = createTemplate(d.template);
|
|
390
|
+
const composed = compose({ ...d.composeDefaults, source, template, issue, ...(typeof flags.subject === 'string' ? { subject: flags.subject } : {}) });
|
|
391
|
+
const webUrl = (typeof flags['web-url'] === 'string' ? flags['web-url'] : undefined) ?? post?.webUrl ?? d.webUrlFor?.(composed.frontmatter);
|
|
392
|
+
if (!webUrl)
|
|
393
|
+
throw new CliError('The web version URL is unknown.\nNext: pass --web-url https://... (the page of this issue on the website).', 2);
|
|
394
|
+
const check = await preflight(composed, { template, webUrl, checkLinks: flags.offline !== true, fetch: io.fetch });
|
|
395
|
+
const errors = check.issues.filter((i) => i.severity === 'error');
|
|
396
|
+
const lines = [
|
|
397
|
+
`${issue}: "${composed.subject}"`, `from ${from} list ${list} web version ${webUrl}`, `HTML ${composed.htmlBytes} bytes, ${composed.links.length} links, ${composed.images.length} images`,
|
|
398
|
+
`pre-send check: ${check.ok ? 'PASSED' : `FAILED (${errors.length} error${errors.length === 1 ? '' : 's'})`}`,
|
|
399
|
+
...check.issues.map((i) => ` [${i.severity}] ${i.code}: ${i.message}${i.where ? ` (${i.where})` : ''}`),
|
|
400
|
+
];
|
|
401
|
+
const data = { issue, subject: composed.subject, checkOk: check.ok, issues: check.issues };
|
|
402
|
+
if (!yes)
|
|
403
|
+
return dry(lines, data);
|
|
404
|
+
const sourceRef = (typeof flags['source-ref'] === 'string' ? flags['source-ref'] : undefined) ?? post?.ref ?? sourcePath;
|
|
405
|
+
const saved = await call('PUT', `/v1/campaigns/${issue}`, { list, subject: composed.subject, preheader: composed.preheader || undefined, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, headers: composed.headers, webUrl, sourceRef, audience });
|
|
406
|
+
const rec = await call('POST', `/v1/campaigns/${issue}/preflight`, { ok: check.ok, issues: check.issues.map((i) => ({ severity: i.severity, code: i.code, message: i.message })) });
|
|
407
|
+
emit([...lines, '', `saved as draft (${saved.changed ? 'new or changed' : 'unchanged'}); check recorded: ${rec.preflightOk ? 'passed' : 'failed'}`, rec.preflightOk ? `Next: campaign preview ${issue} --yes` : 'Next: fix the errors above in the source, then run create again (same id updates the draft).'], { ...data, saved, preflightOk: rec.preflightOk });
|
|
408
|
+
return rec.preflightOk ? 0 : 1;
|
|
409
|
+
}
|
|
410
|
+
function previewLines(id, p, marked) {
|
|
411
|
+
const pf = p.preflight;
|
|
412
|
+
return [
|
|
413
|
+
`${id}: "${p.subject}" (${p.status})`, `HTML ${p.htmlBytes} bytes pre-send check: ${pf ? (pf.ok ? 'passed' : `FAILED (${(pf.errors ?? []).join(', ')})`) : 'not run'}`,
|
|
414
|
+
...(pf?.issues ?? []).map((i) => ` [${i.severity}] ${i.code}: ${i.message}`),
|
|
415
|
+
marked ? 'marked as previewed (approval is now possible for this exact content)' : 'not marked as previewed (add --yes)',
|
|
416
|
+
...(d.previewUrl ? [`owner's preview page: ${d.previewUrl(id)}`] : []),
|
|
417
|
+
...(marked ? [`Next: ask the owner to look at the preview; after a clear yes: campaign approve ${id} --note "..." --yes`] : []),
|
|
418
|
+
];
|
|
419
|
+
}
|
|
420
|
+
async function writePreview(id, p) {
|
|
421
|
+
const out = typeof flags.out === 'string' ? flags.out.replace(/\/+$/, '') : '';
|
|
422
|
+
if (!out)
|
|
423
|
+
return;
|
|
424
|
+
await io.writeFile(`${out}/email.html`, String(p.html));
|
|
425
|
+
await io.writeFile(`${out}/email.txt`, String(p.text));
|
|
426
|
+
await io.writeFile(`${out}/email-no-name.html`, String(p.htmlNoName));
|
|
427
|
+
await io.writeFile(`${out}/check.json`, JSON.stringify(p.preflight, null, 2));
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
catch (e) {
|
|
431
|
+
if (e instanceof CliError) {
|
|
432
|
+
if (json)
|
|
433
|
+
io.out(JSON.stringify({ ok: false, error: e.message }));
|
|
434
|
+
else
|
|
435
|
+
io.err(e.message);
|
|
436
|
+
return e.code;
|
|
437
|
+
}
|
|
438
|
+
throw e;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const pct = (n) => `${(n * 100).toFixed(2)}%`;
|
|
442
|
+
const slim = (p) => ({ id: p.id, status: p.status, subject: p.subject, htmlBytes: p.htmlBytes, preflight: p.preflight, previewed: p.previewed });
|
|
443
|
+
function audienceLines(a) {
|
|
444
|
+
return [
|
|
445
|
+
`audience${a.plan ? ` (warm-up plan ${a.plan}, step ${a.step})` : ''}: ${a.willSend} will receive it (of ${a.subscribed} subscribed)`,
|
|
446
|
+
...a.waves.map((w) => ` wave ${w.wave}: ${w.count} (${w.segments.map((s) => `${s.name} ${s.count}`).join(', ')})`),
|
|
447
|
+
`skipped: ${a.skipped.suppressed} on the suppression list, ${a.skipped.warmup} not in this step of the warm-up`,
|
|
448
|
+
];
|
|
449
|
+
}
|
|
450
|
+
/** 煞車燈號:紅=暫停或網域停寄;黃=任何比率已到門檻的一半;綠=其他。 */
|
|
451
|
+
function brakeLight(s, t) {
|
|
452
|
+
if (t.hold)
|
|
453
|
+
return { icon: 'RED', text: `sender domain on hold (${t.hold.reason})` };
|
|
454
|
+
if (s.status === 'paused')
|
|
455
|
+
return { icon: 'RED', text: 'paused' };
|
|
456
|
+
const cfg = t.config ?? {};
|
|
457
|
+
const r = s.rates ?? { sent: 0 };
|
|
458
|
+
const near = [];
|
|
459
|
+
if (r.sent >= 20 && cfg.brakeHardBounceRate && r.hardBounceRate >= cfg.brakeHardBounceRate / 2)
|
|
460
|
+
near.push(`hard bounces ${pct(r.hardBounceRate)} (brake ${pct(cfg.brakeHardBounceRate)})`);
|
|
461
|
+
if (r.complaints > 0 && cfg.brakeComplaintRate && r.complaintRate >= cfg.brakeComplaintRate / 2)
|
|
462
|
+
near.push(`complaints ${r.complaints} (${pct(r.complaintRate)})`);
|
|
463
|
+
return near.length ? { icon: 'YELLOW', text: near.join('; ') } : { icon: 'GREEN', text: 'no brake close' };
|
|
464
|
+
}
|
|
465
|
+
function nextStep(s) {
|
|
466
|
+
const id = s.id;
|
|
467
|
+
switch (s.status) {
|
|
468
|
+
case 'draft': return s.preflight?.ok ? (s.previewed ? `next: after the owner says yes, campaign approve ${id} --note "..." --yes` : `next: campaign preview ${id} --yes`) : 'next: fix the pre-send check errors and run create again';
|
|
469
|
+
case 'approved': return `next: campaign schedule ${id} --at "YYYY-MM-DD HH:MM" --yes`;
|
|
470
|
+
case 'scheduled': return 'next: nothing; it starts at the scheduled time (campaign unschedule to take it back)';
|
|
471
|
+
case 'sending': return 'next: watch; campaign pause is the emergency stop';
|
|
472
|
+
case 'done': return `next: campaign reconcile ${id} (again after 72 hours)`;
|
|
473
|
+
default: return '';
|
|
474
|
+
}
|
|
475
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// 假點擊標記:資安掃描器會在信寄出後立刻把信裡的連結全部點一遍,這些點擊不是人點的。
|
|
2
|
+
// 這裡只放判斷規則(純函式);事件的記錄與寫入屬轉址服務那一側,它拿到點擊清單後呼叫這個函式,
|
|
3
|
+
// 對回傳的點擊在事件的 detail 寫 suspect='scanner'。只標記、不刪除;報表算點擊時排除。
|
|
4
|
+
/**
|
|
5
|
+
* 規則:寄出後 60 秒內、同一封信點了 3 個以上不同連結 → 這封信窗內的所有點擊都標為疑似掃描器。
|
|
6
|
+
* @param sentAt 每封信的寄出時間(毫秒);查不到寄出時間的信不標記。
|
|
7
|
+
* @returns 要標 suspect='scanner' 的事件編號。
|
|
8
|
+
*/
|
|
9
|
+
export function detectScannerClicks(clicks, sentAt, rule = {}) {
|
|
10
|
+
const windowMs = rule.windowMs ?? 60_000;
|
|
11
|
+
const minLinks = rule.minDistinctLinks ?? 3;
|
|
12
|
+
const sent = (m) => (sentAt instanceof Map ? sentAt.get(m) : Object.prototype.hasOwnProperty.call(sentAt, m) ? sentAt[m] : undefined);
|
|
13
|
+
const byMessage = new Map();
|
|
14
|
+
for (const c of clicks) {
|
|
15
|
+
const t0 = sent(c.messageId);
|
|
16
|
+
if (t0 === undefined || c.at < t0 || c.at - t0 > windowMs)
|
|
17
|
+
continue;
|
|
18
|
+
const list = byMessage.get(c.messageId) ?? [];
|
|
19
|
+
list.push(c);
|
|
20
|
+
byMessage.set(c.messageId, list);
|
|
21
|
+
}
|
|
22
|
+
const flagged = new Set();
|
|
23
|
+
for (const list of byMessage.values()) {
|
|
24
|
+
if (new Set(list.map((c) => c.linkIndex)).size >= minLinks)
|
|
25
|
+
for (const c of list)
|
|
26
|
+
flagged.add(c.id);
|
|
27
|
+
}
|
|
28
|
+
return flagged;
|
|
29
|
+
}
|