chrome-devtools-frontend 1.0.1636056 → 1.0.1640418

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