-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathpreview-worker.js
More file actions
553 lines (487 loc) · 17 KB
/
Copy pathpreview-worker.js
File metadata and controls
553 lines (487 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/* global importScripts, marked, hljs */
let librariesLoaded = false;
let markedConfigured = false;
let mermaidIdCounter = 0;
let abcIdCounter = 0;
let geojsonIdCounter = 0;
let topojsonIdCounter = 0;
let stlIdCounter = 0;
let plantumlIdCounter = 0;
let d2IdCounter = 0;
let graphvizIdCounter = 0;
const markedOptions = {
gfm: true,
breaks: true,
pedantic: false,
sanitize: false,
smartypants: false,
xhtml: false,
headerIds: true,
mangle: false,
};
const BLOCK_MATH_MARKER_PATTERN = /^\$\$/m;
const BLOCK_MATH_PATTERN = /^\$\$[ \t]*\n?([\s\S]*?)\n?\$\$[ \t]*(?:\n|$)/;
const DEFINITION_LIST_ITEM_PATTERN = /^:[ \t]+(.*)$/;
const SUPERSCRIPT_PATTERN = /^\^(?!\s)([^^\n]*?\S)\^(?!\^)/;
const SUBSCRIPT_PATTERN = /^~(?!~)(?!\s)([^~\n]*?\S)~(?!~)/;
const HIGHLIGHT_PATTERN = /^==(?=\S)([\s\S]*?\S)==/;
const MARKDOWN_LIST_MARKER_PATTERN = /^(\s*)(?:[-*+]\s+|\d+\.\s+|>\s+)/;
const EMPTY_LINE_PATTERN = /^\s*$/;
let suppressFootnotePreprocess = false;
const footnoteDefinitions = new Map();
const footnoteOrder = [];
const footnoteRefCounts = new Map();
const footnoteFirstRefId = new Map();
let anonymousFootnoteCounter = 0;
function escapeHtml(str) {
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function escapeHtmlAttribute(value) {
return String(value)
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function resetExtendedMarkdownState() {
footnoteDefinitions.clear();
footnoteOrder.length = 0;
footnoteRefCounts.clear();
footnoteFirstRefId.clear();
anonymousFootnoteCounter = 0;
}
function normalizeFootnoteId(id) {
const normalized = String(id || "")
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]+/g, "-")
.replace(/^-+|-+$/g, "");
if (normalized) return normalized;
anonymousFootnoteCounter += 1;
return `footnote-${anonymousFootnoteCounter}`;
}
function parseInlineWithoutFootnotes(text) {
suppressFootnotePreprocess = true;
try {
return marked.parseInline(text);
} finally {
suppressFootnotePreprocess = false;
}
}
function renderDefinitionContent(content, options) {
const appendHtml = options && options.appendHtml ? options.appendHtml : "";
const paragraphs = String(content || "")
.split(/\n(?:[ \t]*\n)+/)
.map((paragraph) => paragraph.trim())
.filter(Boolean);
if (appendHtml) {
if (paragraphs.length === 0) {
paragraphs.push(appendHtml);
} else {
paragraphs[paragraphs.length - 1] = `${paragraphs[paragraphs.length - 1]} ${appendHtml}`;
}
}
return paragraphs
.map((paragraph) => `<p>${parseInlineWithoutFootnotes(paragraph)}</p>`)
.join("");
}
function extractFootnoteDefinitions(markdown) {
const lines = markdown.split("\n");
const preservedLines = [];
let index = 0;
while (index < lines.length) {
const match = /^([ \t]{0,3})\[\^([^\]\n]+)\]:[ \t]*(.*)$/.exec(lines[index]);
if (!match) {
preservedLines.push(lines[index]);
index += 1;
continue;
}
const baseIndent = match[1] || "";
const id = match[2].trim();
const definitionLines = [match[3] || ""];
index += 1;
while (index < lines.length) {
const line = lines[index];
if (!line.startsWith(baseIndent)) break;
const lineAfterBase = line.slice(baseIndent.length);
const indentedMatch = /^(?: {2,}|\t)(.*)$/.exec(lineAfterBase);
if (indentedMatch) {
definitionLines.push(indentedMatch[1]);
index += 1;
continue;
}
if (lineAfterBase.trim() === "") {
const nextLine = lines[index + 1] || "";
const nextAfterBase = nextLine.startsWith(baseIndent) ? nextLine.slice(baseIndent.length) : "";
if (/^(?: {2,}|\t)/.test(nextAfterBase)) {
definitionLines.push("");
index += 1;
continue;
}
}
break;
}
footnoteDefinitions.set(id, definitionLines.join("\n").trim());
}
return preservedLines.join("\n");
}
function applyFootnotes(markdown) {
const markdownWithReferences = markdown.replace(/\[\^([^\]\n]+)\]/g, function(match, idText) {
const id = idText.trim();
if (!id) return match;
if (!footnoteOrder.includes(id)) footnoteOrder.push(id);
const refCount = (footnoteRefCounts.get(id) || 0) + 1;
footnoteRefCounts.set(id, refCount);
const normalizedId = normalizeFootnoteId(id);
const refId = `fnref-${normalizedId}${refCount > 1 ? `-${refCount}` : ""}`;
if (!footnoteFirstRefId.has(id)) footnoteFirstRefId.set(id, refId);
const noteNumber = footnoteOrder.indexOf(id) + 1;
return `<sup id="${escapeHtmlAttribute(refId)}" class="footnote-ref"><a href="#fn-${escapeHtmlAttribute(normalizedId)}" aria-label="Footnote ${noteNumber}">[${noteNumber}]</a></sup>`;
});
const footnotesHtml = footnoteOrder
.filter((id) => footnoteDefinitions.has(id))
.map((id) => {
const normalizedId = normalizeFootnoteId(id);
const backRefId = footnoteFirstRefId.get(id) || `fnref-${normalizedId}`;
const backRefHtml = `<a href="#${escapeHtmlAttribute(backRefId)}" class="footnote-backref" aria-label="Back to content">←</a>`;
const noteHtml = renderDefinitionContent(footnoteDefinitions.get(id) || "", { appendHtml: backRefHtml });
return `<li id="fn-${escapeHtmlAttribute(normalizedId)}">${noteHtml}</li>`;
})
.join("");
if (!footnotesHtml) return markdownWithReferences;
return `${markdownWithReferences}\n\n<section class="footnotes"><hr><ol>${footnotesHtml}</ol></section>`;
}
function configureMarked() {
if (markedConfigured) return;
const renderer = new marked.Renderer();
const blockMathExtension = {
name: "blockMath",
level: "block",
start(src) {
const match = src.match(BLOCK_MATH_MARKER_PATTERN);
return match ? match.index : undefined;
},
tokenizer(src) {
const match = BLOCK_MATH_PATTERN.exec(src);
if (!match) return undefined;
return { type: "blockMath", raw: match[0], text: match[1] };
},
renderer(token) {
return `<div class="math-block">$$\n${token.text}\n$$</div>\n`;
},
};
const definitionListExtension = {
name: "definitionList",
level: "block",
start(src) {
const match = src.match(/\n:[ \t]+/);
return match ? match.index + 1 : undefined;
},
tokenizer(src) {
const lines = src.split("\n");
if (lines.length < 2) return undefined;
const term = lines[0];
if (EMPTY_LINE_PATTERN.test(term) || MARKDOWN_LIST_MARKER_PATTERN.test(term)) return undefined;
if (!DEFINITION_LIST_ITEM_PATTERN.test(lines[1])) return undefined;
const definitions = [];
const rawLines = [term];
let index = 1;
while (index < lines.length) {
const itemMatch = DEFINITION_LIST_ITEM_PATTERN.exec(lines[index]);
if (!itemMatch) break;
rawLines.push(lines[index]);
const definitionLines = [itemMatch[1]];
index += 1;
while (index < lines.length) {
const line = lines[index];
if (DEFINITION_LIST_ITEM_PATTERN.test(line)) break;
if (EMPTY_LINE_PATTERN.test(line)) {
const nextLine = lines[index + 1] || "";
if (/^(?: {2,}|\t)/.test(nextLine)) {
rawLines.push(line);
definitionLines.push("");
index += 1;
continue;
}
break;
}
const continuationMatch = /^(?: {2,}|\t)(.*)$/.exec(line);
if (!continuationMatch) break;
rawLines.push(line);
definitionLines.push(continuationMatch[1]);
index += 1;
}
definitions.push(definitionLines.join("\n").trim());
}
if (definitions.length === 0) return undefined;
let raw = rawLines.join("\n");
if (src.startsWith(raw + "\n")) raw += "\n";
return { type: "definitionList", raw, term: term.trim(), definitions };
},
renderer(token) {
const termHtml = parseInlineWithoutFootnotes(token.term);
const definitionHtml = token.definitions
.map((definition) => `<dd>${renderDefinitionContent(definition)}</dd>`)
.join("");
return `<dl><dt>${termHtml}</dt>${definitionHtml}</dl>\n`;
},
};
const superscriptExtension = {
name: "superscript",
level: "inline",
start(src) {
const index = src.indexOf("^");
return index >= 0 ? index : undefined;
},
tokenizer(src) {
const match = SUPERSCRIPT_PATTERN.exec(src);
return match ? { type: "superscript", raw: match[0], text: match[1] } : undefined;
},
renderer(token) {
return `<sup>${marked.parseInline(token.text)}</sup>`;
},
};
const subscriptExtension = {
name: "subscript",
level: "inline",
start(src) {
const index = src.indexOf("~");
return index >= 0 ? index : undefined;
},
tokenizer(src) {
const match = SUBSCRIPT_PATTERN.exec(src);
return match ? { type: "subscript", raw: match[0], text: match[1] } : undefined;
},
renderer(token) {
return `<sub>${marked.parseInline(token.text)}</sub>`;
},
};
const highlightExtension = {
name: "highlight",
level: "inline",
start(src) {
const index = src.indexOf("==");
return index >= 0 ? index : undefined;
},
tokenizer(src) {
const match = HIGHLIGHT_PATTERN.exec(src);
return match ? { type: "highlight", raw: match[0], text: match[1] } : undefined;
},
renderer(token) {
return `<mark>${marked.parseInline(token.text)}</mark>`;
},
};
renderer.code = function(code, language) {
if (language === "mermaid") {
const uniqueId = `mermaid-diagram-worker-${mermaidIdCounter++}`;
return `<div class="mermaid-container is-loading"><div class="mermaid" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "abc") {
const uniqueId = `abc-notation-worker-${abcIdCounter++}`;
return `<div class="abc-container is-loading"><div class="abc-notation" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "geojson") {
const uniqueId = `geojson-map-worker-${geojsonIdCounter++}`;
return `<div class="geojson-container is-loading"><div class="geojson-map" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "topojson") {
const uniqueId = `topojson-map-worker-${topojsonIdCounter++}`;
return `<div class="topojson-container is-loading"><div class="topojson-map" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "stl") {
const uniqueId = `stl-viewer-worker-${stlIdCounter++}`;
return `<div class="stl-container is-loading"><div class="stl-viewer" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "plantuml") {
const uniqueId = `plantuml-diagram-worker-${plantumlIdCounter++}`;
return `<div class="plantuml-container is-loading"><div class="plantuml-diagram" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "d2") {
const uniqueId = `d2-diagram-worker-${d2IdCounter++}`;
return `<div class="d2-container is-loading"><div class="d2-diagram" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "graphviz" || language === "dot") {
const uniqueId = `graphviz-diagram-worker-${graphvizIdCounter++}`;
return `<div class="graphviz-container is-loading"><div class="graphviz-diagram" id="${uniqueId}" data-original-code="${encodeURIComponent(code)}">${escapeHtml(code)}</div></div>`;
}
if (language === "math") {
return `<div class="math-block">$$\n${code}\n$$</div>\n`;
}
const validLanguage = hljs && hljs.getLanguage(language) ? language : "plaintext";
const highlightedCode = hljs
? hljs.highlight(code, { language: validLanguage }).value
: escapeHtml(code);
return `<pre><code class="hljs ${escapeHtmlAttribute(validLanguage)}">${highlightedCode}</code></pre>`;
};
renderer.heading = function(text, level, raw) {
let id = raw
.toLowerCase()
.trim()
.replace(/<[^>]*>/g, '')
.replace(/\s+/g, '-')
.replace(/[^\w-]/g, '')
.replace(/-+/g, '-');
if (!id) {
id = `heading-worker-${Math.random().toString(36).substr(2, 9)}`;
}
return `<h${level} id="${id}">${text}</h${level}>`;
};
marked.use({
extensions: [
blockMathExtension,
definitionListExtension,
superscriptExtension,
subscriptExtension,
highlightExtension,
],
hooks: {
preprocess(markdown) {
if (suppressFootnotePreprocess) return markdown;
resetExtendedMarkdownState();
const protectedMarkdown = markdown.replace(/\\\$/g, "$");
return applyFootnotes(extractFootnoteDefinitions(protectedMarkdown));
},
},
});
marked.setOptions(Object.assign({}, markedOptions, { renderer }));
markedConfigured = true;
}
function ensureLibraries(urls) {
if (!librariesLoaded) {
importScripts(urls.marked, urls.highlight);
if (urls.powershell) {
importScripts(urls.powershell);
}
librariesLoaded = true;
}
configureMarked();
}
function isSegmentedPreviewSafe(markdown) {
if (/^\s*---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/.test(markdown)) return false;
if (/^\[[^\]\n]+\]:\s+\S+/m.test(markdown)) return false;
if (/\[\^[^\]\n]+\]/.test(markdown)) return false;
if (/\n:[ \t]+/.test(markdown)) return false;
if (/^\s{0,3}<\/?[a-zA-Z][\w:-]*(?:\s|>|\/>)/m.test(markdown)) return false;
return true;
}
function hashString(value) {
let hash = 2166136261;
for (let i = 0; i < value.length; i += 1) {
hash ^= value.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(36);
}
function splitMarkdownBlocks(markdown) {
const normalized = String(markdown || "").replace(/\r\n/g, "\n");
const lines = normalized.split("\n");
const blocks = [];
let buffer = [];
let startLine = 1;
let inFence = false;
let fenceChar = "";
let fenceLength = 0;
let inMathBlock = false;
function flush(endLine) {
const source = buffer.join("\n").trimEnd();
if (source.trim()) {
blocks.push({
source,
startLine,
endLine,
});
}
buffer = [];
}
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
const lineNumber = index + 1;
const fenceMatch = /^ {0,3}(`{3,}|~{3,})/.exec(line);
const trimmed = line.trim();
if (fenceMatch) {
const marker = fenceMatch[1];
if (!inFence) {
inFence = true;
fenceChar = marker[0];
fenceLength = marker.length;
} else if (marker[0] === fenceChar && marker.length >= fenceLength) {
inFence = false;
}
}
if (!inFence && trimmed === "$$") {
inMathBlock = !inMathBlock;
}
if (!inFence && !inMathBlock && trimmed === "") {
flush(lineNumber);
startLine = lineNumber + 1;
continue;
}
if (buffer.length === 0) startLine = lineNumber;
buffer.push(line);
}
flush(lines.length);
return blocks;
}
function renderSegmentedMarkdown(markdown, options) {
if (!isSegmentedPreviewSafe(markdown)) {
return { mode: "full-required", reason: "unsafe-markdown" };
}
const blocks = splitMarkdownBlocks(markdown);
if (blocks.length < (options.minimumBlocks || 1)) {
return { mode: "full-required", reason: "too-few-blocks" };
}
const seenHashes = new Map();
const renderedBlocks = blocks.map((block) => {
const hash = hashString(block.source);
const seenCount = seenHashes.get(hash) || 0;
seenHashes.set(hash, seenCount + 1);
const html = marked.parse(block.source);
return {
id: `preview-block-${hash}-${seenCount}`,
hash,
html,
htmlLength: html.length,
sourceLength: block.source.length,
startLine: block.startLine,
endLine: block.endLine,
};
});
return {
mode: "segmented",
blocks: renderedBlocks,
blockCount: renderedBlocks.length,
};
}
self.onmessage = function(event) {
const data = event.data || {};
if (data.type !== "render") return;
try {
const options = data.options || {};
ensureLibraries(options.libraryUrls || {});
mermaidIdCounter = 0;
abcIdCounter = 0;
geojsonIdCounter = 0;
topojsonIdCounter = 0;
stlIdCounter = 0;
plantumlIdCounter = 0;
d2IdCounter = 0;
graphvizIdCounter = 0;
const result = renderSegmentedMarkdown(data.markdown || "", options);
self.postMessage({
type: "render-result",
requestId: data.requestId,
result,
});
} catch (error) {
self.postMessage({
type: "render-error",
requestId: data.requestId,
error: error && error.message ? error.message : "Preview worker render failed.",
});
}
};