@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
|
@@ -0,0 +1,637 @@
|
|
|
1
|
+
// 產信第一步:把 markdown 原稿解析成「區塊+行內」結構。純函式,不碰網路,不 import cloudflare:*。
|
|
2
|
+
// 只支援信件排得出來的語法;不認得的東西一律記成 problem(檢查會擋下),絕不默默吞掉或亂猜。
|
|
3
|
+
const clip = (s, n = 60) => (s.length > n ? `${s.slice(0, n)}…` : s).replace(/\s+/g, ' ');
|
|
4
|
+
/** 嵌入類 HTML(互動圖表、影片):信裡放不了,換成「到網站看」的連結卡。 */
|
|
5
|
+
const EMBED_TAG = /^\s*<\s*(iframe|video|audio|embed|object|canvas)\b/i;
|
|
6
|
+
const ANY_TAG = /<\/?[a-zA-Z][^>]*>/;
|
|
7
|
+
const BLOCK_HTML = /^\s*<\/?[a-zA-Z!]/;
|
|
8
|
+
/** 行內標籤開頭的行不是 HTML 區塊,當一般段落(a、b、strong、i、em、br)。 */
|
|
9
|
+
const INLINE_START = /^\s*<\s*(a|b|strong|i|em|br)\b|^\s*<https?:\/\//i;
|
|
10
|
+
/** 原稿裡寫的 \{ 先換成這個私用字元,輸出時才變成真的「{」,避免被當成佔位。 */
|
|
11
|
+
export const LBRACE = '\uE000';
|
|
12
|
+
const protectBraces = (v) => v.replace(/\{\{/g, LBRACE + LBRACE);
|
|
13
|
+
const NAMED = { nbsp: '\u00a0', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
14
|
+
/** 原稿文字裡的 HTML 實體( & ' …)還原成字元;輸出時再統一跳脫一次。 */
|
|
15
|
+
export function decodeEntities(t) {
|
|
16
|
+
return t.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]+);/gi, (m, e) => {
|
|
17
|
+
if (e[0] === '#') {
|
|
18
|
+
const n = e[1].toLowerCase() === 'x' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
19
|
+
return n > 0 && n < 0x110000 && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : m;
|
|
20
|
+
}
|
|
21
|
+
return NAMED[e.toLowerCase()] ?? m;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** 常見的 HTML 標籤名;不在這張表裡的「<…>」多半只是文字(例如 <Research.example>)。 */
|
|
25
|
+
const HTML_TAG_NAMES = new Set('a abbr b blockquote body br button canvas center code dd del details div dl dt em embed figure font footer form h1 h2 h3 h4 h5 h6 head header hr html i iframe img input ins kbd label li link main mark meta nav object ol p picture pre q s samp script section small source span strike strong style sub summary sup svg table tbody td tfoot th thead title tr u ul var video audio'.split(' '));
|
|
26
|
+
function tagProblem(tag, inline) {
|
|
27
|
+
const name = tag.match(/^<\/?\s*([a-zA-Z][\w-]*)/)?.[1]?.toLowerCase() ?? '';
|
|
28
|
+
const where = clip(tag);
|
|
29
|
+
const wellFormed = /^<\/?[a-zA-Z][\w-]*(?:\s[^>]*)?\/?>$/.test(tag.trim()); // </p/100110> 這種名字像標籤、寫法不是標籤的不算
|
|
30
|
+
if (HTML_TAG_NAMES.has(name) && wellFormed)
|
|
31
|
+
return { message: inline ? '原稿有信件排不出來的行內 HTML 標籤' : '原稿有信件排不出來的 HTML 區塊', where };
|
|
32
|
+
return { message: '原稿有看起來像 HTML 標籤的文字(角括號包著的字),引擎會當成標籤而排不出來;如果它不是標籤,請改寫(拿掉角括號,或用反引號包起來)', where };
|
|
33
|
+
}
|
|
34
|
+
const URL_RE = /https?:\/\/[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]+/g;
|
|
35
|
+
function splitFrontmatter(src) {
|
|
36
|
+
const text = src.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
|
|
37
|
+
const m = text.match(/^---\n([\s\S]*?)\n---[ \t]*(?:\n|$)/);
|
|
38
|
+
if (!m)
|
|
39
|
+
return { body: text, fm: {} };
|
|
40
|
+
const fm = {};
|
|
41
|
+
for (const line of m[1].split('\n')) {
|
|
42
|
+
const kv = line.match(/^([A-Za-z_][\w-]*):[ \t]*(.*)$/);
|
|
43
|
+
if (!kv)
|
|
44
|
+
continue;
|
|
45
|
+
let v = kv[2].trim();
|
|
46
|
+
if (v === '' || v.startsWith('[') || v.startsWith('{') || v === '|' || v === '>')
|
|
47
|
+
continue; // 清單/巢狀/多行不收
|
|
48
|
+
if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) || (v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {
|
|
49
|
+
const q = v[0];
|
|
50
|
+
v = v.slice(1, -1);
|
|
51
|
+
v = q === '"' ? v.replace(/\\(["\\])/g, '$1') : v.replace(/''/g, "'");
|
|
52
|
+
}
|
|
53
|
+
fm[kv[1]] = v;
|
|
54
|
+
}
|
|
55
|
+
return { body: text.slice(m[0].length), fm };
|
|
56
|
+
}
|
|
57
|
+
// ───────────── 行內 ─────────────
|
|
58
|
+
/** 從 s[start](必須是 '(')讀一個括號平衡的網址,回傳 [網址, 下一個位置];讀不到回 null。 */
|
|
59
|
+
function readParenUrl(s, start) {
|
|
60
|
+
if (s[start] !== '(')
|
|
61
|
+
return null;
|
|
62
|
+
let depth = 0;
|
|
63
|
+
let i = start;
|
|
64
|
+
for (; i < s.length; i++) {
|
|
65
|
+
const c = s[i];
|
|
66
|
+
if (c === '\n')
|
|
67
|
+
return null;
|
|
68
|
+
if (c === '(')
|
|
69
|
+
depth++;
|
|
70
|
+
else if (c === ')') {
|
|
71
|
+
depth--;
|
|
72
|
+
if (depth === 0)
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (depth !== 0)
|
|
77
|
+
return null;
|
|
78
|
+
const inner = s.slice(start + 1, i).trim();
|
|
79
|
+
// 去掉可選的 "title"
|
|
80
|
+
const m = inner.match(/^(\S+)(?:\s+(?:"[^"]*"|'[^']*'))?$/);
|
|
81
|
+
if (!m)
|
|
82
|
+
return null;
|
|
83
|
+
let url = m[1];
|
|
84
|
+
if (url.startsWith('<') && url.endsWith('>'))
|
|
85
|
+
url = url.slice(1, -1);
|
|
86
|
+
return [url, i + 1];
|
|
87
|
+
}
|
|
88
|
+
/** 從 s[start](必須是 '[')找對應的 ']'(可巢狀),回傳位置。 */
|
|
89
|
+
function matchBracket(s, start) {
|
|
90
|
+
let depth = 0;
|
|
91
|
+
for (let i = start; i < s.length; i++) {
|
|
92
|
+
if (s[i] === '\\') {
|
|
93
|
+
i++;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (s[i] === '[')
|
|
97
|
+
depth++;
|
|
98
|
+
else if (s[i] === ']') {
|
|
99
|
+
depth--;
|
|
100
|
+
if (depth === 0)
|
|
101
|
+
return i;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return -1;
|
|
105
|
+
}
|
|
106
|
+
function trimUrlTail(u) {
|
|
107
|
+
// 網址尾巴的標點不算網址
|
|
108
|
+
let end = u.length;
|
|
109
|
+
while (end > 0 && /[.,;:!?'*]/.test(u[end - 1]))
|
|
110
|
+
end--;
|
|
111
|
+
// 不成對的右括號也不算
|
|
112
|
+
while (end > 0 && u[end - 1] === ')') {
|
|
113
|
+
const sub = u.slice(0, end);
|
|
114
|
+
if ((sub.match(/\(/g) ?? []).length < (sub.match(/\)/g) ?? []).length)
|
|
115
|
+
end--;
|
|
116
|
+
else
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
return u.slice(0, end);
|
|
120
|
+
}
|
|
121
|
+
function autolink(text) {
|
|
122
|
+
const out = [];
|
|
123
|
+
let last = 0;
|
|
124
|
+
for (const m of text.matchAll(URL_RE)) {
|
|
125
|
+
const raw = m[0];
|
|
126
|
+
const url = trimUrlTail(raw);
|
|
127
|
+
const at = m.index ?? 0;
|
|
128
|
+
if (url.length < 9)
|
|
129
|
+
continue;
|
|
130
|
+
if (at > last)
|
|
131
|
+
out.push({ t: 'text', v: text.slice(last, at) });
|
|
132
|
+
out.push({ t: 'link', href: url, c: [{ t: 'text', v: url }], bare: true });
|
|
133
|
+
last = at + url.length;
|
|
134
|
+
}
|
|
135
|
+
if (last < text.length)
|
|
136
|
+
out.push({ t: 'text', v: text.slice(last) });
|
|
137
|
+
return out.map((n) => (n.t === 'text' ? { t: 'text', v: decodeEntities(n.v) } : n));
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* 行內程式碼的唯一判定(解析器與註解剝除共用,兩邊不會對「哪裡是程式碼」有不同看法)。
|
|
141
|
+
* s[i] 是一串反引號的開頭:找下一串「剛好一樣長」的反引號當收尾;空白行(段落分隔)擋住,不能跨段。
|
|
142
|
+
* 找不到=不是程式碼(回 null,反引號當一般字元)。
|
|
143
|
+
*/
|
|
144
|
+
export function codeSpanAt(s, i) {
|
|
145
|
+
let n = 0;
|
|
146
|
+
while (s[i + n] === '`')
|
|
147
|
+
n++;
|
|
148
|
+
let j = i + n;
|
|
149
|
+
while (j < s.length) {
|
|
150
|
+
if (s[j] === '\n' && /^[ \t]*\n/.test(s.slice(j + 1)))
|
|
151
|
+
return null; // 空白行=段落結束
|
|
152
|
+
if (s[j] === '`') {
|
|
153
|
+
let m = 0;
|
|
154
|
+
while (s[j + m] === '`')
|
|
155
|
+
m++;
|
|
156
|
+
if (m === n)
|
|
157
|
+
return { open: n, close: j, end: j + m };
|
|
158
|
+
j += m;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
j++;
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
export function parseInline(s, problems, depth = 0) {
|
|
166
|
+
const out = [];
|
|
167
|
+
let buf = '';
|
|
168
|
+
const flush = () => {
|
|
169
|
+
if (buf) {
|
|
170
|
+
out.push(...autolink(buf));
|
|
171
|
+
buf = '';
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
let i = 0;
|
|
175
|
+
while (i < s.length) {
|
|
176
|
+
const ch = s[i];
|
|
177
|
+
if (ch === '\\' && i + 1 < s.length && /[\\`*_{}[\]()#+\-.!|<>~]/.test(s[i + 1])) {
|
|
178
|
+
buf += s[i + 1] === '{' ? LBRACE : s[i + 1];
|
|
179
|
+
i += 2;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (ch === '\n') {
|
|
183
|
+
buf = buf.replace(/[ \t]+$/, '');
|
|
184
|
+
flush();
|
|
185
|
+
out.push({ t: 'br' });
|
|
186
|
+
i++;
|
|
187
|
+
while (s[i] === ' ' || s[i] === '\t')
|
|
188
|
+
i++;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (ch === '`') {
|
|
192
|
+
const span = codeSpanAt(s, i);
|
|
193
|
+
if (span) {
|
|
194
|
+
flush();
|
|
195
|
+
out.push({ t: 'code', v: protectBraces(s.slice(i + span.open, span.close)) });
|
|
196
|
+
i = span.end;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
// 沒配對的反引號:整串當一般字元
|
|
200
|
+
let n = 0;
|
|
201
|
+
while (s[i + n] === '`')
|
|
202
|
+
n++;
|
|
203
|
+
buf += '`'.repeat(n);
|
|
204
|
+
i += n;
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (ch === '!' && s[i + 1] === '[') {
|
|
208
|
+
const close = matchBracket(s, i + 1);
|
|
209
|
+
if (close > 0 && s[close + 1] === '(') {
|
|
210
|
+
const u = readParenUrl(s, close + 1);
|
|
211
|
+
if (u) {
|
|
212
|
+
flush();
|
|
213
|
+
out.push({ t: 'image', src: u[0], alt: s.slice(i + 2, close).replace(/\\(.)/g, '$1') });
|
|
214
|
+
i = u[1];
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (ch === '[' && depth < 3) {
|
|
220
|
+
const close = matchBracket(s, i);
|
|
221
|
+
if (close > 0 && s[close + 1] === '(') {
|
|
222
|
+
const u = readParenUrl(s, close + 1);
|
|
223
|
+
if (u) {
|
|
224
|
+
flush();
|
|
225
|
+
out.push({ t: 'link', href: u[0], c: parseInline(s.slice(i + 1, close), problems, depth + 1) });
|
|
226
|
+
i = u[1];
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (ch === '<') {
|
|
232
|
+
const br = s.slice(i).match(/^<br\s*\/?>/i);
|
|
233
|
+
if (br) {
|
|
234
|
+
flush();
|
|
235
|
+
out.push({ t: 'br' });
|
|
236
|
+
i += br[0].length;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const auto = s.slice(i).match(/^<(https?:\/\/[^\s<>]+)>/i);
|
|
240
|
+
if (auto) {
|
|
241
|
+
flush();
|
|
242
|
+
out.push({ t: 'link', href: auto[1], c: [{ t: 'text', v: auto[1] }], bare: true });
|
|
243
|
+
i += auto[0].length;
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
// <a href="…">文字</a>:只取 href 當一般連結,其他屬性丟掉
|
|
247
|
+
const a = s.slice(i).match(/^<a\s+([^>]*)>/i);
|
|
248
|
+
if (a) {
|
|
249
|
+
const href = a[1].match(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
|
250
|
+
const closeAt = s.toLowerCase().indexOf('</a>', i + a[0].length);
|
|
251
|
+
if (href && closeAt > 0) {
|
|
252
|
+
flush();
|
|
253
|
+
out.push({ t: 'link', href: decodeEntities(href[1] ?? href[2] ?? ''), c: parseInline(s.slice(i + a[0].length, closeAt), problems, depth + 1) });
|
|
254
|
+
i = closeAt + 4;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
// <b>/<strong>/<i>/<em> 成對才收
|
|
259
|
+
const fmt = s.slice(i).match(/^<(b|strong|i|em)>/i);
|
|
260
|
+
if (fmt) {
|
|
261
|
+
const name = fmt[1].toLowerCase();
|
|
262
|
+
const closeAt = s.toLowerCase().indexOf(`</${name}>`, i + fmt[0].length);
|
|
263
|
+
if (closeAt > 0) {
|
|
264
|
+
flush();
|
|
265
|
+
out.push({ t: name === 'b' || name === 'strong' ? 'strong' : 'em', c: parseInline(s.slice(i + fmt[0].length, closeAt), problems, depth + 1) });
|
|
266
|
+
i = closeAt + name.length + 3;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const tag = s.slice(i).match(/^<\/?[a-zA-Z][^>]*>/);
|
|
271
|
+
if (tag) {
|
|
272
|
+
flush();
|
|
273
|
+
problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(tag[0], true) });
|
|
274
|
+
i += tag[0].length;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (ch === '*' && depth < 4) {
|
|
279
|
+
const strong = s[i + 1] === '*';
|
|
280
|
+
const mark = strong ? '**' : '*';
|
|
281
|
+
const end = s.indexOf(mark, i + mark.length);
|
|
282
|
+
if (end > i + mark.length && !/^\s/.test(s[i + mark.length]) && !/\s$/.test(s.slice(i + mark.length, end))) {
|
|
283
|
+
flush();
|
|
284
|
+
out.push({ t: strong ? 'strong' : 'em', c: parseInline(s.slice(i + mark.length, end), problems, depth + 1) });
|
|
285
|
+
i = end + mark.length;
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (ch === '_' && depth < 4) {
|
|
290
|
+
const prev = s[i - 1] ?? ' ';
|
|
291
|
+
const end = s.indexOf('_', i + 1);
|
|
292
|
+
if (end > i + 1 && !/[A-Za-z0-9]/.test(prev) && !/\s/.test(s[i + 1]) && !/[A-Za-z0-9]/.test(s[end + 1] ?? ' ') && !/\s/.test(s[end - 1])) {
|
|
293
|
+
flush();
|
|
294
|
+
out.push({ t: 'em', c: parseInline(s.slice(i + 1, end), problems, depth + 1) });
|
|
295
|
+
i = end + 1;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
buf += ch;
|
|
300
|
+
i++;
|
|
301
|
+
}
|
|
302
|
+
flush();
|
|
303
|
+
return out;
|
|
304
|
+
}
|
|
305
|
+
// ───────────── 區塊 ─────────────
|
|
306
|
+
const FENCE = /^\s{0,3}(```|~~~)/;
|
|
307
|
+
const LOOSE_FENCE = /^[\s>]*(```|~~~)/;
|
|
308
|
+
const HR = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
|
|
309
|
+
const HEADING = /^\s{0,3}(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/;
|
|
310
|
+
const QUOTE = /^\s{0,3}>/;
|
|
311
|
+
const LIST_ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
|
|
312
|
+
const TABLE_SEP = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/;
|
|
313
|
+
function splitRow(line) {
|
|
314
|
+
let t = line.trim();
|
|
315
|
+
if (t.startsWith('|'))
|
|
316
|
+
t = t.slice(1);
|
|
317
|
+
if (t.endsWith('|') && !t.endsWith('\\|'))
|
|
318
|
+
t = t.slice(0, -1);
|
|
319
|
+
const cells = [];
|
|
320
|
+
let cur = '';
|
|
321
|
+
for (let i = 0; i < t.length; i++) {
|
|
322
|
+
if (t[i] === '\\' && t[i + 1] === '|') {
|
|
323
|
+
cur += '|';
|
|
324
|
+
i++;
|
|
325
|
+
}
|
|
326
|
+
else if (t[i] === '|') {
|
|
327
|
+
cells.push(cur.trim());
|
|
328
|
+
cur = '';
|
|
329
|
+
}
|
|
330
|
+
else
|
|
331
|
+
cur += t[i];
|
|
332
|
+
}
|
|
333
|
+
cells.push(cur.trim());
|
|
334
|
+
return cells;
|
|
335
|
+
}
|
|
336
|
+
function isBlockStart(line, next) {
|
|
337
|
+
return FENCE.test(line) || HR.test(line) || HEADING.test(line) || QUOTE.test(line) || LIST_ITEM.test(line) || (line.includes('|') && next !== undefined && TABLE_SEP.test(next) && line.trim() !== '');
|
|
338
|
+
}
|
|
339
|
+
function parseBlocks(lines, problems) {
|
|
340
|
+
const blocks = [];
|
|
341
|
+
let i = 0;
|
|
342
|
+
while (i < lines.length) {
|
|
343
|
+
const line = lines[i];
|
|
344
|
+
if (line.trim() === '') {
|
|
345
|
+
i++;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
// 圍欄程式碼
|
|
349
|
+
const fence = line.match(FENCE);
|
|
350
|
+
if (fence) {
|
|
351
|
+
const mark = fence[1];
|
|
352
|
+
const lang = line.trim().slice(mark.length).trim().toLowerCase();
|
|
353
|
+
const body = [];
|
|
354
|
+
const start = line;
|
|
355
|
+
i++;
|
|
356
|
+
while (i < lines.length && !lines[i].trim().startsWith(mark))
|
|
357
|
+
body.push(lines[i++]);
|
|
358
|
+
if (i >= lines.length) {
|
|
359
|
+
// 沒收尾的程式碼框:不猜,後面的內容會被整段吃掉,所以直接記 error
|
|
360
|
+
problems.push({ code: 'unclosed_fence', severity: 'error', message: '程式碼框(```)沒有收尾,後面的內容會被吃掉', where: clip(start) });
|
|
361
|
+
}
|
|
362
|
+
i++;
|
|
363
|
+
// 圖表(mermaid)信裡畫不出來:換成「到網站看」連結卡
|
|
364
|
+
if (lang === 'mermaid')
|
|
365
|
+
blocks.push({ t: 'embed' });
|
|
366
|
+
else
|
|
367
|
+
blocks.push({ t: 'code', v: protectBraces(body.join('\n')) });
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (HR.test(line)) {
|
|
371
|
+
blocks.push({ t: 'hr' });
|
|
372
|
+
i++;
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
const h = line.match(HEADING);
|
|
376
|
+
if (h) {
|
|
377
|
+
blocks.push({ t: 'h', level: h[1].length, c: parseInline(h[2], problems) });
|
|
378
|
+
i++;
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
// 只有 <div> 、<div lang="…"> 或 </div> 的行(語言標記的外框;帶 hidden/style 等其他屬性的 div 不收):外框丟掉,裡面的內容照常轉
|
|
382
|
+
if (/^\s*(?:<div(?:\s+lang\s*=\s*(?:"[A-Za-z-]*"|'[A-Za-z-]*'))?\s*>|<\/div\s*>)\s*$/i.test(line)) {
|
|
383
|
+
i++;
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
// 自訂區塊語法(:::note 之類)
|
|
387
|
+
if (line.trim().startsWith(':::')) {
|
|
388
|
+
const start = line;
|
|
389
|
+
while (i < lines.length && lines[i].trim() !== '')
|
|
390
|
+
i++;
|
|
391
|
+
problems.push({ code: 'unsupported_syntax', severity: 'error', message: '原稿有信件轉不了的區塊語法', where: clip(start) });
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
// 區塊 HTML
|
|
395
|
+
if (BLOCK_HTML.test(line) && ANY_TAG.test(line) && !INLINE_START.test(line)) {
|
|
396
|
+
const start = line;
|
|
397
|
+
const chunk = [];
|
|
398
|
+
while (i < lines.length && lines[i].trim() !== '')
|
|
399
|
+
chunk.push(lines[i++]);
|
|
400
|
+
if (EMBED_TAG.test(start)) {
|
|
401
|
+
blocks.push({ t: 'embed' });
|
|
402
|
+
}
|
|
403
|
+
else {
|
|
404
|
+
problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(start.trim().match(/^<\/?[a-zA-Z!][^>]*>?/)?.[0] ?? start, false) });
|
|
405
|
+
}
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (QUOTE.test(line)) {
|
|
409
|
+
const inner = [];
|
|
410
|
+
while (i < lines.length && (QUOTE.test(lines[i]) || (lines[i].trim() !== '' && inner.length > 0 && !isBlockStart(lines[i], lines[i + 1])))) {
|
|
411
|
+
inner.push(lines[i].replace(/^\s{0,3}> ?/, ''));
|
|
412
|
+
i++;
|
|
413
|
+
}
|
|
414
|
+
blocks.push({ t: 'quote', c: parseBlocks(inner, problems) });
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (line.includes('|') && i + 1 < lines.length && TABLE_SEP.test(lines[i + 1])) {
|
|
418
|
+
const head = splitRow(line);
|
|
419
|
+
const align = splitRow(lines[i + 1]).map((c) => (/^:-+:$/.test(c) ? 'center' : /^-+:$/.test(c) ? 'right' : /^:-+$/.test(c) ? 'left' : null));
|
|
420
|
+
i += 2;
|
|
421
|
+
const rows = [];
|
|
422
|
+
while (i < lines.length && lines[i].trim() !== '' && lines[i].includes('|')) {
|
|
423
|
+
const cells = splitRow(lines[i++]);
|
|
424
|
+
while (cells.length < head.length)
|
|
425
|
+
cells.push('');
|
|
426
|
+
rows.push(cells.slice(0, head.length).map((c) => parseInline(c, problems)));
|
|
427
|
+
}
|
|
428
|
+
blocks.push({ t: 'table', head: head.map((c) => parseInline(c, problems)), align, rows });
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
const li = line.match(LIST_ITEM);
|
|
432
|
+
if (li) {
|
|
433
|
+
const base = li[1].length;
|
|
434
|
+
const ordered = /\d/.test(li[2][0]);
|
|
435
|
+
const items = [];
|
|
436
|
+
while (i < lines.length) {
|
|
437
|
+
const m = lines[i].match(LIST_ITEM);
|
|
438
|
+
if (!m || m[1].length !== base || /\d/.test(m[2][0]) !== ordered)
|
|
439
|
+
break;
|
|
440
|
+
const itemLines = [m[3]];
|
|
441
|
+
i++;
|
|
442
|
+
const contentIndent = base + m[2].length + 1;
|
|
443
|
+
while (i < lines.length) {
|
|
444
|
+
const l = lines[i];
|
|
445
|
+
if (l.trim() === '') {
|
|
446
|
+
// 空行後若仍是縮排內容,屬於本項
|
|
447
|
+
let j = i;
|
|
448
|
+
while (j < lines.length && lines[j].trim() === '')
|
|
449
|
+
j++;
|
|
450
|
+
if (j < lines.length && /^\s+\S/.test(lines[j]) && lines[j].search(/\S/) > base) {
|
|
451
|
+
for (; i < j; i++)
|
|
452
|
+
itemLines.push('');
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
const sub = l.match(LIST_ITEM);
|
|
458
|
+
if (sub && sub[1].length <= base)
|
|
459
|
+
break;
|
|
460
|
+
if (sub || /^\s+\S/.test(l)) {
|
|
461
|
+
itemLines.push(l.slice(Math.min(contentIndent, l.search(/\S/))));
|
|
462
|
+
i++;
|
|
463
|
+
}
|
|
464
|
+
else if (!isBlockStart(l, lines[i + 1])) {
|
|
465
|
+
itemLines.push(l); // 懶惰續行
|
|
466
|
+
i++;
|
|
467
|
+
}
|
|
468
|
+
else
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
471
|
+
items.push(parseBlocks(itemLines, problems));
|
|
472
|
+
// 項目之間的空行
|
|
473
|
+
let j = i;
|
|
474
|
+
while (j < lines.length && lines[j].trim() === '')
|
|
475
|
+
j++;
|
|
476
|
+
if (j < lines.length && lines[j].match(LIST_ITEM)?.[1].length === base)
|
|
477
|
+
i = j;
|
|
478
|
+
else
|
|
479
|
+
break;
|
|
480
|
+
}
|
|
481
|
+
blocks.push({ t: 'list', ordered, items });
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
// 段落
|
|
485
|
+
const para = [];
|
|
486
|
+
while (i < lines.length && lines[i].trim() !== '' && (para.length === 0 || !isBlockStart(lines[i], lines[i + 1])) && !(para.length > 0 && BLOCK_HTML.test(lines[i]) && EMBED_TAG.test(lines[i]))) {
|
|
487
|
+
para.push(lines[i++]);
|
|
488
|
+
}
|
|
489
|
+
const inline = parseInline(para.join('\n').trim(), problems);
|
|
490
|
+
// 整段只有一張圖(或一個包著圖的連結)=圖片區塊
|
|
491
|
+
if (inline.length === 1 && inline[0].t === 'image')
|
|
492
|
+
blocks.push({ t: 'image', src: inline[0].src, alt: inline[0].alt });
|
|
493
|
+
else if (inline.length === 1 && inline[0].t === 'link' && inline[0].c.length === 1 && inline[0].c[0].t === 'image') {
|
|
494
|
+
const img = inline[0].c[0];
|
|
495
|
+
blocks.push({ t: 'image', src: img.src, alt: img.alt, link: inline[0] });
|
|
496
|
+
}
|
|
497
|
+
else
|
|
498
|
+
blocks.push({ t: 'p', c: inline });
|
|
499
|
+
}
|
|
500
|
+
return blocks;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* 拿掉 HTML 註解(<!-- … -->):行首、段落下一行、清單項目裡、行內、跨行,位置都一樣處理(CommonMark 的註解可以打斷段落)。
|
|
504
|
+
* 程式碼框(``` 或 ~~~)裡的不動。找不到結尾的註解=記 error,且保留原文(不能把後面整段吃掉)。
|
|
505
|
+
*/
|
|
506
|
+
const MARK = '\uE001';
|
|
507
|
+
/**
|
|
508
|
+
* 拿掉 HTML 註解(<!-- … -->):行首、段落下一行、清單項目裡、行內、跨行,位置都一樣處理(CommonMark 的註解可以打斷段落)。
|
|
509
|
+
* 「程式碼」的判定:程式碼框(``` 或 ~~~,頂格、清單內、引言內都算;開頭與收尾用同一套前綴規則)與行內程式碼(共用 codeSpanAt,
|
|
510
|
+
* 含跨行、不同長度的反引號;反斜線跳脫的反引號不開頭)。程式碼裡的 <!-- 不動。
|
|
511
|
+
* 找不到結尾的註解=記 error,且保留原文(不能把後面整段吃掉)。
|
|
512
|
+
*/
|
|
513
|
+
export function stripComments(lines, problems) {
|
|
514
|
+
const fenceLead = (l) => l.replace(/^[\s>]*/, '');
|
|
515
|
+
// 切成「程式碼框」與「文字」兩種區段
|
|
516
|
+
const segs = [];
|
|
517
|
+
let i = 0;
|
|
518
|
+
while (i < lines.length) {
|
|
519
|
+
const f = lines[i].match(LOOSE_FENCE);
|
|
520
|
+
if (f) {
|
|
521
|
+
const mark = f[1];
|
|
522
|
+
const seg = [lines[i++]];
|
|
523
|
+
while (i < lines.length) {
|
|
524
|
+
const l = lines[i++];
|
|
525
|
+
seg.push(l);
|
|
526
|
+
if (fenceLead(l).startsWith(mark))
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
segs.push({ code: true, lines: seg });
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
const seg = [];
|
|
533
|
+
while (i < lines.length && !LOOSE_FENCE.test(lines[i]))
|
|
534
|
+
seg.push(lines[i++]);
|
|
535
|
+
segs.push({ code: false, lines: seg });
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
const out = [];
|
|
539
|
+
for (const seg of segs) {
|
|
540
|
+
if (seg.code) {
|
|
541
|
+
out.push(...seg.lines);
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
const text = seg.lines.join('\n');
|
|
545
|
+
let res = '';
|
|
546
|
+
let pos = 0;
|
|
547
|
+
let unclosedAt = -1;
|
|
548
|
+
while (pos < text.length) {
|
|
549
|
+
const ch = text[pos];
|
|
550
|
+
if (ch === '\\' && (text[pos + 1] === '`' || text[pos + 1] === '<')) {
|
|
551
|
+
res += ch + text[pos + 1]; // 反斜線跳脫的反引號不開程式碼、跳脫的 < 不開註解(與解析器一致)
|
|
552
|
+
pos += 2;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (ch === '`') {
|
|
556
|
+
const span = codeSpanAt(text, pos);
|
|
557
|
+
if (span) {
|
|
558
|
+
res += text.slice(pos, span.end);
|
|
559
|
+
pos = span.end;
|
|
560
|
+
}
|
|
561
|
+
else {
|
|
562
|
+
let n = 0;
|
|
563
|
+
while (text[pos + n] === '`')
|
|
564
|
+
n++;
|
|
565
|
+
res += text.slice(pos, pos + n);
|
|
566
|
+
pos += n;
|
|
567
|
+
}
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (text.startsWith('<!--', pos)) {
|
|
571
|
+
const e = text.indexOf('-->', pos + 4);
|
|
572
|
+
if (e < 0) {
|
|
573
|
+
unclosedAt = pos;
|
|
574
|
+
res += text.slice(pos);
|
|
575
|
+
pos = text.length;
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
res += MARK;
|
|
579
|
+
pos = e + 3;
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
res += ch;
|
|
583
|
+
pos++;
|
|
584
|
+
}
|
|
585
|
+
if (unclosedAt >= 0) {
|
|
586
|
+
const startLine = text.slice(0, unclosedAt).split('\n').length - 1;
|
|
587
|
+
problems.push({ code: 'unclosed_comment', severity: 'error', message: 'HTML 註解(<!--)沒有收尾,後面的內容會被吃掉', where: clip(seg.lines[startLine] ?? '') });
|
|
588
|
+
}
|
|
589
|
+
// 整行只剩註解=空行;行內註解=直接拿掉
|
|
590
|
+
for (const l of res.split('\n'))
|
|
591
|
+
out.push(l.includes(MARK) && l.split(MARK).join('').trim() === '' ? '' : l.split(MARK).join(''));
|
|
592
|
+
}
|
|
593
|
+
return out;
|
|
594
|
+
}
|
|
595
|
+
/** 保險:解析完之後,程式碼以外的文字節點若還有 <!--,代表註解剝除與解析器對「程式碼在哪」的看法不一致 → 記 error,不放行。 */
|
|
596
|
+
function leakedComments(blocks, problems) {
|
|
597
|
+
const inl = (ns) => {
|
|
598
|
+
for (const n of ns) {
|
|
599
|
+
if (n.t === 'text' && n.v.includes('<!--')) {
|
|
600
|
+
problems.push({ code: 'comment_leaked', severity: 'error', message: '有 HTML 註解沒被剝掉,會原樣出現在信裡(疑似程式碼寫法被誤判);請檢查附近的反引號與程式碼框', where: clip(n.v.slice(Math.max(0, n.v.indexOf('<!--') - 10))) });
|
|
601
|
+
}
|
|
602
|
+
else if (n.t === 'strong' || n.t === 'em' || n.t === 'link')
|
|
603
|
+
inl(n.c);
|
|
604
|
+
else if (n.t === 'image' && n.alt.includes('<!--'))
|
|
605
|
+
problems.push({ code: 'comment_leaked', severity: 'error', message: '圖片替代文字裡有未剝掉的 HTML 註解', where: clip(n.alt) });
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
const walk = (bs) => {
|
|
609
|
+
for (const b of bs) {
|
|
610
|
+
if (b.t === 'p' || b.t === 'h')
|
|
611
|
+
inl(b.c);
|
|
612
|
+
else if (b.t === 'quote')
|
|
613
|
+
walk(b.c);
|
|
614
|
+
else if (b.t === 'list')
|
|
615
|
+
for (const it of b.items)
|
|
616
|
+
walk(it);
|
|
617
|
+
else if (b.t === 'table') {
|
|
618
|
+
for (const c of b.head)
|
|
619
|
+
inl(c);
|
|
620
|
+
for (const r of b.rows)
|
|
621
|
+
for (const c of r)
|
|
622
|
+
inl(c);
|
|
623
|
+
}
|
|
624
|
+
else if (b.t === 'image' && b.alt.includes('<!--'))
|
|
625
|
+
problems.push({ code: 'comment_leaked', severity: 'error', message: '圖片替代文字裡有未剝掉的 HTML 註解', where: clip(b.alt) });
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
walk(blocks);
|
|
629
|
+
}
|
|
630
|
+
export function parseMarkdown(source) {
|
|
631
|
+
const { body, fm } = splitFrontmatter(source);
|
|
632
|
+
const problems = [];
|
|
633
|
+
const blocks = parseBlocks(stripComments(body.split('\n'), problems), problems);
|
|
634
|
+
if (!problems.some((p) => p.code === 'unclosed_comment'))
|
|
635
|
+
leakedComments(blocks, problems);
|
|
636
|
+
return { blocks, problems, frontmatter: fm };
|
|
637
|
+
}
|