@manamerge/mana-atomic-ui 0.0.47 → 0.0.49

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