Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownChunks.ts

177 lines7.3 KB

1// About one screen of rendered Markdown; parsing costs up to ~40 ms per KB with tables and math.
2const CHUNK_TARGET_CHARS = 4 * 1024;
3// A chunk past this (one huge fence or HTML block) is too slow to parse at once; show source.
4export const LARGE_MARKDOWN_CHUNK_MAX_CHARS = 128 * 1024;
5// A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
6const FENCE_OPEN = /^ {0,3}(`{3,}(?![^`\n]*`)|~{3,})/;
7const ATX_HEADING = /^#{1,6}(?:[ \t]|\r?$)/;
8// A thematic break, or a "---" setext underline; no paragraph stays open after either. A lone
9// "===" is paragraph text unless it underlines one, so it is left out.
10const THEMATIC_BREAK = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
11// A column-0 paragraph, quote or table after a blank line closes any open list, quote or table.
12const BLOCK_START = /^[\p{L}\p{N}`[!|>]/u;
13const ORDERED_ITEM = /^\d{1,9}[.)](?:[ \t]|\r?$)/;
14// CommonMark HTML blocks of types 1-5 and display math run past blank lines until their closer.
15const SPANNING_BLOCKS: ReadonlyArray<readonly [open: RegExp, close: RegExp]> = [
16 [/^ {0,3}<(?:script|pre|style|textarea)(?=[\s>]|$)/i, /<\/(?:script|pre|style|textarea)>/i],
17 // "<!-->" and "<!--->" close themselves, so the closer is searched from just after "<!".
18 [/^ {0,3}<!(?=--)/, /-->/],
19 [/^ {0,3}<\?/, /\?>/],
20 [/^ {0,3}<!\[CDATA\[/, /\]\]>/],
21 [/^ {0,3}<![A-Za-z]/, />/],
22 [/^ {0,3}\$\$/, /\$\$/],
23];
24​
25// A tag name, not an autolink such as <https://example.com>.
26const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/;
27const closesAtBlankLine = (next: string) => next.trim() === "";
28​
29// A <details> or <table> wraps the Markdown between its tags, across the blank lines that end
30// each HTML block, so a cut waits until the ones an HTML block opened are closed.
31const WRAPPER_TAG = /<(\/?)(?:details|table)(?=[\s/>]|$)/gi;
32// An end tag that never comes, or back-to-back wrappers, must not make one huge piece.
33const WRAPPED_MAX_CHARS = 32 * 1024;
34​
35function withoutComments(line: string): string {
36 let kept = "";
37 let at = 0;
38 for (let open = line.indexOf("<!--"); open !== -1; open = line.indexOf("<!--", at)) {
39 const close = line.indexOf("-->", open + 4);
40 if (close === -1) break;
41 kept += line.slice(at, open);
42 at = close + 3;
43 }
44 return kept + line.slice(at);
46​
47function openedWrappers(line: string): number {
48 let opened = 0;
49 for (const [, closing] of withoutComments(line).matchAll(WRAPPER_TAG)) {
50 opened += closing ? -1 : 1;
51 }
52 return opened;
54​
55/** Returns how to recognize the end of a block that `line` opens, or null for none. */
56function blockCloser(line: string): ((line: string) => boolean) | null {
57 const fence = FENCE_OPEN.exec(line)?.[1];
58 if (fence) {
59 return (next) => {
60 const closer = FENCE_OPEN.exec(next)?.[1];
61 return (
62 closer !== undefined &&
63 closer[0] === fence[0] &&
64 closer.length >= fence.length &&
65 !next.trim().slice(closer.length)
66 );
67 };
68 }
69 for (const [open, close] of SPANNING_BLOCKS) {
70 const opener = open.exec(line)?.[0];
71 if (opener === undefined) continue;
72 return close.test(line.slice(opener.length)) ? null : (next) => close.test(next);
73 }
74 // Other HTML blocks (CommonMark types 6 and 7) run until a blank line.
75 return HTML_BLOCK_START.test(line) ? closesAtBlankLine : null;
77​
78export interface MarkdownChunk {
79 readonly text: string;
80 readonly lines: number;
82​
83const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/;
84const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/;
85// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one.
86const FRONTMATTER_MAX_LINES = 1000;
87​
88// A one-line link reference definition; footnotes are left alone so each piece does not grow
89// a footnote section.
90const LINK_DEFINITION =
91 /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/;
92// Definitions past this are not repeated into every piece; their parse cost would outweigh links.
93const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024;
94​
95export interface SplitMarkdown {
96 readonly chunks: readonly MarkdownChunk[];
97 readonly definitions: string;
99​
100/**
101 * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs
102 * that start a new top-level block. Leading frontmatter stays in the first piece. Link
103 * definitions are collected so every piece can resolve them; footnotes resolve only inside their
104 * own piece, and duplicate heading slugs restart per piece.
105 */
106export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown {
107 const chunks: MarkdownChunk[] = [];
108 const definitions: string[] = [];
109 let lines: string[] = [];
110 let first = true;
111 let chars = 0;
112 let closes: ((line: string) => boolean) | null = null;
113 let afterBlankLine = false;
114 let afterDefinition = false;
115 let afterHeading = false;
116 let openedFence = false;
117 let definitionChars = 0;
118 let openWrappers = 0;
119 let heldCut = 0;
120 const flush = () => {
121 chunks.push({ text: lines.join("\n"), lines: lines.length });
122 lines = [];
123 chars = 0;
124 heldCut = 0;
125 };
126 for (const line of text.split("\n")) {
127 if (closes !== null) {
128 if (closes(line)) closes = null;
129 } else if (first && FRONTMATTER_OPEN.test(line)) {
130 let seen = 0;
131 closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES;
132 } else {
133 if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0;
134 const cutPoint =
135 chars >= targetChars &&
136 (ATX_HEADING.test(line) ||
137 (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line)));
138 if (cutPoint && openWrappers === 0) flush();
139 else if (cutPoint) heldCut = lines.length;
140 closes = blockCloser(line);
141 // An indented fence may sit in a list item, which this does not track.
142 openedFence = /^[`~]/.test(line) && FENCE_OPEN.test(line);
143 // A definition cannot interrupt a paragraph, so it follows a blank line, a heading,
144 // a closing code fence or another definition.
145 const definition: boolean =
146 (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line);
147 afterDefinition = definition;
148 if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) {
149 definitions.push(line.trim());
150 definitionChars += line.length + 1;
151 }
152 }
153 if (closes === closesAtBlankLine)
154 openWrappers = Math.max(0, openWrappers + openedWrappers(line));
155 first = false;
156 lines.push(line);
157 chars += line.length + 1;
158 // A piece too large to render goes back to the last cut a wrapper held.
159 if (heldCut > 0 && chars - 1 > LARGE_MARKDOWN_CHUNK_MAX_CHARS) {
160 const rest = lines.splice(heldCut);
161 flush();
162 lines = rest;
163 chars = rest.reduce((sum, kept) => sum + kept.length + 1, 0);
164 openWrappers = 0;
165 }
166 afterBlankLine = line.trim() === "";
167 afterHeading =
168 closes === null && (openedFence || ATX_HEADING.test(line) || THEMATIC_BREAK.test(line));
169 }
170 flush();
171 return { chunks, definitions: definitions.join("\n") };
173​
174/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */
175export function withMarkdownDefinitions(text: string, definitions: string): string {
176 return definitions ? `${text}\n\n${definitions}` : text;