@ai-matrx/print 0.5.10 → 0.6.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/dist/markdown.cjs CHANGED
@@ -24,15 +24,21 @@ __export(markdown_exports, {
24
24
  MARKDOWN_ARTICLE_TOKENS_CSS: () => MARKDOWN_ARTICLE_TOKENS_CSS,
25
25
  MARKDOWN_DOCUMENT_CSS: () => MARKDOWN_DOCUMENT_CSS,
26
26
  MARKDOWN_DOCUMENT_TOKENS_CSS: () => MARKDOWN_DOCUMENT_TOKENS_CSS,
27
+ MARKDOWN_PAGE_CSS: () => MARKDOWN_PAGE_CSS,
28
+ MARKDOWN_SHARED_CSS: () => MARKDOWN_SHARED_CSS,
29
+ PAGE_BREAK_CLASS: () => PAGE_BREAK_CLASS,
30
+ PAGE_BREAK_MARKDOWN: () => PAGE_BREAK_MARKDOWN,
27
31
  PRINT_ACTIONS_CSS: () => PRINT_ACTIONS_CSS,
28
32
  getMarkdownStylesheet: () => getMarkdownStylesheet,
29
33
  hasThinkingContent: () => hasThinkingContent,
34
+ isPageBreakLine: () => isPageBreakLine,
30
35
  markdownToArticleHtml: () => markdownToArticleHtml,
31
36
  markdownToHtml: () => markdownToHtml,
32
37
  markdownToHtmlForSkin: () => markdownToHtmlForSkin,
33
38
  printMarkdown: () => printMarkdown,
34
39
  removeThinkingContent: () => removeThinkingContent,
35
- renderMarkdownDocument: () => renderMarkdownDocument
40
+ renderMarkdownDocument: () => renderMarkdownDocument,
41
+ splitAtPageBreaks: () => splitAtPageBreaks
36
42
  });
37
43
  module.exports = __toCommonJS(markdown_exports);
38
44
 
@@ -791,6 +797,257 @@ var MARKDOWN_DOCUMENT_CSS = `/*
791
797
  }
792
798
  `;
793
799
  var MARKDOWN_ARTICLE_CSS = `*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}body{font-family:Georgia,'Times New Roman',serif;font-size:11pt;line-height:1.7;color:var(--matrx-print-fg, #1a1a1a);background:var(--matrx-print-bg, #fff);max-width:780px;margin:0 auto;padding:32px 40px}.print-actions{display:flex;gap:10px;margin-bottom:28px;padding-bottom:20px;border-bottom:2px solid var(--matrx-print-border, #e5e7eb)}.print-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 20px;border-radius:8px;font-size:13px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;cursor:pointer;border:none;font-weight:600;transition:opacity .15s}.print-btn:hover{opacity:.85}.print-btn-primary{background:var(--matrx-print-accent, #2563eb);color:var(--matrx-print-bg, #fff)}.print-btn-secondary{background:var(--matrx-print-surface-sunken, #f3f4f6);color:var(--matrx-print-fg-muted, #374151);border:1px solid var(--matrx-print-border-muted, #d1d5db)}h1,h2,h3,h4,h5,h6{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Helvetica Neue',sans-serif;font-weight:700;line-height:1.3;color:var(--matrx-print-heading, #111827);margin-top:1.6em;margin-bottom:.5em;page-break-after:avoid}h1{font-size:24pt;border-bottom:2px solid var(--matrx-print-border, #e5e7eb);padding-bottom:.3em;margin-top:0}h2{font-size:18pt;border-bottom:1px solid var(--matrx-print-border, #e5e7eb);padding-bottom:.2em}h3{font-size:14pt}p{margin-bottom:.9em;orphans:3;widows:3}a{color:var(--matrx-print-accent, #2563eb);text-decoration:underline;word-break:break-word}ul,ol{margin:.6em 0 .9em 0;padding-left:1.8em}li{margin-bottom:.3em;page-break-inside:avoid}blockquote{margin:1em 0;padding:.7em 1em .7em 1.2em;border-left:4px solid var(--matrx-print-quote-border, #6366f1);background:var(--matrx-print-quote-bg, #f5f3ff);border-radius:0 6px 6px 0;color:var(--matrx-print-fg-muted, #374151);font-style:italic;page-break-inside:avoid}.inline-code{font-family:'JetBrains Mono','Fira Code',monospace;font-size:9.5pt;background:var(--matrx-print-code-bg, #f1f5f9);color:var(--matrx-print-ink, #0f172a);padding:1px 5px;border-radius:4px;border:1px solid var(--matrx-print-line, #e2e8f0)}.code-block-wrapper{position:relative;margin:1em 0 1.2em;border-radius:8px;overflow:hidden;border:1px solid var(--matrx-print-line, #e2e8f0);page-break-inside:avoid}.code-lang{display:block;font-family:-apple-system,sans-serif;font-size:9pt;font-weight:600;color:var(--matrx-print-fg-subtle, #64748b);background:var(--matrx-print-surface, #f8fafc);padding:4px 12px;border-bottom:1px solid var(--matrx-print-line, #e2e8f0);text-transform:uppercase;letter-spacing:.05em}.code-block{margin:0;padding:14px 16px;background:var(--matrx-print-ink, #0f172a);color:var(--matrx-print-line, #e2e8f0);font-family:'JetBrains Mono',monospace;font-size:9pt;line-height:1.6;overflow-x:auto;white-space:pre;tab-size:2}.print-table{width:100%;border-collapse:collapse;margin:1em 0 1.2em;font-size:10pt;page-break-inside:avoid}.print-table th{background:var(--matrx-print-table-head-bg, #1e293b);color:var(--matrx-print-surface, #f8fafc);font-family:-apple-system,sans-serif;font-weight:600;font-size:9.5pt;text-align:left;padding:8px 12px;border:1px solid var(--matrx-print-table-head-border, #334155)}.print-table td{padding:7px 12px;border:1px solid var(--matrx-print-line, #e2e8f0);vertical-align:top}.print-table tr:nth-child(even) td{background:var(--matrx-print-surface, #f8fafc)}hr{border:none;border-top:2px solid var(--matrx-print-border, #e5e7eb);margin:1.5em 0}.print-figure{margin:1em 0 1.2em;page-break-inside:avoid}.print-image{display:block;max-width:100%;height:auto;margin:0 auto;border-radius:6px}.print-figure figcaption{margin-top:.4em;text-align:center;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:9.5pt;color:var(--matrx-print-fg-subtle, #64748b)}@media print{body{max-width:100%;padding:0;font-size:10.5pt}.print-actions{display:none!important}.code-block,.print-table th,blockquote{color-adjust:exact;-webkit-print-color-adjust:exact;print-color-adjust:exact}a[href]::after{content:" ("attr(href)")";font-size:9pt;color:var(--matrx-print-fg-subtle, #64748b)}a[href^="#"]::after,a[href^="javascript:"]::after{content:""}h1,h2,h3{page-break-after:avoid}pre,blockquote,table{page-break-inside:avoid}}`;
