@khanacademy/simple-markdown 0.0.0-PR1039-20240229230747

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