codemirror-languageserver 1.12.1 → 1.14.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/index.js CHANGED
@@ -4,2961 +4,15 @@ import { Facet } from '@codemirror/state';
4
4
  import { ViewPlugin, hoverTooltip } from '@codemirror/view';
5
5
  import { RequestManager, Client, WebSocketTransport } from '@open-rpc/client-js';
6
6
  import { CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity } from 'vscode-languageserver-protocol';
7
-
8
- /**
9
- * marked v15.0.6 - a markdown parser
10
- * Copyright (c) 2011-2025, Christopher Jeffrey. (MIT Licensed)
11
- * https://github.com/markedjs/marked
12
- */
13
-
14
- /**
15
- * DO NOT EDIT THIS FILE
16
- * The code in this file is generated from files in ./src/
17
- */
18
-
19
- /**
20
- * Gets the original marked default options.
21
- */
22
- function _getDefaults() {
23
- return {
24
- async: false,
25
- breaks: false,
26
- extensions: null,
27
- gfm: true,
28
- hooks: null,
29
- pedantic: false,
30
- renderer: null,
31
- silent: false,
32
- tokenizer: null,
33
- walkTokens: null
34
- };
35
- }
36
-
37
- let _defaults = _getDefaults();
38
-
39
- function changeDefaults(newDefaults) {
40
- _defaults = newDefaults;
41
- }
42
-
43
- const noopTest = {
44
- exec: () => null
45
- };
46
-
47
- function edit(regex, opt = '') {
48
- let source = typeof regex === 'string' ? regex : regex.source;
49
- const obj = {
50
- replace: (name, val) => {
51
- let valSource = typeof val === 'string' ? val : val.source;
52
- valSource = valSource.replace(other.caret, '$1');
53
- source = source.replace(name, valSource);
54
- return obj;
55
- },
56
- getRegex: () => {
57
- return new RegExp(source, opt);
58
- }
59
- };
60
- return obj;
61
- }
62
-
63
- const other = {
64
- codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm,
65
- outputLinkReplace: /\\([\[\]])/g,
66
- indentCodeCompensation: /^(\s+)(?:```)/,
67
- beginningSpace: /^\s+/,
68
- endingHash: /#$/,
69
- startingSpaceChar: /^ /,
70
- endingSpaceChar: / $/,
71
- nonSpaceChar: /[^ ]/,
72
- newLineCharGlobal: /\n/g,
73
- tabCharGlobal: /\t/g,
74
- multipleSpaceGlobal: /\s+/g,
75
- blankLine: /^[ \t]*$/,
76
- doubleBlankLine: /\n[ \t]*\n[ \t]*$/,
77
- blockquoteStart: /^ {0,3}>/,
78
- blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g,
79
- blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm,
80
- listReplaceTabs: /^\t+/,
81
- listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,
82
- listIsTask: /^\[[ xX]\] /,
83
- listReplaceTask: /^\[[ xX]\] +/,
84
- anyLine: /\n.*\n/,
85
- hrefBrackets: /^<(.*)>$/,
86
- tableDelimiter: /[:|]/,
87
- tableAlignChars: /^\||\| *$/g,
88
- tableRowBlankLine: /\n[ \t]*$/,
89
- tableAlignRight: /^ *-+: *$/,
90
- tableAlignCenter: /^ *:-+: *$/,
91
- tableAlignLeft: /^ *:-+ *$/,
92
- startATag: /^<a /i,
93
- endATag: /^<\/a>/i,
94
- startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i,
95
- endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i,
96
- startAngleBracket: /^</,
97
- endAngleBracket: />$/,
98
- pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/,
99
- unicodeAlphaNumeric: /[\p{L}\p{N}]/u,
100
- escapeTest: /[&<>"']/,
101
- escapeReplace: /[&<>"']/g,
102
- escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,
103
- escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
104
- unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,
105
- caret: /(^|[^\[])\^/g,
106
- percentDecode: /%25/g,
107
- findPipe: /\|/g,
108
- splitPipe: / \|/,
109
- slashPipe: /\\\|/g,
110
- carriageReturn: /\r\n|\r/g,
111
- spaceLine: /^ +$/gm,
112
- notSpaceStart: /^\S*/,
113
- endingNewline: /\n$/,
114
- listItemRegex: bull => new RegExp(`^( {0,3}${bull})((?:[\t ][^\\n]*)?(?:\\n|$))`),
115
- nextBulletRegex: indent => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),
116
- hrRegex: indent => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),
117
- fencesBeginRegex: indent => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`),
118
- headingBeginRegex: indent => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),
119
- htmlBeginRegex: indent => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i')
120
- };
121
- /**
122
- * Block-Level Grammar
123
- */
124
-
125
- const newline = /^(?:[ \t]*(?:\n|$))+/;
126
- const blockCode = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
127
- const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
128
- const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
129
- const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
130
- const bullet = /(?:[*+-]|\d{1,9}[.)])/;
131
- const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet) // lists can interrupt
132
- .replace(/blockCode/g, /(?: {4}| {0,3}\t)/) // indented code blocks can interrupt
133
- .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt
134
- .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt
135
- .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt
136
- .replace(/html/g, / {0,3}<[^\n>]+>\n/) // block html can interrupt
137
- .getRegex();
138
- const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
139
- const blockText = /^[^\n]+/;
140
- const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
141
- const def = edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace('label', _blockLabel).replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
142
- const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
143
-
144
- const _tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title' + '|tr|track|ul';
145
-
146
- const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
147
- const html = edit('^ {0,3}(?:' // optional indentation
148
- + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
149
- + '|comment[^\\n]*(\\n+|$)' // (2)
150
- + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
151
- + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
152
- + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
153
- + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (6)
154
- + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) open tag
155
- + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)' // (7) closing tag
156
- + ')', 'i').replace('comment', _comment).replace('tag', _tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
157
- const paragraph = edit(_paragraph).replace('hr', hr).replace('heading', ' {0,3}#{1,6}(?:\\s|$)').replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
158
- .replace('|table', '').replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
159
- .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', _tag) // pars can be interrupted by type (6) html blocks
160
- .getRegex();
161
- const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace('paragraph', paragraph).getRegex();
162
- /**
163
- * Normal Block Grammar
164
- */
165
-
166
- const blockNormal = {
167
- blockquote,
168
- code: blockCode,
169
- def,
170
- fences,
171
- heading,
172
- hr,
173
- html,
174
- lheading,
175
- list,
176
- newline,
177
- paragraph,
178
- table: noopTest,
179
- text: blockText
180
- };
181
- /**
182
- * GFM Block Grammar
183
- */
184
-
185
- const gfmTable = edit('^ *([^\\n ].*)\\n' // Header
186
- + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align
187
- + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells
188
- .replace('hr', hr).replace('heading', ' {0,3}#{1,6}(?:\\s|$)').replace('blockquote', ' {0,3}>').replace('code', '(?: {4}| {0,3}\t)[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
189
- .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', _tag) // tables can be interrupted by type (6) html blocks
190
- .getRegex();
191
- const blockGfm = { ...blockNormal,
192
- table: gfmTable,
193
- paragraph: edit(_paragraph).replace('hr', hr).replace('heading', ' {0,3}#{1,6}(?:\\s|$)').replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs
194
- .replace('table', gfmTable) // interrupt paragraphs with table
195
- .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
196
- .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', _tag) // pars can be interrupted by type (6) html blocks
197
- .getRegex()
198
- };
199
- /**
200
- * Pedantic grammar (original John Gruber's loose markdown specification)
201
- */
202
-
203
- const blockPedantic = { ...blockNormal,
204
- html: edit('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
205
- + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', _comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(),
206
- def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
207
- heading: /^(#{1,6})(.*)(?:\n+|$)/,
208
- fences: noopTest,
209
- // fences not supported
210
- lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
211
- paragraph: edit(_paragraph).replace('hr', hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', lheading).replace('|table', '').replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').replace('|tag', '').getRegex()
212
- };
213
- /**
214
- * Inline-Level Grammar
215
- */
216
-
217
- const escape$1 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
218
- const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
219
- const br = /^( {2,}|\\)\n(?!\s*$)/;
220
- const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/; // list of unicode punctuation marks, plus any missing characters from CommonMark spec
221
-
222
- const _punctuation = /[\p{P}\p{S}]/u;
223
- const _punctuationOrSpace = /[\s\p{P}\p{S}]/u;
224
- const _notPunctuationOrSpace = /[^\s\p{P}\p{S}]/u;
225
- const punctuation = edit(/^((?![*_])punctSpace)/, 'u').replace(/punctSpace/g, _punctuationOrSpace).getRegex(); // GFM allows ~ inside strong and em for strikethrough
226
-
227
- const _punctuationGfmStrongEm = /(?!~)[\p{P}\p{S}]/u;
228
- const _punctuationOrSpaceGfmStrongEm = /(?!~)[\s\p{P}\p{S}]/u;
229
- const _notPunctuationOrSpaceGfmStrongEm = /(?:[^\s\p{P}\p{S}]|~)/u; // sequences em should skip over [title](link), `code`, <html>
230
-
231
- const blockSkip = /\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g;
232
- const emStrongLDelimCore = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/;
233
- const emStrongLDelim = edit(emStrongLDelimCore, 'u').replace(/punct/g, _punctuation).getRegex();
234
- const emStrongLDelimGfm = edit(emStrongLDelimCore, 'u').replace(/punct/g, _punctuationGfmStrongEm).getRegex();
235
- const emStrongRDelimAstCore = '^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong
236
- + '|[^*]+(?=[^*])' // Consume to delim
237
- + '|(?!\\*)punct(\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter
238
- + '|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter
239
- + '|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter
240
- + '|[\\s](\\*+)(?!\\*)(?=punct)' // (4) ***# can only be Left Delimiter
241
- + '|(?!\\*)punct(\\*+)(?!\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter
242
- + '|notPunctSpace(\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter
243
-
244
- const emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu').replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
245
- const emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu').replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm).replace(/punct/g, _punctuationGfmStrongEm).getRegex(); // (6) Not allowed for _
246
-
247
- const emStrongRDelimUnd = edit('^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong
248
- + '|[^_]+(?=[^_])' // Consume to delim
249
- + '|(?!_)punct(_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter
250
- + '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter
251
- + '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter
252
- + '|[\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter
253
- + '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter
254
- .replace(/notPunctSpace/g, _notPunctuationOrSpace).replace(/punctSpace/g, _punctuationOrSpace).replace(/punct/g, _punctuation).getRegex();
255
- const anyPunctuation = edit(/\\(punct)/, 'gu').replace(/punct/g, _punctuation).getRegex();
256
- const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
257
-
258
- const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();
259
-
260
- const tag = edit('^comment' + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
261
- + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
262
- + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
263
- + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
264
- + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>') // CDATA section
265
- .replace('comment', _inlineComment).replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
266
- const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
267
- const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace('label', _inlineLabel).replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
268
- const reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace('label', _inlineLabel).replace('ref', _blockLabel).getRegex();
269
- const nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace('ref', _blockLabel).getRegex();
270
- const reflinkSearch = edit('reflink|nolink(?!\\()', 'g').replace('reflink', reflink).replace('nolink', nolink).getRegex();
271
- /**
272
- * Normal Inline Grammar
273
- */
274
-
275
- const inlineNormal = {
276
- _backpedal: noopTest,
277
- // only used for GFM url
278
- anyPunctuation,
279
- autolink,
280
- blockSkip,
281
- br,
282
- code: inlineCode,
283
- del: noopTest,
284
- emStrongLDelim,
285
- emStrongRDelimAst,
286
- emStrongRDelimUnd,
287
- escape: escape$1,
288
- link,
289
- nolink,
290
- punctuation,
291
- reflink,
292
- reflinkSearch,
293
- tag,
294
- text: inlineText,
295
- url: noopTest
296
- };
297
- /**
298
- * Pedantic Inline Grammar
299
- */
300
-
301
- const inlinePedantic = { ...inlineNormal,
302
- link: edit(/^!?\[(label)\]\((.*?)\)/).replace('label', _inlineLabel).getRegex(),
303
- reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', _inlineLabel).getRegex()
304
- };
305
- /**
306
- * GFM Inline Grammar
307
- */
308
-
309
- const inlineGfm = { ...inlineNormal,
310
- emStrongRDelimAst: emStrongRDelimAstGfm,
311
- emStrongLDelim: emStrongLDelimGfm,
312
- url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i').replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
313
- _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
314
- del: /^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,
315
- text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
316
- };
317
- /**
318
- * GFM + Line Breaks Inline Grammar
319
- */
320
-
321
- const inlineBreaks = { ...inlineGfm,
322
- br: edit(br).replace('{2,}', '*').getRegex(),
323
- text: edit(inlineGfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex()
324
- };
325
- /**
326
- * exports
327
- */
328
-
329
- const block = {
330
- normal: blockNormal,
331
- gfm: blockGfm,
332
- pedantic: blockPedantic
333
- };
334
- const inline = {
335
- normal: inlineNormal,
336
- gfm: inlineGfm,
337
- breaks: inlineBreaks,
338
- pedantic: inlinePedantic
339
- };
340
- /**
341
- * Helpers
342
- */
343
-
344
- const escapeReplacements = {
345
- '&': '&amp;',
346
- '<': '&lt;',
347
- '>': '&gt;',
348
- '"': '&quot;',
349
- "'": '&#39;'
350
- };
351
-
352
- const getEscapeReplacement = ch => escapeReplacements[ch];
353
-
354
- function escape(html, encode) {
355
- if (encode) {
356
- if (other.escapeTest.test(html)) {
357
- return html.replace(other.escapeReplace, getEscapeReplacement);
358
- }
359
- } else {
360
- if (other.escapeTestNoEncode.test(html)) {
361
- return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);
362
- }
363
- }
364
-
365
- return html;
366
- }
367
-
368
- function cleanUrl(href) {
369
- try {
370
- href = encodeURI(href).replace(other.percentDecode, '%');
371
- } catch {
372
- return null;
373
- }
374
-
375
- return href;
376
- }
377
-
378
- function splitCells(tableRow, count) {
379
- // ensure that every cell-delimiting pipe has a space
380
- // before it to distinguish it from an escaped pipe
381
- const row = tableRow.replace(other.findPipe, (match, offset, str) => {
382
- let escaped = false;
383
- let curr = offset;
384
-
385
- while (--curr >= 0 && str[curr] === '\\') escaped = !escaped;
386
-
387
- if (escaped) {
388
- // odd number of slashes means | is escaped
389
- // so we leave it alone
390
- return '|';
391
- } else {
392
- // add space before unescaped |
393
- return ' |';
394
- }
395
- }),
396
- cells = row.split(other.splitPipe);
397
- let i = 0; // First/last cell in a row cannot be empty if it has no leading/trailing pipe
398
-
399
- if (!cells[0].trim()) {
400
- cells.shift();
401
- }
402
-
403
- if (cells.length > 0 && !cells.at(-1)?.trim()) {
404
- cells.pop();
405
- }
406
-
407
- if (count) {
408
- if (cells.length > count) {
409
- cells.splice(count);
410
- } else {
411
- while (cells.length < count) cells.push('');
412
- }
413
- }
414
-
415
- for (; i < cells.length; i++) {
416
- // leading or trailing whitespace is ignored per the gfm spec
417
- cells[i] = cells[i].trim().replace(other.slashPipe, '|');
418
- }
419
-
420
- return cells;
421
- }
422
- /**
423
- * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
424
- * /c*$/ is vulnerable to REDOS.
425
- *
426
- * @param str
427
- * @param c
428
- * @param invert Remove suffix of non-c chars instead. Default falsey.
429
- */
430
-
431
-
432
- function rtrim(str, c, invert) {
433
- const l = str.length;
434
-
435
- if (l === 0) {
436
- return '';
437
- } // Length of suffix matching the invert condition.
438
-
439
-
440
- let suffLen = 0; // Step left until we fail to match the invert condition.
441
-
442
- while (suffLen < l) {
443
- const currChar = str.charAt(l - suffLen - 1);
444
-
445
- if (currChar === c && true) {
446
- suffLen++;
447
- } else {
448
- break;
449
- }
450
- }
451
-
452
- return str.slice(0, l - suffLen);
453
- }
454
-
455
- function findClosingBracket(str, b) {
456
- if (str.indexOf(b[1]) === -1) {
457
- return -1;
458
- }
459
-
460
- let level = 0;
461
-
462
- for (let i = 0; i < str.length; i++) {
463
- if (str[i] === '\\') {
464
- i++;
465
- } else if (str[i] === b[0]) {
466
- level++;
467
- } else if (str[i] === b[1]) {
468
- level--;
469
-
470
- if (level < 0) {
471
- return i;
472
- }
473
- }
474
- }
475
-
476
- return -1;
477
- }
478
-
479
- function outputLink(cap, link, raw, lexer, rules) {
480
- const href = link.href;
481
- const title = link.title || null;
482
- const text = cap[1].replace(rules.other.outputLinkReplace, '$1');
483
-
484
- if (cap[0].charAt(0) !== '!') {
485
- lexer.state.inLink = true;
486
- const token = {
487
- type: 'link',
488
- raw,
489
- href,
490
- title,
491
- text,
492
- tokens: lexer.inlineTokens(text)
493
- };
494
- lexer.state.inLink = false;
495
- return token;
496
- }
497
-
498
- return {
499
- type: 'image',
500
- raw,
501
- href,
502
- title,
503
- text
504
- };
505
- }
506
-
507
- function indentCodeCompensation(raw, text, rules) {
508
- const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);
509
-
510
- if (matchIndentToCode === null) {
511
- return text;
512
- }
513
-
514
- const indentToCode = matchIndentToCode[1];
515
- return text.split('\n').map(node => {
516
- const matchIndentInNode = node.match(rules.other.beginningSpace);
517
-
518
- if (matchIndentInNode === null) {
519
- return node;
520
- }
521
-
522
- const [indentInNode] = matchIndentInNode;
523
-
524
- if (indentInNode.length >= indentToCode.length) {
525
- return node.slice(indentToCode.length);
526
- }
527
-
528
- return node;
529
- }).join('\n');
530
- }
531
- /**
532
- * Tokenizer
533
- */
534
-
535
-
536
- class _Tokenizer {
537
- options;
538
- rules; // set by the lexer
539
-
540
- lexer; // set by the lexer
541
-
542
- constructor(options) {
543
- this.options = options || _defaults;
544
- }
545
-
546
- space(src) {
547
- const cap = this.rules.block.newline.exec(src);
548
-
549
- if (cap && cap[0].length > 0) {
550
- return {
551
- type: 'space',
552
- raw: cap[0]
553
- };
554
- }
555
- }
556
-
557
- code(src) {
558
- const cap = this.rules.block.code.exec(src);
559
-
560
- if (cap) {
561
- const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');
562
- return {
563
- type: 'code',
564
- raw: cap[0],
565
- codeBlockStyle: 'indented',
566
- text: !this.options.pedantic ? rtrim(text, '\n') : text
567
- };
568
- }
569
- }
570
-
571
- fences(src) {
572
- const cap = this.rules.block.fences.exec(src);
573
-
574
- if (cap) {
575
- const raw = cap[0];
576
- const text = indentCodeCompensation(raw, cap[3] || '', this.rules);
577
- return {
578
- type: 'code',
579
- raw,
580
- lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],
581
- text
582
- };
583
- }
584
- }
585
-
586
- heading(src) {
587
- const cap = this.rules.block.heading.exec(src);
588
-
589
- if (cap) {
590
- let text = cap[2].trim(); // remove trailing #s
591
-
592
- if (this.rules.other.endingHash.test(text)) {
593
- const trimmed = rtrim(text, '#');
594
-
595
- if (this.options.pedantic) {
596
- text = trimmed.trim();
597
- } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {
598
- // CommonMark requires space before trailing #s
599
- text = trimmed.trim();
600
- }
601
- }
602
-
603
- return {
604
- type: 'heading',
605
- raw: cap[0],
606
- depth: cap[1].length,
607
- text,
608
- tokens: this.lexer.inline(text)
609
- };
610
- }
611
- }
612
-
613
- hr(src) {
614
- const cap = this.rules.block.hr.exec(src);
615
-
616
- if (cap) {
617
- return {
618
- type: 'hr',
619
- raw: rtrim(cap[0], '\n')
620
- };
621
- }
622
- }
623
-
624
- blockquote(src) {
625
- const cap = this.rules.block.blockquote.exec(src);
626
-
627
- if (cap) {
628
- let lines = rtrim(cap[0], '\n').split('\n');
629
- let raw = '';
630
- let text = '';
631
- const tokens = [];
632
-
633
- while (lines.length > 0) {
634
- let inBlockquote = false;
635
- const currentLines = [];
636
- let i;
637
-
638
- for (i = 0; i < lines.length; i++) {
639
- // get lines up to a continuation
640
- if (this.rules.other.blockquoteStart.test(lines[i])) {
641
- currentLines.push(lines[i]);
642
- inBlockquote = true;
643
- } else if (!inBlockquote) {
644
- currentLines.push(lines[i]);
645
- } else {
646
- break;
647
- }
648
- }
649
-
650
- lines = lines.slice(i);
651
- const currentRaw = currentLines.join('\n');
652
- const currentText = currentRaw // precede setext continuation with 4 spaces so it isn't a setext
653
- .replace(this.rules.other.blockquoteSetextReplace, '\n $1').replace(this.rules.other.blockquoteSetextReplace2, '');
654
- raw = raw ? `${raw}\n${currentRaw}` : currentRaw;
655
- text = text ? `${text}\n${currentText}` : currentText; // parse blockquote lines as top level tokens
656
- // merge paragraphs if this is a continuation
657
-
658
- const top = this.lexer.state.top;
659
- this.lexer.state.top = true;
660
- this.lexer.blockTokens(currentText, tokens, true);
661
- this.lexer.state.top = top; // if there is no continuation then we are done
662
-
663
- if (lines.length === 0) {
664
- break;
665
- }
666
-
667
- const lastToken = tokens.at(-1);
668
-
669
- if (lastToken?.type === 'code') {
670
- // blockquote continuation cannot be preceded by a code block
671
- break;
672
- } else if (lastToken?.type === 'blockquote') {
673
- // include continuation in nested blockquote
674
- const oldToken = lastToken;
675
- const newText = oldToken.raw + '\n' + lines.join('\n');
676
- const newToken = this.blockquote(newText);
677
- tokens[tokens.length - 1] = newToken;
678
- raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;
679
- text = text.substring(0, text.length - oldToken.text.length) + newToken.text;
680
- break;
681
- } else if (lastToken?.type === 'list') {
682
- // include continuation in nested list
683
- const oldToken = lastToken;
684
- const newText = oldToken.raw + '\n' + lines.join('\n');
685
- const newToken = this.list(newText);
686
- tokens[tokens.length - 1] = newToken;
687
- raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;
688
- text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;
689
- lines = newText.substring(tokens.at(-1).raw.length).split('\n');
690
- continue;
691
- }
692
- }
693
-
694
- return {
695
- type: 'blockquote',
696
- raw,
697
- tokens,
698
- text
699
- };
700
- }
701
- }
702
-
703
- list(src) {
704
- let cap = this.rules.block.list.exec(src);
705
-
706
- if (cap) {
707
- let bull = cap[1].trim();
708
- const isordered = bull.length > 1;
709
- const list = {
710
- type: 'list',
711
- raw: '',
712
- ordered: isordered,
713
- start: isordered ? +bull.slice(0, -1) : '',
714
- loose: false,
715
- items: []
716
- };
717
- bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
718
-
719
- if (this.options.pedantic) {
720
- bull = isordered ? bull : '[*+-]';
721
- } // Get next list item
722
-
723
-
724
- const itemRegex = this.rules.other.listItemRegex(bull);
725
- let endsWithBlankLine = false; // Check if current bullet point can start a new List Item
726
-
727
- while (src) {
728
- let endEarly = false;
729
- let raw = '';
730
- let itemContents = '';
731
-
732
- if (!(cap = itemRegex.exec(src))) {
733
- break;
734
- }
735
-
736
- if (this.rules.block.hr.test(src)) {
737
- // End list if bullet was actually HR (possibly move into itemRegex?)
738
- break;
739
- }
740
-
741
- raw = cap[0];
742
- src = src.substring(raw.length);
743
- let line = cap[2].split('\n', 1)[0].replace(this.rules.other.listReplaceTabs, t => ' '.repeat(3 * t.length));
744
- let nextLine = src.split('\n', 1)[0];
745
- let blankLine = !line.trim();
746
- let indent = 0;
747
-
748
- if (this.options.pedantic) {
749
- indent = 2;
750
- itemContents = line.trimStart();
751
- } else if (blankLine) {
752
- indent = cap[1].length + 1;
753
- } else {
754
- indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char
755
-
756
- indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent
757
-
758
- itemContents = line.slice(indent);
759
- indent += cap[1].length;
760
- }
761
-
762
- if (blankLine && this.rules.other.blankLine.test(nextLine)) {
763
- // Items begin with at most one blank line
764
- raw += nextLine + '\n';
765
- src = src.substring(nextLine.length + 1);
766
- endEarly = true;
767
- }
768
-
769
- if (!endEarly) {
770
- const nextBulletRegex = this.rules.other.nextBulletRegex(indent);
771
- const hrRegex = this.rules.other.hrRegex(indent);
772
- const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);
773
- const headingBeginRegex = this.rules.other.headingBeginRegex(indent);
774
- const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent); // Check if following lines should be included in List Item
775
-
776
- while (src) {
777
- const rawLine = src.split('\n', 1)[0];
778
- let nextLineWithoutTabs;
779
- nextLine = rawLine; // Re-align to follow commonmark nesting rules
780
-
781
- if (this.options.pedantic) {
782
- nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');
783
- nextLineWithoutTabs = nextLine;
784
- } else {
785
- nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');
786
- } // End list item if found code fences
787
-
788
-
789
- if (fencesBeginRegex.test(nextLine)) {
790
- break;
791
- } // End list item if found start of new heading
792
-
793
-
794
- if (headingBeginRegex.test(nextLine)) {
795
- break;
796
- } // End list item if found start of html block
797
-
798
-
799
- if (htmlBeginRegex.test(nextLine)) {
800
- break;
801
- } // End list item if found start of new bullet
802
-
803
-
804
- if (nextBulletRegex.test(nextLine)) {
805
- break;
806
- } // Horizontal rule found
807
-
808
-
809
- if (hrRegex.test(nextLine)) {
810
- break;
811
- }
812
-
813
- if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) {
814
- // Dedent if possible
815
- itemContents += '\n' + nextLineWithoutTabs.slice(indent);
816
- } else {
817
- // not enough indentation
818
- if (blankLine) {
819
- break;
820
- } // paragraph continuation unless last line was a different block level element
821
-
822
-
823
- if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) {
824
- // indented code block
825
- break;
826
- }
827
-
828
- if (fencesBeginRegex.test(line)) {
829
- break;
830
- }
831
-
832
- if (headingBeginRegex.test(line)) {
833
- break;
834
- }
835
-
836
- if (hrRegex.test(line)) {
837
- break;
838
- }
839
-
840
- itemContents += '\n' + nextLine;
841
- }
842
-
843
- if (!blankLine && !nextLine.trim()) {
844
- // Check if current line is blank
845
- blankLine = true;
846
- }
847
-
848
- raw += rawLine + '\n';
849
- src = src.substring(rawLine.length + 1);
850
- line = nextLineWithoutTabs.slice(indent);
851
- }
852
- }
853
-
854
- if (!list.loose) {
855
- // If the previous item ended with a blank line, the list is loose
856
- if (endsWithBlankLine) {
857
- list.loose = true;
858
- } else if (this.rules.other.doubleBlankLine.test(raw)) {
859
- endsWithBlankLine = true;
860
- }
861
- }
862
-
863
- let istask = null;
864
- let ischecked; // Check for task list items
865
-
866
- if (this.options.gfm) {
867
- istask = this.rules.other.listIsTask.exec(itemContents);
868
-
869
- if (istask) {
870
- ischecked = istask[0] !== '[ ] ';
871
- itemContents = itemContents.replace(this.rules.other.listReplaceTask, '');
872
- }
873
- }
874
-
875
- list.items.push({
876
- type: 'list_item',
877
- raw,
878
- task: !!istask,
879
- checked: ischecked,
880
- loose: false,
881
- text: itemContents,
882
- tokens: []
883
- });
884
- list.raw += raw;
885
- } // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
886
-
887
-
888
- const lastItem = list.items.at(-1);
889
-
890
- if (lastItem) {
891
- lastItem.raw = lastItem.raw.trimEnd();
892
- lastItem.text = lastItem.text.trimEnd();
893
- } else {
894
- // not a list since there were no items
895
- return;
896
- }
897
-
898
- list.raw = list.raw.trimEnd(); // Item child tokens handled here at end because we needed to have the final item to trim it first
899
-
900
- for (let i = 0; i < list.items.length; i++) {
901
- this.lexer.state.top = false;
902
- list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
903
-
904
- if (!list.loose) {
905
- // Check if list should be loose
906
- const spacers = list.items[i].tokens.filter(t => t.type === 'space');
907
- const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));
908
- list.loose = hasMultipleLineBreaks;
909
- }
910
- } // Set all items to loose if list is loose
911
-
912
-
913
- if (list.loose) {
914
- for (let i = 0; i < list.items.length; i++) {
915
- list.items[i].loose = true;
916
- }
917
- }
918
-
919
- return list;
920
- }
921
- }
922
-
923
- html(src) {
924
- const cap = this.rules.block.html.exec(src);
925
-
926
- if (cap) {
927
- const token = {
928
- type: 'html',
929
- block: true,
930
- raw: cap[0],
931
- pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',
932
- text: cap[0]
933
- };
934
- return token;
935
- }
936
- }
937
-
938
- def(src) {
939
- const cap = this.rules.block.def.exec(src);
940
-
941
- if (cap) {
942
- const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');
943
- const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';
944
- const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];
945
- return {
946
- type: 'def',
947
- tag,
948
- raw: cap[0],
949
- href,
950
- title
951
- };
952
- }
953
- }
954
-
955
- table(src) {
956
- const cap = this.rules.block.table.exec(src);
957
-
958
- if (!cap) {
959
- return;
960
- }
961
-
962
- if (!this.rules.other.tableDelimiter.test(cap[2])) {
963
- // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading
964
- return;
965
- }
966
-
967
- const headers = splitCells(cap[1]);
968
- const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');
969
- const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\n') : [];
970
- const item = {
971
- type: 'table',
972
- raw: cap[0],
973
- header: [],
974
- align: [],
975
- rows: []
976
- };
977
-
978
- if (headers.length !== aligns.length) {
979
- // header and align columns must be equal, rows can be different.
980
- return;
981
- }
982
-
983
- for (const align of aligns) {
984
- if (this.rules.other.tableAlignRight.test(align)) {
985
- item.align.push('right');
986
- } else if (this.rules.other.tableAlignCenter.test(align)) {
987
- item.align.push('center');
988
- } else if (this.rules.other.tableAlignLeft.test(align)) {
989
- item.align.push('left');
990
- } else {
991
- item.align.push(null);
992
- }
993
- }
994
-
995
- for (let i = 0; i < headers.length; i++) {
996
- item.header.push({
997
- text: headers[i],
998
- tokens: this.lexer.inline(headers[i]),
999
- header: true,
1000
- align: item.align[i]
1001
- });
1002
- }
1003
-
1004
- for (const row of rows) {
1005
- item.rows.push(splitCells(row, item.header.length).map((cell, i) => {
1006
- return {
1007
- text: cell,
1008
- tokens: this.lexer.inline(cell),
1009
- header: false,
1010
- align: item.align[i]
1011
- };
1012
- }));
1013
- }
1014
-
1015
- return item;
1016
- }
1017
-
1018
- lheading(src) {
1019
- const cap = this.rules.block.lheading.exec(src);
1020
-
1021
- if (cap) {
1022
- return {
1023
- type: 'heading',
1024
- raw: cap[0],
1025
- depth: cap[2].charAt(0) === '=' ? 1 : 2,
1026
- text: cap[1],
1027
- tokens: this.lexer.inline(cap[1])
1028
- };
1029
- }
1030
- }
1031
-
1032
- paragraph(src) {
1033
- const cap = this.rules.block.paragraph.exec(src);
1034
-
1035
- if (cap) {
1036
- const text = cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1];
1037
- return {
1038
- type: 'paragraph',
1039
- raw: cap[0],
1040
- text,
1041
- tokens: this.lexer.inline(text)
1042
- };
1043
- }
1044
- }
1045
-
1046
- text(src) {
1047
- const cap = this.rules.block.text.exec(src);
1048
-
1049
- if (cap) {
1050
- return {
1051
- type: 'text',
1052
- raw: cap[0],
1053
- text: cap[0],
1054
- tokens: this.lexer.inline(cap[0])
1055
- };
1056
- }
1057
- }
1058
-
1059
- escape(src) {
1060
- const cap = this.rules.inline.escape.exec(src);
1061
-
1062
- if (cap) {
1063
- return {
1064
- type: 'escape',
1065
- raw: cap[0],
1066
- text: cap[1]
1067
- };
1068
- }
1069
- }
1070
-
1071
- tag(src) {
1072
- const cap = this.rules.inline.tag.exec(src);
1073
-
1074
- if (cap) {
1075
- if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {
1076
- this.lexer.state.inLink = true;
1077
- } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {
1078
- this.lexer.state.inLink = false;
1079
- }
1080
-
1081
- if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {
1082
- this.lexer.state.inRawBlock = true;
1083
- } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {
1084
- this.lexer.state.inRawBlock = false;
1085
- }
1086
-
1087
- return {
1088
- type: 'html',
1089
- raw: cap[0],
1090
- inLink: this.lexer.state.inLink,
1091
- inRawBlock: this.lexer.state.inRawBlock,
1092
- block: false,
1093
- text: cap[0]
1094
- };
1095
- }
1096
- }
1097
-
1098
- link(src) {
1099
- const cap = this.rules.inline.link.exec(src);
1100
-
1101
- if (cap) {
1102
- const trimmedUrl = cap[2].trim();
1103
-
1104
- if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {
1105
- // commonmark requires matching angle brackets
1106
- if (!this.rules.other.endAngleBracket.test(trimmedUrl)) {
1107
- return;
1108
- } // ending angle bracket cannot be escaped
1109
-
1110
-
1111
- const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
1112
-
1113
- if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
1114
- return;
1115
- }
1116
- } else {
1117
- // find closing parenthesis
1118
- const lastParenIndex = findClosingBracket(cap[2], '()');
1119
-
1120
- if (lastParenIndex > -1) {
1121
- const start = cap[0].indexOf('!') === 0 ? 5 : 4;
1122
- const linkLen = start + cap[1].length + lastParenIndex;
1123
- cap[2] = cap[2].substring(0, lastParenIndex);
1124
- cap[0] = cap[0].substring(0, linkLen).trim();
1125
- cap[3] = '';
1126
- }
1127
- }
1128
-
1129
- let href = cap[2];
1130
- let title = '';
1131
-
1132
- if (this.options.pedantic) {
1133
- // split pedantic href and title
1134
- const link = this.rules.other.pedanticHrefTitle.exec(href);
1135
-
1136
- if (link) {
1137
- href = link[1];
1138
- title = link[3];
1139
- }
1140
- } else {
1141
- title = cap[3] ? cap[3].slice(1, -1) : '';
1142
- }
1143
-
1144
- href = href.trim();
1145
-
1146
- if (this.rules.other.startAngleBracket.test(href)) {
1147
- if (this.options.pedantic && !this.rules.other.endAngleBracket.test(trimmedUrl)) {
1148
- // pedantic allows starting angle bracket without ending angle bracket
1149
- href = href.slice(1);
1150
- } else {
1151
- href = href.slice(1, -1);
1152
- }
1153
- }
1154
-
1155
- return outputLink(cap, {
1156
- href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,
1157
- title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title
1158
- }, cap[0], this.lexer, this.rules);
1159
- }
1160
- }
1161
-
1162
- reflink(src, links) {
1163
- let cap;
1164
-
1165
- if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
1166
- const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');
1167
- const link = links[linkString.toLowerCase()];
1168
-
1169
- if (!link) {
1170
- const text = cap[0].charAt(0);
1171
- return {
1172
- type: 'text',
1173
- raw: text,
1174
- text
1175
- };
1176
- }
1177
-
1178
- return outputLink(cap, link, cap[0], this.lexer, this.rules);
1179
- }
1180
- }
1181
-
1182
- emStrong(src, maskedSrc, prevChar = '') {
1183
- let match = this.rules.inline.emStrongLDelim.exec(src);
1184
- if (!match) return; // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
1185
-
1186
- if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;
1187
- const nextChar = match[1] || match[2] || '';
1188
-
1189
- if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
1190
- // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)
1191
- const lLength = [...match[0]].length - 1;
1192
- let rDelim,
1193
- rLength,
1194
- delimTotal = lLength,
1195
- midDelimTotal = 0;
1196
- const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
1197
- endReg.lastIndex = 0; // Clip maskedSrc to same section of string as src (move to lexer?)
1198
-
1199
- maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
1200
-
1201
- while ((match = endReg.exec(maskedSrc)) != null) {
1202
- rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
1203
- if (!rDelim) continue; // skip single * in __abc*abc__
1204
-
1205
- rLength = [...rDelim].length;
1206
-
1207
- if (match[3] || match[4]) {
1208
- // found another Left Delim
1209
- delimTotal += rLength;
1210
- continue;
1211
- } else if (match[5] || match[6]) {
1212
- // either Left or Right Delim
1213
- if (lLength % 3 && !((lLength + rLength) % 3)) {
1214
- midDelimTotal += rLength;
1215
- continue; // CommonMark Emphasis Rules 9-10
1216
- }
1217
- }
1218
-
1219
- delimTotal -= rLength;
1220
- if (delimTotal > 0) continue; // Haven't found enough closing delimiters
1221
- // Remove extra characters. *a*** -> *a*
1222
-
1223
- rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); // char length can be >1 for unicode characters;
1224
-
1225
- const lastCharLength = [...match[0]][0].length;
1226
- const raw = src.slice(0, lLength + match.index + lastCharLength + rLength); // Create `em` if smallest delimiter has odd char count. *a***
1227
-
1228
- if (Math.min(lLength, rLength) % 2) {
1229
- const text = raw.slice(1, -1);
1230
- return {
1231
- type: 'em',
1232
- raw,
1233
- text,
1234
- tokens: this.lexer.inlineTokens(text)
1235
- };
1236
- } // Create 'strong' if smallest delimiter has even char count. **a***
1237
-
1238
-
1239
- const text = raw.slice(2, -2);
1240
- return {
1241
- type: 'strong',
1242
- raw,
1243
- text,
1244
- tokens: this.lexer.inlineTokens(text)
1245
- };
1246
- }
1247
- }
1248
- }
1249
-
1250
- codespan(src) {
1251
- const cap = this.rules.inline.code.exec(src);
1252
-
1253
- if (cap) {
1254
- let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');
1255
- const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);
1256
- const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);
1257
-
1258
- if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
1259
- text = text.substring(1, text.length - 1);
1260
- }
1261
-
1262
- return {
1263
- type: 'codespan',
1264
- raw: cap[0],
1265
- text
1266
- };
1267
- }
1268
- }
1269
-
1270
- br(src) {
1271
- const cap = this.rules.inline.br.exec(src);
1272
-
1273
- if (cap) {
1274
- return {
1275
- type: 'br',
1276
- raw: cap[0]
1277
- };
1278
- }
1279
- }
1280
-
1281
- del(src) {
1282
- const cap = this.rules.inline.del.exec(src);
1283
-
1284
- if (cap) {
1285
- return {
1286
- type: 'del',
1287
- raw: cap[0],
1288
- text: cap[2],
1289
- tokens: this.lexer.inlineTokens(cap[2])
1290
- };
1291
- }
1292
- }
1293
-
1294
- autolink(src) {
1295
- const cap = this.rules.inline.autolink.exec(src);
1296
-
1297
- if (cap) {
1298
- let text, href;
1299
-
1300
- if (cap[2] === '@') {
1301
- text = cap[1];
1302
- href = 'mailto:' + text;
1303
- } else {
1304
- text = cap[1];
1305
- href = text;
1306
- }
1307
-
1308
- return {
1309
- type: 'link',
1310
- raw: cap[0],
1311
- text,
1312
- href,
1313
- tokens: [{
1314
- type: 'text',
1315
- raw: text,
1316
- text
1317
- }]
1318
- };
1319
- }
1320
- }
1321
-
1322
- url(src) {
1323
- let cap;
1324
-
1325
- if (cap = this.rules.inline.url.exec(src)) {
1326
- let text, href;
1327
-
1328
- if (cap[2] === '@') {
1329
- text = cap[0];
1330
- href = 'mailto:' + text;
1331
- } else {
1332
- // do extended autolink path validation
1333
- let prevCapZero;
1334
-
1335
- do {
1336
- prevCapZero = cap[0];
1337
- cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';
1338
- } while (prevCapZero !== cap[0]);
1339
-
1340
- text = cap[0];
1341
-
1342
- if (cap[1] === 'www.') {
1343
- href = 'http://' + cap[0];
1344
- } else {
1345
- href = cap[0];
1346
- }
1347
- }
1348
-
1349
- return {
1350
- type: 'link',
1351
- raw: cap[0],
1352
- text,
1353
- href,
1354
- tokens: [{
1355
- type: 'text',
1356
- raw: text,
1357
- text
1358
- }]
1359
- };
1360
- }
1361
- }
1362
-
1363
- inlineText(src) {
1364
- const cap = this.rules.inline.text.exec(src);
1365
-
1366
- if (cap) {
1367
- const escaped = this.lexer.state.inRawBlock;
1368
- return {
1369
- type: 'text',
1370
- raw: cap[0],
1371
- text: cap[0],
1372
- escaped
1373
- };
1374
- }
1375
- }
1376
-
1377
- }
1378
- /**
1379
- * Block Lexer
1380
- */
1381
-
1382
-
1383
- class _Lexer {
1384
- tokens;
1385
- options;
1386
- state;
1387
- tokenizer;
1388
- inlineQueue;
1389
-
1390
- constructor(options) {
1391
- // TokenList cannot be created in one go
1392
- this.tokens = [];
1393
- this.tokens.links = Object.create(null);
1394
- this.options = options || _defaults;
1395
- this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
1396
- this.tokenizer = this.options.tokenizer;
1397
- this.tokenizer.options = this.options;
1398
- this.tokenizer.lexer = this;
1399
- this.inlineQueue = [];
1400
- this.state = {
1401
- inLink: false,
1402
- inRawBlock: false,
1403
- top: true
1404
- };
1405
- const rules = {
1406
- other,
1407
- block: block.normal,
1408
- inline: inline.normal
1409
- };
1410
-
1411
- if (this.options.pedantic) {
1412
- rules.block = block.pedantic;
1413
- rules.inline = inline.pedantic;
1414
- } else if (this.options.gfm) {
1415
- rules.block = block.gfm;
1416
-
1417
- if (this.options.breaks) {
1418
- rules.inline = inline.breaks;
1419
- } else {
1420
- rules.inline = inline.gfm;
1421
- }
1422
- }
1423
-
1424
- this.tokenizer.rules = rules;
1425
- }
1426
- /**
1427
- * Expose Rules
1428
- */
1429
-
1430
-
1431
- static get rules() {
1432
- return {
1433
- block,
1434
- inline
1435
- };
1436
- }
1437
- /**
1438
- * Static Lex Method
1439
- */
1440
-
1441
-
1442
- static lex(src, options) {
1443
- const lexer = new _Lexer(options);
1444
- return lexer.lex(src);
1445
- }
1446
- /**
1447
- * Static Lex Inline Method
1448
- */
1449
-
1450
-
1451
- static lexInline(src, options) {
1452
- const lexer = new _Lexer(options);
1453
- return lexer.inlineTokens(src);
1454
- }
1455
- /**
1456
- * Preprocessing
1457
- */
1458
-
1459
-
1460
- lex(src) {
1461
- src = src.replace(other.carriageReturn, '\n');
1462
- this.blockTokens(src, this.tokens);
1463
-
1464
- for (let i = 0; i < this.inlineQueue.length; i++) {
1465
- const next = this.inlineQueue[i];
1466
- this.inlineTokens(next.src, next.tokens);
1467
- }
1468
-
1469
- this.inlineQueue = [];
1470
- return this.tokens;
1471
- }
1472
-
1473
- blockTokens(src, tokens = [], lastParagraphClipped = false) {
1474
- if (this.options.pedantic) {
1475
- src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');
1476
- }
1477
-
1478
- while (src) {
1479
- let token;
1480
-
1481
- if (this.options.extensions?.block?.some(extTokenizer => {
1482
- if (token = extTokenizer.call({
1483
- lexer: this
1484
- }, src, tokens)) {
1485
- src = src.substring(token.raw.length);
1486
- tokens.push(token);
1487
- return true;
1488
- }
1489
-
1490
- return false;
1491
- })) {
1492
- continue;
1493
- } // newline
1494
-
1495
-
1496
- if (token = this.tokenizer.space(src)) {
1497
- src = src.substring(token.raw.length);
1498
- const lastToken = tokens.at(-1);
1499
-
1500
- if (token.raw.length === 1 && lastToken !== undefined) {
1501
- // if there's a single \n as a spacer, it's terminating the last line,
1502
- // so move it there so that we don't get unnecessary paragraph tags
1503
- lastToken.raw += '\n';
1504
- } else {
1505
- tokens.push(token);
1506
- }
1507
-
1508
- continue;
1509
- } // code
1510
-
1511
-
1512
- if (token = this.tokenizer.code(src)) {
1513
- src = src.substring(token.raw.length);
1514
- const lastToken = tokens.at(-1); // An indented code block cannot interrupt a paragraph.
1515
-
1516
- if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {
1517
- lastToken.raw += '\n' + token.raw;
1518
- lastToken.text += '\n' + token.text;
1519
- this.inlineQueue.at(-1).src = lastToken.text;
1520
- } else {
1521
- tokens.push(token);
1522
- }
1523
-
1524
- continue;
1525
- } // fences
1526
-
1527
-
1528
- if (token = this.tokenizer.fences(src)) {
1529
- src = src.substring(token.raw.length);
1530
- tokens.push(token);
1531
- continue;
1532
- } // heading
1533
-
1534
-
1535
- if (token = this.tokenizer.heading(src)) {
1536
- src = src.substring(token.raw.length);
1537
- tokens.push(token);
1538
- continue;
1539
- } // hr
1540
-
1541
-
1542
- if (token = this.tokenizer.hr(src)) {
1543
- src = src.substring(token.raw.length);
1544
- tokens.push(token);
1545
- continue;
1546
- } // blockquote
1547
-
1548
-
1549
- if (token = this.tokenizer.blockquote(src)) {
1550
- src = src.substring(token.raw.length);
1551
- tokens.push(token);
1552
- continue;
1553
- } // list
1554
-
1555
-
1556
- if (token = this.tokenizer.list(src)) {
1557
- src = src.substring(token.raw.length);
1558
- tokens.push(token);
1559
- continue;
1560
- } // html
1561
-
1562
-
1563
- if (token = this.tokenizer.html(src)) {
1564
- src = src.substring(token.raw.length);
1565
- tokens.push(token);
1566
- continue;
1567
- } // def
1568
-
1569
-
1570
- if (token = this.tokenizer.def(src)) {
1571
- src = src.substring(token.raw.length);
1572
- const lastToken = tokens.at(-1);
1573
-
1574
- if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {
1575
- lastToken.raw += '\n' + token.raw;
1576
- lastToken.text += '\n' + token.raw;
1577
- this.inlineQueue.at(-1).src = lastToken.text;
1578
- } else if (!this.tokens.links[token.tag]) {
1579
- this.tokens.links[token.tag] = {
1580
- href: token.href,
1581
- title: token.title
1582
- };
1583
- }
1584
-
1585
- continue;
1586
- } // table (gfm)
1587
-
1588
-
1589
- if (token = this.tokenizer.table(src)) {
1590
- src = src.substring(token.raw.length);
1591
- tokens.push(token);
1592
- continue;
1593
- } // lheading
1594
-
1595
-
1596
- if (token = this.tokenizer.lheading(src)) {
1597
- src = src.substring(token.raw.length);
1598
- tokens.push(token);
1599
- continue;
1600
- } // top-level paragraph
1601
- // prevent paragraph consuming extensions by clipping 'src' to extension start
1602
-
1603
-
1604
- let cutSrc = src;
1605
-
1606
- if (this.options.extensions?.startBlock) {
1607
- let startIndex = Infinity;
1608
- const tempSrc = src.slice(1);
1609
- let tempStart;
1610
- this.options.extensions.startBlock.forEach(getStartIndex => {
1611
- tempStart = getStartIndex.call({
1612
- lexer: this
1613
- }, tempSrc);
1614
-
1615
- if (typeof tempStart === 'number' && tempStart >= 0) {
1616
- startIndex = Math.min(startIndex, tempStart);
1617
- }
1618
- });
1619
-
1620
- if (startIndex < Infinity && startIndex >= 0) {
1621
- cutSrc = src.substring(0, startIndex + 1);
1622
- }
1623
- }
1624
-
1625
- if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
1626
- const lastToken = tokens.at(-1);
1627
-
1628
- if (lastParagraphClipped && lastToken?.type === 'paragraph') {
1629
- lastToken.raw += '\n' + token.raw;
1630
- lastToken.text += '\n' + token.text;
1631
- this.inlineQueue.pop();
1632
- this.inlineQueue.at(-1).src = lastToken.text;
1633
- } else {
1634
- tokens.push(token);
1635
- }
1636
-
1637
- lastParagraphClipped = cutSrc.length !== src.length;
1638
- src = src.substring(token.raw.length);
1639
- continue;
1640
- } // text
1641
-
1642
-
1643
- if (token = this.tokenizer.text(src)) {
1644
- src = src.substring(token.raw.length);
1645
- const lastToken = tokens.at(-1);
1646
-
1647
- if (lastToken?.type === 'text') {
1648
- lastToken.raw += '\n' + token.raw;
1649
- lastToken.text += '\n' + token.text;
1650
- this.inlineQueue.pop();
1651
- this.inlineQueue.at(-1).src = lastToken.text;
1652
- } else {
1653
- tokens.push(token);
1654
- }
1655
-
1656
- continue;
1657
- }
1658
-
1659
- if (src) {
1660
- const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
1661
-
1662
- if (this.options.silent) {
1663
- console.error(errMsg);
1664
- break;
1665
- } else {
1666
- throw new Error(errMsg);
1667
- }
1668
- }
1669
- }
1670
-
1671
- this.state.top = true;
1672
- return tokens;
1673
- }
1674
-
1675
- inline(src, tokens = []) {
1676
- this.inlineQueue.push({
1677
- src,
1678
- tokens
1679
- });
1680
- return tokens;
1681
- }
1682
- /**
1683
- * Lexing/Compiling
1684
- */
1685
-
1686
-
1687
- inlineTokens(src, tokens = []) {
1688
- // String with links masked to avoid interference with em and strong
1689
- let maskedSrc = src;
1690
- let match = null; // Mask out reflinks
1691
-
1692
- if (this.tokens.links) {
1693
- const links = Object.keys(this.tokens.links);
1694
-
1695
- if (links.length > 0) {
1696
- while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
1697
- if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
1698
- maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
1699
- }
1700
- }
1701
- }
1702
- } // Mask out other blocks
1703
-
1704
-
1705
- while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
1706
- maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
1707
- } // Mask out escaped characters
1708
-
1709
-
1710
- while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
1711
- maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
1712
- }
1713
-
1714
- let keepPrevChar = false;
1715
- let prevChar = '';
1716
-
1717
- while (src) {
1718
- if (!keepPrevChar) {
1719
- prevChar = '';
1720
- }
1721
-
1722
- keepPrevChar = false;
1723
- let token; // extensions
1724
-
1725
- if (this.options.extensions?.inline?.some(extTokenizer => {
1726
- if (token = extTokenizer.call({
1727
- lexer: this
1728
- }, src, tokens)) {
1729
- src = src.substring(token.raw.length);
1730
- tokens.push(token);
1731
- return true;
1732
- }
1733
-
1734
- return false;
1735
- })) {
1736
- continue;
1737
- } // escape
1738
-
1739
-
1740
- if (token = this.tokenizer.escape(src)) {
1741
- src = src.substring(token.raw.length);
1742
- tokens.push(token);
1743
- continue;
1744
- } // tag
1745
-
1746
-
1747
- if (token = this.tokenizer.tag(src)) {
1748
- src = src.substring(token.raw.length);
1749
- tokens.push(token);
1750
- continue;
1751
- } // link
1752
-
1753
-
1754
- if (token = this.tokenizer.link(src)) {
1755
- src = src.substring(token.raw.length);
1756
- tokens.push(token);
1757
- continue;
1758
- } // reflink, nolink
1759
-
1760
-
1761
- if (token = this.tokenizer.reflink(src, this.tokens.links)) {
1762
- src = src.substring(token.raw.length);
1763
- const lastToken = tokens.at(-1);
1764
-
1765
- if (token.type === 'text' && lastToken?.type === 'text') {
1766
- lastToken.raw += token.raw;
1767
- lastToken.text += token.text;
1768
- } else {
1769
- tokens.push(token);
1770
- }
1771
-
1772
- continue;
1773
- } // em & strong
1774
-
1775
-
1776
- if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
1777
- src = src.substring(token.raw.length);
1778
- tokens.push(token);
1779
- continue;
1780
- } // code
1781
-
1782
-
1783
- if (token = this.tokenizer.codespan(src)) {
1784
- src = src.substring(token.raw.length);
1785
- tokens.push(token);
1786
- continue;
1787
- } // br
1788
-
1789
-
1790
- if (token = this.tokenizer.br(src)) {
1791
- src = src.substring(token.raw.length);
1792
- tokens.push(token);
1793
- continue;
1794
- } // del (gfm)
1795
-
1796
-
1797
- if (token = this.tokenizer.del(src)) {
1798
- src = src.substring(token.raw.length);
1799
- tokens.push(token);
1800
- continue;
1801
- } // autolink
1802
-
1803
-
1804
- if (token = this.tokenizer.autolink(src)) {
1805
- src = src.substring(token.raw.length);
1806
- tokens.push(token);
1807
- continue;
1808
- } // url (gfm)
1809
-
1810
-
1811
- if (!this.state.inLink && (token = this.tokenizer.url(src))) {
1812
- src = src.substring(token.raw.length);
1813
- tokens.push(token);
1814
- continue;
1815
- } // text
1816
- // prevent inlineText consuming extensions by clipping 'src' to extension start
1817
-
1818
-
1819
- let cutSrc = src;
1820
-
1821
- if (this.options.extensions?.startInline) {
1822
- let startIndex = Infinity;
1823
- const tempSrc = src.slice(1);
1824
- let tempStart;
1825
- this.options.extensions.startInline.forEach(getStartIndex => {
1826
- tempStart = getStartIndex.call({
1827
- lexer: this
1828
- }, tempSrc);
1829
-
1830
- if (typeof tempStart === 'number' && tempStart >= 0) {
1831
- startIndex = Math.min(startIndex, tempStart);
1832
- }
1833
- });
1834
-
1835
- if (startIndex < Infinity && startIndex >= 0) {
1836
- cutSrc = src.substring(0, startIndex + 1);
1837
- }
1838
- }
1839
-
1840
- if (token = this.tokenizer.inlineText(cutSrc)) {
1841
- src = src.substring(token.raw.length);
1842
-
1843
- if (token.raw.slice(-1) !== '_') {
1844
- // Track prevChar before string of ____ started
1845
- prevChar = token.raw.slice(-1);
1846
- }
1847
-
1848
- keepPrevChar = true;
1849
- const lastToken = tokens.at(-1);
1850
-
1851
- if (lastToken?.type === 'text') {
1852
- lastToken.raw += token.raw;
1853
- lastToken.text += token.text;
1854
- } else {
1855
- tokens.push(token);
1856
- }
1857
-
1858
- continue;
1859
- }
1860
-
1861
- if (src) {
1862
- const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
1863
-
1864
- if (this.options.silent) {
1865
- console.error(errMsg);
1866
- break;
1867
- } else {
1868
- throw new Error(errMsg);
1869
- }
1870
- }
1871
- }
1872
-
1873
- return tokens;
1874
- }
1875
-
1876
- }
1877
- /**
1878
- * Renderer
1879
- */
1880
-
1881
-
1882
- class _Renderer {
1883
- options;
1884
- parser; // set by the parser
1885
-
1886
- constructor(options) {
1887
- this.options = options || _defaults;
1888
- }
1889
-
1890
- space(token) {
1891
- return '';
1892
- }
1893
-
1894
- code({
1895
- text,
1896
- lang,
1897
- escaped
1898
- }) {
1899
- const langString = (lang || '').match(other.notSpaceStart)?.[0];
1900
- const code = text.replace(other.endingNewline, '') + '\n';
1901
-
1902
- if (!langString) {
1903
- return '<pre><code>' + (escaped ? code : escape(code, true)) + '</code></pre>\n';
1904
- }
1905
-
1906
- return '<pre><code class="language-' + escape(langString) + '">' + (escaped ? code : escape(code, true)) + '</code></pre>\n';
1907
- }
1908
-
1909
- blockquote({
1910
- tokens
1911
- }) {
1912
- const body = this.parser.parse(tokens);
1913
- return `<blockquote>\n${body}</blockquote>\n`;
1914
- }
1915
-
1916
- html({
1917
- text
1918
- }) {
1919
- return text;
1920
- }
1921
-
1922
- heading({
1923
- tokens,
1924
- depth
1925
- }) {
1926
- return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\n`;
1927
- }
1928
-
1929
- hr(token) {
1930
- return '<hr>\n';
1931
- }
1932
-
1933
- list(token) {
1934
- const ordered = token.ordered;
1935
- const start = token.start;
1936
- let body = '';
1937
-
1938
- for (let j = 0; j < token.items.length; j++) {
1939
- const item = token.items[j];
1940
- body += this.listitem(item);
1941
- }
1942
-
1943
- const type = ordered ? 'ol' : 'ul';
1944
- const startAttr = ordered && start !== 1 ? ' start="' + start + '"' : '';
1945
- return '<' + type + startAttr + '>\n' + body + '</' + type + '>\n';
1946
- }
1947
-
1948
- listitem(item) {
1949
- let itemBody = '';
1950
-
1951
- if (item.task) {
1952
- const checkbox = this.checkbox({
1953
- checked: !!item.checked
1954
- });
1955
-
1956
- if (item.loose) {
1957
- if (item.tokens[0]?.type === 'paragraph') {
1958
- item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
1959
-
1960
- if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
1961
- item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text);
1962
- item.tokens[0].tokens[0].escaped = true;
1963
- }
1964
- } else {
1965
- item.tokens.unshift({
1966
- type: 'text',
1967
- raw: checkbox + ' ',
1968
- text: checkbox + ' ',
1969
- escaped: true
1970
- });
1971
- }
1972
- } else {
1973
- itemBody += checkbox + ' ';
1974
- }
1975
- }
1976
-
1977
- itemBody += this.parser.parse(item.tokens, !!item.loose);
1978
- return `<li>${itemBody}</li>\n`;
1979
- }
1980
-
1981
- checkbox({
1982
- checked
1983
- }) {
1984
- return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox">';
1985
- }
1986
-
1987
- paragraph({
1988
- tokens
1989
- }) {
1990
- return `<p>${this.parser.parseInline(tokens)}</p>\n`;
1991
- }
1992
-
1993
- table(token) {
1994
- let header = ''; // header
1995
-
1996
- let cell = '';
1997
-
1998
- for (let j = 0; j < token.header.length; j++) {
1999
- cell += this.tablecell(token.header[j]);
2000
- }
2001
-
2002
- header += this.tablerow({
2003
- text: cell
2004
- });
2005
- let body = '';
2006
-
2007
- for (let j = 0; j < token.rows.length; j++) {
2008
- const row = token.rows[j];
2009
- cell = '';
2010
-
2011
- for (let k = 0; k < row.length; k++) {
2012
- cell += this.tablecell(row[k]);
2013
- }
2014
-
2015
- body += this.tablerow({
2016
- text: cell
2017
- });
2018
- }
2019
-
2020
- if (body) body = `<tbody>${body}</tbody>`;
2021
- return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n';
2022
- }
2023
-
2024
- tablerow({
2025
- text
2026
- }) {
2027
- return `<tr>\n${text}</tr>\n`;
2028
- }
2029
-
2030
- tablecell(token) {
2031
- const content = this.parser.parseInline(token.tokens);
2032
- const type = token.header ? 'th' : 'td';
2033
- const tag = token.align ? `<${type} align="${token.align}">` : `<${type}>`;
2034
- return tag + content + `</${type}>\n`;
2035
- }
2036
- /**
2037
- * span level renderer
2038
- */
2039
-
2040
-
2041
- strong({
2042
- tokens
2043
- }) {
2044
- return `<strong>${this.parser.parseInline(tokens)}</strong>`;
2045
- }
2046
-
2047
- em({
2048
- tokens
2049
- }) {
2050
- return `<em>${this.parser.parseInline(tokens)}</em>`;
2051
- }
2052
-
2053
- codespan({
2054
- text
2055
- }) {
2056
- return `<code>${escape(text, true)}</code>`;
2057
- }
2058
-
2059
- br(token) {
2060
- return '<br>';
2061
- }
2062
-
2063
- del({
2064
- tokens
2065
- }) {
2066
- return `<del>${this.parser.parseInline(tokens)}</del>`;
2067
- }
2068
-
2069
- link({
2070
- href,
2071
- title,
2072
- tokens
2073
- }) {
2074
- const text = this.parser.parseInline(tokens);
2075
- const cleanHref = cleanUrl(href);
2076
-
2077
- if (cleanHref === null) {
2078
- return text;
2079
- }
2080
-
2081
- href = cleanHref;
2082
- let out = '<a href="' + href + '"';
2083
-
2084
- if (title) {
2085
- out += ' title="' + escape(title) + '"';
2086
- }
2087
-
2088
- out += '>' + text + '</a>';
2089
- return out;
2090
- }
2091
-
2092
- image({
2093
- href,
2094
- title,
2095
- text
2096
- }) {
2097
- const cleanHref = cleanUrl(href);
2098
-
2099
- if (cleanHref === null) {
2100
- return escape(text);
2101
- }
2102
-
2103
- href = cleanHref;
2104
- let out = `<img src="${href}" alt="${text}"`;
2105
-
2106
- if (title) {
2107
- out += ` title="${escape(title)}"`;
2108
- }
2109
-
2110
- out += '>';
2111
- return out;
2112
- }
2113
-
2114
- text(token) {
2115
- return 'tokens' in token && token.tokens ? this.parser.parseInline(token.tokens) : 'escaped' in token && token.escaped ? token.text : escape(token.text);
2116
- }
2117
-
2118
- }
2119
- /**
2120
- * TextRenderer
2121
- * returns only the textual part of the token
2122
- */
2123
-
2124
-
2125
- class _TextRenderer {
2126
- // no need for block level renderers
2127
- strong({
2128
- text
2129
- }) {
2130
- return text;
2131
- }
2132
-
2133
- em({
2134
- text
2135
- }) {
2136
- return text;
2137
- }
2138
-
2139
- codespan({
2140
- text
2141
- }) {
2142
- return text;
2143
- }
2144
-
2145
- del({
2146
- text
2147
- }) {
2148
- return text;
2149
- }
2150
-
2151
- html({
2152
- text
2153
- }) {
2154
- return text;
2155
- }
2156
-
2157
- text({
2158
- text
2159
- }) {
2160
- return text;
2161
- }
2162
-
2163
- link({
2164
- text
2165
- }) {
2166
- return '' + text;
2167
- }
2168
-
2169
- image({
2170
- text
2171
- }) {
2172
- return '' + text;
2173
- }
2174
-
2175
- br() {
2176
- return '';
2177
- }
2178
-
2179
- }
2180
- /**
2181
- * Parsing & Compiling
2182
- */
2183
-
2184
-
2185
- class _Parser {
2186
- options;
2187
- renderer;
2188
- textRenderer;
2189
-
2190
- constructor(options) {
2191
- this.options = options || _defaults;
2192
- this.options.renderer = this.options.renderer || new _Renderer();
2193
- this.renderer = this.options.renderer;
2194
- this.renderer.options = this.options;
2195
- this.renderer.parser = this;
2196
- this.textRenderer = new _TextRenderer();
2197
- }
2198
- /**
2199
- * Static Parse Method
2200
- */
2201
-
2202
-
2203
- static parse(tokens, options) {
2204
- const parser = new _Parser(options);
2205
- return parser.parse(tokens);
2206
- }
2207
- /**
2208
- * Static Parse Inline Method
2209
- */
2210
-
2211
-
2212
- static parseInline(tokens, options) {
2213
- const parser = new _Parser(options);
2214
- return parser.parseInline(tokens);
2215
- }
2216
- /**
2217
- * Parse Loop
2218
- */
2219
-
2220
-
2221
- parse(tokens, top = true) {
2222
- let out = '';
2223
-
2224
- for (let i = 0; i < tokens.length; i++) {
2225
- const anyToken = tokens[i]; // Run any renderer extensions
2226
-
2227
- if (this.options.extensions?.renderers?.[anyToken.type]) {
2228
- const genericToken = anyToken;
2229
- const ret = this.options.extensions.renderers[genericToken.type].call({
2230
- parser: this
2231
- }, genericToken);
2232
-
2233
- if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(genericToken.type)) {
2234
- out += ret || '';
2235
- continue;
2236
- }
2237
- }
2238
-
2239
- const token = anyToken;
2240
-
2241
- switch (token.type) {
2242
- case 'space':
2243
- {
2244
- out += this.renderer.space(token);
2245
- continue;
2246
- }
2247
-
2248
- case 'hr':
2249
- {
2250
- out += this.renderer.hr(token);
2251
- continue;
2252
- }
2253
-
2254
- case 'heading':
2255
- {
2256
- out += this.renderer.heading(token);
2257
- continue;
2258
- }
2259
-
2260
- case 'code':
2261
- {
2262
- out += this.renderer.code(token);
2263
- continue;
2264
- }
2265
-
2266
- case 'table':
2267
- {
2268
- out += this.renderer.table(token);
2269
- continue;
2270
- }
2271
-
2272
- case 'blockquote':
2273
- {
2274
- out += this.renderer.blockquote(token);
2275
- continue;
2276
- }
2277
-
2278
- case 'list':
2279
- {
2280
- out += this.renderer.list(token);
2281
- continue;
2282
- }
2283
-
2284
- case 'html':
2285
- {
2286
- out += this.renderer.html(token);
2287
- continue;
2288
- }
2289
-
2290
- case 'paragraph':
2291
- {
2292
- out += this.renderer.paragraph(token);
2293
- continue;
2294
- }
2295
-
2296
- case 'text':
2297
- {
2298
- let textToken = token;
2299
- let body = this.renderer.text(textToken);
2300
-
2301
- while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {
2302
- textToken = tokens[++i];
2303
- body += '\n' + this.renderer.text(textToken);
2304
- }
2305
-
2306
- if (top) {
2307
- out += this.renderer.paragraph({
2308
- type: 'paragraph',
2309
- raw: body,
2310
- text: body,
2311
- tokens: [{
2312
- type: 'text',
2313
- raw: body,
2314
- text: body,
2315
- escaped: true
2316
- }]
2317
- });
2318
- } else {
2319
- out += body;
2320
- }
2321
-
2322
- continue;
2323
- }
2324
-
2325
- default:
2326
- {
2327
- const errMsg = 'Token with "' + token.type + '" type was not found.';
2328
-
2329
- if (this.options.silent) {
2330
- console.error(errMsg);
2331
- return '';
2332
- } else {
2333
- throw new Error(errMsg);
2334
- }
2335
- }
2336
- }
2337
- }
2338
-
2339
- return out;
2340
- }
2341
- /**
2342
- * Parse Inline Tokens
2343
- */
2344
-
2345
-
2346
- parseInline(tokens, renderer = this.renderer) {
2347
- let out = '';
2348
-
2349
- for (let i = 0; i < tokens.length; i++) {
2350
- const anyToken = tokens[i]; // Run any renderer extensions
2351
-
2352
- if (this.options.extensions?.renderers?.[anyToken.type]) {
2353
- const ret = this.options.extensions.renderers[anyToken.type].call({
2354
- parser: this
2355
- }, anyToken);
2356
-
2357
- if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {
2358
- out += ret || '';
2359
- continue;
2360
- }
2361
- }
2362
-
2363
- const token = anyToken;
2364
-
2365
- switch (token.type) {
2366
- case 'escape':
2367
- {
2368
- out += renderer.text(token);
2369
- break;
2370
- }
2371
-
2372
- case 'html':
2373
- {
2374
- out += renderer.html(token);
2375
- break;
2376
- }
2377
-
2378
- case 'link':
2379
- {
2380
- out += renderer.link(token);
2381
- break;
2382
- }
2383
-
2384
- case 'image':
2385
- {
2386
- out += renderer.image(token);
2387
- break;
2388
- }
2389
-
2390
- case 'strong':
2391
- {
2392
- out += renderer.strong(token);
2393
- break;
2394
- }
2395
-
2396
- case 'em':
2397
- {
2398
- out += renderer.em(token);
2399
- break;
2400
- }
2401
-
2402
- case 'codespan':
2403
- {
2404
- out += renderer.codespan(token);
2405
- break;
2406
- }
2407
-
2408
- case 'br':
2409
- {
2410
- out += renderer.br(token);
2411
- break;
2412
- }
2413
-
2414
- case 'del':
2415
- {
2416
- out += renderer.del(token);
2417
- break;
2418
- }
2419
-
2420
- case 'text':
2421
- {
2422
- out += renderer.text(token);
2423
- break;
2424
- }
2425
-
2426
- default:
2427
- {
2428
- const errMsg = 'Token with "' + token.type + '" type was not found.';
2429
-
2430
- if (this.options.silent) {
2431
- console.error(errMsg);
2432
- return '';
2433
- } else {
2434
- throw new Error(errMsg);
2435
- }
2436
- }
2437
- }
2438
- }
2439
-
2440
- return out;
2441
- }
2442
-
2443
- }
2444
-
2445
- class _Hooks {
2446
- options;
2447
- block;
2448
-
2449
- constructor(options) {
2450
- this.options = options || _defaults;
2451
- }
2452
-
2453
- static passThroughHooks = new Set(['preprocess', 'postprocess', 'processAllTokens']);
2454
- /**
2455
- * Process markdown before marked
2456
- */
2457
-
2458
- preprocess(markdown) {
2459
- return markdown;
2460
- }
2461
- /**
2462
- * Process HTML after marked is finished
2463
- */
2464
-
2465
-
2466
- postprocess(html) {
2467
- return html;
2468
- }
2469
- /**
2470
- * Process all tokens before walk tokens
2471
- */
2472
-
2473
-
2474
- processAllTokens(tokens) {
2475
- return tokens;
2476
- }
2477
- /**
2478
- * Provide function to tokenize markdown
2479
- */
2480
-
2481
-
2482
- provideLexer() {
2483
- return this.block ? _Lexer.lex : _Lexer.lexInline;
2484
- }
2485
- /**
2486
- * Provide function to parse tokens
2487
- */
2488
-
2489
-
2490
- provideParser() {
2491
- return this.block ? _Parser.parse : _Parser.parseInline;
2492
- }
2493
-
2494
- }
2495
-
2496
- class Marked {
2497
- defaults = _getDefaults();
2498
- options = this.setOptions;
2499
- parse = this.parseMarkdown(true);
2500
- parseInline = this.parseMarkdown(false);
2501
- Parser = _Parser;
2502
- Renderer = _Renderer;
2503
- TextRenderer = _TextRenderer;
2504
- Lexer = _Lexer;
2505
- Tokenizer = _Tokenizer;
2506
- Hooks = _Hooks;
2507
-
2508
- constructor(...args) {
2509
- this.use(...args);
2510
- }
2511
- /**
2512
- * Run callback for every token
2513
- */
2514
-
2515
-
2516
- walkTokens(tokens, callback) {
2517
- let values = [];
2518
-
2519
- for (const token of tokens) {
2520
- values = values.concat(callback.call(this, token));
2521
-
2522
- switch (token.type) {
2523
- case 'table':
2524
- {
2525
- const tableToken = token;
2526
-
2527
- for (const cell of tableToken.header) {
2528
- values = values.concat(this.walkTokens(cell.tokens, callback));
2529
- }
2530
-
2531
- for (const row of tableToken.rows) {
2532
- for (const cell of row) {
2533
- values = values.concat(this.walkTokens(cell.tokens, callback));
2534
- }
2535
- }
2536
-
2537
- break;
2538
- }
2539
-
2540
- case 'list':
2541
- {
2542
- const listToken = token;
2543
- values = values.concat(this.walkTokens(listToken.items, callback));
2544
- break;
2545
- }
2546
-
2547
- default:
2548
- {
2549
- const genericToken = token;
2550
-
2551
- if (this.defaults.extensions?.childTokens?.[genericToken.type]) {
2552
- this.defaults.extensions.childTokens[genericToken.type].forEach(childTokens => {
2553
- const tokens = genericToken[childTokens].flat(Infinity);
2554
- values = values.concat(this.walkTokens(tokens, callback));
2555
- });
2556
- } else if (genericToken.tokens) {
2557
- values = values.concat(this.walkTokens(genericToken.tokens, callback));
2558
- }
2559
- }
2560
- }
2561
- }
2562
-
2563
- return values;
2564
- }
2565
-
2566
- use(...args) {
2567
- const extensions = this.defaults.extensions || {
2568
- renderers: {},
2569
- childTokens: {}
2570
- };
2571
- args.forEach(pack => {
2572
- // copy options to new object
2573
- const opts = { ...pack
2574
- }; // set async to true if it was set to true before
2575
-
2576
- opts.async = this.defaults.async || opts.async || false; // ==-- Parse "addon" extensions --== //
2577
-
2578
- if (pack.extensions) {
2579
- pack.extensions.forEach(ext => {
2580
- if (!ext.name) {
2581
- throw new Error('extension name required');
2582
- }
2583
-
2584
- if ('renderer' in ext) {
2585
- // Renderer extensions
2586
- const prevRenderer = extensions.renderers[ext.name];
2587
-
2588
- if (prevRenderer) {
2589
- // Replace extension with func to run new extension but fall back if false
2590
- extensions.renderers[ext.name] = function (...args) {
2591
- let ret = ext.renderer.apply(this, args);
2592
-
2593
- if (ret === false) {
2594
- ret = prevRenderer.apply(this, args);
2595
- }
2596
-
2597
- return ret;
2598
- };
2599
- } else {
2600
- extensions.renderers[ext.name] = ext.renderer;
2601
- }
2602
- }
2603
-
2604
- if ('tokenizer' in ext) {
2605
- // Tokenizer Extensions
2606
- if (!ext.level || ext.level !== 'block' && ext.level !== 'inline') {
2607
- throw new Error("extension level must be 'block' or 'inline'");
2608
- }
2609
-
2610
- const extLevel = extensions[ext.level];
2611
-
2612
- if (extLevel) {
2613
- extLevel.unshift(ext.tokenizer);
2614
- } else {
2615
- extensions[ext.level] = [ext.tokenizer];
2616
- }
2617
-
2618
- if (ext.start) {
2619
- // Function to check for start of token
2620
- if (ext.level === 'block') {
2621
- if (extensions.startBlock) {
2622
- extensions.startBlock.push(ext.start);
2623
- } else {
2624
- extensions.startBlock = [ext.start];
2625
- }
2626
- } else if (ext.level === 'inline') {
2627
- if (extensions.startInline) {
2628
- extensions.startInline.push(ext.start);
2629
- } else {
2630
- extensions.startInline = [ext.start];
2631
- }
2632
- }
2633
- }
2634
- }
2635
-
2636
- if ('childTokens' in ext && ext.childTokens) {
2637
- // Child tokens to be visited by walkTokens
2638
- extensions.childTokens[ext.name] = ext.childTokens;
2639
- }
2640
- });
2641
- opts.extensions = extensions;
2642
- } // ==-- Parse "overwrite" extensions --== //
2643
-
2644
-
2645
- if (pack.renderer) {
2646
- const renderer = this.defaults.renderer || new _Renderer(this.defaults);
2647
-
2648
- for (const prop in pack.renderer) {
2649
- if (!(prop in renderer)) {
2650
- throw new Error(`renderer '${prop}' does not exist`);
2651
- }
2652
-
2653
- if (['options', 'parser'].includes(prop)) {
2654
- // ignore options property
2655
- continue;
2656
- }
2657
-
2658
- const rendererProp = prop;
2659
- const rendererFunc = pack.renderer[rendererProp];
2660
- const prevRenderer = renderer[rendererProp]; // Replace renderer with func to run extension, but fall back if false
2661
-
2662
- renderer[rendererProp] = (...args) => {
2663
- let ret = rendererFunc.apply(renderer, args);
2664
-
2665
- if (ret === false) {
2666
- ret = prevRenderer.apply(renderer, args);
2667
- }
2668
-
2669
- return ret || '';
2670
- };
2671
- }
2672
-
2673
- opts.renderer = renderer;
2674
- }
2675
-
2676
- if (pack.tokenizer) {
2677
- const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
2678
-
2679
- for (const prop in pack.tokenizer) {
2680
- if (!(prop in tokenizer)) {
2681
- throw new Error(`tokenizer '${prop}' does not exist`);
2682
- }
2683
-
2684
- if (['options', 'rules', 'lexer'].includes(prop)) {
2685
- // ignore options, rules, and lexer properties
2686
- continue;
2687
- }
2688
-
2689
- const tokenizerProp = prop;
2690
- const tokenizerFunc = pack.tokenizer[tokenizerProp];
2691
- const prevTokenizer = tokenizer[tokenizerProp]; // Replace tokenizer with func to run extension, but fall back if false
2692
- // @ts-expect-error cannot type tokenizer function dynamically
2693
-
2694
- tokenizer[tokenizerProp] = (...args) => {
2695
- let ret = tokenizerFunc.apply(tokenizer, args);
2696
-
2697
- if (ret === false) {
2698
- ret = prevTokenizer.apply(tokenizer, args);
2699
- }
2700
-
2701
- return ret;
2702
- };
2703
- }
2704
-
2705
- opts.tokenizer = tokenizer;
2706
- } // ==-- Parse Hooks extensions --== //
2707
-
2708
-
2709
- if (pack.hooks) {
2710
- const hooks = this.defaults.hooks || new _Hooks();
2711
-
2712
- for (const prop in pack.hooks) {
2713
- if (!(prop in hooks)) {
2714
- throw new Error(`hook '${prop}' does not exist`);
2715
- }
2716
-
2717
- if (['options', 'block'].includes(prop)) {
2718
- // ignore options and block properties
2719
- continue;
2720
- }
2721
-
2722
- const hooksProp = prop;
2723
- const hooksFunc = pack.hooks[hooksProp];
2724
- const prevHook = hooks[hooksProp];
2725
-
2726
- if (_Hooks.passThroughHooks.has(prop)) {
2727
- // @ts-expect-error cannot type hook function dynamically
2728
- hooks[hooksProp] = arg => {
2729
- if (this.defaults.async) {
2730
- return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
2731
- return prevHook.call(hooks, ret);
2732
- });
2733
- }
2734
-
2735
- const ret = hooksFunc.call(hooks, arg);
2736
- return prevHook.call(hooks, ret);
2737
- };
2738
- } else {
2739
- // @ts-expect-error cannot type hook function dynamically
2740
- hooks[hooksProp] = (...args) => {
2741
- let ret = hooksFunc.apply(hooks, args);
2742
-
2743
- if (ret === false) {
2744
- ret = prevHook.apply(hooks, args);
2745
- }
2746
-
2747
- return ret;
2748
- };
2749
- }
2750
- }
2751
-
2752
- opts.hooks = hooks;
2753
- } // ==-- Parse WalkTokens extensions --== //
2754
-
2755
-
2756
- if (pack.walkTokens) {
2757
- const walkTokens = this.defaults.walkTokens;
2758
- const packWalktokens = pack.walkTokens;
2759
-
2760
- opts.walkTokens = function (token) {
2761
- let values = [];
2762
- values.push(packWalktokens.call(this, token));
2763
-
2764
- if (walkTokens) {
2765
- values = values.concat(walkTokens.call(this, token));
2766
- }
2767
-
2768
- return values;
2769
- };
2770
- }
2771
-
2772
- this.defaults = { ...this.defaults,
2773
- ...opts
2774
- };
2775
- });
2776
- return this;
2777
- }
2778
-
2779
- setOptions(opt) {
2780
- this.defaults = { ...this.defaults,
2781
- ...opt
2782
- };
2783
- return this;
2784
- }
2785
-
2786
- lexer(src, options) {
2787
- return _Lexer.lex(src, options ?? this.defaults);
2788
- }
2789
-
2790
- parser(tokens, options) {
2791
- return _Parser.parse(tokens, options ?? this.defaults);
2792
- }
2793
-
2794
- parseMarkdown(blockType) {
2795
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2796
- const parse = (src, options) => {
2797
- const origOpt = { ...options
2798
- };
2799
- const opt = { ...this.defaults,
2800
- ...origOpt
2801
- };
2802
- const throwError = this.onError(!!opt.silent, !!opt.async); // throw error if an extension set async to true but parse was called with async: false
2803
-
2804
- if (this.defaults.async === true && origOpt.async === false) {
2805
- return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));
2806
- } // throw error in case of non string input
2807
-
2808
-
2809
- if (typeof src === 'undefined' || src === null) {
2810
- return throwError(new Error('marked(): input parameter is undefined or null'));
2811
- }
2812
-
2813
- if (typeof src !== 'string') {
2814
- return throwError(new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected'));
2815
- }
2816
-
2817
- if (opt.hooks) {
2818
- opt.hooks.options = opt;
2819
- opt.hooks.block = blockType;
2820
- }
2821
-
2822
- const lexer = opt.hooks ? opt.hooks.provideLexer() : blockType ? _Lexer.lex : _Lexer.lexInline;
2823
- const parser = opt.hooks ? opt.hooks.provideParser() : blockType ? _Parser.parse : _Parser.parseInline;
2824
-
2825
- if (opt.async) {
2826
- return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then(src => lexer(src, opt)).then(tokens => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then(tokens => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then(tokens => parser(tokens, opt)).then(html => opt.hooks ? opt.hooks.postprocess(html) : html).catch(throwError);
2827
- }
2828
-
2829
- try {
2830
- if (opt.hooks) {
2831
- src = opt.hooks.preprocess(src);
2832
- }
2833
-
2834
- let tokens = lexer(src, opt);
2835
-
2836
- if (opt.hooks) {
2837
- tokens = opt.hooks.processAllTokens(tokens);
2838
- }
2839
-
2840
- if (opt.walkTokens) {
2841
- this.walkTokens(tokens, opt.walkTokens);
2842
- }
2843
-
2844
- let html = parser(tokens, opt);
2845
-
2846
- if (opt.hooks) {
2847
- html = opt.hooks.postprocess(html);
2848
- }
2849
-
2850
- return html;
2851
- } catch (e) {
2852
- return throwError(e);
2853
- }
2854
- };
2855
-
2856
- return parse;
2857
- }
2858
-
2859
- onError(silent, async) {
2860
- return e => {
2861
- e.message += '\nPlease report this to https://github.com/markedjs/marked.';
2862
-
2863
- if (silent) {
2864
- const msg = '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';
2865
-
2866
- if (async) {
2867
- return Promise.resolve(msg);
2868
- }
2869
-
2870
- return msg;
2871
- }
2872
-
2873
- if (async) {
2874
- return Promise.reject(e);
2875
- }
2876
-
2877
- throw e;
2878
- };
2879
- }
2880
-
2881
- }
2882
-
2883
- const markedInstance = new Marked();
2884
-
2885
- function marked(src, opt) {
2886
- return markedInstance.parse(src, opt);
2887
- }
2888
- /**
2889
- * Sets the default options.
2890
- *
2891
- * @param options Hash of options
2892
- */
2893
-
2894
-
2895
- marked.options = marked.setOptions = function (options) {
2896
- markedInstance.setOptions(options);
2897
- marked.defaults = markedInstance.defaults;
2898
- changeDefaults(marked.defaults);
2899
- return marked;
2900
- };
2901
- /**
2902
- * Gets the original marked default options.
2903
- */
2904
-
2905
-
2906
- marked.getDefaults = _getDefaults;
2907
- marked.defaults = _defaults;
2908
- /**
2909
- * Use Extension
2910
- */
2911
-
2912
- marked.use = function (...args) {
2913
- markedInstance.use(...args);
2914
- marked.defaults = markedInstance.defaults;
2915
- changeDefaults(marked.defaults);
2916
- return marked;
2917
- };
2918
- /**
2919
- * Run callback for every token
2920
- */
2921
-
2922
-
2923
- marked.walkTokens = function (tokens, callback) {
2924
- return markedInstance.walkTokens(tokens, callback);
2925
- };
2926
- /**
2927
- * Compiles markdown to HTML without enclosing `p` tag.
2928
- *
2929
- * @param src String of markdown source to be compiled
2930
- * @param options Hash of options
2931
- * @return String of compiled HTML
2932
- */
2933
-
2934
-
2935
- marked.parseInline = markedInstance.parseInline;
2936
- /**
2937
- * Expose
2938
- */
2939
-
2940
- marked.Parser = _Parser;
2941
- marked.parser = _Parser.parse;
2942
- marked.Renderer = _Renderer;
2943
- marked.TextRenderer = _TextRenderer;
2944
- marked.Lexer = _Lexer;
2945
- marked.lexer = _Lexer.lex;
2946
- marked.Tokenizer = _Tokenizer;
2947
- marked.Hooks = _Hooks;
2948
- marked.parse = marked;
2949
- marked.options;
2950
- marked.setOptions;
2951
- marked.use;
2952
- marked.walkTokens;
2953
- marked.parseInline;
2954
- _Parser.parse;
2955
- _Lexer.lex;
7
+ import { marked } from 'marked';
2956
8
 
2957
9
  const timeout = 10000;
2958
10
  const changesDelay = 500;
2959
11
  const CompletionItemKindMap = Object.fromEntries(Object.entries(CompletionItemKind).map(([key, value]) => [value, key]));
2960
- const useLast = (values) => values.reduce((_, v) => v, "");
2961
- const client = Facet.define({ combine: useLast });
12
+ const useLast = (values) => values.reduce((_, v) => v, '');
13
+ const client = Facet.define({
14
+ combine: useLast,
15
+ });
2962
16
  const documentUri = Facet.define({ combine: useLast });
2963
17
  const languageId = Facet.define({ combine: useLast });
2964
18
  class LanguageServerClient {
@@ -2977,11 +31,11 @@ class LanguageServerClient {
2977
31
  if (webSocketTransport && webSocketTransport.connection) {
2978
32
  // XXX(hjr265): Need a better way to do this. Relevant issue:
2979
33
  // https://github.com/FurqanSoftware/codemirror-languageserver/issues/9
2980
- webSocketTransport.connection.addEventListener("message", (message) => {
34
+ webSocketTransport.connection.addEventListener('message', (message) => {
2981
35
  const data = JSON.parse(message.data);
2982
36
  if (data.method && data.id) {
2983
37
  webSocketTransport.connection.send(JSON.stringify({
2984
- jsonrpc: "2.0",
38
+ jsonrpc: '2.0',
2985
39
  id: data.id,
2986
40
  result: null,
2987
41
  }));
@@ -2991,12 +45,12 @@ class LanguageServerClient {
2991
45
  this.initializePromise = this.initialize();
2992
46
  }
2993
47
  async initialize() {
2994
- const { capabilities } = await this.request("initialize", {
48
+ const { capabilities } = await this.request('initialize', {
2995
49
  capabilities: {
2996
50
  textDocument: {
2997
51
  hover: {
2998
52
  dynamicRegistration: true,
2999
- contentFormat: ["plaintext", "markdown"],
53
+ contentFormat: ['plaintext', 'markdown'],
3000
54
  },
3001
55
  moniker: {},
3002
56
  synchronization: {
@@ -3010,7 +64,7 @@ class LanguageServerClient {
3010
64
  completionItem: {
3011
65
  snippetSupport: false,
3012
66
  commitCharactersSupport: true,
3013
- documentationFormat: ["plaintext", "markdown"],
67
+ documentationFormat: ['plaintext', 'markdown'],
3014
68
  deprecatedSupport: false,
3015
69
  preselectSupport: false,
3016
70
  },
@@ -3019,7 +73,7 @@ class LanguageServerClient {
3019
73
  signatureHelp: {
3020
74
  dynamicRegistration: true,
3021
75
  signatureInformation: {
3022
- documentationFormat: ["plaintext", "markdown"],
76
+ documentationFormat: ['plaintext', 'markdown'],
3023
77
  },
3024
78
  },
3025
79
  declaration: {
@@ -3051,23 +105,23 @@ class LanguageServerClient {
3051
105
  workspaceFolders: this.workspaceFolders,
3052
106
  }, timeout * 3);
3053
107
  this.capabilities = capabilities;
3054
- this.notify("initialized", {});
108
+ this.notify('initialized', {});
3055
109
  this.ready = true;
3056
110
  }
3057
111
  close() {
3058
112
  this.client.close();
3059
113
  }
3060
114
  textDocumentDidOpen(params) {
3061
- return this.notify("textDocument/didOpen", params);
115
+ return this.notify('textDocument/didOpen', params);
3062
116
  }
3063
117
  textDocumentDidChange(params) {
3064
- return this.notify("textDocument/didChange", params);
118
+ return this.notify('textDocument/didChange', params);
3065
119
  }
3066
120
  async textDocumentHover(params) {
3067
- return await this.request("textDocument/hover", params, timeout);
121
+ return await this.request('textDocument/hover', params, timeout);
3068
122
  }
3069
123
  async textDocumentCompletion(params) {
3070
- return await this.request("textDocument/completion", params, timeout);
124
+ return await this.request('textDocument/completion', params, timeout);
3071
125
  }
3072
126
  attachPlugin(plugin) {
3073
127
  this.plugins.push(plugin);
@@ -3179,13 +233,13 @@ class LanguageServerPlugin {
3179
233
  if (pos === null) {
3180
234
  return null;
3181
235
  }
3182
- const dom = document.createElement("div");
3183
- dom.classList.add("documentation");
236
+ const dom = document.createElement('div');
237
+ dom.classList.add('documentation');
3184
238
  if (this.allowHTMLContent) {
3185
- dom.innerHTML = formatContents(contents);
239
+ dom.innerHTML = await formatContents(contents);
3186
240
  }
3187
241
  else {
3188
- dom.textContent = formatContents(contents);
242
+ dom.textContent = await formatContents(contents);
3189
243
  }
3190
244
  return {
3191
245
  pos,
@@ -3195,7 +249,8 @@ class LanguageServerPlugin {
3195
249
  };
3196
250
  }
3197
251
  async requestCompletion(context, { line, character }, { triggerKind, triggerCharacter, }) {
3198
- if (!this.client.ready || !this.client.capabilities.completionProvider) {
252
+ if (!this.client.ready ||
253
+ !this.client.capabilities.completionProvider) {
3199
254
  return null;
3200
255
  }
3201
256
  this.sendChange({
@@ -3212,7 +267,7 @@ class LanguageServerPlugin {
3212
267
  if (!result) {
3213
268
  return null;
3214
269
  }
3215
- let items = "items" in result ? result.items : result;
270
+ let items = 'items' in result ? result.items : result;
3216
271
  const [span, match] = prefixMatch(items);
3217
272
  const token = context.matchBefore(match);
3218
273
  let { pos } = context;
@@ -3257,10 +312,12 @@ class LanguageServerPlugin {
3257
312
  }
3258
313
  additionalTextEdits
3259
314
  .sort(({ range: { end: a } }, { range: { end: b } }) => {
3260
- if (posToOffset(view.state.doc, a) < posToOffset(view.state.doc, b)) {
315
+ if (posToOffset(view.state.doc, a) <
316
+ posToOffset(view.state.doc, b)) {
3261
317
  return 1;
3262
318
  }
3263
- else if (posToOffset(view.state.doc, a) > posToOffset(view.state.doc, b)) {
319
+ else if (posToOffset(view.state.doc, a) >
320
+ posToOffset(view.state.doc, b)) {
3264
321
  return -1;
3265
322
  }
3266
323
  return 0;
@@ -3278,7 +335,18 @@ class LanguageServerPlugin {
3278
335
  type: kind && CompletionItemKindMap[kind].toLowerCase(),
3279
336
  };
3280
337
  if (documentation) {
3281
- completion.info = formatContents(documentation);
338
+ completion.info = async () => {
339
+ const dom = document.createElement('div');
340
+ dom.classList.add('documentation');
341
+ if (this.allowHTMLContent) {
342
+ dom.innerHTML = await formatContents(documentation);
343
+ }
344
+ else {
345
+ dom.textContent =
346
+ await formatContents(documentation);
347
+ }
348
+ return dom;
349
+ };
3282
350
  }
3283
351
  return completion;
3284
352
  });
@@ -3291,7 +359,7 @@ class LanguageServerPlugin {
3291
359
  processNotification(notification) {
3292
360
  try {
3293
361
  switch (notification.method) {
3294
- case "textDocument/publishDiagnostics":
362
+ case 'textDocument/publishDiagnostics':
3295
363
  this.processDiagnostics(notification.params);
3296
364
  }
3297
365
  }
@@ -3308,14 +376,17 @@ class LanguageServerPlugin {
3308
376
  from: posToOffset(this.view.state.doc, range.start),
3309
377
  to: posToOffset(this.view.state.doc, range.end),
3310
378
  severity: {
3311
- [DiagnosticSeverity.Error]: "error",
3312
- [DiagnosticSeverity.Warning]: "warning",
3313
- [DiagnosticSeverity.Information]: "info",
3314
- [DiagnosticSeverity.Hint]: "info",
379
+ [DiagnosticSeverity.Error]: 'error',
380
+ [DiagnosticSeverity.Warning]: 'warning',
381
+ [DiagnosticSeverity.Information]: 'info',
382
+ [DiagnosticSeverity.Hint]: 'info',
3315
383
  }[severity],
3316
384
  message,
3317
385
  }))
3318
- .filter(({ from, to }) => from !== null && to !== null && from !== undefined && to !== undefined)
386
+ .filter(({ from, to }) => from !== null &&
387
+ to !== null &&
388
+ from !== undefined &&
389
+ to !== undefined)
3319
390
  .sort((a, b) => {
3320
391
  switch (true) {
3321
392
  case a.from < b.from:
@@ -3339,7 +410,8 @@ function languageServer(options) {
3339
410
  function languageServerWithTransport(options) {
3340
411
  let plugin = null;
3341
412
  return [
3342
- client.of(options.client || new LanguageServerClient({ ...options, autoClose: true })),
413
+ client.of(options.client ||
414
+ new LanguageServerClient({ ...options, autoClose: true })),
3343
415
  documentUri.of(options.documentUri),
3344
416
  languageId.of(options.languageId),
3345
417
  ViewPlugin.define((view) => (plugin = new LanguageServerPlugin(view, options.allowHTMLContent))),
@@ -3393,30 +465,30 @@ function offsetToPos(doc, offset) {
3393
465
  line: line.number - 1,
3394
466
  };
3395
467
  }
3396
- function formatContents(contents) {
468
+ async function formatContents(contents) {
3397
469
  if (isLSPMarkupContent(contents)) {
3398
470
  let value = contents.value;
3399
- if (contents.kind === "markdown") {
3400
- value = marked.parse(value);
471
+ if (contents.kind === 'markdown') {
472
+ value = await marked.parse(value);
3401
473
  }
3402
474
  return value;
3403
475
  }
3404
476
  else if (Array.isArray(contents)) {
3405
- return contents.map((c) => formatContents(c) + "\n\n").join("");
477
+ return contents.map((c) => formatContents(c) + '\n\n').join('');
3406
478
  }
3407
- else if (typeof contents === "string") {
479
+ else if (typeof contents === 'string') {
3408
480
  return contents;
3409
481
  }
3410
482
  }
3411
483
  function toSet(chars) {
3412
- let preamble = "";
3413
- let flat = Array.from(chars).join("");
484
+ let preamble = '';
485
+ let flat = Array.from(chars).join('');
3414
486
  const words = /\w/.test(flat);
3415
487
  if (words) {
3416
- preamble += "\\w";
3417
- flat = flat.replace(/\w/g, "");
488
+ preamble += '\\w';
489
+ flat = flat.replace(/\w/g, '');
3418
490
  }
3419
- return `[${preamble}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
491
+ return `[${preamble}${flat.replace(/[^\w\s]/g, '\\$&')}]`;
3420
492
  }
3421
493
  function prefixMatch(items) {
3422
494
  var _a;
@@ -3429,8 +501,8 @@ function prefixMatch(items) {
3429
501
  rest.add(char);
3430
502
  }
3431
503
  }
3432
- const source = toSet(first) + toSet(rest) + "*$";
3433
- return [new RegExp("^" + source), new RegExp(source)];
504
+ const source = toSet(first) + toSet(rest) + '*$';
505
+ return [new RegExp('^' + source), new RegExp(source)];
3434
506
  }
3435
507
  function isLSPTextEdit(textEdit) {
3436
508
  return (textEdit === null || textEdit === void 0 ? void 0 : textEdit.range) !== undefined;