-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmain.js
More file actions
3640 lines (3615 loc) · 166 KB
/
Copy pathmain.js
File metadata and controls
3640 lines (3615 loc) · 166 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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/core/artifact-goals.js
var require_artifact_goals = __commonJS({
"src/core/artifact-goals.js"(exports2, module2) {
"use strict";
var artifactGoals = [
{
id: "read",
name: "Readable artifact",
description: "Make a long note easier to read, navigate, and share.",
instruction: "Optimize the HTML for reading and navigation. Use strong information hierarchy, scan-friendly sections, generated navigation, tables where useful, and responsive layout."
},
{
id: "decide",
name: "Decision room",
description: "Turn the note into an interactive decision surface.",
instruction: "Make the HTML behave like a decision room: extract the core question, options, criteria, tradeoffs, risks, recommendation, dissenting view, and decision log. In trusted mode, add useful local controls such as criteria weighting, option filters, editable notes, or copy-next-decision-prompt behavior."
},
{
id: "review",
name: "Review room",
description: "Help readers leave structured feedback and copy it back to AI.",
instruction: "Make the HTML behave like a review room: add section-level review prompts, findings, open questions, reader notes, and copy-feedback-to-AI affordances. If comments are enabled, make the reader feedback section feel like the natural final step."
},
{
id: "compare",
name: "Compare options",
description: "Lay out alternatives side by side with tradeoffs.",
instruction: "Make the HTML compare alternatives side by side. Use matrices, scorecards, pros/cons, visual labels, and clear tradeoff summaries. In trusted mode, add filters, sorting, or lightweight scoring controls when useful."
},
{
id: "tune",
name: "Prompt playground",
description: "Create a small editable interface with copyable state.",
instruction: "Make the HTML a purpose-built playground: identify tunable parts of the note, provide editable fields or controls, show the resulting state, and include copy-as-prompt or copy-state behavior so the reader can bring changes back into Claude/Codex."
},
{
id: "explain-code",
name: "PR / code explainer",
description: "Explain code, diffs, or technical plans with annotations.",
instruction: "Make the HTML explain technical work: show architecture, data flow, annotated snippets or diffs when present, risk areas, reviewer checklist, and gotchas. Use diagrams or structured visual explanations where useful."
},
{
id: "publish",
name: "Public article",
description: "Prepare a polished public page for sharing.",
instruction: "Make the HTML a polished public article with strong title, excerpt, section rhythm, clear takeaways, social-share-friendly framing, and a reader-friendly ending."
}
];
function listArtifactGoals3() {
return artifactGoals.map(({ id, name, description }) => ({ id, name, description }));
}
function getArtifactGoal(id) {
return artifactGoals.find((goal) => goal.id === id) || artifactGoals[0];
}
function getArtifactGoalInstruction(id) {
return getArtifactGoal(id).instruction;
}
module2.exports = {
getArtifactGoal,
getArtifactGoalInstruction,
listArtifactGoals: listArtifactGoals3
};
}
});
// src/core/html.js
var require_html = __commonJS({
"src/core/html.js"(exports2, module2) {
"use strict";
function escapeHtml(value) {
return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
function slugify2(value) {
return String(value).trim().toLowerCase().replace(/[^a-z0-9가-힣]+/g, "-").replace(/^-+|-+$/g, "") || "note";
}
module2.exports = {
escapeHtml,
slugify: slugify2
};
}
});
// src/core/assets.js
var require_assets = __commonJS({
"src/core/assets.js"(exports2, module2) {
"use strict";
var path = require("node:path");
var { slugify: slugify2 } = require_html();
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".avif", ".bmp"]);
function extractMarkdownImageReferences2(markdown) {
const references = [];
const seen = /* @__PURE__ */ new Set();
const text = String(markdown || "");
for (const match of text.matchAll(/!\[\[([^\]]+)]]/g)) {
const raw = String(match[1] || "").trim();
const target = normalizeImageTarget(raw);
addReference(references, seen, target, raw);
}
for (const match of text.matchAll(/!\[([^\]]*)]\(([^)]+)\)/g)) {
const raw = String(match[2] || "").trim();
const target = normalizeImageTarget(raw);
addReference(references, seen, target, raw);
}
return references;
}
function normalizeImageTarget(value) {
let target = String(value || "").trim();
if (target.startsWith("<") && target.endsWith(">")) {
target = target.slice(1, -1).trim();
}
target = target.split("|")[0].trim();
target = target.split("#")[0].trim();
return decodeUriSafely(target);
}
function isLocalImageTarget(target) {
const value = String(target || "").trim();
if (!value || /^(?:https?:|data:|blob:|mailto:|#)/i.test(value)) {
return false;
}
return IMAGE_EXTENSIONS.has(path.extname(value).toLowerCase());
}
function buildAssetFileName2(originalPath, index, used = /* @__PURE__ */ new Set()) {
const extension = path.extname(originalPath).toLowerCase();
const base = slugify2(path.basename(originalPath, path.extname(originalPath))) || `image-${index}`;
let candidate = `${base}${extension}`;
let suffix = 2;
while (used.has(candidate)) {
candidate = `${base}-${suffix}${extension}`;
suffix += 1;
}
used.add(candidate);
return candidate;
}
function rewriteHtmlImageSources2(html, mappings) {
const replacements = buildReplacementMap(mappings);
if (replacements.size === 0) {
return String(html || "");
}
return String(html || "").replace(/(<img\b[^>]*\bsrc\s*=\s*)(["'])(.*?)\2/gi, (match, prefix, quote, src) => {
const normalized = normalizeImageTarget(src);
const replacement = replacements.get(src) || replacements.get(normalized) || replacements.get(decodeUriSafely(src));
if (!replacement) {
return match;
}
return `${prefix}${quote}${replacement}${quote}`;
});
}
function buildAiAssetInstruction(mappings) {
if (!Array.isArray(mappings) || mappings.length === 0) {
return "";
}
const lines = mappings.map((mapping) => `- ${mapping.original}: ${mapping.relativeSrc}`).join("\n");
return `
Local image assets are available. Preserve these images and use the mapped src values exactly:
${lines}`;
}
function buildReplacementMap(mappings) {
const replacements = /* @__PURE__ */ new Map();
for (const mapping of mappings || []) {
if (!mapping || !mapping.relativeSrc) {
continue;
}
for (const key of mapping.aliases || []) {
if (key) {
replacements.set(key, mapping.relativeSrc);
replacements.set(`./${key}`, mapping.relativeSrc);
replacements.set(encodeURI(key), mapping.relativeSrc);
replacements.set(`./${encodeURI(key)}`, mapping.relativeSrc);
}
}
}
return replacements;
}
function addReference(references, seen, target, raw) {
if (!isLocalImageTarget(target) || seen.has(target)) {
return;
}
seen.add(target);
references.push({ target, raw });
}
function decodeUriSafely(value) {
try {
return decodeURI(String(value || ""));
} catch (e) {
return String(value || "");
}
}
module2.exports = {
buildAiAssetInstruction,
buildAssetFileName: buildAssetFileName2,
extractMarkdownImageReferences: extractMarkdownImageReferences2,
isLocalImageTarget,
normalizeImageTarget,
rewriteHtmlImageSources: rewriteHtmlImageSources2
};
}
});
// src/core/sanitizer.js
var require_sanitizer = __commonJS({
"src/core/sanitizer.js"(exports2, module2) {
"use strict";
function sanitizeHtml(html, options = {}) {
if (options.trusted) {
return html;
}
return String(html).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<iframe\b[^>]*>[\s\S]*?<\/iframe>/gi, "").replace(/<object\b[^>]*>[\s\S]*?<\/object>/gi, "").replace(/<embed\b[^>]*>[\s\S]*?<\/embed>/gi, "").replace(/<svg\b[^>]*>[\s\S]*?<\/svg>/gi, "").replace(/<math\b[^>]*>[\s\S]*?<\/math>/gi, "").replace(/<meta\b[^>]*>/gi, "").replace(/<link\b[^>]*>/gi, "").replace(/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(/\s+style\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(/\s+srcset\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(/\s+(href|src|action|formaction|poster|xlink:href)\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, (match, _name, value) => {
const cleaned = String(value || "").replace(/^['"]|['"]$/g, "").trim().toLowerCase();
return /^(javascript:|data:text\/html|https?:\/\/)/i.test(cleaned) ? "" : match;
});
}
function looksLikeHtmlDocument(html) {
const value = String(html || "").trim();
return /<\/?[a-z][\s\S]*>/i.test(value);
}
module2.exports = {
looksLikeHtmlDocument,
sanitizeHtml
};
}
});
// src/core/templates.js
var require_templates = __commonJS({
"src/core/templates.js"(exports2, module2) {
"use strict";
var { escapeHtml } = require_html();
var templates = [
{
id: "minimal",
name: "Minimal",
description: "Clean readable document styling for faithful note exports.",
css: `
:root { color-scheme: light; }
body { margin: 0; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #1f2933; background: #f7f8fa; }
main { max-width: 820px; margin: 0 auto; padding: 48px 28px 72px; background: #ffffff; min-height: 100vh; box-sizing: border-box; }
h1, h2, h3 { color: #101828; line-height: 1.18; }
p, li { line-height: 1.68; }
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
pre { overflow: auto; padding: 16px; background: #111827; color: #f9fafb; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; margin: 18px 0; }
th, td { border: 1px solid #d8dee8; padding: 8px 10px; text-align: left; }
img { max-width: 100%; height: auto; border-radius: 6px; }
.frontmatter { white-space: pre-wrap; border: 1px solid #d8dee8; background: #f2f5f9; padding: 14px; border-radius: 8px; color: #475467; }
.callout { border-left: 4px solid #3b82f6; background: #eff6ff; padding: 12px 16px; margin: 18px 0; border-radius: 6px; }
.callout-title { font-weight: 700; margin-bottom: 6px; }
`
},
{
id: "editorial",
name: "Editorial",
description: "Magazine-like layout for polished long-form notes.",
css: `
body { margin: 0; font-family: Georgia, "Times New Roman", serif; color: #202124; background: #faf7f2; }
main { max-width: 900px; margin: 0 auto; padding: 56px 36px 80px; box-sizing: border-box; }
article { background: #fffdf8; border: 1px solid #e6ddcf; padding: 44px; }
h1 { font-size: 44px; line-height: 1.05; margin-top: 0; }
h2 { margin-top: 42px; border-top: 1px solid #dfd5c8; padding-top: 24px; }
p, li { font-size: 18px; line-height: 1.75; }
a { color: #8b3a2b; }
pre { overflow: auto; padding: 18px; background: #25211d; color: #f7efe4; border-radius: 6px; }
table { width: 100%; border-collapse: collapse; margin: 22px 0; background: #fff; }
th, td { border-bottom: 1px solid #e6ddcf; padding: 10px 12px; }
img { max-width: 100%; height: auto; display: block; margin: 24px auto; }
.frontmatter { white-space: pre-wrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; background: #f1eadf; padding: 14px; color: #5f574f; }
.callout { border: 1px solid #d8b98c; background: #fff6e5; padding: 16px 18px; margin: 24px 0; }
.callout-title { font-family: ui-sans-serif, system-ui, sans-serif; font-weight: 800; text-transform: uppercase; font-size: 12px; letter-spacing: .08em; }
`
},
{
id: "deck",
name: "Deck",
description: "Slide-like sections for presentation-style reading.",
css: `
body { margin: 0; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #172033; background: #e8edf4; }
main { max-width: 1120px; margin: 0 auto; padding: 36px 24px 60px; }
article > h1, article > h2 { background: #ffffff; border: 1px solid #cfd8e5; border-radius: 8px; padding: 30px; margin: 24px 0 14px; }
article > p, article > ul, article > ol, article > pre, article > table, .callout, .frontmatter { background: #ffffff; border: 1px solid #d7dfeb; border-radius: 8px; padding: 18px 22px; }
h1 { font-size: 42px; }
h2 { font-size: 30px; }
p, li { line-height: 1.6; }
pre { overflow: auto; background: #111827; color: #f9fafb; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #d7dfeb; padding: 10px; }
img { max-width: 100%; height: auto; border-radius: 8px; }
.frontmatter { white-space: pre-wrap; color: #526173; }
.callout { border-left: 5px solid #2563eb; }
.callout-title { font-weight: 800; }
`
},
{
id: "dashboard",
name: "Dashboard",
description: "Dense report dashboard with KPI-like sections and scan-friendly cards.",
css: `
body { margin: 0; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #182230; background: #f3f6fb; }
main { max-width: 1180px; margin: 0 auto; padding: 32px 22px 56px; }
article { display: grid; grid-template-columns: repeat(12, 1fr); gap: 14px; }
article > * { grid-column: 1 / -1; background: #ffffff; border: 1px solid #d9e2ef; border-radius: 8px; padding: 18px 20px; box-shadow: 0 8px 24px rgba(22, 34, 51, .05); }
h1 { font-size: 34px; border-left: 6px solid #0f766e; }
h2 { font-size: 24px; color: #0f3d4c; }
p, li { line-height: 1.62; }
pre { overflow: auto; background: #101828; color: #f8fafc; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid #d9e2ef; padding: 10px; }
.callout { border-left: 5px solid #0f766e; background: #ecfdf5; }
img { max-width: 100%; height: auto; }
`
},
{
id: "investor-brief",
name: "Investor Brief",
description: "Sharp memo style for strategy, market, and investment analysis.",
css: `
body { margin: 0; font-family: "Avenir Next", Inter, ui-sans-serif, system-ui, sans-serif; background: #111318; color: #eceff4; }
main { max-width: 960px; margin: 0 auto; padding: 56px 28px 80px; }
article { border-top: 4px solid #d7b56d; }
h1 { font-size: 46px; line-height: 1.05; color: #f5ddb0; }
h2 { margin-top: 42px; color: #ffffff; border-bottom: 1px solid #343946; padding-bottom: 10px; }
p, li { color: #d8dee9; line-height: 1.72; font-size: 17px; }
strong { color: #ffffff; }
a { color: #8ecae6; }
pre, table, .frontmatter, .callout { background: #1d222c; border: 1px solid #343946; border-radius: 8px; }
pre { overflow: auto; padding: 16px; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid #343946; padding: 10px; }
.callout { border-left: 4px solid #d7b56d; padding: 16px; }
img { max-width: 100%; height: auto; border-radius: 8px; }
`
},
{
id: "research-memo",
name: "Research Memo",
description: "Academic memo styling for long-form reasoning and source-heavy notes.",
css: `
body { margin: 0; font-family: "Source Serif 4", Georgia, serif; color: #1c2331; background: #f6f8fb; }
main { max-width: 860px; margin: 0 auto; padding: 64px 28px 88px; }
article { counter-reset: section; }
h1 { font-size: 42px; line-height: 1.12; }
h2 { counter-increment: section; margin-top: 44px; color: #243b53; }
h2::before { content: counter(section) ". "; color: #627d98; }
p, li { font-size: 18px; line-height: 1.78; }
blockquote, .callout { background: #eef4fb; border-left: 4px solid #486581; padding: 14px 18px; }
pre { overflow: auto; background: #102a43; color: #f0f4f8; padding: 16px; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; background: #fff; }
th, td { border: 1px solid #d9e2ec; padding: 10px; }
img { max-width: 100%; height: auto; }
`
},
{
id: "interactive-report",
name: "Interactive Report",
description: "Self-contained report with progress, generated TOC, and collapsible sections in trusted mode.",
css: `
body { margin: 0; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f7fafc; color: #1a202c; }
.progress { position: fixed; top: 0; left: 0; height: 4px; width: 0; background: #2563eb; z-index: 10; }
main { max-width: 1040px; margin: 0 auto; padding: 48px 24px 80px; }
.toc { background: #ffffff; border: 1px solid #dbe4f0; border-radius: 8px; padding: 16px 18px; margin-bottom: 20px; }
.toc a { display: inline-block; margin: 4px 12px 4px 0; color: #1d4ed8; text-decoration: none; }
.toolbox { position: sticky; top: 12px; z-index: 9; display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; margin-bottom: 12px; }
.toolbox input { min-width: 220px; border: 1px solid #bfdbfe; background: #ffffff; color: #1a202c; border-radius: 6px; padding: 8px 10px; }
.toolbox button { border: 1px solid #bfdbfe; background: #ffffff; color: #1d4ed8; border-radius: 6px; padding: 8px 10px; cursor: pointer; }
.toolbox button:hover { background: #eff6ff; }
article section.marktl-filter-hidden, article .marktl-filter-hidden { display: none; }
article { background: #ffffff; border: 1px solid #dbe4f0; border-radius: 8px; padding: 34px; }
h1 { font-size: 42px; line-height: 1.08; }
h2 { cursor: pointer; margin-top: 34px; padding: 14px 16px; background: #eef4ff; border-radius: 8px; }
p, li { line-height: 1.68; }
pre { overflow: auto; background: #111827; color: #f9fafb; padding: 16px; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid #dbe4f0; padding: 10px; }
.callout { border-left: 5px solid #2563eb; background: #eff6ff; padding: 14px 18px; border-radius: 8px; }
img { max-width: 100%; height: auto; border-radius: 8px; }
`,
script: `
const progress = document.createElement('div');
progress.className = 'progress';
document.body.prepend(progress);
const updateProgress = () => {
const max = document.documentElement.scrollHeight - innerHeight;
progress.style.width = max > 0 ? ((scrollY / max) * 100) + '%' : '0';
};
addEventListener('scroll', updateProgress, { passive: true });
updateProgress();
const copyText = async (label, text) => {
try {
await navigator.clipboard.writeText(text);
label.textContent = 'Copied';
setTimeout(() => { label.textContent = label.dataset.label; }, 1200);
} catch {
label.textContent = 'Copy failed';
}
};
const toolbox = document.createElement('div');
toolbox.className = 'toolbox';
const filter = document.createElement('input');
filter.type = 'search';
filter.placeholder = 'Filter sections';
filter.setAttribute('aria-label', 'Filter sections');
toolbox.append(filter);
const makeButton = (label, getText) => {
const button = document.createElement('button');
button.type = 'button';
button.textContent = label;
button.dataset.label = label;
button.addEventListener('click', () => copyText(button, getText()));
toolbox.append(button);
};
makeButton('Copy as prompt', () => 'Use this HTML artifact as context and continue from its decisions and structure:\\n\\n' + document.body.innerText);
makeButton('Copy as markdown', () => document.querySelector('article').innerText);
makeButton('Copy summary', () => [...document.querySelectorAll('h1,h2,h3')].map((h) => '- ' + h.textContent).join('\\n'));
makeButton('Copy outline JSON', () => JSON.stringify([...document.querySelectorAll('h1,h2,h3')].map((h) => ({ level: h.tagName, text: h.textContent.trim(), id: h.id || '' })), null, 2));
const expandButton = document.createElement('button');
expandButton.type = 'button';
expandButton.textContent = 'Expand all';
expandButton.addEventListener('click', () => {
document.querySelectorAll('article [hidden]').forEach((node) => { node.hidden = false; });
});
toolbox.append(expandButton);
document.querySelector('main').prepend(toolbox);
const headings = [...document.querySelectorAll('article h2')];
filter.addEventListener('input', () => {
const query = filter.value.trim().toLowerCase();
headings.forEach((heading) => {
const group = [heading];
let node = heading.nextElementSibling;
while (node && !/^H2$/.test(node.tagName)) {
group.push(node);
node = node.nextElementSibling;
}
const text = group.map((node) => node.textContent || '').join(' ').toLowerCase();
group.forEach((node) => node.classList.toggle('marktl-filter-hidden', Boolean(query && !text.includes(query))));
});
});
if (headings.length) {
const toc = document.createElement('nav');
toc.className = 'toc';
toc.innerHTML = '<strong>Contents</strong> ';
headings.forEach((heading, index) => {
heading.id = heading.id || 'section-' + (index + 1);
const link = document.createElement('a');
link.href = '#' + heading.id;
link.textContent = heading.textContent;
toc.append(link);
heading.addEventListener('click', () => {
let node = heading.nextElementSibling;
while (node && !/^H2$/.test(node.tagName)) {
node.hidden = !node.hidden;
node = node.nextElementSibling;
}
});
});
document.querySelector('main').prepend(toc);
}
`
},
{
id: "playground",
name: "Playground",
description: "Purpose-built working surface with editable notes, sliders, and copyable state.",
css: `
body { margin: 0; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f4f7f6; color: #16201d; }
main { max-width: 1180px; margin: 0 auto; padding: 32px 22px 72px; }
article { background: #ffffff; border: 1px solid #d8e2dd; border-radius: 8px; padding: 28px; }
h1 { font-size: 40px; line-height: 1.08; margin-top: 0; }
h2 { margin-top: 30px; border-top: 1px solid #d8e2dd; padding-top: 20px; color: #10433b; }
p, li { line-height: 1.66; }
table { width: 100%; border-collapse: collapse; margin: 18px 0; }
th, td { border: 1px solid #d8e2dd; padding: 10px; vertical-align: top; }
pre { overflow: auto; background: #101820; color: #f8fafc; padding: 16px; border-radius: 8px; }
img { max-width: 100%; height: auto; border-radius: 8px; }
.playground-panel { position: sticky; top: 12px; z-index: 9; display: grid; grid-template-columns: minmax(220px, 1fr) auto auto; gap: 10px; align-items: center; background: #ffffff; border: 1px solid #bdd6ce; border-radius: 8px; padding: 12px; margin-bottom: 16px; box-shadow: 0 12px 30px rgba(16, 67, 59, .08); }
.playground-panel input[type="range"] { width: 100%; }
.playground-panel button { border: 1px solid #9bc4b8; background: #e7f5ef; color: #10433b; border-radius: 6px; padding: 8px 10px; cursor: pointer; }
.playground-panel button:hover { background: #d9eee6; }
.playground-note { min-height: 90px; border: 1px dashed #9bc4b8; border-radius: 8px; padding: 12px; background: #fbfefd; outline: none; }
.playground-note:focus { border-style: solid; box-shadow: 0 0 0 3px rgba(42, 157, 143, .15); }
.playground-muted { color: #5f6f69; font-size: 13px; }
.playground-emphasis-low h2 { font-size: 22px; }
.playground-emphasis-medium h2 { font-size: 28px; }
.playground-emphasis-high h2 { font-size: 34px; }
@media (max-width: 720px) { .playground-panel { grid-template-columns: 1fr; } article { padding: 20px; } }
`,
script: `
const article = document.querySelector('article');
const panel = document.createElement('div');
panel.className = 'playground-panel';
panel.innerHTML = '<label><span class="playground-muted">Emphasis</span><input type="range" min="1" max="3" value="2" aria-label="Emphasis"></label><button type="button" data-action="copy-prompt">Copy prompt</button><button type="button" data-action="copy-state">Copy state JSON</button>';
document.querySelector('main').prepend(panel);
const note = document.createElement('section');
note.innerHTML = '<h2>Working notes</h2><div class="playground-note" contenteditable="true" role="textbox" aria-label="Working notes">Edit this area while reviewing the artifact. Use Copy prompt or Copy state JSON to bring the result back to your AI session.</div>';
article.prepend(note);
const applyEmphasis = () => {
article.classList.remove('playground-emphasis-low', 'playground-emphasis-medium', 'playground-emphasis-high');
article.classList.add(['playground-emphasis-low', 'playground-emphasis-medium', 'playground-emphasis-high'][Number(panel.querySelector('input').value) - 1]);
};
panel.querySelector('input').addEventListener('input', applyEmphasis);
applyEmphasis();
const state = () => ({
emphasis: Number(panel.querySelector('input').value),
workingNotes: document.querySelector('.playground-note').innerText.trim(),
outline: [...document.querySelectorAll('article h1, article h2, article h3')].map((heading) => ({ level: heading.tagName, text: heading.innerText.trim() })),
});
const copy = async (button, text) => {
const original = button.textContent;
try {
await navigator.clipboard.writeText(text);
button.textContent = 'Copied';
} catch {
button.textContent = 'Copy failed';
}
setTimeout(() => { button.textContent = original; }, 1200);
};
panel.querySelector('[data-action="copy-state"]').addEventListener('click', (event) => copy(event.currentTarget, JSON.stringify(state(), null, 2)));
panel.querySelector('[data-action="copy-prompt"]').addEventListener('click', (event) => copy(event.currentTarget, 'Use this reviewed HTML artifact state as feedback for the next iteration:\\n\\n' + JSON.stringify(state(), null, 2)));
`
}
];
function listTemplates3() {
return templates.map(({ id, name, description }) => ({ id, name, description }));
}
function getTemplate(id) {
return templates.find((template) => template.id === id) || templates[0];
}
function wrapWithTemplate(bodyHtml, options = {}) {
const template = getTemplate(options.template);
const title = options.title || "Exported note";
const script = options.trusted && template.script ? `<script>${template.script}</script>` : "";
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<style>${template.css}</style>
</head>
<body>
<main data-template="${escapeHtml(template.id)}">
<article>
${bodyHtml}
</article>
</main>
${script}
</body>
</html>`;
}
module2.exports = {
getTemplate,
listTemplates: listTemplates3,
wrapWithTemplate
};
}
});
// src/core/converter.js
var require_converter = __commonJS({
"src/core/converter.js"(exports2, module2) {
"use strict";
var path = require("node:path");
var { normalizeImageTarget } = require_assets();
var { escapeHtml } = require_html();
var { sanitizeHtml } = require_sanitizer();
var { wrapWithTemplate } = require_templates();
function convertMarkdownToHtml(markdown, options = {}) {
const parsed = splitFrontmatter(markdown);
const bodyHtml = blocksToHtml(parsed.body, options);
const frontmatterHtml = parsed.frontmatter ? `<pre class="frontmatter">${escapeHtml(parsed.frontmatter)}</pre>
` : "";
const title = inferTitle(parsed.body, options.sourcePath);
const html = wrapWithTemplate(`${frontmatterHtml}${bodyHtml}`, {
template: options.template,
title,
trusted: Boolean(options.trusted)
});
return sanitizeHtml(html, { trusted: Boolean(options.trusted) });
}
function splitFrontmatter(markdown) {
const normalized = String(markdown || "").replace(/\r\n/g, "\n");
if (!normalized.startsWith("---\n")) {
return { frontmatter: "", body: normalized };
}
const closeIndex = normalized.indexOf("\n---\n", 4);
if (closeIndex === -1) {
return { frontmatter: "", body: normalized };
}
return {
frontmatter: normalized.slice(4, closeIndex).trim(),
body: normalized.slice(closeIndex + 5).trimStart()
};
}
function inferTitle(markdown, sourcePath) {
const heading = String(markdown || "").split("\n").find((line) => /^#\s+/.test(line));
if (heading) {
return heading.replace(/^#\s+/, "").trim();
}
if (sourcePath) {
return path.basename(sourcePath, path.extname(sourcePath));
}
return "Exported note";
}
function blocksToHtml(markdown, options) {
const lines = String(markdown || "").replace(/\r\n/g, "\n").split("\n");
const blocks = [];
let index = 0;
while (index < lines.length) {
const line = lines[index];
if (!line.trim()) {
index += 1;
continue;
}
if (/^```/.test(line)) {
const language = line.replace(/^```/, "").trim();
const code = [];
index += 1;
while (index < lines.length && !/^```/.test(lines[index])) {
code.push(lines[index]);
index += 1;
}
index += 1;
blocks.push(`<pre><code${language ? ` class="language-${escapeHtml(language)}"` : ""}>${escapeHtml(code.join("\n"))}</code></pre>`);
continue;
}
const callout = readCallout(lines, index);
if (callout) {
blocks.push(callout.html);
index = callout.nextIndex;
continue;
}
const table = readTable(lines, index);
if (table) {
blocks.push(table.html);
index = table.nextIndex;
continue;
}
const list = readList(lines, index);
if (list) {
blocks.push(list.html);
index = list.nextIndex;
continue;
}
const heading = /^(#{1,6})\s+(.+)$/.exec(line);
if (heading) {
const level = heading[1].length;
blocks.push(`<h${level}>${inlineMarkdown(heading[2], options)}</h${level}>`);
index += 1;
continue;
}
const paragraph = [];
while (index < lines.length && lines[index].trim() && !isBlockStart(lines[index])) {
paragraph.push(lines[index].trim());
index += 1;
}
blocks.push(`<p>${inlineMarkdown(paragraph.join(" "), options)}</p>`);
}
return blocks.join("\n");
}
function isBlockStart(line) {
return /^(```|#{1,6}\s+|>\s+\[!|\s*[-*]\s+|\s*\d+\.\s+)/.test(line) || readTable([line, "| - |"], 0);
}
function readCallout(lines, start) {
const match = /^>\s+\[!(\w+)]\s*(.*)$/.exec(lines[start]);
if (!match) {
return null;
}
const type = match[1].toLowerCase();
const title = match[2].trim() || match[1].toUpperCase();
const body = [];
let index = start + 1;
while (index < lines.length && /^>/.test(lines[index])) {
body.push(lines[index].replace(/^>\s?/, ""));
index += 1;
}
return {
html: `<aside class="callout callout-${escapeHtml(type)}"><div class="callout-title">${escapeHtml(title)}</div><div class="callout-body">${blocksToHtml(body.join("\n"), {})}</div></aside>`,
nextIndex: index
};
}
function readTable(lines, start) {
if (!/^\s*\|.+\|\s*$/.test(lines[start] || "") || !/^\s*\|[\s:-]+\|/.test(lines[start + 1] || "")) {
return null;
}
const rows = [];
let index = start;
while (index < lines.length && /^\s*\|.+\|\s*$/.test(lines[index])) {
rows.push(splitTableRow(lines[index]));
index += 1;
}
const header = rows[0];
const body = rows.slice(2);
const headerHtml = `<thead><tr>${header.map((cell) => `<th>${inlineMarkdown(cell, {})}</th>`).join("")}</tr></thead>`;
const bodyHtml = `<tbody>${body.map((row) => `<tr>${row.map((cell) => `<td>${inlineMarkdown(cell, {})}</td>`).join("")}</tr>`).join("")}</tbody>`;
return {
html: `<table>${headerHtml}${bodyHtml}</table>`,
nextIndex: index
};
}
function splitTableRow(line) {
return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim());
}
function readList(lines, start) {
const ordered = /^\s*\d+\.\s+/.test(lines[start]);
const unordered = /^\s*[-*]\s+/.test(lines[start]);
if (!ordered && !unordered) {
return null;
}
const items = [];
let index = start;
const matcher = ordered ? /^\s*\d+\.\s+/ : /^\s*[-*]\s+/;
while (index < lines.length && matcher.test(lines[index])) {
items.push(lines[index].replace(matcher, "").trim());
index += 1;
}
const tag = ordered ? "ol" : "ul";
return {
html: `<${tag}>${items.map((item) => `<li>${inlineMarkdown(item, {})}</li>`).join("")}</${tag}>`,
nextIndex: index
};
}
function inlineMarkdown(value) {
return escapeHtml(value).replace(/!\[\[([^\]]+)]]/g, (_match, target) => {
const src = normalizeImageTarget(target);
return `<img src="${escapeHtml(src)}" alt="${escapeHtml(path.basename(src))}">`;
}).replace(/!\[([^\]]*)]\(([^)]+)\)/g, (_match, alt, src) => {
const normalizedSrc = normalizeImageTarget(src);
return `<img src="${escapeHtml(normalizedSrc)}" alt="${escapeHtml(alt)}">`;
}).replace(/\[([^\]]+)]\(([^)]+)\)/g, (_match, label, href) => `<a href="${escapeHtml(href)}">${escapeHtml(label)}</a>`).replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/`([^`]+)`/g, "<code>$1</code>");
}
module2.exports = {
convertMarkdownToHtml,
inferTitle,
splitFrontmatter
};
}
});
// src/core/ai.js
var require_ai = __commonJS({
"src/core/ai.js"(exports2, module2) {
"use strict";
var { spawn } = require("node:child_process");
var fs = require("node:fs");
var os = require("node:os");
var path = require("node:path");
var { buildAiAssetInstruction } = require_assets();
var { getArtifactGoalInstruction } = require_artifact_goals();
var { convertMarkdownToHtml } = require_converter();
var { looksLikeHtmlDocument, sanitizeHtml } = require_sanitizer();
var providerCommands = {
claude: {
command: "claude",
args: ["-p"],
promptAsArgument: true,
unsetEnv: ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]
},
codex: { command: "codex", args: ["exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "-"], parser: "codex-json", promptAsArgument: false }
};
var unixCliPath = [
"/opt/homebrew/bin",
"/usr/local/bin",
"/usr/bin",
"/bin",
"/usr/sbin",
"/sbin"
];
async function convertWithAiFallback2(markdown, options = {}) {
if (!options.provider || options.provider === "none") {
return {
html: convertMarkdownToHtml(markdown, options),
usedFallback: true,
warnings: ["AI provider is disabled; used local conversion."]
};
}
const runProvider = options.runProvider || runCliProvider;
try {
const aiHtml = extractHtmlFromAiOutput(await runProvider(markdown, options));
if (!looksLikeHtmlDocument(aiHtml)) {
throw new Error("AI provider returned invalid HTML");
}
return {
html: sanitizeHtml(aiHtml, { trusted: Boolean(options.trusted) }),
usedFallback: false,
warnings: []
};
} catch (error) {
if (options.strictAiFailures) {
throw error;
}
return {
html: convertMarkdownToHtml(markdown, options),
usedFallback: true,
warnings: [`AI conversion failed: ${error.message}. Used local fallback.`]
};
}
}
async function runCliProvider(markdown, options = {}) {
const provider = providerCommands[options.provider];
if (!provider) {
throw new Error(`Unsupported AI provider: ${options.provider}`);
}
const prompt = buildPrompt(markdown, options);
const timeout = Number(options.timeoutMs || 9e5);
const command = options.cliPaths && options.cliPaths[options.provider] ? options.cliPaths[options.provider] : provider.command;
const args = provider.promptAsArgument ? [...provider.args, prompt] : provider.args;
const execOptions = {
timeout,
maxBuffer: 10 * 1024 * 1024,
env: buildProviderEnv(provider),
shell: process.platform === "win32"
};
if (!provider.promptAsArgument) {
execOptions.input = prompt;
}
try {
const executeProcess = options.runProcess || runProcess;
const { stdout, stderr } = await executeProcess(command, args, execOptions);
const output = parseProviderOutput(stdout, provider);
if (!String(output || "").trim()) {
throw new Error(`AI provider returned empty output${stderr ? `: ${cleanProviderError(stderr)}` : ""}`);
}
return output;
} catch (error) {
const details = [
cleanProviderError(error.stderr),
parseProviderErrorOutput(error.stdout, provider),
cleanProviderError(error.stdout),
cleanProviderError(error.message)
].filter(Boolean).join("\n");
throw new Error(details || String(error));
}
}
function getProviderPrivacyNote3(provider) {
return provider === "claude" ? "Claude Code CLI receives the note prompt as a command-line argument; avoid sending private notes if local process inspection is a concern." : "";
}
function buildProviderEnv(provider, baseEnv = process.env) {
const env = {
...baseEnv,
PATH: mergePath(baseEnv.PATH, { env: baseEnv })
};
for (const key of provider.unsetEnv || []) {
delete env[key];
}
return env;
}
function runProcess(command, args, options) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
env: options.env,
shell: Boolean(options.shell),
stdio: ["pipe", "pipe", "pipe"]
});
let stdout = "";
let stderr = "";
let settled = false;
const timeout = setTimeout(() => {
if (settled) {
return;
}
settled = true;
child.kill("SIGTERM");
const error = new Error(`Provider timed out after ${options.timeout}ms`);
error.stdout = stdout;
error.stderr = stderr;
reject(error);
}, options.timeout);
child.stdout.on("data", (chunk) => {
stdout += chunk;
if (stdout.length > options.maxBuffer) {
child.kill("SIGTERM");
}
});
child.stderr.on("data", (chunk) => {
stderr += chunk;
if (stderr.length > options.maxBuffer) {
child.kill("SIGTERM");
}
});
if (options.input) {
child.stdin.write(options.input);
}
child.stdin.end();
child.on("error", (error) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timeout);
error.stdout = stdout;
error.stderr = stderr;
reject(error);
});
child.on("close", (code, signal) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timeout);
if (code === 0) {
resolve({ stdout, stderr });
return;
}
const error = new Error(`Provider exited with ${signal || code}`);
error.stdout = stdout;
error.stderr = stderr;
reject(error);
});
});
}
function buildPrompt(markdown, options = {}) {
const artifactGoal = options.artifactGoal || "read";
const goalInstruction = getArtifactGoalInstruction(artifactGoal);
const artifactInstruction = getArtifactInstruction(options.artifactType || "faithful-note");
const modeInstruction = {
preserve: "Preserve the source content. Improve semantic HTML, visual hierarchy, typography, spacing, and responsive styling. Do not summarize or remove content.",
presentation: "Create a premium presentation-style HTML document with section cards, strong visual rhythm, concise slide-like grouping, summaries, and visual emphasis.",
blog: "Create a polished editorial blog-style HTML article with refined typography, pull quotes, section rhythm, and light restructuring.",
landing: "Create a landing-page-style HTML document with strong hero treatment, benefit sections, emphasis copy, and deliberate visual hierarchy."
}[options.mode || "preserve"];
const dynamicInstruction = options.trusted ? "Trusted mode is enabled: you may include small inline JavaScript for useful interactions, animations, toggles, table-of-contents behavior, or reveal effects. Keep it self-contained and do not load remote resources." : "Sanitized mode is enabled: do not use JavaScript, iframes, external CSS, external scripts, or remote assets. Use rich CSS-only layout and interactions instead.";
const affordanceInstruction = getGoalAffordanceInstruction(artifactGoal, Boolean(options.trusted));
const interactionStandard = getInteractionStandard(artifactGoal, options.template || "minimal", Boolean(options.trusted));
return `Convert this Obsidian Markdown note to a complete standalone HTML document.
Artifact goal: ${artifactGoal}
Artifact type: ${options.artifactType || "faithful-note"}
Template: ${options.template || "minimal"}
Mode: ${options.mode || "preserve"}
Goal instruction: ${goalInstruction}
Artifact instruction: ${artifactInstruction}
Instruction: ${modeInstruction}
Design standard: produce a refined, modern, visually designed HTML page rather than plain Markdown-looking output. Use responsive CSS, strong spacing, tasteful color, cards/sections where helpful, and readable Korean typography if the content is Korean.
Dynamic policy: ${dynamicInstruction}
Goal-specific affordances: ${affordanceInstruction}
Interaction standard: ${interactionStandard}
${buildAiAssetInstruction(options.assetMappings)}
${options.contextPack ? `
Context pack:
${options.contextPack}
` : ""}
Return only HTML. Do not wrap it in Markdown fences.
${markdown}`;
}
function getArtifactInstruction(artifactType) {
return {
"faithful-note": "Render the note faithfully with better readability, visual hierarchy, and navigation. Do not substantially reorder or summarize unless the source already does.",
"strategy-brief": "Create an executive strategy brief with TL;DR, decision context, options, tradeoffs, risks, recommendation, and next actions.",
"research-report": "Create a research report with abstract, key findings, evidence sections, source notes, diagrams or tables where useful, and implications.",
"decision-memo": "Create a decision memo optimized for choosing: question, criteria, options, comparison matrix, recommendation, dissenting view, and decision log.",
"interactive-explainer": "Create an interactive explainer with progressive disclosure, visual examples, generated TOC, copy buttons, and local controls only when their purpose is clear to the reader.",
"slide-deck": "Create a slide-like artifact with concise sections, strong headings, visual rhythm, and one idea per section while preserving source meaning."
}[artifactType] || "Render a readable, useful HTML artifact from the note.";
}
function extractHtmlFromAiOutput(output) {
const value = String(output || "").trim();
if (!value) {
return "";
}
const fenced = /```(?:html)?\s*([\s\S]*?)```/i.exec(value);
const candidate = fenced ? fenced[1].trim() : value;
const documentMatch = /(?:<!doctype\s+html[^>]*>\s*)?<html\b[\s\S]*<\/html>/i.exec(candidate);
if (documentMatch) {
return documentMatch[0].trim();
}
const bodyMatch = /<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(candidate);
if (bodyMatch) {
return `<!doctype html><html><body>${bodyMatch[1].trim()}</body></html>`;
}
const firstTag = candidate.search(/<[a-z][\s\S]*?>/i);
const lastTag = Math.max(candidate.lastIndexOf(">"), candidate.lastIndexOf("/>"));