@khanacademy/simple-markdown 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1450 @@
1
+ import { addLibraryVersionToPerseusDebug } from '@khanacademy/perseus-utils';
2
+
3
+ // This file is processed by a Rollup plugin (replace) to inject the production
4
+ // version number during the release build.
5
+ // In dev, you'll never see the version number.
6
+
7
+ const libName = "@khanacademy/simple-markdown";
8
+ const libVersion = "2.0.0";
9
+ addLibraryVersionToPerseusDebug(libName, libVersion);
10
+
11
+ /* eslint-disable prefer-spread, no-regex-spaces, guard-for-in, no-console, no-var */
12
+ /**
13
+ * Simple-Markdown
14
+ * ===============
15
+ *
16
+ * Simple-Markdown's primary goal is to be easy to adapt. It aims
17
+ * to be compliant with John Gruber's [Markdown Syntax page][1],
18
+ * but compatiblity with other markdown implementations' edge-cases
19
+ * will be sacrificed where it conflicts with simplicity or
20
+ * extensibility.
21
+ *
22
+ * If your goal is to simply embed a standard markdown implementation
23
+ * in your website, simple-markdown is probably not the best library
24
+ * for you (although it should work). But if you have struggled to
25
+ * customize an existing library to meet your needs, simple-markdown
26
+ * might be able to help.
27
+ *
28
+ * Many of the regexes and original logic has been adapted from
29
+ * the wonderful [marked.js](https://github.com/chjj/marked)
30
+ */
31
+
32
+
33
+ // Type Definitions:
34
+
35
+ // We want to clarify our defaultRules types a little bit more so clients can
36
+ // reuse defaultRules built-ins. So we make some stronger guarantess when
37
+ // we can:
38
+
39
+ // End TypeScript Definitions
40
+
41
+ var CR_NEWLINE_R = /\r\n?/g;
42
+ var TAB_R = /\t/g;
43
+ var FORMFEED_R = /\f/g;
44
+
45
+ /**
46
+ * Turn various whitespace into easy-to-process whitespace
47
+ */
48
+ var preprocess = function preprocess(source) {
49
+ return source.replace(CR_NEWLINE_R, "\n").replace(FORMFEED_R, "").replace(TAB_R, " ");
50
+ };
51
+ var populateInitialState = function populateInitialState(givenState, defaultState) {
52
+ var state = givenState || {};
53
+ if (defaultState != null) {
54
+ for (var prop in defaultState) {
55
+ if (Object.prototype.hasOwnProperty.call(defaultState, prop)) {
56
+ state[prop] = defaultState[prop];
57
+ }
58
+ }
59
+ }
60
+ return state;
61
+ };
62
+
63
+ /**
64
+ * Creates a parser for a given set of rules, with the precedence
65
+ * specified as a list of rules.
66
+ *
67
+ * @param {SimpleMarkdown.ParserRules} rules
68
+ * an object containing
69
+ * rule type -> {match, order, parse} objects
70
+ * (lower order is higher precedence)
71
+ * @param {SimpleMarkdown.OptionalState} [defaultState]
72
+ *
73
+ * @returns {SimpleMarkdown.Parser}
74
+ * The resulting parse function, with the following parameters:
75
+ * @source: the input source string to be parsed
76
+ * @state: an optional object to be threaded through parse
77
+ * calls. Allows clients to add stateful operations to
78
+ * parsing, such as keeping track of how many levels deep
79
+ * some nesting is. For an example use-case, see passage-ref
80
+ * parsing in src/widgets/passage/passage-markdown.jsx
81
+ */
82
+ var parserFor = function parserFor(rules, defaultState) {
83
+ // Sorts rules in order of increasing order, then
84
+ // ascending rule name in case of ties.
85
+ var ruleList = Object.keys(rules).filter(function (type) {
86
+ var rule = rules[type];
87
+ if (rule == null || rule.match == null) {
88
+ return false;
89
+ }
90
+ var order = rule.order;
91
+ if ((typeof order !== "number" || !isFinite(order)) && typeof console !== "undefined") {
92
+ console.warn("simple-markdown: Invalid order for rule `" + type + "`: " + String(order));
93
+ }
94
+ return true;
95
+ });
96
+ ruleList.sort(function (typeA, typeB) {
97
+ var ruleA = rules[typeA];
98
+ var ruleB = rules[typeB];
99
+ var orderA = ruleA.order;
100
+ var orderB = ruleB.order;
101
+
102
+ // First sort based on increasing order
103
+ if (orderA !== orderB) {
104
+ return orderA - orderB;
105
+ }
106
+ var secondaryOrderA = ruleA.quality ? 0 : 1;
107
+ var secondaryOrderB = ruleB.quality ? 0 : 1;
108
+ if (secondaryOrderA !== secondaryOrderB) {
109
+ return secondaryOrderA - secondaryOrderB;
110
+
111
+ // Then based on increasing unicode lexicographic ordering
112
+ } else if (typeA < typeB) {
113
+ return -1;
114
+ } else if (typeA > typeB) {
115
+ return 1;
116
+ } else {
117
+ // Rules should never have the same name,
118
+ // but this is provided for completeness.
119
+ return 0;
120
+ }
121
+ });
122
+ var latestState;
123
+ var nestedParse = function nestedParse(source, state) {
124
+ var result = [];
125
+ state = state || latestState;
126
+ latestState = state;
127
+ while (source) {
128
+ // store the best match, it's rule, and quality:
129
+ var ruleType = null;
130
+ var rule = null;
131
+ var capture = null;
132
+ var quality = NaN;
133
+
134
+ // loop control variables:
135
+ var i = 0;
136
+ var currRuleType = ruleList[0];
137
+ var currRule = rules[currRuleType];
138
+ do {
139
+ var currOrder = currRule.order;
140
+ var prevCaptureStr = state.prevCapture == null ? "" : state.prevCapture[0];
141
+ var currCapture = currRule.match(source, state, prevCaptureStr);
142
+ if (currCapture) {
143
+ var currQuality = currRule.quality ? currRule.quality(currCapture, state, prevCaptureStr) : 0;
144
+ // This should always be true the first time because
145
+ // the initial quality is NaN (that's why there's the
146
+ // condition negation).
147
+ if (!(currQuality <= quality)) {
148
+ // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
149
+ ruleType = currRuleType;
150
+ // @ts-expect-error - TS2322 - Type 'ParserRule' is not assignable to type 'null'.
151
+ rule = currRule;
152
+ // @ts-expect-error - TS2322 - Type 'Capture' is not assignable to type 'null'.
153
+ capture = currCapture;
154
+ quality = currQuality;
155
+ }
156
+ }
157
+
158
+ // Move on to the next item.
159
+ // Note that this makes `currRule` be the next item
160
+ i++;
161
+ currRuleType = ruleList[i];
162
+ currRule = rules[currRuleType];
163
+ } while (
164
+ // keep looping while we're still within the ruleList
165
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
166
+ currRule && (
167
+ // if we don't have a match yet, continue
168
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
169
+ !capture ||
170
+ // or if we have a match, but the next rule is
171
+ // at the same order, and has a quality measurement
172
+ // functions, then this rule must have a quality
173
+ // measurement function (since they are sorted before
174
+ // those without), and we need to check if there is
175
+ // a better quality match
176
+ currRule.order === currOrder && currRule.quality));
177
+
178
+ // TODO(aria): Write tests for these
179
+ if (rule == null || capture == null) {
180
+ throw new Error("Could not find a matching rule for the below " + "content. The rule with highest `order` should " + "always match content provided to it. Check " + "the definition of `match` for '" + ruleList[ruleList.length - 1] + "'. It seems to not match the following source:\n" + source);
181
+ }
182
+ // @ts-expect-error - TS2339 - Property 'index' does not exist on type 'never'.
183
+ if (capture.index) {
184
+ // If present and non-zero, i.e. a non-^ regexp result:
185
+ throw new Error("`match` must return a capture starting at index 0 " + "(the current parse index). Did you forget a ^ at the " + "start of the RegExp?");
186
+ }
187
+
188
+ // @ts-expect-error - TS2339 - Property 'parse' does not exist on type 'never'.
189
+ var parsed = rule.parse(capture, nestedParse, state);
190
+ // We maintain the same object here so that rules can
191
+ // store references to the objects they return and
192
+ // modify them later. (oops sorry! but this adds a lot
193
+ // of power--see reflinks.)
194
+ if (Array.isArray(parsed)) {
195
+ Array.prototype.push.apply(result, parsed);
196
+ } else {
197
+ if (parsed == null || typeof parsed !== "object") {
198
+ throw new Error(`parse() function returned invalid parse result: '${parsed}'`);
199
+ }
200
+
201
+ // We also let rules override the default type of
202
+ // their parsed node if they would like to, so that
203
+ // there can be a single output function for all links,
204
+ // even if there are several rules to parse them.
205
+ if (parsed.type == null) {
206
+ parsed.type = ruleType;
207
+ }
208
+ result.push(parsed);
209
+ }
210
+ state.prevCapture = capture;
211
+ source = source.substring(state.prevCapture[0].length);
212
+ }
213
+ return result;
214
+ };
215
+ var outerParse = function outerParse(source, state) {
216
+ latestState = populateInitialState(state, defaultState);
217
+ if (!latestState.inline && !latestState.disableAutoBlockNewlines) {
218
+ source = source + "\n\n";
219
+ }
220
+ // We store the previous capture so that match functions can
221
+ // use some limited amount of lookbehind. Lists use this to
222
+ // ensure they don't match arbitrary '- ' or '* ' in inline
223
+ // text (see the list rule for more information). This stores
224
+ // the full regex capture object, if there is one.
225
+ latestState.prevCapture = null;
226
+ return nestedParse(preprocess(source), latestState);
227
+ };
228
+ return outerParse;
229
+ };
230
+
231
+ // Creates a match function for an inline scoped element from a regex
232
+ var inlineRegex = function inlineRegex(regex) {
233
+ var match = function match(source, state, prevCapture) {
234
+ if (state.inline) {
235
+ return regex.exec(source);
236
+ } else {
237
+ return null;
238
+ }
239
+ };
240
+ // @ts-expect-error - TS2339 - Property 'regex' does not exist on type '(source: string, state: State, prevCapture: string) => Capture | null | undefined'.
241
+ match.regex = regex;
242
+ return match;
243
+ };
244
+
245
+ // Creates a match function for a block scoped element from a regex
246
+ var blockRegex = function blockRegex(regex) {
247
+ var match = function match(source, state) {
248
+ if (state.inline) {
249
+ return null;
250
+ } else {
251
+ return regex.exec(source);
252
+ }
253
+ };
254
+ match.regex = regex;
255
+ return match;
256
+ };
257
+
258
+ // Creates a match function from a regex, ignoring block/inline scope
259
+ var anyScopeRegex = function anyScopeRegex(regex) {
260
+ var match = function match(source, state) {
261
+ return regex.exec(source);
262
+ };
263
+ match.regex = regex;
264
+ return match;
265
+ };
266
+ var TYPE_SYMBOL = typeof Symbol === "function" &&
267
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
268
+ Symbol.for &&
269
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
270
+ Symbol.for("react.element") || 0xeac7;
271
+ var reactElement = function reactElement(type, key, props) {
272
+ var element = {
273
+ $$typeof: TYPE_SYMBOL,
274
+ type: type,
275
+ key: key == null ? undefined : key,
276
+ ref: null,
277
+ props: props,
278
+ _owner: null
279
+ };
280
+ return element;
281
+ };
282
+
283
+ /** Returns a closed HTML tag.
284
+ * @param {string} tagName - Name of HTML tag (eg. "em" or "a")
285
+ * @param {string} content - Inner content of tag
286
+ * @param {{ [attr: string]: SimpleMarkdown.Attr }} [attributes] - Optional extra attributes of tag as an object of key-value pairs
287
+ * eg. { "href": "http://google.com" }. Falsey attributes are filtered out.
288
+ * @param {boolean} [isClosed] - boolean that controls whether tag is closed or not (eg. img tags).
289
+ * defaults to true
290
+ */
291
+ var htmlTag = function htmlTag(tagName, content, attributes, isClosed) {
292
+ attributes = attributes || {};
293
+ isClosed = typeof isClosed !== "undefined" ? isClosed : true;
294
+ var attributeString = "";
295
+ for (var attr in attributes) {
296
+ var attribute = attributes[attr];
297
+ // Removes falsey attributes
298
+ if (Object.prototype.hasOwnProperty.call(attributes, attr) &&
299
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
300
+ attribute) {
301
+ attributeString += " " + sanitizeText(attr) + '="' + sanitizeText(attribute) + '"';
302
+ }
303
+ }
304
+ var unclosedTag = "<" + tagName + attributeString + ">";
305
+ if (isClosed) {
306
+ return unclosedTag + content + "</" + tagName + ">";
307
+ } else {
308
+ return unclosedTag;
309
+ }
310
+ };
311
+ var EMPTY_PROPS = {};
312
+
313
+ /**
314
+ * @param {string | null | undefined} url - url to sanitize
315
+ * @returns {string | null} - url if safe, or null if a safe url could not be made
316
+ */
317
+ var sanitizeUrl = function sanitizeUrl(url) {
318
+ if (url == null) {
319
+ return null;
320
+ }
321
+ try {
322
+ var prot = new URL(url, "https://localhost").protocol;
323
+ if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) {
324
+ return null;
325
+ }
326
+ } catch (_unused) {
327
+ // invalid URLs should throw a TypeError
328
+ // see for instance: `new URL("");`
329
+ return null;
330
+ }
331
+ return url;
332
+ };
333
+ var SANITIZE_TEXT_R = /[<>&"']/g;
334
+ var SANITIZE_TEXT_CODES = {
335
+ "<": "&lt;",
336
+ ">": "&gt;",
337
+ "&": "&amp;",
338
+ '"': "&quot;",
339
+ "'": "&#x27;",
340
+ "/": "&#x2F;",
341
+ "`": "&#96;"
342
+ };
343
+ var sanitizeText = function sanitizeText(text) {
344
+ return String(text).replace(SANITIZE_TEXT_R, function (chr) {
345
+ return SANITIZE_TEXT_CODES[chr];
346
+ });
347
+ };
348
+ var UNESCAPE_URL_R = /\\([^0-9A-Za-z\s])/g;
349
+ var unescapeUrl = function unescapeUrl(rawUrlString) {
350
+ return rawUrlString.replace(UNESCAPE_URL_R, "$1");
351
+ };
352
+
353
+ /**
354
+ * Parse some content with the parser `parse`, with state.inline
355
+ * set to true. Useful for block elements; not generally necessary
356
+ * to be used by inline elements (where state.inline is already true.
357
+ */
358
+ var parseInline = function parseInline(parse, content, state) {
359
+ var isCurrentlyInline = state.inline || false;
360
+ state.inline = true;
361
+ var result = parse(content, state);
362
+ state.inline = isCurrentlyInline;
363
+ return result;
364
+ };
365
+ var parseBlock = function parseBlock(parse, content, state) {
366
+ var isCurrentlyInline = state.inline || false;
367
+ state.inline = false;
368
+ var result = parse(content + "\n\n", state);
369
+ state.inline = isCurrentlyInline;
370
+ return result;
371
+ };
372
+ var parseCaptureInline = function parseCaptureInline(capture, parse, state) {
373
+ return {
374
+ content: parseInline(parse, capture[1], state)
375
+ };
376
+ };
377
+ var ignoreCapture = function ignoreCapture() {
378
+ return {};
379
+ };
380
+
381
+ // recognize a `*` `-`, `+`, `1.`, `2.`... list bullet
382
+ var LIST_BULLET = "(?:[*+-]|\\d+\\.)";
383
+ // recognize the start of a list item:
384
+ // leading space plus a bullet plus a space (` * `)
385
+ var LIST_ITEM_PREFIX = "( *)(" + LIST_BULLET + ") +";
386
+ var LIST_ITEM_PREFIX_R = new RegExp("^" + LIST_ITEM_PREFIX);
387
+ // recognize an individual list item:
388
+ // * hi
389
+ // this is part of the same item
390
+ //
391
+ // as is this, which is a new paragraph in the same item
392
+ //
393
+ // * but this is not part of the same item
394
+ var LIST_ITEM_R = new RegExp(LIST_ITEM_PREFIX + "[^\\n]*(?:\\n" + "(?!\\1" + LIST_BULLET + " )[^\\n]*)*(\n|$)", "gm");
395
+ var BLOCK_END_R = /\n{2,}$/;
396
+ var INLINE_CODE_ESCAPE_BACKTICKS_R = /^ (?= *`)|(` *) $/g;
397
+ // recognize the end of a paragraph block inside a list item:
398
+ // two or more newlines at end end of the item
399
+ var LIST_BLOCK_END_R = BLOCK_END_R;
400
+ var LIST_ITEM_END_R = / *\n+$/;
401
+ // check whether a list item has paragraphs: if it does,
402
+ // we leave the newlines at the end
403
+ var LIST_R = new RegExp("^( *)(" + LIST_BULLET + ") " + "[\\s\\S]+?(?:\n{2,}(?! )" + "(?!\\1" + LIST_BULLET + " )\\n*" +
404
+ // the \\s*$ here is so that we can parse the inside of nested
405
+ // lists, where our content might end before we receive two `\n`s
406
+ "|\\s*\n*$)");
407
+ var LIST_LOOKBEHIND_R = /(?:^|\n)( *)$/;
408
+ var TABLES = function () {
409
+ // predefine regexes so we don't have to create them inside functions
410
+ // sure, regex literals should be fast, even inside functions, but they
411
+ // aren't in all browsers.
412
+ var TABLE_ROW_SEPARATOR_TRIM = /^ *\| *| *\| *$/g;
413
+ var TABLE_CELL_END_TRIM = / *$/;
414
+ var TABLE_RIGHT_ALIGN = /^ *-+: *$/;
415
+ var TABLE_CENTER_ALIGN = /^ *:-+: *$/;
416
+ var TABLE_LEFT_ALIGN = /^ *:-+ *$/;
417
+
418
+ // TODO: This needs a real type
419
+
420
+ var parseTableAlignCapture = function parseTableAlignCapture(alignCapture) {
421
+ if (TABLE_RIGHT_ALIGN.test(alignCapture)) {
422
+ return "right";
423
+ } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {
424
+ return "center";
425
+ } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {
426
+ return "left";
427
+ } else {
428
+ return null;
429
+ }
430
+ };
431
+ var parseTableAlign = function parseTableAlign(source, parse, state, trimEndSeparators) {
432
+ if (trimEndSeparators) {
433
+ source = source.replace(TABLE_ROW_SEPARATOR_TRIM, "");
434
+ }
435
+ var alignText = source.trim().split("|");
436
+ return alignText.map(parseTableAlignCapture);
437
+ };
438
+ var parseTableRow = function parseTableRow(source, parse, state, trimEndSeparators) {
439
+ var prevInTable = state.inTable;
440
+ state.inTable = true;
441
+ var tableRow = parse(source.trim(), state);
442
+ state.inTable = prevInTable;
443
+ var cells = [[]];
444
+ tableRow.forEach(function (node, i) {
445
+ if (node.type === "tableSeparator") {
446
+ // Filter out empty table separators at the start/end:
447
+ if (!trimEndSeparators || i !== 0 && i !== tableRow.length - 1) {
448
+ // Split the current row:
449
+ cells.push([]);
450
+ }
451
+ } else {
452
+ if (node.type === "text" && (tableRow[i + 1] == null || tableRow[i + 1].type === "tableSeparator")) {
453
+ node.content = node.content.replace(TABLE_CELL_END_TRIM, "");
454
+ }
455
+ // @ts-expect-error - TS2345 - Argument of type 'SingleASTNode' is not assignable to parameter of type 'never'.
456
+ cells[cells.length - 1].push(node);
457
+ }
458
+ });
459
+ return cells;
460
+ };
461
+
462
+ /**
463
+ * @param {string} source
464
+ * @param {SimpleMarkdown.Parser} parse
465
+ * @param {SimpleMarkdown.State} state
466
+ * @param {boolean} trimEndSeparators
467
+ * @returns {SimpleMarkdown.ASTNode[][]}
468
+ */
469
+ var parseTableCells = function parseTableCells(source, parse, state, trimEndSeparators) {
470
+ var rowsText = source.trim().split("\n");
471
+ return rowsText.map(function (rowText) {
472
+ return parseTableRow(rowText, parse, state, trimEndSeparators);
473
+ });
474
+ };
475
+
476
+ /**
477
+ * @param {boolean} trimEndSeparators
478
+ * @returns {SimpleMarkdown.SingleNodeParseFunction}
479
+ */
480
+ var parseTable = function parseTable(trimEndSeparators) {
481
+ return function (capture, parse, state) {
482
+ state.inline = true;
483
+ var header = parseTableRow(capture[1], parse, state, trimEndSeparators);
484
+ var align = parseTableAlign(capture[2], parse, state, trimEndSeparators);
485
+ var cells = parseTableCells(capture[3], parse, state, trimEndSeparators);
486
+ state.inline = false;
487
+ return {
488
+ type: "table",
489
+ header: header,
490
+ align: align,
491
+ cells: cells
492
+ };
493
+ };
494
+ };
495
+ return {
496
+ parseTable: parseTable(true),
497
+ parseNpTable: parseTable(false),
498
+ TABLE_REGEX: /^ *(\|.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/,
499
+ NPTABLE_REGEX: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/
500
+ };
501
+ }();
502
+ var LINK_INSIDE = "(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*";
503
+ var LINK_HREF_AND_TITLE = "\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*";
504
+ var AUTOLINK_MAILTO_CHECK_R = /mailto:/i;
505
+ var parseRef = function parseRef(capture, state, refNode) {
506
+ var ref = (capture[2] || capture[1]).replace(/\s+/g, " ").toLowerCase();
507
+
508
+ // We store information about previously seen defs on
509
+ // state._defs (_ to deconflict with client-defined
510
+ // state). If the def for this reflink/refimage has
511
+ // already been seen, we can use its target/source
512
+ // and title here:
513
+ if (state._defs && state._defs[ref]) {
514
+ var def = state._defs[ref];
515
+ // `refNode` can be a link or an image. Both use
516
+ // target and title properties.
517
+ refNode.target = def.target;
518
+ refNode.title = def.title;
519
+ }
520
+
521
+ // In case we haven't seen our def yet (or if someone
522
+ // overwrites that def later on), we add this node
523
+ // to the list of ref nodes for that def. Then, when
524
+ // we find the def, we can modify this link/image AST
525
+ // node :).
526
+ // I'm sorry.
527
+ state._refs = state._refs || {};
528
+ state._refs[ref] = state._refs[ref] || [];
529
+ state._refs[ref].push(refNode);
530
+ return refNode;
531
+ };
532
+ var currOrder = 0;
533
+ var defaultRules = {
534
+ Array: {
535
+ react: function (arr, output, state) {
536
+ var oldKey = state.key;
537
+ var result = [];
538
+
539
+ // map output over the ast, except group any text
540
+ // nodes together into a single string output.
541
+ for (var i = 0, key = 0; i < arr.length; i++, key++) {
542
+ // `key` is our numerical `state.key`, which we increment for
543
+ // every output node, but don't change for joined text nodes.
544
+ // (i, however, must change for joined text nodes)
545
+ state.key = "" + i;
546
+ var node = arr[i];
547
+ if (node.type === "text") {
548
+ node = {
549
+ type: "text",
550
+ content: node.content
551
+ };
552
+ for (; i + 1 < arr.length && arr[i + 1].type === "text"; i++) {
553
+ node.content += arr[i + 1].content;
554
+ }
555
+ }
556
+ result.push(output(node, state));
557
+ }
558
+ state.key = oldKey;
559
+ return result;
560
+ },
561
+ html: function (arr, output, state) {
562
+ var result = "";
563
+
564
+ // map output over the ast, except group any text
565
+ // nodes together into a single string output.
566
+ for (var i = 0; i < arr.length; i++) {
567
+ var node = arr[i];
568
+ if (node.type === "text") {
569
+ node = {
570
+ type: "text",
571
+ content: node.content
572
+ };
573
+ for (; i + 1 < arr.length && arr[i + 1].type === "text"; i++) {
574
+ node.content += arr[i + 1].content;
575
+ }
576
+ }
577
+ result += output(node, state);
578
+ }
579
+ return result;
580
+ }
581
+ },
582
+ heading: {
583
+ order: currOrder++,
584
+ match: blockRegex(/^ *(#{1,6})([^\n]+?)#* *(?:\n *)+\n/),
585
+ parse: function (capture, parse, state) {
586
+ return {
587
+ level: capture[1].length,
588
+ content: parseInline(parse, capture[2].trim(), state)
589
+ };
590
+ },
591
+ react: function (node, output, state) {
592
+ return reactElement("h" + node.level, state.key, {
593
+ children: output(node.content, state)
594
+ });
595
+ },
596
+ html: function (node, output, state) {
597
+ return htmlTag("h" + node.level, output(node.content, state));
598
+ }
599
+ },
600
+ nptable: {
601
+ order: currOrder++,
602
+ match: blockRegex(TABLES.NPTABLE_REGEX),
603
+ parse: TABLES.parseNpTable,
604
+ react: null,
605
+ html: null
606
+ },
607
+ lheading: {
608
+ order: currOrder++,
609
+ match: blockRegex(/^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/),
610
+ parse: function (capture, parse, state) {
611
+ return {
612
+ type: "heading",
613
+ level: capture[2] === "=" ? 1 : 2,
614
+ content: parseInline(parse, capture[1], state)
615
+ };
616
+ },
617
+ react: null,
618
+ html: null
619
+ },
620
+ hr: {
621
+ order: currOrder++,
622
+ match: blockRegex(/^( *[-*_]){3,} *(?:\n *)+\n/),
623
+ parse: ignoreCapture,
624
+ react: function (node, output, state) {
625
+ return reactElement("hr", state.key, {
626
+ "aria-hidden": true
627
+ });
628
+ },
629
+ html: function (node, output, state) {
630
+ return '<hr aria-hidden="true">';
631
+ }
632
+ },
633
+ codeBlock: {
634
+ order: currOrder++,
635
+ match: blockRegex(/^(?: [^\n]+\n*)+(?:\n *)+\n/),
636
+ parse: function (capture, parse, state) {
637
+ var content = capture[0].replace(/^ /gm, "").replace(/\n+$/, "");
638
+ return {
639
+ lang: undefined,
640
+ content: content
641
+ };
642
+ },
643
+ react: function (node, output, state) {
644
+ var className = node.lang ? "markdown-code-" + node.lang : undefined;
645
+ return reactElement("pre", state.key, {
646
+ children: reactElement("code", null, {
647
+ className: className,
648
+ children: node.content
649
+ })
650
+ });
651
+ },
652
+ html: function (node, output, state) {
653
+ var className = node.lang ? "markdown-code-" + node.lang : undefined;
654
+ var codeBlock = htmlTag("code", sanitizeText(node.content), {
655
+ class: className
656
+ });
657
+ return htmlTag("pre", codeBlock);
658
+ }
659
+ },
660
+ fence: {
661
+ order: currOrder++,
662
+ match: blockRegex(/^ *(`{3,}|~{3,}) *(?:(\S+) *)?\n([\s\S]+?)\n?\1 *(?:\n *)+\n/),
663
+ parse: function (capture, parse, state) {
664
+ return {
665
+ type: "codeBlock",
666
+ lang: capture[2] || undefined,
667
+ content: capture[3]
668
+ };
669
+ },
670
+ react: null,
671
+ html: null
672
+ },
673
+ blockQuote: {
674
+ order: currOrder++,
675
+ match: blockRegex(/^( *>[^\n]+(\n[^\n]+)*\n*)+\n{2,}/),
676
+ parse: function (capture, parse, state) {
677
+ var content = capture[0].replace(/^ *> ?/gm, "");
678
+ return {
679
+ content: parse(content, state)
680
+ };
681
+ },
682
+ react: function (node, output, state) {
683
+ return reactElement("blockquote", state.key, {
684
+ children: output(node.content, state)
685
+ });
686
+ },
687
+ html: function (node, output, state) {
688
+ return htmlTag("blockquote", output(node.content, state));
689
+ }
690
+ },
691
+ list: {
692
+ order: currOrder++,
693
+ match: function (source, state) {
694
+ // We only want to break into a list if we are at the start of a
695
+ // line. This is to avoid parsing "hi * there" with "* there"
696
+ // becoming a part of a list.
697
+ // You might wonder, "but that's inline, so of course it wouldn't
698
+ // start a list?". You would be correct! Except that some of our
699
+ // lists can be inline, because they might be inside another list,
700
+ // in which case we can parse with inline scope, but need to allow
701
+ // nested lists inside this inline scope.
702
+ var prevCaptureStr = state.prevCapture == null ? "" : state.prevCapture[0];
703
+ var isStartOfLineCapture = LIST_LOOKBEHIND_R.exec(prevCaptureStr);
704
+ var isListBlock = state._list || !state.inline;
705
+ if (isStartOfLineCapture && isListBlock) {
706
+ source = isStartOfLineCapture[1] + source;
707
+ return LIST_R.exec(source);
708
+ } else {
709
+ return null;
710
+ }
711
+ },
712
+ parse: function (capture, parse, state) {
713
+ var bullet = capture[2];
714
+ var ordered = bullet.length > 1;
715
+ var start = ordered ? +bullet : undefined;
716
+ // @ts-expect-error - TS2322 - Type 'RegExpMatchArray | null' is not assignable to type 'string[]'.
717
+ var items = capture[0].replace(LIST_BLOCK_END_R, "\n").match(LIST_ITEM_R);
718
+
719
+ // We know this will match here, because of how the regexes are
720
+ // defined
721
+
722
+ var lastItemWasAParagraph = false;
723
+ var itemContent = items.map(function (item, i) {
724
+ // We need to see how far indented this item is:
725
+ var prefixCapture = LIST_ITEM_PREFIX_R.exec(item);
726
+ var space = prefixCapture ? prefixCapture[0].length : 0;
727
+ // And then we construct a regex to "unindent" the subsequent
728
+ // lines of the items by that amount:
729
+ var spaceRegex = new RegExp("^ {1," + space + "}", "gm");
730
+
731
+ // Before processing the item, we need a couple things
732
+ var content = item
733
+ // remove indents on trailing lines:
734
+ .replace(spaceRegex, "")
735
+ // remove the bullet:
736
+ .replace(LIST_ITEM_PREFIX_R, "");
737
+
738
+ // I'm not sur4 why this is necessary again?
739
+
740
+ // Handling "loose" lists, like:
741
+ //
742
+ // * this is wrapped in a paragraph
743
+ //
744
+ // * as is this
745
+ //
746
+ // * as is this
747
+ var isLastItem = i === items.length - 1;
748
+ var containsBlocks = content.indexOf("\n\n") !== -1;
749
+
750
+ // Any element in a list is a block if it contains multiple
751
+ // newlines. The last element in the list can also be a block
752
+ // if the previous item in the list was a block (this is
753
+ // because non-last items in the list can end with \n\n, but
754
+ // the last item can't, so we just "inherit" this property
755
+ // from our previous element).
756
+ var thisItemIsAParagraph = containsBlocks || isLastItem && lastItemWasAParagraph;
757
+ lastItemWasAParagraph = thisItemIsAParagraph;
758
+
759
+ // backup our state for restoration afterwards. We're going to
760
+ // want to set state._list to true, and state.inline depending
761
+ // on our list's looseness.
762
+ var oldStateInline = state.inline;
763
+ var oldStateList = state._list;
764
+ state._list = true;
765
+
766
+ // Parse inline if we're in a tight list, or block if we're in
767
+ // a loose list.
768
+ var adjustedContent;
769
+ if (thisItemIsAParagraph) {
770
+ state.inline = false;
771
+ adjustedContent = content.replace(LIST_ITEM_END_R, "\n\n");
772
+ } else {
773
+ state.inline = true;
774
+ adjustedContent = content.replace(LIST_ITEM_END_R, "");
775
+ }
776
+ var result = parse(adjustedContent, state);
777
+
778
+ // Restore our state before returning
779
+ state.inline = oldStateInline;
780
+ state._list = oldStateList;
781
+ return result;
782
+ });
783
+ return {
784
+ ordered: ordered,
785
+ start: start,
786
+ items: itemContent
787
+ };
788
+ },
789
+ react: function (node, output, state) {
790
+ var ListWrapper = node.ordered ? "ol" : "ul";
791
+ return reactElement(ListWrapper, state.key, {
792
+ start: node.start,
793
+ children: node.items.map(function (item, i) {
794
+ return reactElement("li", "" + i, {
795
+ children: output(item, state)
796
+ });
797
+ })
798
+ });
799
+ },
800
+ html: function (node, output, state) {
801
+ var listItems = node.items.map(function (item) {
802
+ return htmlTag("li", output(item, state));
803
+ }).join("");
804
+ var listTag = node.ordered ? "ol" : "ul";
805
+ var attributes = {
806
+ start: node.start
807
+ };
808
+ return htmlTag(listTag, listItems, attributes);
809
+ }
810
+ },
811
+ def: {
812
+ order: currOrder++,
813
+ // TODO(aria): This will match without a blank line before the next
814
+ // block element, which is inconsistent with most of the rest of
815
+ // simple-markdown.
816
+ match: blockRegex(/^ *\[([^\]]+)\]: *<?([^\s>]*)>?(?: +["(]([^\n]+)[")])? *\n(?: *\n)*/),
817
+ parse: function (capture, parse, state) {
818
+ var def = capture[1].replace(/\s+/g, " ").toLowerCase();
819
+ var target = capture[2];
820
+ var title = capture[3];
821
+
822
+ // Look for previous links/images using this def
823
+ // If any links/images using this def have already been declared,
824
+ // they will have added themselves to the state._refs[def] list
825
+ // (_ to deconflict with client-defined state). We look through
826
+ // that list of reflinks for this def, and modify those AST nodes
827
+ // with our newly found information now.
828
+ // Sorry :(.
829
+ if (state._refs && state._refs[def]) {
830
+ // `refNode` can be a link or an image
831
+ state._refs[def].forEach(function (refNode) {
832
+ refNode.target = target;
833
+ refNode.title = title;
834
+ });
835
+ }
836
+
837
+ // Add this def to our map of defs for any future links/images
838
+ // In case we haven't found any or all of the refs referring to
839
+ // this def yet, we add our def to the table of known defs, so
840
+ // that future reflinks can modify themselves appropriately with
841
+ // this information.
842
+ state._defs = state._defs || {};
843
+ state._defs[def] = {
844
+ target: target,
845
+ title: title
846
+ };
847
+
848
+ // return the relevant parsed information
849
+ // for debugging only.
850
+ return {
851
+ def: def,
852
+ target: target,
853
+ title: title
854
+ };
855
+ },
856
+ react: function () {
857
+ return null;
858
+ },
859
+ html: function () {
860
+ return "";
861
+ }
862
+ },
863
+ table: {
864
+ order: currOrder++,
865
+ match: blockRegex(TABLES.TABLE_REGEX),
866
+ parse: TABLES.parseTable,
867
+ react: function (node, output, state) {
868
+ var getStyle = function getStyle(colIndex) {
869
+ return node.align[colIndex] == null ? {} : {
870
+ textAlign: node.align[colIndex]
871
+ };
872
+ };
873
+ var headers = node.header.map(function (content, i) {
874
+ return reactElement("th", "" + i, {
875
+ style: getStyle(i),
876
+ scope: "col",
877
+ children: output(content, state)
878
+ });
879
+ });
880
+ var rows = node.cells.map(function (row, r) {
881
+ return reactElement("tr", "" + r, {
882
+ children: row.map(function (content, c) {
883
+ return reactElement("td", "" + c, {
884
+ style: getStyle(c),
885
+ children: output(content, state)
886
+ });
887
+ })
888
+ });
889
+ });
890
+ return reactElement("table", state.key, {
891
+ children: [reactElement("thead", "thead", {
892
+ children: reactElement("tr", null, {
893
+ children: headers
894
+ })
895
+ }), reactElement("tbody", "tbody", {
896
+ children: rows
897
+ })]
898
+ });
899
+ },
900
+ html: function (node, output, state) {
901
+ var getStyle = function getStyle(colIndex) {
902
+ return node.align[colIndex] == null ? "" : "text-align:" + node.align[colIndex] + ";";
903
+ };
904
+ var headers = node.header.map(function (content, i) {
905
+ return htmlTag("th", output(content, state), {
906
+ style: getStyle(i),
907
+ scope: "col"
908
+ });
909
+ }).join("");
910
+ var rows = node.cells.map(function (row) {
911
+ var cols = row.map(function (content, c) {
912
+ return htmlTag("td", output(content, state), {
913
+ style: getStyle(c)
914
+ });
915
+ }).join("");
916
+ return htmlTag("tr", cols);
917
+ }).join("");
918
+ var thead = htmlTag("thead", htmlTag("tr", headers));
919
+ var tbody = htmlTag("tbody", rows);
920
+ return htmlTag("table", thead + tbody);
921
+ }
922
+ },
923
+ newline: {
924
+ order: currOrder++,
925
+ match: blockRegex(/^(?:\n *)*\n/),
926
+ parse: ignoreCapture,
927
+ react: function (node, output, state) {
928
+ return "\n";
929
+ },
930
+ html: function (node, output, state) {
931
+ return "\n";
932
+ }
933
+ },
934
+ paragraph: {
935
+ order: currOrder++,
936
+ match: blockRegex(/^((?:[^\n]|\n(?! *\n))+)(?:\n *)+\n/),
937
+ parse: parseCaptureInline,
938
+ react: function (node, output, state) {
939
+ return reactElement("div", state.key, {
940
+ className: "paragraph",
941
+ children: output(node.content, state)
942
+ });
943
+ },
944
+ html: function (node, output, state) {
945
+ var attributes = {
946
+ class: "paragraph"
947
+ };
948
+ return htmlTag("div", output(node.content, state), attributes);
949
+ }
950
+ },
951
+ escape: {
952
+ order: currOrder++,
953
+ // We don't allow escaping numbers, letters, or spaces here so that
954
+ // backslashes used in plain text still get rendered. But allowing
955
+ // escaping anything else provides a very flexible escape mechanism,
956
+ // regardless of how this grammar is extended.
957
+ match: inlineRegex(/^\\([^0-9A-Za-z\s])/),
958
+ parse: function (capture, parse, state) {
959
+ return {
960
+ type: "text",
961
+ content: capture[1]
962
+ };
963
+ },
964
+ react: null,
965
+ html: null
966
+ },
967
+ tableSeparator: {
968
+ order: currOrder++,
969
+ match: function (source, state) {
970
+ if (!state.inTable) {
971
+ return null;
972
+ }
973
+ return /^ *\| */.exec(source);
974
+ },
975
+ parse: function () {
976
+ return {
977
+ type: "tableSeparator"
978
+ };
979
+ },
980
+ // These shouldn't be reached, but in case they are, be reasonable:
981
+ react: function () {
982
+ return " | ";
983
+ },
984
+ html: function () {
985
+ return " &vert; ";
986
+ }
987
+ },
988
+ autolink: {
989
+ order: currOrder++,
990
+ match: inlineRegex(/^<([^: >]+:\/[^ >]+)>/),
991
+ parse: function (capture, parse, state) {
992
+ return {
993
+ type: "link",
994
+ content: [{
995
+ type: "text",
996
+ content: capture[1]
997
+ }],
998
+ target: capture[1]
999
+ };
1000
+ },
1001
+ react: null,
1002
+ html: null
1003
+ },
1004
+ mailto: {
1005
+ order: currOrder++,
1006
+ match: inlineRegex(/^<([^ >]+@[^ >]+)>/),
1007
+ parse: function (capture, parse, state) {
1008
+ var address = capture[1];
1009
+ var target = capture[1];
1010
+
1011
+ // Check for a `mailto:` already existing in the link:
1012
+ if (!AUTOLINK_MAILTO_CHECK_R.test(target)) {
1013
+ target = "mailto:" + target;
1014
+ }
1015
+ return {
1016
+ type: "link",
1017
+ content: [{
1018
+ type: "text",
1019
+ content: address
1020
+ }],
1021
+ target: target
1022
+ };
1023
+ },
1024
+ react: null,
1025
+ html: null
1026
+ },
1027
+ url: {
1028
+ order: currOrder++,
1029
+ match: inlineRegex(/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/),
1030
+ parse: function (capture, parse, state) {
1031
+ return {
1032
+ type: "link",
1033
+ content: [{
1034
+ type: "text",
1035
+ content: capture[1]
1036
+ }],
1037
+ target: capture[1],
1038
+ title: undefined
1039
+ };
1040
+ },
1041
+ react: null,
1042
+ html: null
1043
+ },
1044
+ link: {
1045
+ order: currOrder++,
1046
+ match: inlineRegex(new RegExp("^\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)")),
1047
+ parse: function (capture, parse, state) {
1048
+ var link = {
1049
+ content: parse(capture[1], state),
1050
+ target: unescapeUrl(capture[2]),
1051
+ title: capture[3]
1052
+ };
1053
+ return link;
1054
+ },
1055
+ react: function (node, output, state) {
1056
+ return reactElement("a", state.key, {
1057
+ href: sanitizeUrl(node.target),
1058
+ title: node.title,
1059
+ children: output(node.content, state)
1060
+ });
1061
+ },
1062
+ html: function (node, output, state) {
1063
+ var attributes = {
1064
+ href: sanitizeUrl(node.target),
1065
+ title: node.title
1066
+ };
1067
+ return htmlTag("a", output(node.content, state), attributes);
1068
+ }
1069
+ },
1070
+ image: {
1071
+ order: currOrder++,
1072
+ match: inlineRegex(new RegExp("^!\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)")),
1073
+ parse: function (capture, parse, state) {
1074
+ var image = {
1075
+ alt: capture[1],
1076
+ target: unescapeUrl(capture[2]),
1077
+ title: capture[3]
1078
+ };
1079
+ return image;
1080
+ },
1081
+ react: function (node, output, state) {
1082
+ return reactElement("img", state.key, {
1083
+ src: sanitizeUrl(node.target),
1084
+ alt: node.alt,
1085
+ title: node.title
1086
+ });
1087
+ },
1088
+ html: function (node, output, state) {
1089
+ var attributes = {
1090
+ src: sanitizeUrl(node.target),
1091
+ alt: node.alt,
1092
+ title: node.title
1093
+ };
1094
+ return htmlTag("img", "", attributes, false);
1095
+ }
1096
+ },
1097
+ reflink: {
1098
+ order: currOrder++,
1099
+ match: inlineRegex(new RegExp(
1100
+ // The first [part] of the link
1101
+ "^\\[(" + LINK_INSIDE + ")\\]" +
1102
+ // The [ref] target of the link
1103
+ "\\s*\\[([^\\]]*)\\]")),
1104
+ parse: function (capture, parse, state) {
1105
+ return parseRef(capture, state, {
1106
+ type: "link",
1107
+ content: parse(capture[1], state)
1108
+ });
1109
+ },
1110
+ react: null,
1111
+ html: null
1112
+ },
1113
+ refimage: {
1114
+ order: currOrder++,
1115
+ match: inlineRegex(new RegExp(
1116
+ // The first [part] of the link
1117
+ "^!\\[(" + LINK_INSIDE + ")\\]" +
1118
+ // The [ref] target of the link
1119
+ "\\s*\\[([^\\]]*)\\]")),
1120
+ parse: function (capture, parse, state) {
1121
+ return parseRef(capture, state, {
1122
+ type: "image",
1123
+ alt: capture[1]
1124
+ });
1125
+ },
1126
+ react: null,
1127
+ html: null
1128
+ },
1129
+ em: {
1130
+ order: currOrder /* same as strong/u */,
1131
+ match: inlineRegex(new RegExp(
1132
+ // only match _s surrounding words.
1133
+ "^\\b_" + "((?:__|\\\\[\\s\\S]|[^\\\\_])+?)_" + "\\b" +
1134
+ // Or match *s:
1135
+ "|" +
1136
+ // Only match *s that are followed by a non-space:
1137
+ "^\\*(?=\\S)(" +
1138
+ // Match at least one of:
1139
+ "(?:" +
1140
+ // - `**`: so that bolds inside italics don't close the
1141
+ // italics
1142
+ "\\*\\*|" +
1143
+ // - escape sequence: so escaped *s don't close us
1144
+ "\\\\[\\s\\S]|" +
1145
+ // - whitespace: followed by a non-* (we don't
1146
+ // want ' *' to close an italics--it might
1147
+ // start a list)
1148
+ "\\s+(?:\\\\[\\s\\S]|[^\\s\\*\\\\]|\\*\\*)|" +
1149
+ // - non-whitespace, non-*, non-backslash characters
1150
+ "[^\\s\\*\\\\]" + ")+?" +
1151
+ // followed by a non-space, non-* then *
1152
+ ")\\*(?!\\*)")),
1153
+ quality: function (capture) {
1154
+ // precedence by length, `em` wins ties:
1155
+ return capture[0].length + 0.2;
1156
+ },
1157
+ parse: function (capture, parse, state) {
1158
+ return {
1159
+ content: parse(capture[2] || capture[1], state)
1160
+ };
1161
+ },
1162
+ react: function (node, output, state) {
1163
+ return reactElement("em", state.key, {
1164
+ children: output(node.content, state)
1165
+ });
1166
+ },
1167
+ html: function (node, output, state) {
1168
+ return htmlTag("em", output(node.content, state));
1169
+ }
1170
+ },
1171
+ strong: {
1172
+ order: currOrder /* same as em */,
1173
+ match: inlineRegex(/^\*\*((?:\\[\s\S]|[^\\])+?)\*\*(?!\*)/),
1174
+ quality: function (capture) {
1175
+ // precedence by length, wins ties vs `u`:
1176
+ return capture[0].length + 0.1;
1177
+ },
1178
+ parse: parseCaptureInline,
1179
+ react: function (node, output, state) {
1180
+ return reactElement("strong", state.key, {
1181
+ children: output(node.content, state)
1182
+ });
1183
+ },
1184
+ html: function (node, output, state) {
1185
+ return htmlTag("strong", output(node.content, state));
1186
+ }
1187
+ },
1188
+ u: {
1189
+ order: currOrder++ /* same as em&strong; increment for next rule */,
1190
+ match: inlineRegex(/^__((?:\\[\s\S]|[^\\])+?)__(?!_)/),
1191
+ quality: function (capture) {
1192
+ // precedence by length, loses all ties
1193
+ return capture[0].length;
1194
+ },
1195
+ parse: parseCaptureInline,
1196
+ react: function (node, output, state) {
1197
+ return reactElement("u", state.key, {
1198
+ children: output(node.content, state)
1199
+ });
1200
+ },
1201
+ html: function (node, output, state) {
1202
+ return htmlTag("u", output(node.content, state));
1203
+ }
1204
+ },
1205
+ del: {
1206
+ order: currOrder++,
1207
+ match: inlineRegex(/^~~(?=\S)((?:\\[\s\S]|~(?!~)|[^\s~\\]|\s(?!~~))+?)~~/),
1208
+ parse: parseCaptureInline,
1209
+ react: function (node, output, state) {
1210
+ return reactElement("del", state.key, {
1211
+ children: output(node.content, state)
1212
+ });
1213
+ },
1214
+ html: function (node, output, state) {
1215
+ return htmlTag("del", output(node.content, state));
1216
+ }
1217
+ },
1218
+ inlineCode: {
1219
+ order: currOrder++,
1220
+ match: inlineRegex(/^(`+)([\s\S]*?[^`])\1(?!`)/),
1221
+ parse: function (capture, parse, state) {
1222
+ return {
1223
+ content: capture[2].replace(INLINE_CODE_ESCAPE_BACKTICKS_R, "$1")
1224
+ };
1225
+ },
1226
+ react: function (node, output, state) {
1227
+ return reactElement("code", state.key, {
1228
+ children: node.content
1229
+ });
1230
+ },
1231
+ html: function (node, output, state) {
1232
+ return htmlTag("code", sanitizeText(node.content));
1233
+ }
1234
+ },
1235
+ br: {
1236
+ order: currOrder++,
1237
+ match: anyScopeRegex(/^ {2,}\n/),
1238
+ parse: ignoreCapture,
1239
+ react: function (node, output, state) {
1240
+ return reactElement("br", state.key, EMPTY_PROPS);
1241
+ },
1242
+ html: function (node, output, state) {
1243
+ return "<br>";
1244
+ }
1245
+ },
1246
+ text: {
1247
+ order: currOrder++,
1248
+ // Here we look for anything followed by non-symbols,
1249
+ // double newlines, or double-space-newlines
1250
+ // We break on any symbol characters so that this grammar
1251
+ // is easy to extend without needing to modify this regex
1252
+ match: anyScopeRegex(/^[\s\S]+?(?=[^0-9A-Za-z\s\u00c0-\uffff]|\n\n| {2,}\n|\w+:\S|$)/),
1253
+ parse: function (capture, parse, state) {
1254
+ return {
1255
+ content: capture[0]
1256
+ };
1257
+ },
1258
+ react: function (node, output, state) {
1259
+ return node.content;
1260
+ },
1261
+ html: function (node, output, state) {
1262
+ return sanitizeText(node.content);
1263
+ }
1264
+ }
1265
+ };
1266
+
1267
+ /** (deprecated) */
1268
+ var ruleOutput = function ruleOutput(rules, property) {
1269
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1270
+ if (!property && typeof console !== "undefined") {
1271
+ console.warn("simple-markdown ruleOutput should take 'react' or " + "'html' as the second argument.");
1272
+ }
1273
+ var nestedRuleOutput = function nestedRuleOutput(ast, outputFunc, state) {
1274
+ // @ts-expect-error - TS2349 - This expression is not callable.
1275
+ // Type 'unknown' has no call signatures.
1276
+ return rules[ast.type][property](ast, outputFunc, state);
1277
+ };
1278
+ return nestedRuleOutput;
1279
+ };
1280
+
1281
+ /** (deprecated)
1282
+ */
1283
+ var reactFor = function reactFor(outputFunc) {
1284
+ var nestedOutput = function nestedOutput(ast, state) {
1285
+ state = state || {};
1286
+ if (Array.isArray(ast)) {
1287
+ var oldKey = state.key;
1288
+ var result = [];
1289
+
1290
+ // map nestedOutput over the ast, except group any text
1291
+ // nodes together into a single string output.
1292
+ var lastResult = null;
1293
+ for (var i = 0; i < ast.length; i++) {
1294
+ state.key = "" + i;
1295
+ var nodeOut = nestedOutput(ast[i], state);
1296
+ if (typeof nodeOut === "string" && typeof lastResult === "string") {
1297
+ // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
1298
+ lastResult = lastResult + nodeOut;
1299
+ result[result.length - 1] = lastResult;
1300
+ } else {
1301
+ result.push(nodeOut);
1302
+ // @ts-expect-error - TS2322 - Type 'ReactNode' is not assignable to type 'null'.
1303
+ lastResult = nodeOut;
1304
+ }
1305
+ }
1306
+ state.key = oldKey;
1307
+ return result;
1308
+ } else {
1309
+ return outputFunc(ast, nestedOutput, state);
1310
+ }
1311
+ };
1312
+ return nestedOutput;
1313
+ };
1314
+
1315
+ /** (deprecated)
1316
+ */
1317
+ var htmlFor = function htmlFor(outputFunc) {
1318
+ var nestedOutput = function nestedOutput(ast, state) {
1319
+ state = state || {};
1320
+ if (Array.isArray(ast)) {
1321
+ return ast.map(function (node) {
1322
+ return nestedOutput(node, state);
1323
+ }).join("");
1324
+ } else {
1325
+ return outputFunc(ast, nestedOutput, state);
1326
+ }
1327
+ };
1328
+ return nestedOutput;
1329
+ };
1330
+ var outputFor = function outputFor(rules, property, defaultState = {}) {
1331
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1332
+ if (!property) {
1333
+ throw new Error("simple-markdown: outputFor: `property` must be " + "defined. " + "if you just upgraded, you probably need to replace `outputFor` " + "with `reactFor`");
1334
+ }
1335
+ var latestState;
1336
+ var arrayRule = rules.Array || defaultRules.Array;
1337
+
1338
+ // Tricks to convince tsc that this var is not null:
1339
+ // @ts-expect-error - TS2538 - Type 'symbol' cannot be used as an index type.
1340
+ var arrayRuleCheck = arrayRule[property];
1341
+ if (!arrayRuleCheck) {
1342
+ throw new Error("simple-markdown: outputFor: to join nodes of type `" +
1343
+ // @ts-expect-error - TS2469 - The '+' operator cannot be applied to type 'symbol'.
1344
+ property + "` you must provide an `Array:` joiner rule with that type, " + "Please see the docs for details on specifying an Array rule.");
1345
+ }
1346
+ var arrayRuleOutput = arrayRuleCheck;
1347
+ var nestedOutput = function nestedOutput(ast, state) {
1348
+ state = state || latestState;
1349
+ latestState = state;
1350
+ if (Array.isArray(ast)) {
1351
+ return arrayRuleOutput(ast, nestedOutput, state);
1352
+ } else {
1353
+ // @ts-expect-error - TS2349 - This expression is not callable.
1354
+ // Type 'unknown' has no call signatures.
1355
+ return rules[ast.type][property](ast, nestedOutput, state);
1356
+ }
1357
+ };
1358
+ var outerOutput = function outerOutput(ast, state) {
1359
+ latestState = populateInitialState(state, defaultState);
1360
+ return nestedOutput(ast, latestState);
1361
+ };
1362
+ return outerOutput;
1363
+ };
1364
+
1365
+ // @ts-expect-error - TS2345 - Argument of type 'DefaultRules' is not assignable to parameter of type 'ParserRules'.
1366
+ var defaultRawParse = parserFor(defaultRules);
1367
+ var defaultBlockParse = function defaultBlockParse(source, state) {
1368
+ state = state || {};
1369
+ state.inline = false;
1370
+ return defaultRawParse(source, state);
1371
+ };
1372
+ var defaultInlineParse = function defaultInlineParse(source, state) {
1373
+ state = state || {};
1374
+ state.inline = true;
1375
+ return defaultRawParse(source, state);
1376
+ };
1377
+ var defaultImplicitParse = function defaultImplicitParse(source, state) {
1378
+ var isBlock = BLOCK_END_R.test(source);
1379
+ state = state || {};
1380
+ state.inline = !isBlock;
1381
+ return defaultRawParse(source, state);
1382
+ };
1383
+ var defaultReactOutput = outputFor(defaultRules, "react");
1384
+ var defaultHtmlOutput = outputFor(defaultRules, "html");
1385
+ var markdownToReact = function markdownToReact(source, state) {
1386
+ return defaultReactOutput(defaultBlockParse(source, state), state);
1387
+ };
1388
+ var markdownToHtml = function markdownToHtml(source, state) {
1389
+ return defaultHtmlOutput(defaultBlockParse(source, state), state);
1390
+ };
1391
+
1392
+ // TODO: This needs definition
1393
+
1394
+ var ReactMarkdown = function ReactMarkdown(props) {
1395
+ var divProps = {};
1396
+ for (var prop in props) {
1397
+ if (prop !== "source" && Object.prototype.hasOwnProperty.call(props, prop)) {
1398
+ divProps[prop] = props[prop];
1399
+ }
1400
+ }
1401
+ divProps.children = markdownToReact(props.source);
1402
+ return reactElement("div", null, divProps);
1403
+ };
1404
+ var SimpleMarkdown = {
1405
+ defaultRules: defaultRules,
1406
+ parserFor: parserFor,
1407
+ outputFor: outputFor,
1408
+ inlineRegex: inlineRegex,
1409
+ blockRegex: blockRegex,
1410
+ anyScopeRegex: anyScopeRegex,
1411
+ parseInline: parseInline,
1412
+ parseBlock: parseBlock,
1413
+ // default wrappers:
1414
+ markdownToReact: markdownToReact,
1415
+ markdownToHtml: markdownToHtml,
1416
+ ReactMarkdown: ReactMarkdown,
1417
+ defaultBlockParse: defaultBlockParse,
1418
+ defaultInlineParse: defaultInlineParse,
1419
+ defaultImplicitParse: defaultImplicitParse,
1420
+ defaultReactOutput: defaultReactOutput,
1421
+ defaultHtmlOutput: defaultHtmlOutput,
1422
+ preprocess: preprocess,
1423
+ sanitizeText: sanitizeText,
1424
+ sanitizeUrl: sanitizeUrl,
1425
+ unescapeUrl: unescapeUrl,
1426
+ htmlTag: htmlTag,
1427
+ reactElement: reactElement,
1428
+ // deprecated:
1429
+ defaultRawParse: defaultRawParse,
1430
+ ruleOutput: ruleOutput,
1431
+ reactFor: reactFor,
1432
+ htmlFor: htmlFor,
1433
+ defaultParse: function (...args) {
1434
+ if (typeof console !== "undefined") {
1435
+ console.warn("defaultParse is deprecated, please use `defaultImplicitParse`");
1436
+ }
1437
+ // @ts-expect-error - Argument of type 'any[]' is not assignable to parameter of type '[node: ASTNode, state?: State | null | undefined]'. Target requires 1 element(s) but source may have fewer.
1438
+ return defaultImplicitParse.apply(null, args);
1439
+ },
1440
+ defaultOutput: function (...args) {
1441
+ if (typeof console !== "undefined") {
1442
+ console.warn("defaultOutput is deprecated, please use `defaultReactOutput`");
1443
+ }
1444
+ // @ts-expect-error - Argument of type 'any[]' is not assignable to parameter of type '[node: ASTNode, state?: State | null | undefined]'. Target requires 1 element(s) but source may have fewer.
1445
+ return defaultReactOutput.apply(null, args);
1446
+ }
1447
+ };
1448
+
1449
+ export { SimpleMarkdown as default, libVersion };
1450
+ //# sourceMappingURL=index.js.map