Open History to see the last commit
1import type { InlineNode, InlineParser, ParseOptions } from './types.js'
2import { footnoteId, normalizeReferenceLabel, parseDestination, plainText, sanitizeUrl } from './utils.js'
3
4export function parseInline(value: string, options: ParseOptions = {}): InlineNode[] {
5 const parsers = options.extensions?.flatMap(extension => extension.inlineParser ? [extension.inlineParser] : []) ?? []
6 const marker = parsers.length
7 ? new RegExp(inlineMarker.source + '|[' + parsers.map(parser => parser.markers).join('').replace(/[\\\]\[\-^]/g, '\\$&') + ']', 'g')
8 : inlineMarker
9 let result = parseInlineRaw(value, options, {
10 scans: Math.max(value.length * scansPerCharacter, 1024), depth: 0, links: 0, parsers, marker,
11 })
12
13 for (const extension of options.extensions ?? []) {
14 result = extension.transformInline?.(result, { options }) ?? result
15 }
16
17 return result
18}
19
20function hasLink(node: InlineNode): boolean {
21 return node.type === 'link' || ('children' in node && node.children.some(hasLink))
22}
23
24interface InlineParseBudget {
25 scans: number
26 depth: number
27 links: number
28 parsers: InlineParser[]
29 marker: RegExp
30}
31
32const maxInlineDepth = 32
33const scansPerCharacter = 16
34const inlineMarker = /[\\`!\[_*~<]/g
35
36function parseInlineRaw(
37 value: string,
38 options: ParseOptions,
39 budget: InlineParseBudget,
40 inLink = false,
41): InlineNode[] {
42 if (budget.depth >= maxInlineDepth) return value ? [{ type: 'text', value }] : []
43 budget.depth++
44 // Image alt text is parsed with stripped options and shares only the budget.
45 const parsers = options.extensions ? budget.parsers : []
46 const marker = parsers.length ? budget.marker : inlineMarker
47
48 const nodes: InlineNode[] = []
49 let index = 0
50 let text = ''
51
52 const pushText = () => {
53 if (text) {
54 nodes.push({ type: 'text', value: text })
55 text = ''
56 }
57 }
58
59 scan: while (index < value.length) {
60 const char = value[index]!
61 const next = value[index + 1]
62
63 if (char === '\\') {
64 if (next === '\n') {
65 pushText()
66 nodes.push({ type: 'break' })
67 index += 2
68 continue
69 }
70
71 if (next && /[!-/:-@\[-`{-~]/.test(next)) {
72 text += next
73 index += 2
74 continue
75 }
76 }
77
78 if (char === '`') {
79 const tickCount = countRun(value, index, '`')
80 const close = findClosingRun(value, index + tickCount, '`', tickCount, budget)
81 if (close !== -1) {
82 pushText()
83 nodes.push({
84 type: 'inlineCode',
85 // Strip one padding space at each end, except in an all-space span.
86 value: value.slice(index + tickCount, close).replace(/\n/g, ' ').replace(/^ (?! *$)(.*) $/s, '$1'),
87 })
88 index = close + tickCount
89 continue
90 }
91 text += value.slice(index, index + tickCount)
92 index += tickCount
93 continue
94 }
95
96 for (const parser of parsers) {
97 if (!parser.markers.includes(char) || budget.scans-- <= 0) continue
98 const result = parser.parse({
99 source: value, index, options, inLink,
100 parseInline: source => parseInlineRaw(source, options, budget, inLink),
101 })
102 if (!result) continue
103 if (!Number.isInteger(result.length) || result.length <= 0 || result.length > value.length - index) {
104 throw new RangeError('Inline parser must consume a positive length within the source')
105 }
106 pushText()
107 nodes.push(result.node)
108 if (hasLink(result.node)) budget.links++
109 index += result.length
110 continue scan
111 }
112
113 if (char === '[' || (char === '!' && next === '[')) {
114 const image = char === '!'
115 const footnote = next === '^' && parseFootnoteReference(value, index, options, budget)
116 if (footnote) {
117 pushText()
118 nodes.push(footnote.node)
119 budget.links++
120 index = footnote.end
121 continue
122 }
123
124 const parsed = parseLinkish(value, index + Number(image), options, budget)
125 if (parsed) {
126 const links = budget.links
127 const children = parseInlineRaw(parsed.label, image ? (options.references ? { references: options.references } : {}) : options, budget, !image)
128 const nested = !image && budget.links !== links
129 const defaultUrl = sanitizeUrl(parsed.href)
130 const href = options.urlTransform ? options.urlTransform(parsed.href, image ? 'image' : 'link', defaultUrl) : defaultUrl
131 if (href !== null && (image || (!nested && (href || !parsed.href)))) {
132 pushText()
133 nodes.push({
134 ...(image ? { type: 'image' as const, src: href, alt: plainText(children) } : { type: 'link' as const, href, children }),
135 ...(parsed.title ? { title: parsed.title } : {}),
136 })
137 } else {
138 if (nested) text += '['
139 for (const child of children) {
140 if (child.type === 'text') text += child.value
141 else {
142 pushText()
143 nodes.push(child)
144 }
145 }
146 }
147 // An inner link disables its outer opener, but not the trailing markup.
148 budget.links = image ? links : budget.links + 1
149 index = nested ? index + parsed.label.length + 1 : parsed.end
150 continue
151 }
152 }
153
154 if (char === '*' && next === '*' && value[index + 2] === '*') {
155 const close = findDelimiter(value, index + 3, '***', budget)
156 if (close !== -1) {
157 pushText()
158 nodes.push({
159 type: 'emphasis',
160 children: parseInlineRaw(value.slice(index + 1, close + 2), options, budget, inLink),
161 })
162 index = close + 3
163 continue
164 }
165 }
166
167 if (char === '~' && next === '~' && value[index + 2] === '~') {
168 const run = countRun(value, index, '~')
169 text += value.slice(index, index + run)
170 index += run
171 continue
172 }
173
174 if (char === '*' || char === '_' || char === '~') {
175 const size = next === char ? 2 : 1
176 const close = char === '_' && !canUseUnderscore(value, index, size, true) ? -1 : findDelimiter(value, index + size, char.repeat(size), budget)
177 if (close !== -1) {
178 pushText()
179 nodes.push({
180 type: char === '~' ? 'strike' : size === 2 ? 'strong' : 'emphasis',
181 children: parseInlineRaw(value.slice(index + size, close), options, budget, inLink),
182 })
183 index = close + size
184 } else {
185 text += char.repeat(size)
186 index += size
187 }
188 continue
189 }
190
191 if (char === '<' && options.allowHtml) {
192 const close = findCharacter(value, index + 1, '>', budget)
193 if (close !== -1 && isInlineHtml(value.slice(index, close + 1))) {
194 pushText()
195 nodes.push({ type: 'inlineHtml', value: value.slice(index, close + 1) })
196 index = close + 1
197 continue
198 }
199 }
200
201 // Reset after recursive parsing; exhausted budgets still allow escapes.
202 marker.lastIndex = index + 1
203 const end = budget.scans > 0 ? marker.exec(value)?.index ?? value.length : value.indexOf('\\', index + 1)
204 text += value.slice(index, end < 0 ? value.length : end)
205 index = end < 0 ? value.length : end
206 }
207
208 pushText()
209 budget.depth--
210 return nodes
211}
212
213interface ParsedFootnoteReference {
214 node: InlineNode
215 end: number
216}
217
218interface ParsedLink {
219 label: string
220 href: string
221 title?: string
222 end: number
223}
224
225function parseFootnoteReference(value: string, open: number, options: ParseOptions, budget: InlineParseBudget): ParsedFootnoteReference | undefined {
226 const close = findCharacter(value, open + 2, ']', budget)
227 if (close === -1) return undefined
228
229 const label = value.slice(open + 2, close)
230 const key = normalizeReferenceLabel(label)
231 const definition = options.footnotes?.[key]
232 if (!definition || !options.footnoteOrder) return undefined
233
234 let number = options.footnoteOrder.indexOf(key) + 1
235 if (!number) number = options.footnoteOrder.push(key)
236
237 const referenceIndex = (options.footnoteCounts?.[key] ?? 0) + 1
238 if (options.footnoteCounts) options.footnoteCounts[key] = referenceIndex
239
240 return {
241 node: {
242 type: 'footnoteReference',
243 id: definition.id ?? footnoteId(definition.label),
244 number,
245 ...(referenceIndex > 1 ? { referenceIndex } : {}),
246 },
247 end: close + 1,
248 }
249}
250
251function parseLinkish(value: string, open: number, options: ParseOptions, budget: InlineParseBudget): ParsedLink | undefined {
252 const closeBracket = findBalanced(value, open, '[', ']', budget)
253 if (closeBracket === -1) return undefined
254
255 const label = value.slice(open + 1, closeBracket)
256 let end = closeBracket + 1
257 let definition: { href: string; title?: string } | undefined
258
259 if (value[end] === '(') {
260 const closeParen = findBalanced(value, end, '(', ')', budget)
261 if (closeParen === -1) return undefined
262
263 definition = parseDestination(value.slice(end + 1, closeParen).trim())
264 end = closeParen + 1
265 } else if (value[end] === '[') {
266 const closeReference = findBalanced(value, end, '[', ']', budget)
267 if (closeReference === -1) return undefined
268
269 definition = options.references?.[normalizeReferenceLabel(value.slice(end + 1, closeReference) || label)]
270 end = closeReference + 1
271 } else {
272 definition = options.references?.[normalizeReferenceLabel(label)]
273 }
274
275 if (definition) {
276 return {
277 ...definition,
278 label,
279 end,
280 }
281 }
282
283 return undefined
284}
285
286function isInlineHtml(value: string): boolean {
287 return /^<(?:!--(?:[\s\S]*--|-?)|\?[\s\S]*\?|![A-Z][\s\S]*|!\[CDATA\[[\s\S]*\]\]|\/[A-Za-z][\w:-]*\s*|[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?)>$/.test(value)
288}
289
290function findBalanced(value: string, openIndex: number, open: string, close: string, budget: InlineParseBudget): number {
291 // Reject missing closers with a native search, charging the same shared budget.
292 if (findCharacter(value, openIndex + 1, close, budget) === -1) return -1
293 let depth = 0
294 for (let index = openIndex; index < value.length; index++) {
295 if (--budget.scans < 0) return -1
296 if (value[index] === '\\') {
297 index++
298 continue
299 }
300 if (value[index] === open) depth++
301 if (value[index] === close) {
302 depth--
303 if (depth === 0) return index
304 }
305 }
306 return -1
307}
308
309function countRun(value: string, index: number, char: string, budget?: InlineParseBudget): number {
310 let count = 0
311 while (value[index + count] === char) {
312 if (budget && --budget.scans < 0) break
313 count++
314 }
315 return count
316}
317
318function findClosingRun(value: string, start: number, char: string, count: number, budget: InlineParseBudget): number {
319 let index = start
320 while ((index = findCharacter(value, index, char, budget)) !== -1) {
321 const size = countRun(value, index, char, budget)
322 if (size === count) return index
323 index += size
324 }
325 return -1
326}
327
328function findDelimiter(value: string, start: number, delimiter: string, budget: InlineParseBudget): number {
329 if (delimiter === '~' && /[\s\d]/.test(value[start] ?? '')) return -1
330 for (let index = start; index < value.length; index++) {
331 if (--budget.scans < 0) return -1
332 if (value[index] === '\\') {
333 index++
334 continue
335 }
336 if (!value.startsWith(delimiter, index)) continue
337 if (delimiter[0] === '~') {
338 if (value[index - 1] === '~' || value[index + delimiter.length] === '~') continue
339 if (delimiter === '~' && /\s/.test(value[index - 1] ?? '')) return -1
340 } else if (value[index + 1] === delimiter) {
341 const size = countRun(value, index, delimiter, budget)
342 const close = findDelimiter(value, index + size, delimiter.repeat(size), budget)
343 if (close > index + size) {
344 index = close + size - 1
345 continue
346 }
347 }
348 if (delimiter[0] === '_' && !canUseUnderscore(value, index, delimiter.length, false)) continue
349 return index
350 }
351 return -1
352}
353
354function findCharacter(value: string, start: number, character: string, budget: InlineParseBudget): number {
355 if (budget.scans <= 0) return -1
356 const index = value.indexOf(character, start)
357 budget.scans -= (index < 0 ? value.length : index + 1) - start
358 return budget.scans < 0 ? -1 : index
359}
360
361function canUseUnderscore(value: string, index: number, size: number, opening: boolean): boolean {
362 const inside = value[opening ? index + size : index - 1]
363 const outside = value[opening ? index - 1 : index + size]
364 return inside !== undefined && !/\s/.test(inside) && (outside === undefined || /[^\p{L}\p{N}]/u.test(outside))
365}