@khanacademy/simple-markdown 0.0.0-PR443-20230328215601

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