@infaris/calendar-cli 0.9.0 → 0.12.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 +181 -13
- package/dist/api.js +147 -26
- package/dist/auth.js +24 -1
- package/dist/crm-api.js +5 -1
- package/dist/crm-index.js +4 -2
- package/dist/crm-quote.js +174 -0
- package/dist/index.js +536 -23
- package/dist/mail-draft.js +357 -0
- package/dist/mail-send.js +97 -0
- package/dist/voice.js +321 -0
- package/package.json +1 -1
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, isAbsolute, resolve } from "node:path";
|
|
3
|
+
import { guessMimeType, MAX_DRAFT_BYTES, } from "./api.js";
|
|
4
|
+
const REMOTE_SRC = /^(?:https?:|data:|cid:|\/\/)/i;
|
|
5
|
+
function dataUrl(path, read) {
|
|
6
|
+
let content;
|
|
7
|
+
try {
|
|
8
|
+
content = read(path);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
throw new Error(`Afbeelding niet gevonden: ${path}`);
|
|
12
|
+
}
|
|
13
|
+
const mime = guessMimeType(path);
|
|
14
|
+
if (!mime.startsWith("image/")) {
|
|
15
|
+
throw new Error(`Geen afbeelding (png, jpg, gif, webp): ${path}`);
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
url: `data:${mime};base64,${content.toString("base64")}`,
|
|
19
|
+
bytes: content.byteLength,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Vervangt elke `<img src>` die naar een lokaal bestand wijst (relatief aan
|
|
24
|
+
* `baseDir`, absoluut of `file://`) door een `data:`-URL. Externe URL's,
|
|
25
|
+
* `data:` en `cid:` blijven staan.
|
|
26
|
+
*/
|
|
27
|
+
export function inlineLocalImages(html, baseDir, read = readFileSync) {
|
|
28
|
+
const images = [];
|
|
29
|
+
const out = html.replace(/(<img\b[^>]*?\bsrc\s*=\s*)(["'])([^"']+)\2/gi, (match, pre, quote, src) => {
|
|
30
|
+
const raw = src.trim();
|
|
31
|
+
if (REMOTE_SRC.test(raw))
|
|
32
|
+
return match;
|
|
33
|
+
const local = decodeURI(raw.replace(/^file:\/\//i, ""));
|
|
34
|
+
const path = isAbsolute(local) ? local : resolve(baseDir, local);
|
|
35
|
+
const { url, bytes } = dataUrl(path, read);
|
|
36
|
+
images.push({ path, bytes });
|
|
37
|
+
return `${pre}${quote}${url}${quote}`;
|
|
38
|
+
});
|
|
39
|
+
return { html: out, images };
|
|
40
|
+
}
|
|
41
|
+
function escapeAttr(value) {
|
|
42
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Een afbeelding als eigen alinea onder de tekst (`--image`), op volle
|
|
46
|
+
* breedte begrensd zodat een grote screenshot de mail niet oprekt.
|
|
47
|
+
*/
|
|
48
|
+
export function imageParagraph(path, read = readFileSync) {
|
|
49
|
+
const { url, bytes } = dataUrl(path, read);
|
|
50
|
+
const alt = escapeAttr(basename(path).replace(/\.[^.]+$/, ""));
|
|
51
|
+
return {
|
|
52
|
+
html: `<p><img src="${url}" alt="${alt}" style="max-width:100%;height:auto"></p>`,
|
|
53
|
+
image: { path, bytes },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Formaat uit `--format`, anders uit de extensie van `--body-file`; standaard HTML. */
|
|
57
|
+
export function bodyFormat(explicit, file) {
|
|
58
|
+
if (explicit) {
|
|
59
|
+
const value = explicit.toLowerCase();
|
|
60
|
+
if (value === "md")
|
|
61
|
+
return "markdown";
|
|
62
|
+
if (value === "html" || value === "markdown" || value === "text") {
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
throw new Error(`Unknown --format ${explicit}; use html, markdown or text`);
|
|
66
|
+
}
|
|
67
|
+
if (file && /\.(md|markdown)$/i.test(file))
|
|
68
|
+
return "markdown";
|
|
69
|
+
if (file && /\.txt$/i.test(file))
|
|
70
|
+
return "text";
|
|
71
|
+
return "html";
|
|
72
|
+
}
|
|
73
|
+
function escapeHtml(value) {
|
|
74
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
75
|
+
}
|
|
76
|
+
/** Platte tekst: lege regel = nieuwe alinea, enkele regel = `<br>`. */
|
|
77
|
+
export function textToHtml(text) {
|
|
78
|
+
return text
|
|
79
|
+
.replace(/\r/g, "")
|
|
80
|
+
.trim()
|
|
81
|
+
.split(/\n{2,}/)
|
|
82
|
+
.map((p) => `<p>${escapeHtml(p).replace(/\n/g, "<br>")}</p>`)
|
|
83
|
+
.join("");
|
|
84
|
+
}
|
|
85
|
+
function inlineMarkdown(text) {
|
|
86
|
+
return escapeHtml(text)
|
|
87
|
+
.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (_m, alt, src) => `<img src="${src}" alt="${alt.replace(/"/g, """)}" style="max-width:100%;height:auto">`)
|
|
88
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2">$1</a>')
|
|
89
|
+
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
|
90
|
+
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
91
|
+
.replace(/__([^_]+)__/g, "<strong>$1</strong>")
|
|
92
|
+
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1<em>$2</em>")
|
|
93
|
+
.replace(/(^|[^\w])_([^_\s][^_]*)_(?=[^\w]|$)/g, "$1<em>$2</em>");
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Het stukje Markdown dat in een mail past: alinea's, kopjes, vet/cursief,
|
|
97
|
+
* links, afbeeldingen (``, daarna inline), lijsten, citaten en
|
|
98
|
+
* code. Geen tabellen of HTML-passthrough: wie dat nodig heeft schrijft HTML.
|
|
99
|
+
*/
|
|
100
|
+
export function markdownToHtml(markdown) {
|
|
101
|
+
const blocks = markdown.replace(/\r/g, "").trim().split(/\n{2,}/);
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const block of blocks) {
|
|
104
|
+
const lines = block.split("\n");
|
|
105
|
+
const heading = block.match(/^(#{1,3})\s+(.+)$/);
|
|
106
|
+
if (heading && lines.length === 1) {
|
|
107
|
+
const level = (heading[1] ?? "#").length + 1; // # → h2: h1 is te groot in een mail
|
|
108
|
+
out.push(`<h${level}>${inlineMarkdown(heading[2] ?? "")}</h${level}>`);
|
|
109
|
+
}
|
|
110
|
+
else if (lines.every((l) => /^\s*[-*+]\s+/.test(l))) {
|
|
111
|
+
out.push(`<ul>${lines.map((l) => `<li>${inlineMarkdown(l.replace(/^\s*[-*+]\s+/, ""))}</li>`).join("")}</ul>`);
|
|
112
|
+
}
|
|
113
|
+
else if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l))) {
|
|
114
|
+
out.push(`<ol>${lines.map((l) => `<li>${inlineMarkdown(l.replace(/^\s*\d+[.)]\s+/, ""))}</li>`).join("")}</ol>`);
|
|
115
|
+
}
|
|
116
|
+
else if (lines.every((l) => l.startsWith(">"))) {
|
|
117
|
+
out.push(`<blockquote>${markdownToHtml(lines.map((l) => l.replace(/^>\s?/, "")).join("\n"))}</blockquote>`);
|
|
118
|
+
}
|
|
119
|
+
else if (/^```/.test(block)) {
|
|
120
|
+
const code = lines.slice(1, lines.at(-1)?.startsWith("```") ? -1 : undefined);
|
|
121
|
+
out.push(`<pre><code>${escapeHtml(code.join("\n"))}</code></pre>`);
|
|
122
|
+
}
|
|
123
|
+
else if (/^(-{3,}|\*{3,})$/.test(block.trim())) {
|
|
124
|
+
out.push("<hr>");
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
out.push(`<p>${lines.map(inlineMarkdown).join("<br>")}</p>`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return out.join("");
|
|
131
|
+
}
|
|
132
|
+
/** Zet een body in het gekozen formaat om naar HTML. */
|
|
133
|
+
export function bodyToHtml(body, format) {
|
|
134
|
+
if (format === "markdown")
|
|
135
|
+
return markdownToHtml(body);
|
|
136
|
+
if (format === "text")
|
|
137
|
+
return textToHtml(body);
|
|
138
|
+
return body;
|
|
139
|
+
}
|
|
140
|
+
/** Per extern plaatje; groter is geen mailplaatje meer. */
|
|
141
|
+
const MAX_REMOTE_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
142
|
+
const REMOTE_TIMEOUT_MS = 15_000;
|
|
143
|
+
/**
|
|
144
|
+
* Haalt `<img src="https://...">` op en zet ze inline. Mailprogramma's
|
|
145
|
+
* blokkeren externe afbeeldingen standaard ("Afbeeldingen weergeven"), dus een
|
|
146
|
+
* plaatje van een website komt anders bij de ontvanger als leeg vak aan.
|
|
147
|
+
* Draait op de eigen machine (de CLI), niet op de server: zo kan een concept
|
|
148
|
+
* de Calendar-server geen interne adressen laten opvragen. Een plaatje dat
|
|
149
|
+
* niet lukt blijft als externe URL staan, met een waarschuwing.
|
|
150
|
+
*/
|
|
151
|
+
export async function inlineRemoteImages(html, fetchImpl = fetch) {
|
|
152
|
+
const images = [];
|
|
153
|
+
const warnings = [];
|
|
154
|
+
const pattern = /(<img\b[^>]*?\bsrc\s*=\s*)(["'])(https?:\/\/[^"']+)\2/gi;
|
|
155
|
+
const urls = [...new Set([...html.matchAll(pattern)].map((m) => m[3]))];
|
|
156
|
+
const inlined = new Map();
|
|
157
|
+
for (const raw of urls) {
|
|
158
|
+
const url = raw.replace(/&/g, "&");
|
|
159
|
+
try {
|
|
160
|
+
const res = await fetchImpl(url, {
|
|
161
|
+
signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS),
|
|
162
|
+
redirect: "follow",
|
|
163
|
+
});
|
|
164
|
+
if (!res.ok)
|
|
165
|
+
throw new Error(`HTTP ${res.status}`);
|
|
166
|
+
const mime = (res.headers.get("content-type") ?? "").split(";")[0].trim();
|
|
167
|
+
if (!/^image\/(png|jpe?g|gif|webp)$/i.test(mime)) {
|
|
168
|
+
throw new Error(`geen png/jpg/gif/webp (${mime || "onbekend"})`);
|
|
169
|
+
}
|
|
170
|
+
const content = Buffer.from(await res.arrayBuffer());
|
|
171
|
+
if (content.byteLength > MAX_REMOTE_IMAGE_BYTES) {
|
|
172
|
+
throw new Error("groter dan 5 MB");
|
|
173
|
+
}
|
|
174
|
+
inlined.set(raw, `data:${mime};base64,${content.toString("base64")}`);
|
|
175
|
+
images.push({ path: url, bytes: content.byteLength });
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
warnings.push(`Extern plaatje blijft een link (${err instanceof Error ? err.message : String(err)}): ${url}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
html: html.replace(pattern, (match, pre, quote, src) => {
|
|
183
|
+
const data = inlined.get(src);
|
|
184
|
+
return data ? `${pre}${quote}${data}${quote}` : match;
|
|
185
|
+
}),
|
|
186
|
+
images,
|
|
187
|
+
warnings,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function addressList(value) {
|
|
191
|
+
if (value === undefined)
|
|
192
|
+
return undefined;
|
|
193
|
+
return (Array.isArray(value) ? value : [value])
|
|
194
|
+
.flatMap((v) => v.split(/[,;]/))
|
|
195
|
+
.map((v) => v.trim())
|
|
196
|
+
.filter(Boolean);
|
|
197
|
+
}
|
|
198
|
+
function positiveUid(value, field) {
|
|
199
|
+
if (value === undefined || value === null)
|
|
200
|
+
return undefined;
|
|
201
|
+
const uid = Number(value);
|
|
202
|
+
if (!Number.isInteger(uid) || uid <= 0) {
|
|
203
|
+
throw new Error(`${field} must be a positive message UID`);
|
|
204
|
+
}
|
|
205
|
+
return uid;
|
|
206
|
+
}
|
|
207
|
+
/** Leest body, plaatjes en bijlagen en maakt de request voor `/api/mail/drafts`. */
|
|
208
|
+
export async function buildDraft(spec, baseDir, deps = {}) {
|
|
209
|
+
const read = deps.read ?? readFileSync;
|
|
210
|
+
const reply = positiveUid(spec.reply, "reply");
|
|
211
|
+
const replyAll = positiveUid(spec.replyAll, "replyAll");
|
|
212
|
+
const forward = positiveUid(spec.forward, "forward");
|
|
213
|
+
if ([reply, replyAll, forward].filter(Boolean).length > 1) {
|
|
214
|
+
throw new Error("Use only one of reply, replyAll or forward");
|
|
215
|
+
}
|
|
216
|
+
const edit = positiveUid(spec.edit, "edit");
|
|
217
|
+
if (edit && (reply || replyAll || forward || spec.replace !== undefined)) {
|
|
218
|
+
throw new Error("edit does not combine with reply, replyAll, forward or replace");
|
|
219
|
+
}
|
|
220
|
+
// Bij edit blijft de tekst staan tenzij je nieuwe tekst of plaatjes meegeeft.
|
|
221
|
+
const newText = spec.body !== undefined || spec.bodyFile !== undefined || (spec.images?.length ?? 0) > 0;
|
|
222
|
+
let source = spec.body ?? "";
|
|
223
|
+
let bodyDir = baseDir;
|
|
224
|
+
if (spec.bodyFile === "-") {
|
|
225
|
+
source = (deps.stdin ?? (() => readFileSync(0, "utf8")))();
|
|
226
|
+
}
|
|
227
|
+
else if (spec.bodyFile) {
|
|
228
|
+
const path = resolve(baseDir, spec.bodyFile);
|
|
229
|
+
try {
|
|
230
|
+
source = read(path).toString("utf8");
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
throw new Error(`Body file not found: ${path}`);
|
|
234
|
+
}
|
|
235
|
+
bodyDir = dirname(path);
|
|
236
|
+
}
|
|
237
|
+
const local = inlineLocalImages(bodyToHtml(source, bodyFormat(spec.format, spec.bodyFile)), bodyDir, read);
|
|
238
|
+
let html = local.html;
|
|
239
|
+
const images = [...local.images];
|
|
240
|
+
const warnings = [];
|
|
241
|
+
if (spec.inlineRemote !== false) {
|
|
242
|
+
const remote = await inlineRemoteImages(html, deps.fetch);
|
|
243
|
+
html = remote.html;
|
|
244
|
+
images.push(...remote.images);
|
|
245
|
+
warnings.push(...remote.warnings);
|
|
246
|
+
}
|
|
247
|
+
for (const path of spec.images ?? []) {
|
|
248
|
+
const block = imageParagraph(resolve(baseDir, path), read);
|
|
249
|
+
html += block.html;
|
|
250
|
+
images.push(block.image);
|
|
251
|
+
}
|
|
252
|
+
const attachments = (spec.attach ?? []).map((path) => {
|
|
253
|
+
const full = resolve(baseDir, path);
|
|
254
|
+
let content;
|
|
255
|
+
try {
|
|
256
|
+
content = read(full);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
throw new Error(`Attachment not found: ${full}`);
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
filename: basename(full) || "bijlage",
|
|
263
|
+
contentBase64: content.toString("base64"),
|
|
264
|
+
contentType: guessMimeType(full),
|
|
265
|
+
bytes: content.byteLength,
|
|
266
|
+
};
|
|
267
|
+
});
|
|
268
|
+
const totalBytes = attachments.reduce((n, a) => n + a.bytes, 0) +
|
|
269
|
+
images.reduce((n, image) => n + image.bytes, 0);
|
|
270
|
+
if (totalBytes > MAX_DRAFT_BYTES) {
|
|
271
|
+
throw new Error(`Images and attachments total ${(totalBytes / 1024 / 1024).toFixed(1)} MB; the limit is 20 MB`);
|
|
272
|
+
}
|
|
273
|
+
const ref = { folder: spec.folder ?? "INBOX", mailboxId: spec.sourceMailbox };
|
|
274
|
+
const input = {
|
|
275
|
+
to: addressList(spec.to),
|
|
276
|
+
cc: addressList(spec.cc),
|
|
277
|
+
bcc: addressList(spec.bcc),
|
|
278
|
+
subject: spec.subject,
|
|
279
|
+
html: edit && !newText ? undefined : html,
|
|
280
|
+
fromAddress: spec.from,
|
|
281
|
+
signature: spec.signature ?? true,
|
|
282
|
+
optimizeImages: spec.optimizeImages ?? true,
|
|
283
|
+
attachments: attachments.map(({ bytes: _bytes, ...a }) => a),
|
|
284
|
+
replyTo: reply || replyAll
|
|
285
|
+
? { ...ref, uid: (reply ?? replyAll), all: Boolean(replyAll) }
|
|
286
|
+
: undefined,
|
|
287
|
+
forward: forward
|
|
288
|
+
? { ...ref, uid: forward, attachments: spec.forwardAttachments ?? true }
|
|
289
|
+
: undefined,
|
|
290
|
+
replaceUid: positiveUid(spec.replace, "replace"),
|
|
291
|
+
editUid: edit,
|
|
292
|
+
mailbox: spec.mailbox,
|
|
293
|
+
dropAttachments: spec.dropAttachments || undefined,
|
|
294
|
+
note: spec.note,
|
|
295
|
+
};
|
|
296
|
+
if (!input.to?.length && !input.replyTo && !edit) {
|
|
297
|
+
warnings.push("No recipient: the draft is saved without To");
|
|
298
|
+
}
|
|
299
|
+
return { input, html, images, totalBytes, warnings };
|
|
300
|
+
}
|
|
301
|
+
/** Wat `--dry-run` toont: alles behalve de (grote) inhoud zelf. */
|
|
302
|
+
export function draftSummary(built) {
|
|
303
|
+
return {
|
|
304
|
+
...built.input,
|
|
305
|
+
html: undefined,
|
|
306
|
+
bodyChars: built.html.length,
|
|
307
|
+
images: built.images.map((i) => ({ path: i.path, size: i.bytes })),
|
|
308
|
+
attachments: (built.input.attachments ?? []).map((a) => ({
|
|
309
|
+
filename: a.filename,
|
|
310
|
+
contentType: a.contentType,
|
|
311
|
+
size: Math.floor((a.contentBase64.length * 3) / 4),
|
|
312
|
+
})),
|
|
313
|
+
totalBytes: built.totalBytes,
|
|
314
|
+
warnings: built.warnings.length ? built.warnings : undefined,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
/** Losstaande HTML-pagina om de body met plaatjes te bekijken. */
|
|
318
|
+
export function previewPage(built) {
|
|
319
|
+
const title = (built.input.subject ?? "Concept").replace(/</g, "<");
|
|
320
|
+
const signature = built.input.signature
|
|
321
|
+
? "[standaardhandtekening komt hier]"
|
|
322
|
+
: "[geen handtekening]";
|
|
323
|
+
return (`<!doctype html><meta charset="utf-8"><title>${title}</title>` +
|
|
324
|
+
`<body style="font-family:Arial,sans-serif;font-size:14px;max-width:720px;margin:24px auto">${built.html}` +
|
|
325
|
+
`<p style="color:#888;border-top:1px solid #ddd;padding-top:8px">${signature}</p></body>`);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Sleutel waarmee een concept in een `--replace-map` wordt teruggevonden: het
|
|
329
|
+
* eerste Aan-adres (kleine letters), anders het onderwerp. Zo kun je een batch
|
|
330
|
+
* na het aanpassen van de tekst opnieuw draaien en vervangt elk concept zijn
|
|
331
|
+
* voorganger in plaats van ernaast te komen staan.
|
|
332
|
+
*/
|
|
333
|
+
export function replaceKey(input) {
|
|
334
|
+
return input.to?.[0]?.toLowerCase() || input.subject?.trim().toLowerCase() || null;
|
|
335
|
+
}
|
|
336
|
+
/** Zet `replaceUid` uit de map, tenzij het concept er zelf al een heeft. */
|
|
337
|
+
export function applyReplaceMap(input, map) {
|
|
338
|
+
if (input.replaceUid)
|
|
339
|
+
return undefined;
|
|
340
|
+
const key = replaceKey(input);
|
|
341
|
+
const uid = key ? map[key] : undefined;
|
|
342
|
+
if (uid)
|
|
343
|
+
input.replaceUid = uid;
|
|
344
|
+
return uid;
|
|
345
|
+
}
|
|
346
|
+
/** Leest een `--replace-map`-bestand: `{ "kees@example.com": 4812, ... }`. */
|
|
347
|
+
export function parseReplaceMap(json) {
|
|
348
|
+
const value = JSON.parse(json);
|
|
349
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
350
|
+
throw new Error("A replace map is a JSON object of recipient (or subject) to draft UID");
|
|
351
|
+
}
|
|
352
|
+
const map = {};
|
|
353
|
+
for (const [key, uid] of Object.entries(value)) {
|
|
354
|
+
map[key.toLowerCase()] = positiveUid(uid, `replace map entry "${key}"`);
|
|
355
|
+
}
|
|
356
|
+
return map;
|
|
357
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logica rond `mail send`: wie er in een batch zit, hoe snel er verstuurd
|
|
3
|
+
* wordt en wat er gebeurt als er één mislukt. Zonder netwerk of klok, zodat de
|
|
4
|
+
* veiligheidsregels te testen zijn.
|
|
5
|
+
*/
|
|
6
|
+
/** Meer dan dit gaat nooit in één aanroep de deur uit. */
|
|
7
|
+
export const MAX_SEND_PER_RUN = 100;
|
|
8
|
+
/** Pauze tussen twee verzendingen van een batch, in seconden. */
|
|
9
|
+
export const DEFAULT_SEND_DELAY_SECONDS = 10;
|
|
10
|
+
/** "12,13 14" of ["12", "13,14"] → [12, 13, 14], zonder dubbelen. */
|
|
11
|
+
export function parseUidList(values) {
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const raw of values.flatMap((v) => v.split(/[\s,;]+/)).filter(Boolean)) {
|
|
14
|
+
const uid = Number(raw);
|
|
15
|
+
if (!Number.isInteger(uid) || uid <= 0) {
|
|
16
|
+
throw new Error(`"${raw}" is not a message UID`);
|
|
17
|
+
}
|
|
18
|
+
if (!out.includes(uid))
|
|
19
|
+
out.push(uid);
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
export function parseDelay(value, count) {
|
|
24
|
+
if (value === undefined)
|
|
25
|
+
return count > 1 ? DEFAULT_SEND_DELAY_SECONDS : 0;
|
|
26
|
+
const seconds = Number(value);
|
|
27
|
+
if (!Number.isFinite(seconds) || seconds < 0 || seconds > 3600) {
|
|
28
|
+
throw new Error("--delay must be between 0 and 3600 seconds");
|
|
29
|
+
}
|
|
30
|
+
return seconds;
|
|
31
|
+
}
|
|
32
|
+
export function parseMax(value) {
|
|
33
|
+
if (value === undefined)
|
|
34
|
+
return MAX_SEND_PER_RUN;
|
|
35
|
+
const max = Number(value);
|
|
36
|
+
if (!Number.isInteger(max) || max < 1) {
|
|
37
|
+
throw new Error("--max must be a positive whole number");
|
|
38
|
+
}
|
|
39
|
+
if (max > MAX_SEND_PER_RUN) {
|
|
40
|
+
throw new Error(`--max cannot be more than ${MAX_SEND_PER_RUN} per run`);
|
|
41
|
+
}
|
|
42
|
+
return max;
|
|
43
|
+
}
|
|
44
|
+
/** Eén regel per concept voor `--dry-run` en de controle vóór verzenden. */
|
|
45
|
+
export function describeSend(result) {
|
|
46
|
+
const to = [...result.to, ...result.cc.map((a) => `cc:${a}`), ...result.bcc.map((a) => `bcc:${a}`)];
|
|
47
|
+
const flags = [
|
|
48
|
+
result.attachments.length ? `${result.attachments.length} file(s)` : "",
|
|
49
|
+
result.inlineImages ? `${result.inlineImages} inline image(s)` : "",
|
|
50
|
+
`${result.signatureCount} signature(s)`,
|
|
51
|
+
].filter(Boolean);
|
|
52
|
+
const state = result.state === "already-sent"
|
|
53
|
+
? " ALREADY SENT (skipped)"
|
|
54
|
+
: result.state === "blocked"
|
|
55
|
+
? ` BLOCKED: ${result.problems.join("; ")}`
|
|
56
|
+
: "";
|
|
57
|
+
return `${String(result.uid).padStart(6)} ${result.from ?? "-"} -> ${to.join(", ") || "-"} "${result.subject}" [${flags.join(", ")}]${state}`;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Verstuurt de concepten één voor één met `delaySeconds` ertussen en stopt bij
|
|
61
|
+
* de eerste fout: een volgende verzending na een onduidelijke uitkomst is
|
|
62
|
+
* precies wat dubbele mail veroorzaakt. `isUnknown` herkent de fout waarbij
|
|
63
|
+
* onbekend is of de mail is weggegaan.
|
|
64
|
+
*/
|
|
65
|
+
export async function sendBatch(uids, deps, delaySeconds) {
|
|
66
|
+
const outcome = { sent: [], alreadySent: [], failed: null, notAttempted: [] };
|
|
67
|
+
let paused = false;
|
|
68
|
+
for (const [index, uid] of uids.entries()) {
|
|
69
|
+
// Alleen wachten als de vorige echt verstuurd is.
|
|
70
|
+
if (paused && delaySeconds > 0) {
|
|
71
|
+
deps.onWait?.(delaySeconds);
|
|
72
|
+
await deps.sleep(delaySeconds * 1000);
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const result = await deps.send(uid);
|
|
76
|
+
if (result.state === "sent") {
|
|
77
|
+
outcome.sent.push(result);
|
|
78
|
+
paused = true;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
outcome.alreadySent.push(result);
|
|
82
|
+
paused = false;
|
|
83
|
+
}
|
|
84
|
+
deps.onSent?.(result, index);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
outcome.failed = {
|
|
88
|
+
uid,
|
|
89
|
+
error: error instanceof Error ? error.message : String(error),
|
|
90
|
+
unknown: deps.isUnknown(error),
|
|
91
|
+
};
|
|
92
|
+
outcome.notAttempted = uids.slice(index + 1);
|
|
93
|
+
return outcome;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return outcome;
|
|
97
|
+
}
|