800
+ var MARKDOWN_SHARED_CSS = `
801
+ .matrx-page-break {
802
+ position: relative;
803
+ clear: both;
804
+ height: 0;
805
+ margin: 2.75rem 0;
806
+ border: 0;
807
+ border-top: 2px dashed var(--matrx-print-border-muted, #d1d5db);
808
+ }
809
+ .matrx-page-break::after {
810
+ content: attr(data-label);
811
+ position: absolute;
812
+ left: 50%;
813
+ top: 0;
814
+ transform: translate(-50%, -50%);
815
+ padding: 0 0.75rem;
816
+ background: var(--matrx-print-bg, #ffffff);
817
+ color: var(--matrx-print-fg-subtle, #6b7280);
818
+ font: 600 10px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
819
+ letter-spacing: 0.08em;
820
+ text-transform: uppercase;
821
+ white-space: nowrap;
822
+ }
823
+
824
+ .matrx-artifact {
825
+ margin: 1.25em 0;
826
+ border: 1px solid var(--matrx-print-border, #e5e7eb);
827
+ border-radius: 8px;
828
+ overflow: hidden;
829
+ }
830
+ .matrx-artifact-header {
831
+ display: flex;
832
+ align-items: baseline;
833
+ gap: 0.6em;
834
+ padding: 0.45em 0.9em;
835
+ background: var(--matrx-print-surface, #f8fafc);
836
+ border-bottom: 1px solid var(--matrx-print-border, #e5e7eb);
837
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
838
+ }
839
+ .matrx-artifact-kind {
840
+ font-size: 0.72em;
841
+ font-weight: 700;
842
+ letter-spacing: 0.06em;
843
+ text-transform: uppercase;
844
+ color: var(--matrx-print-accent, #2563eb);
845
+ }
846
+ .matrx-artifact-title {
847
+ font-weight: 600;
848
+ color: var(--matrx-print-fg, #1a1a1a);
849
+ }
850
+ .matrx-artifact-body {
851
+ padding: 0.8em 0.9em;
852
+ }
853
+ .matrx-artifact-body > :first-child {
854
+ margin-top: 0;
855
+ }
856
+ .matrx-artifact-body > :last-child {
857
+ margin-bottom: 0;
858
+ }
859
+ .matrx-artifact-empty {
860
+ margin: 0;
861
+ font-style: italic;
862
+ color: var(--matrx-print-fg-subtle, #6b7280);
863
+ }
864
+
865
+ li.matrx-task-item {
866
+ list-style: none;
867
+ }
868
+ .matrx-task-box {
869
+ position: relative;
870
+ display: inline-block;
871
+ width: 0.9em;
872
+ height: 0.9em;
873
+ margin: 0 0.5em 0 -1.35em;
874
+ border: 1.5px solid var(--matrx-print-fg-muted, #4a4a4a);
875
+ border-radius: 3px;
876
+ vertical-align: -0.1em;
877
+ }
878
+ .matrx-task-box.is-checked::after {
879
+ content: "\\2713";
880
+ position: absolute;
881
+ inset: 0;
882
+ font-size: 0.8em;
883
+ font-weight: 700;
884
+ line-height: 1.1em;
885
+ text-align: center;
886
+ color: var(--matrx-print-fg, #1a1a1a);
887
+ }
888
+
889
+ :is(.matrx-content-container, .content) del {
890
+ color: var(--matrx-print-fg-muted, #4a4a4a);
891
+ text-decoration: line-through;
892
+ }
893
+ :is(.matrx-content-container, .content) hr.matrx-hr-accent {
894
+ height: 2px;
895
+ margin: 1.75em 0;
896
+ border: 0;
897
+ border-radius: 2px;
898
+ background: var(--matrx-print-accent, #2563eb);
899
+ opacity: 0.6;
900
+ }
901
+ :is(.matrx-content-container, .content) hr.matrx-hr-heavy {
902
+ height: 4px;
903
+ margin: 2.25em 0;
904
+ border: 0;
905
+ border-radius: 4px;
906
+ background: var(--matrx-print-accent, #2563eb);
907
+ }
908
+
909
+ .matrx-flashcards-print {
910
+ margin: 1em 0 1.2em;
911
+ }
912
+ .matrx-fc {
913
+ display: grid;
914
+ grid-template-columns: 1fr 1fr;
915
+ margin-bottom: 0.5em;
916
+ border: 1px solid var(--matrx-print-border, #e5e7eb);
917
+ border-radius: 6px;
918
+ }
919
+ .matrx-fc-front,
920
+ .matrx-fc-back {
921
+ padding: 0.6em 0.8em;
922
+ }
923
+ .matrx-fc-front {
924
+ font-weight: 600;
925
+ border-right: 1px dashed var(--matrx-print-border-muted, #d1d5db);
926
+ }
927
+ .matrx-fc-num {
928
+ display: inline-block;
929
+ min-width: 1.6em;
930
+ font-size: 0.85em;
931
+ color: var(--matrx-print-fg-subtle, #6b7280);
932
+ }
933
+
934
+ @media print {
935
+ .matrx-page-break {
936
+ margin: 0;
937
+ border: 0;
938
+ break-after: page;
939
+ page-break-after: always;
940
+ }
941
+ .matrx-page-break::after {
942
+ content: none;
943
+ }
944
+ .matrx-page-break + * {
945
+ margin-top: 0;
946
+ }
947
+
948
+ /* Scoped to the rendered markdown (.matrx-content-container = document
949
+ skin, .content = print window) so a host page that carries this sheet
950
+ \u2014 a WordPress theme \u2014 keeps its own print rules everywhere else. */
951
+
952
+ /* Long tables flow across pages: the header row repeats, rows never split. */
953
+ :is(.matrx-content-container, .content) thead {
954
+ display: table-header-group;
955
+ }
956
+ :is(.matrx-content-container, .content) :is(tr, img, figure),
957
+ .matrx-fc,
958
+ .matrx-task-item {
959
+ break-inside: avoid;
960
+ page-break-inside: avoid;
961
+ }
962
+ :is(.matrx-content-container, .content) :is(h1, h2, h3, h4, h5, h6),
963
+ .matrx-artifact-header {
964
+ break-after: avoid;
965
+ page-break-after: avoid;
966
+ break-inside: avoid;
967
+ }
968
+
969
+ /* Paper cannot scroll: long code lines wrap instead of being cut off. */
970
+ :is(.matrx-content-container, .content) :is(pre, pre code) {
971
+ white-space: pre-wrap !important;
972
+ overflow-wrap: anywhere;
973
+ overflow: visible !important;
974
+ }
975
+ .code-block-wrapper,
976
+ .matrx-artifact {
977
+ overflow: visible;
978
+ }
979
+ :is(.matrx-content-container, .content) img {
980
+ max-width: 100% !important;
981
+ }
982
+
983
+ .matrx-artifact-header,
984
+ .matrx-task-box {
985
+ -webkit-print-color-adjust: exact;
986
+ print-color-adjust: exact;
987
+ }
988
+
989
+ a.matrx-link[href^="http"]::after {
990
+ content: " (" attr(href) ")";
991
+ font-size: 0.85em;
992
+ color: var(--matrx-print-fg-subtle, #6b7280);
993
+ overflow-wrap: anywhere;
994
+ }
995
+ }
996
+ `;
997
+ var MARKDOWN_PAGE_CSS = `
998
+ @page {
999
+ margin: 0.6in 0.65in 0.7in;
1000
+ @bottom-center {
1001
+ content: counter(page) " / " counter(pages);
1002
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
1003
+ font-size: 8pt;
1004
+ color: var(--matrx-print-fg-subtle, #6b7280);
1005
+ }
1006
+ }
1007
+ `;
1008
+ var MARKDOWN_PAGE_PLAIN_CSS = `
1009
+ @page {
1010
+ margin: 0.6in 0.65in 0.7in;
1011
+ }
1012
+ `;
1013
+
1014
+ // src/directives.ts
1015
+ var PAGE_BREAK_MARKDOWN = "<!-- pagebreak -->";
1016
+ var PAGE_BREAK_CLASS = "matrx-page-break";
1017
+ var PAGE_BREAK_LABEL = "Page break";
1018
+ var COMMENT_FORM = /^<!--\s*(?:page[\s_-]?break|new[\s_-]?page)\s*-->$/i;
1019
+ var LATEX_FORM = /^\\(?:pagebreak|newpage|clearpage)\s*(?:\{\s*\})?$/i;
1020
+ var DIV_FORM = /^<div\b([^>]*)>\s*<\/div>$|^<div\b([^>]*)\/>$/i;
1021
+ var DIV_BREAK_ATTR = /(?:page-break-(?:after|before)\s*:\s*always|break-(?:after|before)\s*:\s*page|class\s*=\s*["'](?:[^"']*\s)?page-?break(?:\s[^"']*)?["'])/i;
1022
+ function isPageBreakLine(line) {
1023
+ const t = line.trim();
1024
+ if (t.length < 8 || t.length > 200) return false;
1025
+ if (COMMENT_FORM.test(t) || LATEX_FORM.test(t)) return true;
1026
+ const div = DIV_FORM.exec(t);
1027
+ if (!div) return false;
1028
+ return DIV_BREAK_ATTR.test(div[1] ?? div[2] ?? "");
1029
+ }
1030
+ function splitAtPageBreaks(markdown) {
1031
+ const lines = markdown.split(/\r?\n/);
1032
+ const pieces = [];
1033
+ let current = [];
1034
+ let fence = null;
1035
+ for (const line of lines) {
1036
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
1037
+ if (fenceMatch) {
1038
+ const marker = fenceMatch[1];
1039
+ if (fence === null) fence = marker;
1040
+ else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null;
1041
+ } else if (fence === null && isPageBreakLine(line)) {
1042
+ if (current.join("\n").trim()) pieces.push(current.join("\n"));
1043
+ current = [];
1044
+ continue;
1045
+ }
1046
+ current.push(line);
1047
+ }
1048
+ if (current.join("\n").trim() || pieces.length === 0) pieces.push(current.join("\n"));
1049
+ return pieces;
1050
+ }
794
1051
 
795
1052
  // src/markdown.ts
796
1053
  function removeThinkingContent(content) {
@@ -803,80 +1060,166 @@ function hasThinkingContent(content) {
803
1060
  if (!content) return false;
804
1061
  return /<thinking>|<think>|<reasoning>/i.test(content);
805
1062
  }
806
- function convertMarkdownTables(html) {
807
- const tableRegex = /^(\|.*\|)\s*\n(\|[-\s:|]*\|)\s*\n((?:\|.*\|\s*\n?)*)/gm;
808
- return html.replace(
809
- tableRegex,
810
- (_match, headerRow, _separatorRow, bodyRows) => {
811
- const headers = headerRow.split("|").map((cell) => cell.trim()).filter((cell) => cell !== "");
812
- const rows = bodyRows.trim().split("\n").filter((row) => row.trim()).map(
813
- (row) => row.split("|").map((cell) => cell.trim()).filter((cell) => cell !== "")
814
- );
815
- let tableHtml = '<table class="matrx-table">\n';
816
- if (headers.length > 0) {
817
- tableHtml += '<thead class="matrx-table-head">\n<tr class="matrx-table-row">\n';
818
- for (const header of headers) {
819
- tableHtml += `<th class="matrx-table-header">${header}</th>
820
- `;
821
- }
822
- tableHtml += "</tr>\n</thead>\n";
823
- }
824
- if (rows.length > 0) {
825
- tableHtml += '<tbody class="matrx-table-body">\n';
826
- for (const row of rows) {
827
- if (row.length === 0) continue;
828
- tableHtml += '<tr class="matrx-table-row">\n';
829
- for (const cell of row) {
830
- tableHtml += `<td class="matrx-table-cell">${cell}</td>
831
- `;
832
- }
833
- tableHtml += "</tr>\n";
834
- }
835
- tableHtml += "</tbody>\n";
836
- }
837
- return `${tableHtml}</table>
838
- `;
1063
+ var TOKEN_OPEN = "\uE000";
1064
+ var TOKEN_CLOSE = "\uE001";
1065
+ var BLOCK_TOKEN = (i) => `${TOKEN_OPEN}B${i}${TOKEN_CLOSE}`;
1066
+ var INLINE_TOKEN = (i) => `${TOKEN_OPEN}I${i}${TOKEN_CLOSE}`;
1067
+ var TOKEN_RE = /\uE000([BI])(\d+)\uE001/g;
1068
+ var PARAGRAPH_WRAPPED_BLOCK_RE = /<p[^>]*>\s*(\uE000B\d+\uE001)\s*<\/p>/g;
1069
+ var Stash = class {
1070
+ items = [];
1071
+ block(html) {
1072
+ return BLOCK_TOKEN(this.items.push(html) - 1);
1073
+ }
1074
+ inline(html) {
1075
+ return INLINE_TOKEN(this.items.push(html) - 1);
1076
+ }
1077
+ restore(html) {
1078
+ let out = html;
1079
+ for (let pass = 0; pass < 8 && out.includes(TOKEN_OPEN); pass++) {
1080
+ out = out.replace(PARAGRAPH_WRAPPED_BLOCK_RE, "$1").replace(TOKEN_RE, (_m, _k, i) => this.items[Number(i)] ?? "");
839
1081
  }
840
- );
1082
+ return out;
1083
+ }
1084
+ };
1085
+ var DOCUMENT_GRAMMAR = {
1086
+ skin: "document",
1087
+ table: "matrx-table",
1088
+ thead: "matrx-table-head",
1089
+ tbody: "matrx-table-body",
1090
+ tr: "matrx-table-row",
1091
+ th: "matrx-table-header",
1092
+ td: "matrx-table-cell",
1093
+ ul: "matrx-list matrx-bullet-list",
1094
+ ol: "matrx-list matrx-numbered-list",
1095
+ ulNested: "matrx-list matrx-bullet-list matrx-nested-list",
1096
+ olNested: "matrx-list matrx-numbered-list matrx-nested-list",
1097
+ li: "matrx-list-item",
1098
+ hr: "matrx-hr",
1099
+ del: "matrx-del",
1100
+ strong: "matrx-strong",
1101
+ em: "matrx-em",
1102
+ inlineCode: "matrx-inline-code"
1103
+ };
1104
+ var ARTICLE_GRAMMAR = {
1105
+ skin: "article",
1106
+ table: "print-table",
1107
+ thead: "",
1108
+ tbody: "",
1109
+ tr: "",
1110
+ th: "",
1111
+ td: "",
1112
+ ul: "",
1113
+ ol: "",
1114
+ ulNested: "",
1115
+ olNested: "",
1116
+ li: "",
1117
+ hr: "",
1118
+ del: "",
1119
+ strong: "",
1120
+ em: "",
1121
+ inlineCode: "inline-code"
1122
+ };
1123
+ var cls = (...names) => {
1124
+ const joined = names.filter(Boolean).join(" ");
1125
+ return joined ? ` class="${joined}"` : "";
1126
+ };
1127
+ var PAGE_BREAK_HTML = `<div class="${PAGE_BREAK_CLASS}" role="separator" aria-label="${PAGE_BREAK_LABEL}" data-label="${PAGE_BREAK_LABEL}"></div>`;
1128
+ function codeBlockHtml(g, code, language) {
1129
+ const body = (0, import_html_escape2.escapeHtml)(code.replace(/\n$/, ""));
1130
+ const lang = language.trim();
1131
+ if (g.skin === "article") {
1132
+ const label = lang ? `<span class="code-lang">${(0, import_html_escape2.escapeHtml)(lang)}</span>` : "";
1133
+ return `<div class="code-block-wrapper">${label}<pre class="code-block"><code>${body}</code></pre></div>`;
1134
+ }
1135
+ const dataLang = lang ? ` data-language="${(0, import_html_escape2.escapeHtml)(lang)}"` : "";
1136
+ return `<pre class="matrx-code-block"${dataLang}><code class="matrx-code">${body}</code></pre>`;
1137
+ }
1138
+ var CODE_ARTIFACT_LANGUAGE = {
1139
+ html: "html",
1140
+ react: "tsx",
1141
+ svg: "svg",
1142
+ mermaid: "mermaid",
1143
+ diff: "diff",
1144
+ iframe: "html",
1145
+ code: ""
1146
+ };
1147
+ var ARTIFACT_TYPE_LABEL = {
1148
+ html: "HTML",
1149
+ svg: "SVG",
1150
+ react: "React",
1151
+ iframe: "Embed"
1152
+ };
1153
+ function parseTagAttributes(tag) {
1154
+ const attrs = {};
1155
+ for (const m of tag.matchAll(/([a-zA-Z_][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
1156
+ attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? "";
1157
+ }
1158
+ return attrs;
1159
+ }
1160
+ function artifactLabel(type) {
1161
+ if (!type) return "Artifact";
1162
+ return ARTIFACT_TYPE_LABEL[type] ?? type.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1163
+ }
1164
+ function looksLikeJson(body) {
1165
+ const t = body.trim();
1166
+ if (!/^[[{]/.test(t)) return false;
1167
+ try {
1168
+ JSON.parse(t);
1169
+ return true;
1170
+ } catch {
1171
+ return false;
1172
+ }
841
1173
  }
842
- function markdownToHtml(markdown, options = {}) {
843
- const notice = options.onNotice;
844
- if (!markdown) {
845
- notice?.({
846
- code: "empty-output",
847
- message: "markdownToHtml received an empty string.",
848
- remedy: "Check the content is loaded before converting; nothing was rendered."
849
- });
850
- return "";
1174
+ function artifactHtml(g, attrs, body, ctx) {
1175
+ const type = (attrs.type ?? "").toLowerCase();
1176
+ const title = attrs.title?.trim() ?? "";
1177
+ const header = `<div class="matrx-artifact-header"><span class="matrx-artifact-kind">${(0, import_html_escape2.escapeHtml)(
1178
+ artifactLabel(type)
1179
+ )}</span>${title ? `<span class="matrx-artifact-title">${(0, import_html_escape2.escapeHtml)(title)}</span>` : ""}</div>`;
1180
+ let inner;
1181
+ const trimmed = (body ?? "").replace(/^\n+|\n+$/g, "");
1182
+ if (body === null || !trimmed.trim()) {
1183
+ inner = `<p class="matrx-artifact-empty">Saved artifact \u2014 open it in AI Matrx to view its content.</p>`;
1184
+ } else if (/^\s*(`{3,}|~{3,})/.test(trimmed)) {
1185
+ inner = convertBody(g.skin, trimmed, ctx);
1186
+ } else if (type in CODE_ARTIFACT_LANGUAGE) {
1187
+ inner = codeBlockHtml(g, trimmed, CODE_ARTIFACT_LANGUAGE[type] || attrs.language || attrs.lang || "");
1188
+ } else if (looksLikeJson(trimmed)) {
1189
+ inner = codeBlockHtml(g, JSON.stringify(JSON.parse(trimmed), null, 2), "json");
1190
+ } else {
1191
+ inner = convertBody(g.skin, trimmed, ctx);
851
1192
  }
852
- const startWrapper = '<div class="matrx-content-container">';
853
- const endWrapper = "</div>";
854
- let html = options.includeThinking ? markdown : removeThinkingContent(markdown);
855
- const flashcardPlaceholders = [];
856
- let flashcardIndex = 0;
857
- let globalCardIndex = 0;
858
- html = html.replace(
859
- /<flashcards>([\s\S]*?)<\/flashcards>/gi,
860
- (_match, content) => {
861
- const cards = content.split(/\n*---\n*/g).map((card) => card.trim()).filter((card) => card.length > 0);
862
- if (cards.length === 0) return "";
863
- let flashcardsHtml = '<div class="matrx-flashcards-container">\n';
864
- for (const card of cards) {
865
- const frontMatch = card.match(/Front:\s*(.+?)(?=\n|$)/i);
866
- const backMatch = card.match(/Back:\s*([\s\S]+?)$/i);
867
- const front = frontMatch?.[1]?.trim();
868
- const back = backMatch?.[1]?.trim();
869
- if (!front || !back) {
870
- notice?.({
871
- code: "flashcard-malformed",
872
- message: `A flashcard was skipped: it is missing a ${front ? "Back:" : "Front:"} line.`,
873
- remedy: 'Every card inside <flashcards> needs both "Front: \u2026" and "Back: \u2026", separated from the next card by ---.'
874
- });
875
- continue;
876
- }
877
- globalCardIndex++;
878
- const cardId = `card${globalCardIndex}`;
879
- flashcardsHtml += ` <div class="matrx-flashcard">
1193
+ return `<section class="matrx-artifact" data-artifact-type="${(0, import_html_escape2.escapeHtml)(type || "artifact")}">${header}<div class="matrx-artifact-body">${inner}</div></section>`;
1194
+ }
1195
+ function parseFlashcards(content, notice) {
1196
+ const cards = [];
1197
+ for (const card of content.split(/\n*---\n*/g).map((c) => c.trim()).filter(Boolean)) {
1198
+ const front = card.match(/Front:\s*(.+?)(?=\n|$)/i)?.[1]?.trim();
1199
+ const back = card.match(/Back:\s*([\s\S]+?)$/i)?.[1]?.trim();
1200
+ if (!front || !back) {
1201
+ notice?.({
1202
+ code: "flashcard-malformed",
1203
+ message: `A flashcard was skipped: it is missing a ${front ? "Back:" : "Front:"} line.`,
1204
+ remedy: 'Every card inside <flashcards> needs both "Front: \u2026" and "Back: \u2026", separated from the next card by ---.'
1205
+ });
1206
+ continue;
1207
+ }
1208
+ cards.push({ front, back });
1209
+ }
1210
+ return cards;
1211
+ }
1212
+ function flashcardsHtml(g, cards, ctx) {
1213
+ if (g.skin === "article") {
1214
+ return `<div class="matrx-flashcards-print">${cards.map(
1215
+ (c, i) => `<div class="matrx-fc"><div class="matrx-fc-front"><span class="matrx-fc-num">${i + 1}</span>${c.front}</div><div class="matrx-fc-back">${c.back}</div></div>`
1216
+ ).join("")}</div>`;
1217
+ }
1218
+ let out = '<div class="matrx-flashcards-container">\n';
1219
+ for (const { front, back } of cards) {
1220
+ ctx.cardIndex++;
1221
+ const cardId = `card${ctx.cardIndex}`;
1222
+ out += ` <div class="matrx-flashcard">
880
1223
  <input type="checkbox" class="matrx-flashcard-input" id="${cardId}">
881
1224
  <label for="${cardId}" class="matrx-flashcard-label"></label>
882
1225
  <div class="matrx-flashcard-inner">
@@ -896,154 +1239,318 @@ function markdownToHtml(markdown, options = {}) {
896
1239
  </div>
897
1240
 
898
1241
  `;
1242
+ }
1243
+ return `${out}</div>
1244
+ `;
1245
+ }
1246
+ var FENCE_OPEN = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
1247
+ function protectRegions(markdown, g, stash, ctx) {
1248
+ const lines = markdown.split(/\r?\n/);
1249
+ const out = [];
1250
+ for (let i = 0; i < lines.length; i++) {
1251
+ const line = lines[i];
1252
+ const fence = FENCE_OPEN.exec(line);
1253
+ if (fence) {
1254
+ const marker = fence[2];
1255
+ const code = [];
1256
+ let j = i + 1;
1257
+ for (; j < lines.length; j++) {
1258
+ const close = /^\s*(`{3,}|~{3,})\s*$/.exec(lines[j]);
1259
+ if (close && close[1][0] === marker[0] && close[1].length >= marker.length) break;
1260
+ code.push(lines[j]);
899
1261
  }
900
- flashcardsHtml += "</div>\n";
901
- const placeholder = `\u03A9FLASHCARD\u03A9${flashcardIndex}\u03A9FLASHCARD\u03A9`;
902
- flashcardPlaceholders.push({ placeholder, html: flashcardsHtml });
903
- flashcardIndex++;
904
- return placeholder;
1262
+ const indent = fence[1].length;
1263
+ const dedented = code.map((l) => l.slice(Math.min(indent, l.length - l.trimStart().length)));
1264
+ out.push(stash.block(codeBlockHtml(g, dedented.join("\n"), fence[3] ?? "")));
1265
+ i = j;
1266
+ continue;
1267
+ }
1268
+ if (isPageBreakLine(line)) {
1269
+ out.push(stash.block(PAGE_BREAK_HTML));
1270
+ continue;
905
1271
  }
1272
+ const open = /^\s*<artifact\b((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>(.*)$/i.exec(line);
1273
+ if (open) {
1274
+ const attrs = parseTagAttributes(open[1] ?? "");
1275
+ if (open[2] === "/") {
1276
+ out.push(stash.block(artifactHtml(g, attrs, null, ctx)));
1277
+ if (open[3]?.trim()) out.push(open[3]);
1278
+ continue;
1279
+ }
1280
+ const bodyLines = [];
1281
+ let rest = open[3] ?? "";
1282
+ let after = "";
1283
+ let j = i;
1284
+ let inFence = null;
1285
+ for (; ; ) {
1286
+ const closeAt = inFence ? -1 : rest.search(/<\/artifact\s*>/i);
1287
+ if (closeAt >= 0) {
1288
+ bodyLines.push(rest.slice(0, closeAt));
1289
+ after = rest.slice(closeAt).replace(/^<\/artifact\s*>/i, "");
1290
+ break;
1291
+ }
1292
+ bodyLines.push(rest);
1293
+ const f = /^\s*(`{3,}|~{3,})/.exec(rest);
1294
+ if (f) {
1295
+ const m = f[1];
1296
+ if (inFence === null) inFence = m;
1297
+ else if (m[0] === inFence[0] && m.length >= inFence.length) inFence = null;
1298
+ }
1299
+ j++;
1300
+ if (j >= lines.length) break;
1301
+ rest = lines[j];
1302
+ }
1303
+ const html = ctx.depth >= 3 ? codeBlockHtml(g, bodyLines.join("\n"), "") : artifactHtml(g, attrs, bodyLines.join("\n"), { ...ctx, depth: ctx.depth + 1 });
1304
+ out.push(stash.block(html));
1305
+ if (after.trim()) out.push(after);
1306
+ i = j;
1307
+ continue;
1308
+ }
1309
+ out.push(line);
1310
+ }
1311
+ let text = out.join("\n");
1312
+ text = text.replace(
1313
+ /`([^`\n]+)`/g,
1314
+ (_m, code) => stash.inline(`<code${cls(g.inlineCode)}>${(0, import_html_escape2.escapeHtml)(code)}</code>`)
906
1315
  );
907
- html = html.replace(/^[-]{3,}$/gm, '<hr class="matrx-hr">');
908
- html = html.replace(/^[*]{3,}$/gm, '<hr class="matrx-hr">');
909
- const imagePlaceholders = [];
910
- let imageIndex = 0;
911
- html = html.replace(
912
- /!\[([^\]]*)\]\(([^)]+)\)/g,
913
- (_match, altText, url) => {
914
- const placeholder = `\u03A9IMAGE\u03A9${imageIndex}\u03A9IMAGE\u03A9`;
915
- imagePlaceholders.push({
916
- placeholder,
917
- html: `<img class="matrx-image" src="${url}" alt="${altText}" />`
918
- });
919
- imageIndex++;
920
- return placeholder;
1316
+ text = text.replace(/<!--[\s\S]*?-->/g, "");
1317
+ const before = text;
1318
+ for (let pass = 0; pass < 8; pass++) {
1319
+ const next = text.replace(/<(script|style|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "").replace(/<\/?(?:script|style|head|html|body)\b[^>]*>/gi, "").replace(/<!DOCTYPE[^>]*>/gi, "");
1320
+ if (next === text) break;
1321
+ text = next;
1322
+ }
1323
+ text = sanitizeRawTags(text);
1324
+ if (text !== before && !ctx.strippedAnnounced) {
1325
+ ctx.strippedAnnounced = true;
1326
+ ctx.options.onNotice?.({
1327
+ code: "html-stripped",
1328
+ message: "Unsafe or page-level markup (a <script>, <style>, <head>, an <html>/<body> shell, an on\u2026 event handler, or a javascript: URL) was removed from the rendered copy.",
1329
+ remedy: 'To show a full HTML page, put it in an ```html fence or an <artifact type="html"> block \u2014 it is printed as its source.'
1330
+ });
1331
+ }
1332
+ text = text.replace(/<flashcards>([\s\S]*?)<\/flashcards>/gi, (_m, content) => {
1333
+ const cards = parseFlashcards(content, ctx.options.onNotice);
1334
+ return cards.length ? `
1335
+ ${stash.block(flashcardsHtml(g, cards, ctx))}
1336
+ ` : "";
1337
+ });
1338
+ return text;
1339
+ }
1340
+ var URL_ATTRS = /* @__PURE__ */ new Set(["href", "src", "action", "formaction", "xlink:href", "poster", "background"]);
1341
+ function decodeForSchemeCheck(value) {
1342
+ return value.replace(/&#x([0-9a-f]+);?/gi, (_m, h) => String.fromCharCode(parseInt(h, 16))).replace(/&#(\d+);?/g, (_m, d) => String.fromCharCode(Number(d))).replace(/&colon;/gi, ":").replace(/[\u0000-\u0020]+/g, "").toLowerCase();
1343
+ }
1344
+ function sanitizeRawTags(text) {
1345
+ return text.replace(
1346
+ /<([a-zA-Z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/g,
1347
+ (whole, tag, rawAttrs) => {
1348
+ if (!/[=\s]/.test(rawAttrs)) return whole;
1349
+ let changed = false;
1350
+ const attrs = rawAttrs.replace(
1351
+ /(\s+)([^\s"'=<>/]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,
1352
+ (m, _sp, name, _eq, dq, sq, bare) => {
1353
+ const lower = name.toLowerCase();
1354
+ if (lower.startsWith("on") || lower === "srcdoc") {
1355
+ changed = true;
1356
+ return "";
1357
+ }
1358
+ if (URL_ATTRS.has(lower)) {
1359
+ const value = decodeForSchemeCheck(dq ?? sq ?? bare ?? "");
1360
+ if (/^(?:javascript|vbscript):|^data:text\/html/.test(value)) {
1361
+ changed = true;
1362
+ return ` ${name}="#"`;
1363
+ }
1364
+ }
1365
+ return m;
1366
+ }
1367
+ );
1368
+ return changed ? `<${tag}${attrs}>` : whole;
921
1369
  }
922
1370
  );
923
- const linkPlaceholders = [];
924
- let linkIndex = 0;
925
- html = html.replace(
926
- /\[([^\]]+)\]\(([^)]+)\)/g,
927
- (_match, linkText, url) => {
928
- const placeholder = `\u03A9LINK\u03A9${linkIndex}\u03A9LINK\u03A9`;
929
- linkPlaceholders.push({
930
- placeholder,
931
- html: `<a class="matrx-link" href="${url}">${linkText}</a>`
1371
+ }
1372
+ function safeUrl(url) {
1373
+ const u = url.trim();
1374
+ if (/^(?:javascript|vbscript):|^data:text\/html/.test(decodeForSchemeCheck(u))) return "#";
1375
+ return u.replace(/"/g, "%22");
1376
+ }
1377
+ function convertEmphasis(html, g) {
1378
+ const strong = `<strong${cls(g.strong)}>`;
1379
+ const em = `<em${cls(g.em)}>`;
1380
+ return html.replace(/\*\*\*(?!\s)(.+?)(?<!\s)\*\*\*/g, `${strong}${em}$1</em></strong>`).replace(/\*\*(?!\s)(.+?)(?<!\s)\*\*/g, `${strong}$1</strong>`).replace(/(?<![\w*])\*(?![\s*])(.+?)(?<![\s*])\*(?![\w*])/g, `${em}$1</em>`).replace(/(?<![\w_])___(?!\s)(.+?)(?<!\s)___(?![\w_])/g, `${strong}${em}$1</em></strong>`).replace(/(?<![\w_])__(?!\s)(.+?)(?<!\s)__(?![\w_])/g, `${strong}$1</strong>`).replace(/(?<![\w_])_(?![\s_])(.+?)(?<![\s_])_(?![\w_])/g, `${em}$1</em>`).replace(/~~(?!\s)(.+?)(?<!\s)~~/g, `<del${cls(g.del)}>$1</del>`);
1381
+ }
1382
+ var LINK_URL = String.raw`((?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?`;
1383
+ var IMAGE_RE = new RegExp(String.raw`!\[([^\]]*)\]\(` + LINK_URL + String.raw`\)`, "g");
1384
+ var LINK_RE = new RegExp(String.raw`\[([^\]]+)\]\(` + LINK_URL + String.raw`\)`, "g");
1385
+ function convertRules(html, g) {
1386
+ return html.replace(/^\s{0,3}#\s*={3,}\s*$/gm, `<hr${cls(g.hr, "matrx-hr-heavy")}>`).replace(/^\s{0,3}\*(?:\s*\*){2,}\s*$/gm, `<hr${cls(g.hr, "matrx-hr-accent")}>`).replace(/^\s{0,3}(?:-\s*){3,}$/gm, `<hr${cls(g.hr)}>`).replace(/^\s{0,3}(?:_\s*){3,}$/gm, `<hr${cls(g.hr)}>`);
1387
+ }
1388
+ function splitTableRow(row) {
1389
+ let r = row.trim();
1390
+ if (r.startsWith("|")) r = r.slice(1);
1391
+ if (r.endsWith("|") && !r.endsWith("\\|")) r = r.slice(0, -1);
1392
+ return r.split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
1393
+ }
1394
+ function cellAlign(separator) {
1395
+ const s = separator.trim();
1396
+ const left = s.startsWith(":");
1397
+ const right = s.endsWith(":");
1398
+ if (left && right) return ' style="text-align:center"';
1399
+ if (right) return ' style="text-align:right"';
1400
+ return "";
1401
+ }
1402
+ function convertTables(html, g) {
1403
+ const tableRegex = /^(\|.*\|)\s*\n(\|[-\s:|]*\|)\s*\n((?:\|.*\|\s*\n?)*)/gm;
1404
+ return html.replace(
1405
+ tableRegex,
1406
+ (_m, headerRow, separatorRow, bodyRows) => {
1407
+ const headers = splitTableRow(headerRow);
1408
+ const aligns = splitTableRow(separatorRow).map(cellAlign);
1409
+ const rows = bodyRows.trim().split("\n").filter((r) => r.trim()).map(splitTableRow);
1410
+ let t = `<table${cls(g.table)}>
1411
+ <thead${cls(g.thead)}>
1412
+ <tr${cls(g.tr)}>
1413
+ `;
1414
+ headers.forEach((h, i) => {
1415
+ t += `<th${cls(g.th)}${aligns[i] ?? ""}>${h}</th>
1416
+ `;
932
1417
  });
933
- linkIndex++;
934
- return placeholder;
1418
+ t += "</tr>\n</thead>\n";
1419
+ if (rows.length > 0) {
1420
+ t += `<tbody${cls(g.tbody)}>
1421
+ `;
1422
+ for (const row of rows) {
1423
+ t += `<tr${cls(g.tr)}>
1424
+ `;
1425
+ row.forEach((c, i) => {
1426
+ t += `<td${cls(g.td)}${aligns[i] ?? ""}>${c}</td>
1427
+ `;
1428
+ });
1429
+ t += "</tr>\n";
1430
+ }
1431
+ t += "</tbody>\n";
1432
+ }
1433
+ return `${t}</table>
1434
+ `;
935
1435
  }
936
1436
  );
937
- html = html.replace(/^# (.+)$/gm, '<h1 class="matrx-h1">$1</h1>').replace(/^## (.+)$/gm, '<h2 class="matrx-h2">$1</h2>').replace(/^### (.+)$/gm, '<h3 class="matrx-h3">$1</h3>').replace(/^#### (.+)$/gm, '<h4 class="matrx-h4">$1</h4>').replace(/^##### (.+)$/gm, '<h5 class="matrx-h5">$1</h5>').replace(/^###### (.+)$/gm, '<h6 class="matrx-h6">$1</h6>');
938
- html = html.replace(/\*\*(.+?)\*\*/g, '<strong class="matrx-strong">$1</strong>').replace(/\*(.+?)\*/g, '<em class="matrx-em">$1</em>').replace(/__(.+?)__/g, '<strong class="matrx-strong">$1</strong>').replace(/_(.+?)_/g, '<em class="matrx-em">$1</em>');
1437
+ }
1438
+ function convertLists(html, g) {
939
1439
  const lines = html.split("\n");
940
- let processedHtml = "";
1440
+ let processed = "";
941
1441
  const listStack = [];
942
1442
  let lastListItem = "";
1443
+ const li = `<li${cls(g.li)}>`;
943
1444
  const top = () => listStack[listStack.length - 1];
944
- const closeDeeperThan = (indent) => {
945
- while (listStack.length > 0 && top().indent > indent) {
946
- if (lastListItem) {
947
- processedHtml += "</li>\n";
948
- lastListItem = "";
949
- }
950
- const closing = listStack.pop();
951
- if (!closing) break;
952
- processedHtml += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
953
- if (listStack.length > 0) processedHtml += "</li>\n";
1445
+ const openTag = (type, nested) => type === "ol" ? `<ol${cls(nested ? g.olNested : g.ol)}>
1446
+ ` : `<ul${cls(nested ? g.ulNested : g.ul)}>
1447
+ `;
1448
+ const popOne = () => {
1449
+ if (lastListItem) {
1450
+ processed += "</li>\n";
1451
+ lastListItem = "";
954
1452
  }
1453
+ const closing = listStack.pop();
1454
+ if (!closing) return;
1455
+ processed += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
1456
+ if (listStack.length > 0) processed += "</li>\n";
1457
+ };
1458
+ const closeDeeperThan = (indent) => {
1459
+ while (listStack.length > 0 && top().indent > indent) popOne();
955
1460
  };
956
1461
  for (const line of lines) {
957
- const numberedMatch = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
958
- if (numberedMatch) {
959
- const indent = (numberedMatch[1] ?? "").length;
960
- const content = numberedMatch[3] ?? "";
1462
+ const numbered = line.match(/^(\s*)(\d+)[.)]\s+(.+)$/);
1463
+ const bullet = numbered ? null : line.match(/^(\s*)[*\-+]\s+(.+)$/);
1464
+ if (numbered || bullet) {
1465
+ const type = numbered ? "ol" : "ul";
1466
+ const indent = (numbered ?? bullet)[1]?.length ?? 0;
1467
+ const content = (numbered ? numbered[3] : bullet[2]) ?? "";
961
1468
  const current = top();
962
1469
  if (current && indent > current.indent) {
963
- processedHtml += '\n<ol class="matrx-list matrx-numbered-list matrx-nested-list">\n';
964
- listStack.push({ type: "ol", indent });
965
- processedHtml += `<li class="matrx-list-item">${content}`;
966
- lastListItem = "ol";
1470
+ processed += `
1471
+ ${openTag(type, true)}`;
1472
+ listStack.push({ type, indent });
967
1473
  } else {
968
1474
  closeDeeperThan(indent);
969
- if (lastListItem && top()?.indent === indent) processedHtml += "</li>\n";
1475
+ if (lastListItem && top()?.indent === indent) processed += "</li>\n";
970
1476
  const now = top();
971
- if (!now || now.indent !== indent || now.type !== "ol") {
972
- processedHtml += '<ol class="matrx-list matrx-numbered-list">\n';
973
- listStack.push({ type: "ol", indent });
1477
+ if (now && now.indent === indent && now.type !== type) {
1478
+ const closing = listStack.pop();
1479
+ processed += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
974
1480
  }
975
- processedHtml += `<li class="matrx-list-item">${content}`;
976
- lastListItem = "ol";
977
- }
978
- continue;
979
- }
980
- const bulletMatch = line.match(/^(\s*)[*\-+]\s+(.+)$/);
981
- if (bulletMatch) {
982
- const indent = (bulletMatch[1] ?? "").length;
983
- const content = bulletMatch[2] ?? "";
984
- const current = top();
985
- if (current && indent > current.indent) {
986
- processedHtml += '\n<ul class="matrx-list matrx-bullet-list matrx-nested-list">\n';
987
- listStack.push({ type: "ul", indent });
988
- processedHtml += `<li class="matrx-list-item">${content}`;
989
- lastListItem = "ul";
990
- } else {
991
- closeDeeperThan(indent);
992
- if (lastListItem && top()?.indent === indent) processedHtml += "</li>\n";
993
- const now = top();
994
- if (!now || now.indent !== indent || now.type !== "ul") {
995
- processedHtml += '<ul class="matrx-list matrx-bullet-list">\n';
996
- listStack.push({ type: "ul", indent });
1481
+ const after = top();
1482
+ if (!after || after.indent !== indent || after.type !== type) {
1483
+ processed += openTag(type, listStack.length > 0);
1484
+ listStack.push({ type, indent });
997
1485
  }
998
- processedHtml += `<li class="matrx-list-item">${content}`;
999
- lastListItem = "ul";
1000
1486
  }
1487
+ processed += `${li}${content}`;
1488
+ lastListItem = type;
1001
1489
  continue;
1002
1490
  }
1003
1491
  if (line.trim() !== "") {
1004
- while (listStack.length > 0) {
1005
- if (lastListItem) {
1006
- processedHtml += "</li>\n";
1007
- lastListItem = "";
1008
- }
1009
- const closing = listStack.pop();
1010
- if (!closing) break;
1011
- processedHtml += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
1012
- if (listStack.length > 0) processedHtml += "</li>\n";
1013
- }
1492
+ while (listStack.length > 0) popOne();
1014
1493
  }
1015
- processedHtml += `${line}
1494
+ processed += `${line}
1016
1495
  `;
1017
1496
  }
1018
- while (listStack.length > 0) {
1019
- if (lastListItem) {
1020
- processedHtml += "</li>\n";
1021
- lastListItem = "";
1022
- }
1023
- const closing = listStack.pop();
1024
- if (!closing) break;
1025
- processedHtml += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
1026
- if (listStack.length > 0) processedHtml += "</li>\n";
1497
+ while (listStack.length > 0) popOne();
1498
+ return processed.replace(
1499
+ /<li( class="([^"]*)")?>\s*\[([ xX])\]\s+/g,
1500
+ (_m, _c, classes, mark) => `<li${cls(classes ?? "", "matrx-task-item")}><span class="matrx-task-box${mark === " " ? "" : " is-checked"}" aria-hidden="true"></span>`
1501
+ );
1502
+ }
1503
+ function convertBody(skin, markdown, ctx) {
1504
+ return skin === "article" ? articleBody(markdown, ctx) : documentBody(markdown, ctx);
1505
+ }
1506
+ function scrubTokens(markdown) {
1507
+ return markdown.replace(/[\uE000\uE001]/g, "");
1508
+ }
1509
+ function newContext(options) {
1510
+ return { options, depth: 0, cardIndex: 0, strippedAnnounced: false };
1511
+ }
1512
+ function markdownToHtml(markdown, options = {}) {
1513
+ if (!markdown) {
1514
+ options.onNotice?.({
1515
+ code: "empty-output",
1516
+ message: "markdownToHtml received an empty string.",
1517
+ remedy: "Check the content is loaded before converting; nothing was rendered."
1518
+ });
1519
+ return "";
1027
1520
  }
1028
- html = processedHtml;
1029
- html = html.replace(/^> (.+)$/gm, '<blockquote class="matrx-blockquote">$1</blockquote>');
1521
+ const source = scrubTokens(options.includeThinking ? markdown : removeThinkingContent(markdown));
1522
+ return `<div class="matrx-content-container">${documentBody(source, newContext(options))}</div>`;
1523
+ }
1524
+ function documentBody(markdown, ctx) {
1525
+ const g = DOCUMENT_GRAMMAR;
1526
+ const stash = new Stash();
1527
+ let html = protectRegions(markdown, g, stash, ctx);
1528
+ html = convertRules(html, g);
1030
1529
  html = html.replace(
1031
- /```([^`]+)```/gs,
1032
- '<pre class="matrx-code-block"><code class="matrx-code">$1</code></pre>'
1530
+ IMAGE_RE,
1531
+ (_m, alt, url) => stash.block(`<img class="matrx-image" src="${safeUrl(url)}" alt="${(0, import_html_escape2.escapeHtml)(alt)}" />`)
1033
1532
  );
1034
- html = html.replace(/`([^`]+)`/g, '<code class="matrx-inline-code">$1</code>');
1035
- html = convertMarkdownTables(html);
1036
- html = html.replace(/<table>/g, '<table class="matrx-table">').replace(/<thead>/g, '<thead class="matrx-table-head">').replace(/<tbody>/g, '<tbody class="matrx-table-body">').replace(/<tr>/g, '<tr class="matrx-table-row">').replace(/<th>/g, '<th class="matrx-table-header">').replace(/<td>/g, '<td class="matrx-table-cell">');
1037
- html = html.replace(/<img([^>]*)>/g, '<img class="matrx-image"$1>');
1038
- html = html.replace(/<div(?!\s+class="matrx-)([^>]*)>/g, '<div class="matrx-div"$1>');
1039
- html = html.replace(/<span([^>]*)>/g, '<span class="matrx-span"$1>');
1040
- html = html.replace(/^([^<\n].+)$/gm, '<p class="matrx-paragraph">$1</p>');
1041
1533
  html = html.replace(
1042
- /<\/p>\s*<p class="matrx-paragraph">/g,
1043
- '</p><p class="matrx-paragraph">'
1534
+ LINK_RE,
1535
+ (_m, text, url) => stash.inline(`<a class="matrx-link" href="${safeUrl(url)}">${convertEmphasis(text, g)}</a>`)
1044
1536
  );
1537
+ html = html.replace(/^# (.+)$/gm, '<h1 class="matrx-h1">$1</h1>').replace(/^## (.+)$/gm, '<h2 class="matrx-h2">$1</h2>').replace(/^### (.+)$/gm, '<h3 class="matrx-h3">$1</h3>').replace(/^#### (.+)$/gm, '<h4 class="matrx-h4">$1</h4>').replace(/^##### (.+)$/gm, '<h5 class="matrx-h5">$1</h5>').replace(/^###### (.+)$/gm, '<h6 class="matrx-h6">$1</h6>');
1538
+ html = convertLists(html, g);
1539
+ html = convertEmphasis(html, g);
1540
+ html = html.replace(/^> ?(.+)$/gm, '<blockquote class="matrx-blockquote">$1</blockquote>');
1541
+ html = convertTables(html, g);
1542
+ html = html.replace(/<table>/g, '<table class="matrx-table">').replace(/<thead>/g, '<thead class="matrx-table-head">').replace(/<tbody>/g, '<tbody class="matrx-table-body">').replace(/<tr>/g, '<tr class="matrx-table-row">').replace(/<th>/g, '<th class="matrx-table-header">').replace(/<td>/g, '<td class="matrx-table-cell">');
1543
+ html = html.replace(/<img(?![^>]*class=)([^>]*)>/g, '<img class="matrx-image"$1>');
1544
+ html = html.replace(/<div\b([^>]*)>/g, (m, attrs) => {
1545
+ if (/\bclass="matrx-/.test(attrs)) return m;
1546
+ if (/\bclass="/.test(attrs)) return `<div${attrs.replace(/\bclass="/, 'class="matrx-div ')}>`;
1547
+ return `<div class="matrx-div"${attrs}>`;
1548
+ });
1549
+ html = html.replace(/<span(?![^>]*class=)([^>]*)>/g, '<span class="matrx-span"$1>');
1550
+ html = html.replace(/^([^<\n].+)$/gm, '<p class="matrx-paragraph">$1</p>');
1551
+ html = html.replace(/<\/p>\s*<p class="matrx-paragraph">/g, '</p><p class="matrx-paragraph">');
1045
1552
  html = html.replace(
1046
- /(<h1 class="matrx-h1">[\s\S]*?<\/h1>\s*)<p class="matrx-paragraph">([\s\S]*?)<\/p>/g,
1553
+ /(<h1 class="matrx-h1">[\s\S]*?<\/h1>\s*)<p class="matrx-paragraph">((?:(?!\uE000B)[\s\S])*?)<\/p>/g,
1047
1554
  '$1<p class="matrx-intro">$2</p>'
1048
1555
  );
1049
1556
  html = html.replace(
@@ -1070,42 +1577,7 @@ function markdownToHtml(markdown, options = {}) {
1070
1577
  /(<div class="matrx-faq-answer">)<p class="matrx-paragraph">([\s\S]*?)<\/p>(<\/div>)/g,
1071
1578
  "$1$2$3"
1072
1579
  );
1073
- for (const { placeholder, html: imageHtml } of imagePlaceholders) {
1074
- if (html.includes(placeholder)) html = html.replaceAll(placeholder, imageHtml);
1075
- }
1076
- html = html.replace(/<p class="matrx-paragraph">\s*(<img[^>]*>)\s*<\/p>/g, "$1");
1077
- for (const { placeholder, html: linkHtml } of linkPlaceholders) {
1078
- if (html.includes(placeholder)) html = html.replaceAll(placeholder, linkHtml);
1079
- }
1080
- for (const { placeholder, html: cardHtml } of flashcardPlaceholders) {
1081
- if (html.includes(placeholder)) html = html.replaceAll(placeholder, cardHtml);
1082
- }
1083
- return startWrapper + html + endWrapper;
1084
- }
1085
- function convertArticleTables(html) {
1086
- const tableRegex = /^(\|.*\|)\s*\n(\|[-\s:|]*\|)\s*\n((?:\|.*\|\s*\n?)*)/gm;
1087
- return html.replace(
1088
- tableRegex,
1089
- (_match, headerRow, _sep, bodyRows) => {
1090
- const headers = headerRow.split("|").map((c) => c.trim()).filter((c) => c !== "");
1091
- const rows = bodyRows.trim().split("\n").filter((r) => r.trim()).map(
1092
- (r) => r.split("|").map((c) => c.trim()).filter((c) => c !== "")
1093
- );
1094
- let t = '<table class="print-table">\n';
1095
- if (headers.length) {
1096
- t += `<thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead>
1097
- `;
1098
- }
1099
- if (rows.length) {
1100
- t += `<tbody>${rows.map(
1101
- (r) => r.length ? `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>` : ""
1102
- ).join("\n")}</tbody>
1103
- `;
1104
- }
1105
- return `${t}</table>
1106
- `;
1107
- }
1108
- );
1580
+ return stash.restore(html);
1109
1581
  }
1110
1582
  function markdownToArticleHtml(markdown, options = {}) {
1111
1583
  if (!markdown) {
@@ -1116,117 +1588,38 @@ function markdownToArticleHtml(markdown, options = {}) {
1116
1588
  });
1117
1589
  return "";
1118
1590
  }
1119
- let html = options.includeThinking ? markdown : removeThinkingContent(markdown);
1120
- html = convertArticleTables(html);
1121
- const codeBlockPlaceholders = [];
1122
- let codeIdx = 0;
1591
+ const source = scrubTokens(options.includeThinking ? markdown : removeThinkingContent(markdown));
1592
+ return articleBody(source, newContext(options));
1593
+ }
1594
+ function articleBody(markdown, ctx) {
1595
+ const g = ARTICLE_GRAMMAR;
1596
+ const stash = new Stash();
1597
+ let html = protectRegions(markdown, g, stash, ctx);
1598
+ html = convertTables(html, g);
1599
+ html = convertRules(html, g);
1123
1600
  html = html.replace(
1124
- /```(\w*)\n?([\s\S]*?)```/g,
1125
- (_m, lang, code) => {
1126
- const ph = `\u03A9CODEBLOCK\u03A9${codeIdx}\u03A9CODEBLOCK\u03A9`;
1127
- const langLabel = lang ? `<span class="code-lang">${lang}</span>` : "";
1128
- codeBlockPlaceholders.push({
1129
- placeholder: ph,
1130
- html: `<div class="code-block-wrapper">${langLabel}<pre class="code-block"><code>${(0, import_html_escape2.escapeHtml)(
1131
- code.trim()
1132
- )}</code></pre></div>`
1133
- });
1134
- codeIdx++;
1135
- return ph;
1136
- }
1601
+ IMAGE_RE,
1602
+ (_m, alt, url) => stash.block(
1603
+ `<figure class="print-figure"><img class="print-image" src="${safeUrl(url)}" alt="${(0, import_html_escape2.escapeHtml)(alt)}" />${alt ? `<figcaption>${(0, import_html_escape2.escapeHtml)(alt)}</figcaption>` : ""}</figure>`
1604
+ )
1137
1605
  );
1138
- const imagePlaceholders = [];
1139
- let imageIdx = 0;
1140
1606
  html = html.replace(
1141
- /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g,
1142
- (_m, alt, url) => {
1143
- const ph = `\u03A9IMAGE\u03A9${imageIdx}\u03A9IMAGE\u03A9`;
1144
- imagePlaceholders.push({
1145
- placeholder: ph,
1146
- html: `<figure class="print-figure"><img class="print-image" src="${url}" alt="${(0, import_html_escape2.escapeHtml)(alt)}" />${alt ? `<figcaption>${(0, import_html_escape2.escapeHtml)(alt)}</figcaption>` : ""}</figure>`
1147
- });
1148
- imageIdx++;
1149
- return ph;
1150
- }
1151
- );
1152
- const linkPlaceholders = [];
1153
- let linkIdx = 0;
1154
- html = html.replace(
1155
- /\[([^\]]+)\]\(([^)]+)\)/g,
1156
- (_m, text, url) => {
1157
- const ph = `\u03A9LINK\u03A9${linkIdx}\u03A9LINK\u03A9`;
1158
- linkPlaceholders.push({ placeholder: ph, html: `<a href="${url}">${text}</a>` });
1159
- linkIdx++;
1160
- return ph;
1161
- }
1607
+ LINK_RE,
1608
+ (_m, text, url) => stash.inline(`<a href="${safeUrl(url)}">${convertEmphasis(text, g)}</a>`)
1162
1609
  );
1163
1610
  html = html.replace(/^#{6}\s+(.+)$/gm, "<h6>$1</h6>").replace(/^#{5}\s+(.+)$/gm, "<h5>$1</h5>").replace(/^#{4}\s+(.+)$/gm, "<h4>$1</h4>").replace(/^#{3}\s+(.+)$/gm, "<h3>$1</h3>").replace(/^#{2}\s+(.+)$/gm, "<h2>$1</h2>").replace(/^#{1}\s+(.+)$/gm, "<h1>$1</h1>");
1164
- html = html.replace(/^> (.+)$/gm, "<blockquote>$1</blockquote>");
1165
- html = html.replace(/^[-*_]{3,}$/gm, "<hr>");
1166
- html = html.replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>").replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>").replace(/\*(.+?)\*/g, "<em>$1</em>").replace(/___(.+?)___/g, "<strong><em>$1</em></strong>").replace(/__(.+?)__/g, "<strong>$1</strong>").replace(/_([^_\s][^_]*)_/g, "<em>$1</em>");
1167
- html = html.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
1168
- const lines = html.split("\n");
1169
- const result = [];
1170
- let inUl = false;
1171
- let inOl = false;
1172
- for (const line of lines) {
1173
- const ulMatch = line.match(/^(\s*)[-*+]\s+(.+)$/);
1174
- const olMatch = line.match(/^(\s*)\d+\.\s+(.+)$/);
1175
- if (ulMatch) {
1176
- if (inOl) {
1177
- result.push("</ol>");
1178
- inOl = false;
1179
- }
1180
- if (!inUl) {
1181
- result.push("<ul>");
1182
- inUl = true;
1183
- }
1184
- result.push(`<li>${ulMatch[2] ?? ""}</li>`);
1185
- } else if (olMatch) {
1186
- if (inUl) {
1187
- result.push("</ul>");
1188
- inUl = false;
1189
- }
1190
- if (!inOl) {
1191
- result.push("<ol>");
1192
- inOl = true;
1193
- }
1194
- result.push(`<li>${olMatch[2] ?? ""}</li>`);
1195
- } else {
1196
- if (inUl) {
1197
- result.push("</ul>");
1198
- inUl = false;
1199
- }
1200
- if (inOl) {
1201
- result.push("</ol>");
1202
- inOl = false;
1203
- }
1204
- result.push(line);
1205
- }
1206
- }
1207
- if (inUl) result.push("</ul>");
1208
- if (inOl) result.push("</ol>");
1209
- html = result.join("\n");
1611
+ html = html.replace(/^> ?(.+)$/gm, "<blockquote>$1</blockquote>");
1612
+ html = convertLists(html, g);
1613
+ html = convertEmphasis(html, g);
1210
1614
  html = html.split("\n").map((line) => {
1211
1615
  const t = line.trim();
1212
1616
  if (!t) return "";
1213
- if (/^<\/?(h[1-6]|ul|ol|li|blockquote|pre|hr|table|thead|tbody|tr|th|td|div|figure)/.test(t) || /^Ω(CODEBLOCK|IMAGE)Ω/.test(t)) {
1617
+ if (/^<\/?(h[1-6]|ul|ol|li|blockquote|pre|hr|table|thead|tbody|tr|th|td|div|figure|section)/.test(t) || /^\uE000B\d+\uE001$/.test(t)) {
1214
1618
  return line;
1215
1619
  }
1216
1620
  return `<p>${t}</p>`;
1217
1621
  }).join("\n");
1218
- for (const { placeholder, html: ph } of codeBlockPlaceholders) {
1219
- html = html.replace(`<p>${placeholder}</p>`, ph);
1220
- html = html.replace(placeholder, ph);
1221
- }
1222
- for (const { placeholder, html: ph } of imagePlaceholders) {
1223
- html = html.replaceAll(`<p>${placeholder}</p>`, ph);
1224
- html = html.replaceAll(placeholder, ph);
1225
- }
1226
- for (const { placeholder, html: ph } of linkPlaceholders) {
1227
- html = html.replaceAll(placeholder, ph);
1228
- }
1229
- return html;
1622
+ return stash.restore(html).replace(/\n{3,}/g, "\n\n").trim();
1230
1623
  }
1231
1624
  var PRINT_ACTIONS_CSS = `
1232
1625
  .print-actions { display: flex; gap: 10px; margin: 0 auto 28px; max-width: 800px; padding: 0 2rem 20px; border-bottom: 2px solid var(--matrx-print-border, #e1e1e1); }
@@ -1240,7 +1633,8 @@ function getMarkdownStylesheet(options = {}) {
1240
1633
  const base = skin === "article" ? `${MARKDOWN_ARTICLE_TOKENS_CSS}
1241
1634
  ${MARKDOWN_ARTICLE_CSS}` : `${MARKDOWN_DOCUMENT_TOKENS_CSS}
1242
1635
  ${MARKDOWN_DOCUMENT_CSS}`;
1243
- return [base, options.tokens ?? "", options.extraCss ?? ""].filter((part) => part.trim().length > 0).join("\n");
1636
+ const page = options.pageNumbers === false ? MARKDOWN_PAGE_PLAIN_CSS : MARKDOWN_PAGE_CSS;
1637
+ return [base, MARKDOWN_SHARED_CSS, page, options.tokens ?? "", options.extraCss ?? ""].filter((part) => part.trim().length > 0).join("\n");
1244
1638
  }
1245
1639
  function markdownToHtmlForSkin(markdown, skin, options = {}) {
1246
1640
  return skin === "article" ? markdownToArticleHtml(markdown, options) : markdownToHtml(markdown, options);