dsh-postbox 0.0.0-stage → 0.2.2

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/lib/mime.js ADDED
@@ -0,0 +1,381 @@
1
+ // lib/mime.js — 纯 Node MIME 解析与构建(收发两端共用,零依赖)。
2
+ //
3
+ // 解析:RFC 2047 头部解码、multipart 递归、base64/QP 解码、HTML 剥离。
4
+ // 构建:From/To/Cc/Subject/Date/Message-ID + multipart/alternative + 附件,
5
+ // 正文与附件一律 base64,避开换行/编码地雷。
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+
10
+ // ---- RFC 2047 -----------------------------------------------------------
11
+
12
+ /** 常见 charset 别名 → WHATWG 解码标签。
13
+ * gb2312/gbk/cp936 一律走 gb18030(超集,能解前两者;Node 自带完整 ICU)。 */
14
+ const CHARSET_ALIASES = {
15
+ utf8: "utf-8", "utf-8": "utf-8",
16
+ gb2312: "gb18030", gbk: "gb18030", gb18030: "gb18030", cp936: "gb18030", ms936: "gb18030",
17
+ big5: "big5", "big5-hkscs": "big5", cp950: "big5",
18
+ shift_jis: "shift_jis", "shift-jis": "shift_jis", sjis: "shift_jis", cp932: "shift_jis",
19
+ "euc-kr": "euc-kr", euc_kr: "euc-kr", "ks_c_5601-1987": "euc-kr", cp949: "euc-kr",
20
+ "iso-8859-1": "windows-1252", latin1: "windows-1252", "windows-1252": "windows-1252",
21
+ };
22
+
23
+ /** 字节 → 文本,按**声明的 charset** 解;认不出或没声明才退回 utf-8。
24
+ *
25
+ * 为什么必须有这一层:RFC 2047 的编码字里 charset 是权威信息,忽略它就会把 GBK/日文
26
+ * 等字节按 UTF-8 硬解 —— GBK 的 D4 B7 恰好是合法 UTF-8 序列,会解成「Է」,其余字节变
27
+ * U+FFFD,**字节当场不可逆丢失**(2026-10-17 实测:某封中文主题就是这样坏的)。 */
28
+ export function decodeBytesWithCharset(buf, charset) {
29
+ const raw = String(charset ?? "").trim().toLowerCase().replace(/^["']|["']$/g, "");
30
+ const label = CHARSET_ALIASES[raw] ?? raw;
31
+ if (label) {
32
+ try { return stripBom(new TextDecoder(label, { fatal: false }).decode(buf)); } catch { /* 未知标签 → 退回 utf-8 */ }
33
+ }
34
+ return stripBom(buf.toString("utf8"));
35
+ }
36
+
37
+ function decodeB64Word(word) {
38
+ const m = word.match(/^=\?([^?]+)\?([Bb])\?(.*)\?=/);
39
+ if (!m) return word;
40
+ let payload = m[3].replace(/=+$/, "");
41
+ payload += "=".repeat((4 - (payload.length % 4)) % 4);
42
+ try { return decodeBytesWithCharset(Buffer.from(payload, "base64"), m[1]); }
43
+ catch { return word; }
44
+ }
45
+
46
+ function decodeQWord(word) {
47
+ const m = word.match(/^=\?([^?]+)\?([Qq])\?(.*)\?=/);
48
+ if (!m) return word;
49
+ // Q 编码必须先还原成**字节**再解码:旧实现用 String.fromCharCode 拼字符串、再按 utf8
50
+ // 还原,遇到非 UTF-8 字符集必然坏(同上)。这里逐字节处理,和 B 编码同一条出口。
51
+ const bytes = [];
52
+ const s = m[3];
53
+ for (let i = 0; i < s.length; i += 1) {
54
+ const c = s[i];
55
+ if (c === "_") { bytes.push(0x20); continue; } // RFC 2047:下划线代表空格
56
+ if (c === "=" && /^[0-9A-Fa-f]{2}$/.test(s.slice(i + 1, i + 3))) {
57
+ bytes.push(parseInt(s.slice(i + 1, i + 3), 16)); i += 2; continue; // =XX 恰好是一个字节
58
+ }
59
+ bytes.push(c.charCodeAt(0) & 0xff);
60
+ }
61
+ try { return decodeBytesWithCharset(Buffer.from(bytes), m[1]); }
62
+ catch { return word; }
63
+ }
64
+
65
+ /** 头部值里若出现原始 8bit 字节(非 encoded-word:不合规但真实存在,
66
+ * 某些客户端/打印机直接塞 UTF-8 字节),按 UTF-8 重解一次。
67
+ * 重解结果含替换字符说明本来就不是 UTF-8(如 latin1/GBK 原文),保持原样。
68
+ * 纯 ASCII 与 encoded-word 都不含高位字节,不受影响。 */
69
+ function fixRaw8bit(value) {
70
+ if (!/[\u0080-\u00ff]/.test(value)) return value;
71
+ const utf8 = Buffer.from(value, "latin1").toString("utf8");
72
+ return utf8.includes("\ufffd") ? value : utf8;
73
+ }
74
+
75
+ /** 解码一个可能含 =?charset?enc?encoded?= 的头部值(可含多个连续词)。 */
76
+ export function decodeHeaderWord(value) {
77
+ if (!value) return value;
78
+ let result = fixRaw8bit(String(value));
79
+ let guard = 0;
80
+ while (guard++ < 12 && /=\?[^?]+\?[BbQq]\?/.test(result)) {
81
+ result = result.replace(/=\?([^?]+)\?([BbqQ])\?([^?]*)\?=/g, (_m, cs, enc, payload) => {
82
+ const word = `=?${cs}?${enc.toUpperCase()}?${payload}?=`;
83
+ return enc.toUpperCase() === "B" ? decodeB64Word(word) : decodeQWord(word);
84
+ });
85
+ }
86
+ return result.trim();
87
+ }
88
+
89
+ /** 头部块(展开 continuation 后)→ 小写 key 映射,同 key 合并。 */
90
+ export function parseHeaders(raw) {
91
+ const unfolded = raw.split(/\r?\n/).reduce((acc, line) => {
92
+ if (/^[ \t]/.test(line) && acc.length) acc[acc.length - 1] += line.trim();
93
+ else if (line) acc.push(line);
94
+ return acc;
95
+ }, []);
96
+ const headers = {};
97
+ for (const line of unfolded) {
98
+ const idx = line.indexOf(":");
99
+ if (idx === -1) continue;
100
+ const key = line.slice(0, idx).trim().toLowerCase();
101
+ const val = line.slice(idx + 1).trim();
102
+ headers[key] = headers[key] ? `${headers[key]}, ${val}` : val;
103
+ }
104
+ return headers;
105
+ }
106
+
107
+ function boundaryOf(contentType) {
108
+ const m = /;\s*boundary=("?)([^";]+)\1/i.exec(contentType || "");
109
+ return m ? m[2].trim() : null;
110
+ }
111
+
112
+ function splitMultipart(body, boundary) {
113
+ const delim = "--" + boundary;
114
+ const pieces = body.split(delim);
115
+ const parts = [];
116
+ for (let i = 1; i < pieces.length; i++) {
117
+ let chunk = pieces[i];
118
+ if (chunk.startsWith("--")) break; // 终止符
119
+ if (chunk.startsWith("\r\n")) chunk = chunk.slice(2);
120
+ else if (chunk.startsWith("\n")) chunk = chunk.slice(1);
121
+ chunk = chunk.replace(/\r?\n$/, "");
122
+ parts.push(chunk);
123
+ }
124
+ return parts;
125
+ }
126
+
127
+ function transferDecode(body, encoding) {
128
+ switch (String(encoding || "").toLowerCase()) {
129
+ case "base64": {
130
+ let clean = body.replace(/\s+/g, "");
131
+ clean += "=".repeat((4 - (clean.length % 4)) % 4);
132
+ try { return Buffer.from(clean, "base64"); }
133
+ catch { return Buffer.from(body, "latin1"); }
134
+ }
135
+ case "quoted-printable": {
136
+ const s = body.replace(/=\r?\n/g, "");
137
+ const bytes = [];
138
+ for (let i = 0; i < s.length; i++) {
139
+ if (s[i] === "=" && /^[0-9A-Fa-f]{2}$/.test(s.slice(i + 1, i + 3))) {
140
+ bytes.push(parseInt(s.slice(i + 1, i + 3), 16)); i += 2; continue;
141
+ }
142
+ bytes.push(s.charCodeAt(i) & 0xff);
143
+ }
144
+ return Buffer.from(bytes);
145
+ }
146
+ default:
147
+ // body 是 latin1 视图的字符串(每个字符 == 一个原始字节),取回字节必须用
148
+ // latin1。这里若用 utf8 会双重编码:UTF-8 的「你」→ "ä½ " → 再编码成
149
+ // c3a4 c2bd c2a0 → 正文全变乱码(实测踩过)。
150
+ return Buffer.from(body, "latin1");
151
+ }
152
+ }
153
+
154
+ /** 按声明的 charset 解码文本部件;未声明或解码器不支持时退回 utf-8。
155
+ * Node 自带完整 ICU,gbk/gb18030/big5/shift_jis 等都能直接解。
156
+ * M6.6:与头部编码字共用 decodeBytesWithCharset —— 别名只维护一份(gb2312→gb18030 等)。 */
157
+ function decodeTextPart(buf, contentType) {
158
+ const raw = /charset\s*=\s*"?([\w.:-]+)"?/i.exec(contentType || "")?.[1] ?? "utf-8";
159
+ const cs = raw.toLowerCase();
160
+ if (cs === "utf-8" || cs === "utf8" || cs === "us-ascii" || cs === "ascii") return stripBom(buf.toString("utf8"));
161
+ return decodeBytesWithCharset(buf, cs);
162
+ }
163
+
164
+ function stripBom(s) {
165
+ return s.charCodeAt(0) === 0xfeff ? s.slice(1) : s;
166
+ }
167
+
168
+ export function fileNameOf(headerValue) {
169
+ if (!headerValue) return null;
170
+ // RFC 5987: filename*=UTF-8''pct-encoded
171
+ const ext = /filename\*\s*=\s*(?:UTF-8)?'[^']*'([^;]+)/i.exec(headerValue);
172
+ if (ext) {
173
+ try { return decodeURIComponent(ext[1].trim()); } catch { /* fall through */ }
174
+ }
175
+ // RFC 2231/2047: filename="..." 或 filename=(quoted)
176
+ const m = /filename\s*=\s*"([^"]+)"|filename\s*=\s*([^;]+)/i.exec(headerValue);
177
+ if (m) return (m[1] ?? m[2]).trim();
178
+ return null;
179
+ }
180
+
181
+ export function sanitizeName(name) {
182
+ return String(name || "attachment")
183
+ .replace(/[\\/:*?"<>|]/g, "_")
184
+ .replace(/\s+/g, "_")
185
+ .slice(0, 80) || "attachment";
186
+ }
187
+
188
+ /** 递归解析 MIME。
189
+ * 返回 { subject, from, to, date, bodyText, html, attachments: [...] }。
190
+ * 顶层信封字段由调用方从头部块直接提取(见 parseMime 尾部)。 */
191
+ export function parseMime(rawBytes) {
192
+ const text = Buffer.isBuffer(rawBytes) ? rawBytes.toString("latin1") : String(rawBytes);
193
+ const result = { bodyText: "", html: "", attachments: [] };
194
+
195
+ function walk(partRaw) {
196
+ // 头部块结束于「空行」(LF/LF 或 CRLF/CRLF),之后是 body
197
+ let headRaw, body, sepLen;
198
+ const mBlank = partRaw.match(/\r?\n\r?\n/);
199
+ if (mBlank) {
200
+ const idx = partRaw.indexOf(mBlank[0]);
201
+ headRaw = partRaw.slice(0, idx);
202
+ sepLen = mBlank[0].length;
203
+ body = partRaw.slice(idx + sepLen);
204
+ } else {
205
+ headRaw = partRaw;
206
+ body = "";
207
+ }
208
+ const headers = parseHeaders(headRaw);
209
+ const type = (headers["content-type"] || "text/plain").split(";")[0].trim().toLowerCase();
210
+ const cte = (headers["content-transfer-encoding"] || "7bit").toLowerCase();
211
+ const disp = headers["content-disposition"] || "";
212
+
213
+ if (type.startsWith("multipart/")) {
214
+ const boundary = boundaryOf(headers["content-type"]);
215
+ if (boundary) for (const part of splitMultipart(body, boundary)) walk(part);
216
+ return;
217
+ }
218
+
219
+ const buf = transferDecode(body, cte);
220
+ if (type.startsWith("text/html")) {
221
+ const s = decodeTextPart(buf, headers["content-type"]);
222
+ if (!result.html) result.html = s;
223
+ } else if (disp.toLowerCase().includes("attachment") || (disp && !type.startsWith("text/"))) {
224
+ const name = fileNameOf(headers["content-disposition"]) || fileNameOf(headers["content-type"]) || `part_${result.attachments.length + 1}`;
225
+ result.attachments.push({ name, size: buf.length, contentType: type, payload: buf });
226
+ } else if (type.startsWith("text/") || type === "") {
227
+ if (!result.bodyText) result.bodyText = decodeTextPart(buf, headers["content-type"]);
228
+ }
229
+ // 内嵌图片等其他类型 v1 跳过
230
+ }
231
+
232
+ walk(text);
233
+ if (!result.bodyText && result.html) {
234
+ result.bodyText = result.html
235
+ .replace(/<style[\s\S]*?<\/style>/gi, "")
236
+ .replace(/<script[\s\S]*?<\/script>/gi, "")
237
+ .replace(/<br\s*\/?>/gi, "\n")
238
+ .replace(/<\/(p|div|tr|li|h[1-6])>/gi, "\n")
239
+ .replace(/<[^>]+>/g, "")
240
+ .replace(/&nbsp;/g, " ")
241
+ .replace(/&amp;/g, "&")
242
+ .replace(/&lt;/g, "<")
243
+ .replace(/&gt;/g, ">")
244
+ .replace(/&quot;/g, '"')
245
+ .replace(/[ \t]{2,}/g, " ")
246
+ .replace(/\n{3,}/g, "\n\n")
247
+ .trim();
248
+ }
249
+ const head = parseHeaders(text.split(/\r?\n\r?\n/, 1)[0]);
250
+ if (head["subject"]) result.subject = decodeHeaderWord(head["subject"]);
251
+ if (head["from"]) result.from = decodeHeaderWord(head["from"]);
252
+ if (head["to"]) result.to = decodeHeaderWord(head["to"]);
253
+ if (head["date"]) result.date = head["date"];
254
+ // R8(2026-11-30):回复链路需要原始 Message-ID 与引用链(去掉尖括号外的空白)
255
+ if (head["message-id"]) result.messageId = String(head["message-id"]).trim();
256
+ if (head["in-reply-to"]) result.inReplyTo = String(head["in-reply-to"]).trim();
257
+ if (head["references"]) result.references = String(head["references"]).trim();
258
+ return result;
259
+ }
260
+
261
+ /** 单封邮件附件落盘的默认上限:25 MB(2026-11-30,B9)。
262
+ * 为什么要有:B10 那条已说 archive.mode=full 时原始信明文入 sqlite,真机上单账户
263
+ * 已到 119.9 MB;附件再无限落盘,磁盘只增不减、也没有清理入口。上限按「一封邮件的
264
+ * 附件总量」算,不是单个文件 —— 一封带 30 个 1 MB 图的信同样不该整封铺开。 */
265
+ export const MAX_ATTACH_BYTES = 25 * 1024 * 1024;
266
+
267
+ /** 落盘附件:dir 下按 uid 建子目录;同名同大小视为幂等跳过;超上限整封跳过余下附件。
268
+ * B14(2026-11-30):原来用 `dir.replace(/[^/\\]*$/, "") + \`uid_${uid}\`` 拼路径 ——
269
+ * 这等于**删掉最后一段**,于是附件落在 attachDir 的父目录(真机:`<profile>/mailbox/uid_4530`),
270
+ * 而 `<profile>/mailbox/attachments/` 根本没被创建。改用 path.join 直接挂子目录。
271
+ * 返回 [{name, path, size, status}],status: written | skipped | rewritten | too-large。 */
272
+ export function saveAttachments(attachments, dir, uid, { maxBytes = MAX_ATTACH_BYTES } = {}) {
273
+ const targetDir = path.join(String(dir ?? "."), `uid_${uid}`);
274
+ const limit = Number.isFinite(Number(maxBytes)) && Number(maxBytes) > 0 ? Number(maxBytes) : 0;
275
+ fs.mkdirSync(targetDir, { recursive: true });
276
+ const manifest = [];
277
+ let total = 0;
278
+ for (const att of attachments) {
279
+ const name = sanitizeName(att.name);
280
+ const file = path.join(targetDir, name);
281
+ const payload = att.payload ?? Buffer.alloc(0);
282
+ const size = Number(att.size ?? payload.length ?? 0);
283
+ if (limit > 0 && total + size > limit) {
284
+ // 不写盘,但也报出来:用户需要知道"这封信的附件没落地"而不是以为已保存
285
+ manifest.push({ name: att.name, path: file, size, status: "too-large" });
286
+ continue;
287
+ }
288
+ let status;
289
+ if (fs.existsSync(file)) {
290
+ status = fs.statSync(file).size === payload.length ? "skipped" : "rewritten";
291
+ if (status === "rewritten") fs.writeFileSync(file, payload);
292
+ } else {
293
+ fs.writeFileSync(file, payload);
294
+ status = "written";
295
+ }
296
+ total += size;
297
+ manifest.push({ name: att.name, path: file, size: att.size, status });
298
+ }
299
+ return manifest;
300
+ }
301
+
302
+ // ---- 构建出站 MIME -------------------------------------------------------
303
+
304
+ function b64Block(buf) {
305
+ return buf.toString("base64")
306
+ .replace(/.{76}/g, (m) => m + "\r\n").trimEnd();
307
+ }
308
+
309
+ export function genMessageId(email) {
310
+ const rand = Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
311
+ const domain = String(email || "").includes("@") ? String(email).split("@")[1] : "mailbox.local";
312
+ return `<${rand}@${domain}>`;
313
+ }
314
+
315
+ function needsEncode(s) { return /[^\x20-\x7e]/.test(s); }
316
+ function encodeWord(s) {
317
+ return `=?UTF-8?B?${Buffer.from(String(s), "utf8").toString("base64")}?=`;
318
+ }
319
+ /** 非 ASCII 头字段值 → RFC 2047 UTF-8 B 词(Subject/From 等);ASCII 原样。 */
320
+ function headerWord(s) {
321
+ s = String(s ?? "");
322
+ return needsEncode(s) ? `=?UTF-8?B?${Buffer.from(s, "utf8").toString("base64")}?=` : s;
323
+ }
324
+
325
+ /** 构造完整 MIME 邮件字节(Buffer)。
326
+ * params: { from, to[], cc[], bcc[](不进头部), subject, bodyText?, bodyHtml?,
327
+ * attachments?: [{name, contentType?, payload: Buffer}],
328
+ * inReplyTo?: string, references?: string } // R8:回复时喂原始 Message-ID */
329
+ export function buildMessage(params) {
330
+ const { from, to = [], cc = [], bcc = [], subject, bodyText = "", bodyHtml, attachments = [],
331
+ inReplyTo, references } = params;
332
+ void bcc; // bcc 只影响 send() 的 RCPT,不进头部
333
+ const head = [
334
+ `From: ${headerWord(from)}`,
335
+ `To: ${to.map(headerWord).join(", ")}`,
336
+ cc.length ? `Cc: ${cc.map(headerWord).join(", ")}` : null,
337
+ `Subject: ${headerWord(subject)}`,
338
+ `Date: ${new Date().toUTCString()}`,
339
+ `Message-ID: ${genMessageId(from)}`,
340
+ // R8(2026-11-30):这两个头是「同一会话」的唯一凭据。少了它们,对方的 Outlook
341
+ // 会把回信当成新邮件另起一条线程,本地归档也串不起来(只能靠主题猜)。
342
+ inReplyTo ? `In-Reply-To: ${inReplyTo}` : null,
343
+ references ? `References: ${references}` : null,
344
+ "MIME-Version: 1.0",
345
+ ].filter(Boolean).join("\r\n");
346
+
347
+ // 有非空 HTML 或附件 → 统一 multipart;否则最简纯文本消息
348
+ const html = bodyHtml?.trim() ? bodyHtml : undefined;
349
+ if (!html && !attachments.length) {
350
+ return Buffer.from(`${head}\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Block(Buffer.from(bodyText, "utf8"))}\r\n`, "utf8");
351
+ }
352
+
353
+ const boundary = `mbx-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
354
+ const parts = []; // 每个 part 形如 "--boundary\r\n<headers>\r\n\r\n<body>",最后一个终止符统一收尾
355
+
356
+ if (html) {
357
+ const inner = boundary + "-alt";
358
+ const innerParts = [];
359
+ if (bodyText) innerParts.push(
360
+ `--${inner}\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Block(Buffer.from(bodyText, "utf8"))}\r\n`);
361
+ innerParts.push(
362
+ `--${inner}\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Block(Buffer.from(html, "utf8"))}\r\n` +
363
+ `--${inner}--\r\n`);
364
+ parts.push(`--${boundary}\r\nContent-Type: multipart/alternative; boundary="${inner}"\r\n\r\n${innerParts.join("")}`);
365
+ } else {
366
+ parts.push(`--${boundary}\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Block(Buffer.from(bodyText, "utf8"))}`);
367
+ }
368
+
369
+ for (const att of attachments) {
370
+ const rawName = att.name;
371
+ const safeName = sanitizeName(rawName);
372
+ // 非 ASCII 文件名用 RFC 5987 filename*(UTF-8 百分号编码);ASCII 直接引号
373
+ const filenameField = needsEncode(safeName)
374
+ ? `filename*=UTF-8''${encodeURIComponent(safeName)}`
375
+ : `filename="${safeName}"`;
376
+ parts.push(`--${boundary}\r\nContent-Type: ${att.contentType || "application/octet-stream"}\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; ${filenameField}\r\n\r\n${b64Block(Buffer.from(att.payload))}`);
377
+ }
378
+
379
+ const body = parts.join("\r\n") + `\r\n--${boundary}--\r\n`;
380
+ return Buffer.from(`${head}\r\nContent-Type: multipart/mixed; boundary="${boundary}"\r\n\r\n${body}`, "utf8");
381
+ }
package/lib/mutf7.js ADDED
@@ -0,0 +1,54 @@
1
+ // lib/mutf7.js — IMAP modified UTF-7(RFC 3501 §5.1.3)编解码。
2
+ //
3
+ // 为什么需要:IMAP 的邮箱名规范上只能用 ASCII,非 ASCII(中文文件夹名)以
4
+ // modified UTF-7 传输。真实抓包里 Outlook 的「存档」就是 `&W1hoYw-`。
5
+ // * 解码:列表/显示时把 `&W1hoYw-` 还原成「存档」
6
+ // * 编码:把用户输入的中文文件夹名(或解码后的名字)编回 `&W1hoYw-` 再发命令,
7
+ // 否则 SELECT "存档" 会把裸 UTF-8 塞进 quoted string,服务器可能直接 BAD
8
+ //
9
+ // 规则:`&` 开始一段,`-` 结束;段内是 base64(字母表用 `,` 代替 `/`),内容是 UTF-16BE;
10
+ // 字面 `&` 写作 `&-`;段外只能是可打印 ASCII。
11
+
12
+ /** modified UTF-7 → 可读文本。不合法段落原样保留(不抛异常)。 */
13
+ export function decodeMutf7(name) {
14
+ const s = String(name ?? "");
15
+ if (!s.includes("&")) return s;
16
+ return s.replace(/&([^-]*)-/g, (whole, b64) => {
17
+ if (b64 === "") return "&"; // "&-" 表示字面 &
18
+ try {
19
+ const t = b64.replace(/,/g, "/");
20
+ const buf = Buffer.from(t + "=".repeat((4 - (t.length % 4)) % 4), "base64");
21
+ if (buf.length === 0) return whole;
22
+ let out = "";
23
+ for (let i = 0; i + 1 < buf.length; i += 2) out += String.fromCharCode(buf.readUInt16BE(i));
24
+ return out;
25
+ } catch {
26
+ return whole;
27
+ }
28
+ });
29
+ }
30
+
31
+ /** 可读文本 → modified UTF-7。纯可打印 ASCII(不含 &)原样返回,其余段编码。 */
32
+ export function encodeMutf7(name) {
33
+ const s = String(name ?? "");
34
+ if (!/[^\u0020-\u007e]|&/.test(s)) return s;
35
+ let out = "";
36
+ let units = [];
37
+ const flush = () => {
38
+ if (!units.length) return;
39
+ out += "&" + Buffer.from(units).toString("base64").replace(/\//g, ",").replace(/=+$/, "") + "-";
40
+ units = [];
41
+ };
42
+ for (const ch of s) {
43
+ if (ch === "&") { flush(); out += "&-"; continue; }
44
+ const cp = ch.codePointAt(0);
45
+ if (cp >= 0x20 && cp <= 0x7e) { flush(); out += ch; continue; }
46
+ // 非 ASCII:按 UTF-16BE 追加(非 BMP 字符是代理对,ch.length === 2)
47
+ for (let i = 0; i < ch.length; i++) {
48
+ const u = ch.charCodeAt(i);
49
+ units.push((u >> 8) & 0xff, u & 0xff);
50
+ }
51
+ }
52
+ flush();
53
+ return out;
54
+ }