@khanacademy/simple-markdown 0.11.1 → 0.11.3

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/src/index.ts DELETED
@@ -1,2100 +0,0 @@
1
- /* eslint-disable prefer-spread, no-regex-spaces, @typescript-eslint/no-unused-vars, guard-for-in, no-console, no-var */
2
- /**
3
- * Simple-Markdown
4
- * ===============
5
- *
6
- * Simple-Markdown's primary goal is to be easy to adapt. It aims
7
- * to be compliant with John Gruber's [Markdown Syntax page][1],
8
- * but compatiblity with other markdown implementations' edge-cases
9
- * will be sacrificed where it conflicts with simplicity or
10
- * extensibility.
11
- *
12
- * If your goal is to simply embed a standard markdown implementation
13
- * in your website, simple-markdown is probably not the best library
14
- * for you (although it should work). But if you have struggled to
15
- * customize an existing library to meet your needs, simple-markdown
16
- * might be able to help.
17
- *
18
- * Many of the regexes and original logic has been adapted from
19
- * the wonderful [marked.js](https://github.com/chjj/marked)
20
- */
21
- import type {Capture, MatchFunction, State} from "./troublesome-types";
22
- import type * as React from "react";
23
-
24
- export {libVersion} from "./version";
25
-
26
- // Type Definitions:
27
-
28
- type Attr = string | number | boolean | null | undefined;
29
-
30
- type SingleASTNode = {
31
- type: string;
32
- [key: string]: any;
33
- };
34
-
35
- type UnTypedASTNode = {
36
- [key: string]: any;
37
- };
38
-
39
- type ASTNode = SingleASTNode | Array<SingleASTNode>;
40
-
41
- type ReactElement = React.ReactElement<any>;
42
- type ReactElements = React.ReactNode;
43
-
44
- type Parser = (
45
- source: string,
46
- state?: State | null | undefined,
47
- ) => Array<SingleASTNode>;
48
-
49
- type ParseFunction = (
50
- capture: Capture,
51
- nestedParse: Parser,
52
- state: State,
53
- ) => UnTypedASTNode | ASTNode;
54
-
55
- type SingleNodeParseFunction = (
56
- capture: Capture,
57
- nestedParse: Parser,
58
- state: State,
59
- ) => UnTypedASTNode;
60
-
61
- type Output<Result> = (
62
- node: ASTNode,
63
- state?: State | null | undefined,
64
- ) => Result;
65
-
66
- type NodeOutput<Result> = (
67
- node: SingleASTNode,
68
- nestedOutput: Output<Result>,
69
- state: State,
70
- ) => Result;
71
-
72
- type ArrayNodeOutput<Result> = (
73
- node: Array<SingleASTNode>,
74
- nestedOutput: Output<Result>,
75
- state: State,
76
- ) => Result;
77
-
78
- type ReactOutput = Output<ReactElements>;
79
- type ReactNodeOutput = NodeOutput<ReactElements>;
80
- type HtmlOutput = Output<string>;
81
- type HtmlNodeOutput = NodeOutput<string>;
82
-
83
- type ParserRule = {
84
- readonly order: number;
85
- readonly match: MatchFunction;
86
- readonly quality?: (
87
- capture: Capture,
88
- state: State,
89
- prevCapture: string,
90
- ) => number;
91
- readonly parse: ParseFunction;
92
- };
93
-
94
- type SingleNodeParserRule = {
95
- readonly order: number;
96
- readonly match: MatchFunction;
97
- readonly quality?: (
98
- capture: Capture,
99
- state: State,
100
- prevCapture: string,
101
- ) => number;
102
- readonly parse: SingleNodeParseFunction;
103
- };
104
-
105
- type ReactOutputRule = {
106
- // we allow null because some rules are never output results, and that's
107
- // legal as long as no parsers return an AST node matching that rule.
108
- // We don't use ? because this makes it be explicitly defined as either
109
- // a valid function or null, so it can't be forgotten.
110
- readonly react: ReactNodeOutput | null;
111
- };
112
-
113
- type HtmlOutputRule = {
114
- readonly html: HtmlNodeOutput | null;
115
- };
116
-
117
- type ArrayRule = {
118
- // @ts-expect-error - TS2411 - Property 'react' of type 'ArrayNodeOutput<ReactNode> | undefined' is not assignable to 'string' index type 'ArrayNodeOutput<any>'.
119
- readonly react?: ArrayNodeOutput<ReactElements>;
120
- // @ts-expect-error - TS2411 - Property 'html' of type 'ArrayNodeOutput<string> | undefined' is not assignable to 'string' index type 'ArrayNodeOutput<any>'.
121
- readonly html?: ArrayNodeOutput<string>;
122
- readonly [key: string]: ArrayNodeOutput<any>;
123
- };
124
-
125
- type ParserRules = {
126
- // @ts-expect-error - TS2411 - Property 'Array' of type 'ArrayRule | undefined' is not assignable to 'string' index type 'ParserRule'.
127
- readonly Array?: ArrayRule;
128
- readonly [type: string]: ParserRule;
129
- };
130
-
131
- type OutputRules<Rule> = {
132
- // @ts-expect-error - TS2411 - Property 'Array' of type 'ArrayRule | undefined' is not assignable to 'string' index type 'Rule'.
133
- readonly Array?: ArrayRule;
134
- readonly [type: string]: Rule;
135
- };
136
- type Rules<OutputRule> = {
137
- // @ts-expect-error - TS2411 - Property 'Array' of type 'ArrayRule | undefined' is not assignable to 'string' index type 'ParserRule & OutputRule'.
138
- readonly Array?: ArrayRule;
139
- readonly [type: string]: ParserRule & OutputRule;
140
- };
141
- type ReactRules = {
142
- // @ts-expect-error - TS2411 - Property 'Array' of type '{ readonly react: ArrayNodeOutput<ReactNode>; } | undefined' is not assignable to 'string' index type 'ParserRule & ReactOutputRule'.
143
- readonly Array?: {
144
- readonly react: ArrayNodeOutput<ReactElements>;
145
- };
146
- readonly [type: string]: ParserRule & ReactOutputRule;
147
- };
148
- type HtmlRules = {
149
- // @ts-expect-error - TS2411 - Property 'Array' of type '{ readonly html: ArrayNodeOutput<string>; } | undefined' is not assignable to 'string' index type 'ParserRule & HtmlOutputRule'.
150
- readonly Array?: {
151
- readonly html: ArrayNodeOutput<string>;
152
- };
153
- readonly [type: string]: ParserRule & HtmlOutputRule;
154
- };
155
-
156
- // We want to clarify our defaultRules types a little bit more so clients can
157
- // reuse defaultRules built-ins. So we make some stronger guarantess when
158
- // we can:
159
- type NonNullReactOutputRule = {
160
- readonly react: ReactNodeOutput;
161
- };
162
- type ElementReactOutputRule = {
163
- readonly react: NodeOutput<ReactElement>;
164
- };
165
- type TextReactOutputRule = {
166
- readonly react: NodeOutput<string>;
167
- };
168
- type NonNullHtmlOutputRule = {
169
- readonly html: HtmlNodeOutput;
170
- };
171
-
172
- type DefaultInRule = SingleNodeParserRule & ReactOutputRule & HtmlOutputRule;
173
- type TextInOutRule = SingleNodeParserRule &
174
- TextReactOutputRule &
175
- NonNullHtmlOutputRule;
176
- type LenientInOutRule = SingleNodeParserRule &
177
- NonNullReactOutputRule &
178
- NonNullHtmlOutputRule;
179
- type DefaultInOutRule = SingleNodeParserRule &
180
- ElementReactOutputRule &
181
- NonNullHtmlOutputRule;
182
-
183
- type DefaultRules = {
184
- readonly Array: {
185
- readonly react: ArrayNodeOutput<ReactElements>;
186
- readonly html: ArrayNodeOutput<string>;
187
- };
188
- readonly heading: DefaultInOutRule;
189
- readonly nptable: DefaultInRule;
190
- readonly lheading: DefaultInRule;
191
- readonly hr: DefaultInOutRule;
192
- readonly codeBlock: DefaultInOutRule;
193
- readonly fence: DefaultInRule;
194
- readonly blockQuote: DefaultInOutRule;
195
- readonly list: DefaultInOutRule;
196
- readonly def: LenientInOutRule;
197
- readonly table: DefaultInOutRule;
198
- readonly tableSeparator: DefaultInRule;
199
- readonly newline: TextInOutRule;
200
- readonly paragraph: DefaultInOutRule;
201
- readonly escape: DefaultInRule;
202
- readonly autolink: DefaultInRule;
203
- readonly mailto: DefaultInRule;
204
- readonly url: DefaultInRule;
205
- readonly link: DefaultInOutRule;
206
- readonly image: DefaultInOutRule;
207
- readonly reflink: DefaultInRule;
208
- readonly refimage: DefaultInRule;
209
- readonly em: DefaultInOutRule;
210
- readonly strong: DefaultInOutRule;
211
- readonly u: DefaultInOutRule;
212
- readonly del: DefaultInOutRule;
213
- readonly inlineCode: DefaultInOutRule;
214
- readonly br: DefaultInOutRule;
215
- readonly text: TextInOutRule;
216
- };
217
-
218
- type RefNode = {
219
- type: string;
220
- content?: ASTNode;
221
- target?: string;
222
- title?: string;
223
- alt?: string;
224
- };
225
-
226
- // End TypeScript Definitions
227
-
228
- var CR_NEWLINE_R = /\r\n?/g;
229
- var TAB_R = /\t/g;
230
- var FORMFEED_R = /\f/g;
231
-
232
- /**
233
- * Turn various whitespace into easy-to-process whitespace
234
- */
235
- var preprocess = function (source: string): string {
236
- return source
237
- .replace(CR_NEWLINE_R, "\n")
238
- .replace(FORMFEED_R, "")
239
- .replace(TAB_R, " ");
240
- };
241
-
242
- var populateInitialState = function (
243
- givenState?: State | null,
244
- defaultState?: State | null,
245
- ): State {
246
- var state: State = givenState || {};
247
- if (defaultState != null) {
248
- for (var prop in defaultState) {
249
- if (Object.prototype.hasOwnProperty.call(defaultState, prop)) {
250
- state[prop] = defaultState[prop];
251
- }
252
- }
253
- }
254
- return state;
255
- };
256
-
257
- /**
258
- * Creates a parser for a given set of rules, with the precedence
259
- * specified as a list of rules.
260
- *
261
- * @param {SimpleMarkdown.ParserRules} rules
262
- * an object containing
263
- * rule type -> {match, order, parse} objects
264
- * (lower order is higher precedence)
265
- * @param {SimpleMarkdown.OptionalState} [defaultState]
266
- *
267
- * @returns {SimpleMarkdown.Parser}
268
- * The resulting parse function, with the following parameters:
269
- * @source: the input source string to be parsed
270
- * @state: an optional object to be threaded through parse
271
- * calls. Allows clients to add stateful operations to
272
- * parsing, such as keeping track of how many levels deep
273
- * some nesting is. For an example use-case, see passage-ref
274
- * parsing in src/widgets/passage/passage-markdown.jsx
275
- */
276
- var parserFor = function (
277
- rules: ParserRules,
278
- defaultState?: State | null,
279
- ): Parser {
280
- // Sorts rules in order of increasing order, then
281
- // ascending rule name in case of ties.
282
- var ruleList = Object.keys(rules).filter(function (type) {
283
- var rule = rules[type];
284
- if (rule == null || rule.match == null) {
285
- return false;
286
- }
287
- var order = rule.order;
288
- if (
289
- (typeof order !== "number" || !isFinite(order)) &&
290
- typeof console !== "undefined"
291
- ) {
292
- console.warn(
293
- "simple-markdown: Invalid order for rule `" +
294
- type +
295
- "`: " +
296
- String(order),
297
- );
298
- }
299
- return true;
300
- });
301
-
302
- ruleList.sort(function (typeA, typeB) {
303
- var ruleA: ParserRule = rules[typeA] as any;
304
- var ruleB: ParserRule = rules[typeB] as any;
305
- var orderA = ruleA.order;
306
- var orderB = ruleB.order;
307
-
308
- // First sort based on increasing order
309
- if (orderA !== orderB) {
310
- return orderA - orderB;
311
- }
312
-
313
- var secondaryOrderA = ruleA.quality ? 0 : 1;
314
- var secondaryOrderB = ruleB.quality ? 0 : 1;
315
-
316
- if (secondaryOrderA !== secondaryOrderB) {
317
- return secondaryOrderA - secondaryOrderB;
318
-
319
- // Then based on increasing unicode lexicographic ordering
320
- } else if (typeA < typeB) {
321
- return -1;
322
- } else if (typeA > typeB) {
323
- return 1;
324
- } else {
325
- // Rules should never have the same name,
326
- // but this is provided for completeness.
327
- return 0;
328
- }
329
- });
330
-
331
- var latestState: State;
332
- var nestedParse: Parser = function (
333
- source: string,
334
- state?: State | null,
335
- ): Array<SingleASTNode> {
336
- var result: Array<SingleASTNode> = [];
337
- state = state || latestState;
338
- latestState = state;
339
- while (source) {
340
- // store the best match, it's rule, and quality:
341
- var ruleType = null;
342
- var rule = null;
343
- var capture = null;
344
- var quality = NaN;
345
-
346
- // loop control variables:
347
- var i = 0;
348
- var currRuleType = ruleList[0];
349
-
350
- var currRule: ParserRule = rules[currRuleType];
351
-
352
- do {
353
- var currOrder = currRule.order;
354
- var prevCaptureStr =
355
- state.prevCapture == null ? "" : state.prevCapture[0];
356
- var currCapture = currRule.match(source, state, prevCaptureStr);
357
-
358
- if (currCapture) {
359
- var currQuality = currRule.quality
360
- ? currRule.quality(currCapture, state, prevCaptureStr)
361
- : 0;
362
- // This should always be true the first time because
363
- // the initial quality is NaN (that's why there's the
364
- // condition negation).
365
- if (!(currQuality <= quality)) {
366
- // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
367
- ruleType = currRuleType;
368
- // @ts-expect-error - TS2322 - Type 'ParserRule' is not assignable to type 'null'.
369
- rule = currRule;
370
- // @ts-expect-error - TS2322 - Type 'Capture' is not assignable to type 'null'.
371
- capture = currCapture;
372
- quality = currQuality;
373
- }
374
- }
375
-
376
- // Move on to the next item.
377
- // Note that this makes `currRule` be the next item
378
- i++;
379
- currRuleType = ruleList[i];
380
- currRule = rules[currRuleType];
381
- } while (
382
- // keep looping while we're still within the ruleList
383
- currRule &&
384
- // if we don't have a match yet, continue
385
- (!capture ||
386
- // or if we have a match, but the next rule is
387
- // at the same order, and has a quality measurement
388
- // functions, then this rule must have a quality
389
- // measurement function (since they are sorted before
390
- // those without), and we need to check if there is
391
- // a better quality match
392
- (currRule.order === currOrder && currRule.quality))
393
- );
394
-
395
- // TODO(aria): Write tests for these
396
- if (rule == null || capture == null) {
397
- throw new Error(
398
- "Could not find a matching rule for the below " +
399
- "content. The rule with highest `order` should " +
400
- "always match content provided to it. Check " +
401
- "the definition of `match` for '" +
402
- ruleList[ruleList.length - 1] +
403
- "'. It seems to not match the following source:\n" +
404
- source,
405
- );
406
- }
407
- // @ts-expect-error - TS2339 - Property 'index' does not exist on type 'never'.
408
- if (capture.index) {
409
- // If present and non-zero, i.e. a non-^ regexp result:
410
- throw new Error(
411
- "`match` must return a capture starting at index 0 " +
412
- "(the current parse index). Did you forget a ^ at the " +
413
- "start of the RegExp?",
414
- );
415
- }
416
-
417
- // @ts-expect-error - TS2339 - Property 'parse' does not exist on type 'never'.
418
- var parsed = rule.parse(capture, nestedParse, state);
419
- // We maintain the same object here so that rules can
420
- // store references to the objects they return and
421
- // modify them later. (oops sorry! but this adds a lot
422
- // of power--see reflinks.)
423
- if (Array.isArray(parsed)) {
424
- Array.prototype.push.apply(result, parsed);
425
- } else {
426
- if (parsed == null || typeof parsed !== "object") {
427
- throw new Error(
428
- `parse() function returned invalid parse result: '${parsed}'`,
429
- );
430
- }
431
-
432
- // We also let rules override the default type of
433
- // their parsed node if they would like to, so that
434
- // there can be a single output function for all links,
435
- // even if there are several rules to parse them.
436
- if (parsed.type == null) {
437
- parsed.type = ruleType;
438
- }
439
- result.push(parsed);
440
- }
441
-
442
- state.prevCapture = capture;
443
- source = source.substring(state.prevCapture[0].length);
444
- }
445
-
446
- return result;
447
- };
448
-
449
- var outerParse: Parser = function (
450
- source: string,
451
- state?: State | null,
452
- ): Array<SingleASTNode> {
453
- latestState = populateInitialState(state, defaultState);
454
- if (!latestState.inline && !latestState.disableAutoBlockNewlines) {
455
- source = source + "\n\n";
456
- }
457
- // We store the previous capture so that match functions can
458
- // use some limited amount of lookbehind. Lists use this to
459
- // ensure they don't match arbitrary '- ' or '* ' in inline
460
- // text (see the list rule for more information). This stores
461
- // the full regex capture object, if there is one.
462
- latestState.prevCapture = null;
463
- return nestedParse(preprocess(source), latestState);
464
- };
465
-
466
- return outerParse;
467
- };
468
-
469
- // Creates a match function for an inline scoped element from a regex
470
- var inlineRegex = function (regex: RegExp): MatchFunction {
471
- var match = function (
472
- source: string,
473
- state: State,
474
- prevCapture: string,
475
- ): Capture | null | undefined {
476
- if (state.inline) {
477
- return regex.exec(source);
478
- } else {
479
- return null;
480
- }
481
- };
482
- // @ts-expect-error - TS2339 - Property 'regex' does not exist on type '(source: string, state: State, prevCapture: string) => Capture | null | undefined'.
483
- match.regex = regex;
484
-
485
- return match;
486
- };
487
-
488
- // Creates a match function for a block scoped element from a regex
489
- var blockRegex = function (regex: RegExp): MatchFunction {
490
- var match: MatchFunction = function (source, state) {
491
- if (state.inline) {
492
- return null;
493
- } else {
494
- return regex.exec(source);
495
- }
496
- };
497
- match.regex = regex;
498
- return match;
499
- };
500
-
501
- // Creates a match function from a regex, ignoring block/inline scope
502
- var anyScopeRegex = function (regex: RegExp): MatchFunction {
503
- var match: MatchFunction = function (source, state) {
504
- return regex.exec(source);
505
- };
506
- match.regex = regex;
507
- return match;
508
- };
509
-
510
- var TYPE_SYMBOL =
511
- (typeof Symbol === "function" &&
512
- Symbol.for &&
513
- Symbol.for("react.element")) ||
514
- 0xeac7;
515
-
516
- var reactElement = function (
517
- type: string,
518
- key: string | number | null | undefined,
519
- props: {
520
- [key: string]: any;
521
- },
522
- ): ReactElement {
523
- var element: ReactElement = {
524
- $$typeof: TYPE_SYMBOL,
525
- type: type,
526
- key: key == null ? undefined : key,
527
- ref: null,
528
- props: props,
529
- _owner: null,
530
- } as any;
531
- return element;
532
- };
533
-
534
- /** Returns a closed HTML tag.
535
- * @param {string} tagName - Name of HTML tag (eg. "em" or "a")
536
- * @param {string} content - Inner content of tag
537
- * @param {{ [attr: string]: SimpleMarkdown.Attr }} [attributes] - Optional extra attributes of tag as an object of key-value pairs
538
- * eg. { "href": "http://google.com" }. Falsey attributes are filtered out.
539
- * @param {boolean} [isClosed] - boolean that controls whether tag is closed or not (eg. img tags).
540
- * defaults to true
541
- */
542
- var htmlTag = function (
543
- tagName: string,
544
- content: string,
545
- attributes?: Partial<Record<any, Attr | null | undefined>> | null,
546
- isClosed?: boolean | null,
547
- ) {
548
- attributes = attributes || {};
549
- isClosed = typeof isClosed !== "undefined" ? isClosed : true;
550
-
551
- var attributeString = "";
552
- for (var attr in attributes) {
553
- var attribute = attributes[attr];
554
- // Removes falsey attributes
555
- if (
556
- Object.prototype.hasOwnProperty.call(attributes, attr) &&
557
- attribute
558
- ) {
559
- attributeString +=
560
- " " + sanitizeText(attr) + '="' + sanitizeText(attribute) + '"';
561
- }
562
- }
563
-
564
- var unclosedTag = "<" + tagName + attributeString + ">";
565
-
566
- if (isClosed) {
567
- return unclosedTag + content + "</" + tagName + ">";
568
- } else {
569
- return unclosedTag;
570
- }
571
- };
572
-
573
- var EMPTY_PROPS: Record<string, any> = {};
574
-
575
- /**
576
- * @param {string | null | undefined} url - url to sanitize
577
- * @returns {string | null} - url if safe, or null if a safe url could not be made
578
- */
579
- var sanitizeUrl = function (url?: string | null) {
580
- if (url == null) {
581
- return null;
582
- }
583
- try {
584
- var prot = new URL(url, "https://localhost").protocol;
585
- if (
586
- prot.indexOf("javascript:") === 0 ||
587
- prot.indexOf("vbscript:") === 0 ||
588
- prot.indexOf("data:") === 0
589
- ) {
590
- return null;
591
- }
592
- } catch (e: any) {
593
- // invalid URLs should throw a TypeError
594
- // see for instance: `new URL("");`
595
- return null;
596
- }
597
- return url;
598
- };
599
-
600
- var SANITIZE_TEXT_R = /[<>&"']/g;
601
- var SANITIZE_TEXT_CODES = {
602
- "<": "&lt;",
603
- ">": "&gt;",
604
- "&": "&amp;",
605
- '"': "&quot;",
606
- "'": "&#x27;",
607
- "/": "&#x2F;",
608
- "`": "&#96;",
609
- };
610
-
611
- var sanitizeText = function (text: Attr): string {
612
- return String(text).replace(SANITIZE_TEXT_R, function (chr) {
613
- return SANITIZE_TEXT_CODES[chr];
614
- });
615
- };
616
-
617
- var UNESCAPE_URL_R = /\\([^0-9A-Za-z\s])/g;
618
-
619
- var unescapeUrl = function (rawUrlString: string): string {
620
- return rawUrlString.replace(UNESCAPE_URL_R, "$1");
621
- };
622
-
623
- /**
624
- * Parse some content with the parser `parse`, with state.inline
625
- * set to true. Useful for block elements; not generally necessary
626
- * to be used by inline elements (where state.inline is already true.
627
- */
628
- var parseInline = function (
629
- parse: Parser,
630
- content: string,
631
- state: State,
632
- ): ASTNode {
633
- var isCurrentlyInline = state.inline || false;
634
- state.inline = true;
635
- var result = parse(content, state);
636
- state.inline = isCurrentlyInline;
637
- return result;
638
- };
639
-
640
- var parseBlock = function (
641
- parse: Parser,
642
- content: string,
643
- state: State,
644
- ): ASTNode {
645
- var isCurrentlyInline = state.inline || false;
646
- state.inline = false;
647
- var result = parse(content + "\n\n", state);
648
- state.inline = isCurrentlyInline;
649
- return result;
650
- };
651
-
652
- var parseCaptureInline = function (
653
- capture: Capture,
654
- parse: Parser,
655
- state: State,
656
- ): UnTypedASTNode {
657
- return {
658
- content: parseInline(parse, capture[1], state),
659
- };
660
- };
661
-
662
- var ignoreCapture = function (): UnTypedASTNode {
663
- return {};
664
- };
665
-
666
- // recognize a `*` `-`, `+`, `1.`, `2.`... list bullet
667
- var LIST_BULLET = "(?:[*+-]|\\d+\\.)";
668
- // recognize the start of a list item:
669
- // leading space plus a bullet plus a space (` * `)
670
- var LIST_ITEM_PREFIX = "( *)(" + LIST_BULLET + ") +";
671
- var LIST_ITEM_PREFIX_R = new RegExp("^" + LIST_ITEM_PREFIX);
672
- // recognize an individual list item:
673
- // * hi
674
- // this is part of the same item
675
- //
676
- // as is this, which is a new paragraph in the same item
677
- //
678
- // * but this is not part of the same item
679
- var LIST_ITEM_R = new RegExp(
680
- LIST_ITEM_PREFIX +
681
- "[^\\n]*(?:\\n" +
682
- "(?!\\1" +
683
- LIST_BULLET +
684
- " )[^\\n]*)*(\n|$)",
685
- "gm",
686
- );
687
- var BLOCK_END_R = /\n{2,}$/;
688
- var INLINE_CODE_ESCAPE_BACKTICKS_R = /^ (?= *`)|(` *) $/g;
689
- // recognize the end of a paragraph block inside a list item:
690
- // two or more newlines at end end of the item
691
- var LIST_BLOCK_END_R = BLOCK_END_R;
692
- var LIST_ITEM_END_R = / *\n+$/;
693
- // check whether a list item has paragraphs: if it does,
694
- // we leave the newlines at the end
695
- var LIST_R = new RegExp(
696
- "^( *)(" +
697
- LIST_BULLET +
698
- ") " +
699
- "[\\s\\S]+?(?:\n{2,}(?! )" +
700
- "(?!\\1" +
701
- LIST_BULLET +
702
- " )\\n*" +
703
- // the \\s*$ here is so that we can parse the inside of nested
704
- // lists, where our content might end before we receive two `\n`s
705
- "|\\s*\n*$)",
706
- );
707
- var LIST_LOOKBEHIND_R = /(?:^|\n)( *)$/;
708
-
709
- var TABLES = (function () {
710
- // predefine regexes so we don't have to create them inside functions
711
- // sure, regex literals should be fast, even inside functions, but they
712
- // aren't in all browsers.
713
- var TABLE_BLOCK_TRIM = /\n+/g;
714
- var TABLE_ROW_SEPARATOR_TRIM = /^ *\| *| *\| *$/g;
715
- var TABLE_CELL_END_TRIM = / *$/;
716
- var TABLE_RIGHT_ALIGN = /^ *-+: *$/;
717
- var TABLE_CENTER_ALIGN = /^ *:-+: *$/;
718
- var TABLE_LEFT_ALIGN = /^ *:-+ *$/;
719
-
720
- // TODO: This needs a real type
721
- type TableAlignment = any;
722
-
723
- var parseTableAlignCapture = function (
724
- alignCapture: string,
725
- ): TableAlignment {
726
- if (TABLE_RIGHT_ALIGN.test(alignCapture)) {
727
- return "right";
728
- } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {
729
- return "center";
730
- } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {
731
- return "left";
732
- } else {
733
- return null;
734
- }
735
- };
736
-
737
- var parseTableAlign = function (
738
- source: string,
739
- parse: Parser,
740
- state: State,
741
- trimEndSeparators: boolean,
742
- ): Array<TableAlignment> {
743
- if (trimEndSeparators) {
744
- source = source.replace(TABLE_ROW_SEPARATOR_TRIM, "");
745
- }
746
- var alignText = source.trim().split("|");
747
- return alignText.map(parseTableAlignCapture);
748
- };
749
-
750
- var parseTableRow = function (
751
- source: string,
752
- parse: Parser,
753
- state: State,
754
- trimEndSeparators: boolean,
755
- ): Array<Array<SingleASTNode>> {
756
- var prevInTable = state.inTable;
757
- state.inTable = true;
758
- var tableRow = parse(source.trim(), state);
759
- state.inTable = prevInTable;
760
-
761
- var cells = [[]];
762
- tableRow.forEach(function (node, i) {
763
- if (node.type === "tableSeparator") {
764
- // Filter out empty table separators at the start/end:
765
- if (
766
- !trimEndSeparators ||
767
- (i !== 0 && i !== tableRow.length - 1)
768
- ) {
769
- // Split the current row:
770
- cells.push([]);
771
- }
772
- } else {
773
- if (
774
- node.type === "text" &&
775
- (tableRow[i + 1] == null ||
776
- tableRow[i + 1].type === "tableSeparator")
777
- ) {
778
- node.content = node.content.replace(
779
- TABLE_CELL_END_TRIM,
780
- "",
781
- );
782
- }
783
- // @ts-expect-error - TS2345 - Argument of type 'SingleASTNode' is not assignable to parameter of type 'never'.
784
- cells[cells.length - 1].push(node);
785
- }
786
- });
787
-
788
- return cells;
789
- };
790
-
791
- /**
792
- * @param {string} source
793
- * @param {SimpleMarkdown.Parser} parse
794
- * @param {SimpleMarkdown.State} state
795
- * @param {boolean} trimEndSeparators
796
- * @returns {SimpleMarkdown.ASTNode[][]}
797
- */
798
- var parseTableCells = function (
799
- source: string,
800
- parse: Parser,
801
- state: State,
802
- trimEndSeparators: boolean,
803
- ): Array<Array<ASTNode>> {
804
- var rowsText = source.trim().split("\n");
805
-
806
- return rowsText.map(function (rowText) {
807
- return parseTableRow(rowText, parse, state, trimEndSeparators);
808
- });
809
- };
810
-
811
- /**
812
- * @param {boolean} trimEndSeparators
813
- * @returns {SimpleMarkdown.SingleNodeParseFunction}
814
- */
815
- var parseTable = function (trimEndSeparators: boolean) {
816
- return function (capture: Capture, parse: Parser, state: State) {
817
- state.inline = true;
818
- var header = parseTableRow(
819
- capture[1],
820
- parse,
821
- state,
822
- trimEndSeparators,
823
- );
824
- var align = parseTableAlign(
825
- capture[2],
826
- parse,
827
- state,
828
- trimEndSeparators,
829
- );
830
- var cells = parseTableCells(
831
- capture[3],
832
- parse,
833
- state,
834
- trimEndSeparators,
835
- );
836
- state.inline = false;
837
-
838
- return {
839
- type: "table",
840
- header: header,
841
- align: align,
842
- cells: cells,
843
- };
844
- };
845
- };
846
-
847
- return {
848
- parseTable: parseTable(true),
849
- parseNpTable: parseTable(false),
850
- TABLE_REGEX:
851
- /^ *(\|.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/,
852
- NPTABLE_REGEX:
853
- /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
854
- };
855
- })();
856
-
857
- var LINK_INSIDE = "(?:\\[[^\\]]*\\]|[^\\[\\]]|\\](?=[^\\[]*\\]))*";
858
- var LINK_HREF_AND_TITLE =
859
- "\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*";
860
- var AUTOLINK_MAILTO_CHECK_R = /mailto:/i;
861
-
862
- var parseRef = function (
863
- capture: Capture,
864
- state: State,
865
- refNode: RefNode,
866
- ): RefNode {
867
- var ref = (capture[2] || capture[1]).replace(/\s+/g, " ").toLowerCase();
868
-
869
- // We store information about previously seen defs on
870
- // state._defs (_ to deconflict with client-defined
871
- // state). If the def for this reflink/refimage has
872
- // already been seen, we can use its target/source
873
- // and title here:
874
- if (state._defs && state._defs[ref]) {
875
- var def = state._defs[ref];
876
- // `refNode` can be a link or an image. Both use
877
- // target and title properties.
878
- refNode.target = def.target;
879
- refNode.title = def.title;
880
- }
881
-
882
- // In case we haven't seen our def yet (or if someone
883
- // overwrites that def later on), we add this node
884
- // to the list of ref nodes for that def. Then, when
885
- // we find the def, we can modify this link/image AST
886
- // node :).
887
- // I'm sorry.
888
- state._refs = state._refs || {};
889
- state._refs[ref] = state._refs[ref] || [];
890
- state._refs[ref].push(refNode);
891
-
892
- return refNode;
893
- };
894
-
895
- var currOrder = 0;
896
-
897
- var defaultRules: DefaultRules = {
898
- Array: {
899
- react: function (arr, output, state) {
900
- var oldKey = state.key;
901
- var result: Array<ReactElements> = [];
902
-
903
- // map output over the ast, except group any text
904
- // nodes together into a single string output.
905
- for (var i = 0, key = 0; i < arr.length; i++, key++) {
906
- // `key` is our numerical `state.key`, which we increment for
907
- // every output node, but don't change for joined text nodes.
908
- // (i, however, must change for joined text nodes)
909
- state.key = "" + i;
910
-
911
- var node = arr[i];
912
- if (node.type === "text") {
913
- node = {type: "text", content: node.content};
914
- for (
915
- ;
916
- i + 1 < arr.length && arr[i + 1].type === "text";
917
- i++
918
- ) {
919
- node.content += arr[i + 1].content;
920
- }
921
- }
922
-
923
- result.push(output(node, state));
924
- }
925
-
926
- state.key = oldKey;
927
- return result;
928
- },
929
- html: function (arr, output, state) {
930
- var result = "";
931
-
932
- // map output over the ast, except group any text
933
- // nodes together into a single string output.
934
- for (var i = 0, key = 0; i < arr.length; i++) {
935
- var node = arr[i];
936
- if (node.type === "text") {
937
- node = {type: "text", content: node.content};
938
- for (
939
- ;
940
- i + 1 < arr.length && arr[i + 1].type === "text";
941
- i++
942
- ) {
943
- node.content += arr[i + 1].content;
944
- }
945
- }
946
-
947
- result += output(node, state);
948
- }
949
- return result;
950
- },
951
- },
952
- heading: {
953
- order: currOrder++,
954
- match: blockRegex(/^ *(#{1,6})([^\n]+?)#* *(?:\n *)+\n/),
955
- parse: function (capture, parse, state) {
956
- return {
957
- level: capture[1].length,
958
- content: parseInline(parse, capture[2].trim(), state),
959
- };
960
- },
961
- react: function (node, output, state) {
962
- return reactElement("h" + node.level, state.key, {
963
- children: output(node.content, state),
964
- });
965
- },
966
- html: function (node, output, state) {
967
- return htmlTag("h" + node.level, output(node.content, state));
968
- },
969
- },
970
- nptable: {
971
- order: currOrder++,
972
- match: blockRegex(TABLES.NPTABLE_REGEX),
973
- parse: TABLES.parseNpTable,
974
- react: null,
975
- html: null,
976
- },
977
- lheading: {
978
- order: currOrder++,
979
- match: blockRegex(/^([^\n]+)\n *(=|-){3,} *(?:\n *)+\n/),
980
- parse: function (capture, parse, state) {
981
- return {
982
- type: "heading",
983
- level: capture[2] === "=" ? 1 : 2,
984
- content: parseInline(parse, capture[1], state),
985
- };
986
- },
987
- react: null,
988
- html: null,
989
- },
990
- hr: {
991
- order: currOrder++,
992
- match: blockRegex(/^( *[-*_]){3,} *(?:\n *)+\n/),
993
- parse: ignoreCapture,
994
- react: function (node, output, state) {
995
- return reactElement("hr", state.key, EMPTY_PROPS);
996
- },
997
- html: function (node, output, state) {
998
- return "<hr>";
999
- },
1000
- },
1001
- codeBlock: {
1002
- order: currOrder++,
1003
- match: blockRegex(/^(?: [^\n]+\n*)+(?:\n *)+\n/),
1004
- parse: function (capture, parse, state) {
1005
- var content = capture[0].replace(/^ /gm, "").replace(/\n+$/, "");
1006
- return {
1007
- lang: undefined,
1008
- content: content,
1009
- };
1010
- },
1011
- react: function (node, output, state) {
1012
- var className = node.lang
1013
- ? "markdown-code-" + node.lang
1014
- : undefined;
1015
-
1016
- return reactElement("pre", state.key, {
1017
- children: reactElement("code", null, {
1018
- className: className,
1019
- children: node.content,
1020
- }),
1021
- });
1022
- },
1023
- html: function (node, output, state) {
1024
- var className = node.lang
1025
- ? "markdown-code-" + node.lang
1026
- : undefined;
1027
-
1028
- var codeBlock = htmlTag("code", sanitizeText(node.content), {
1029
- class: className,
1030
- });
1031
- return htmlTag("pre", codeBlock);
1032
- },
1033
- },
1034
- fence: {
1035
- order: currOrder++,
1036
- match: blockRegex(
1037
- /^ *(`{3,}|~{3,}) *(?:(\S+) *)?\n([\s\S]+?)\n?\1 *(?:\n *)+\n/,
1038
- ),
1039
- parse: function (capture, parse, state) {
1040
- return {
1041
- type: "codeBlock",
1042
- lang: capture[2] || undefined,
1043
- content: capture[3],
1044
- };
1045
- },
1046
- react: null,
1047
- html: null,
1048
- },
1049
- blockQuote: {
1050
- order: currOrder++,
1051
- match: blockRegex(/^( *>[^\n]+(\n[^\n]+)*\n*)+\n{2,}/),
1052
- parse: function (capture, parse, state) {
1053
- var content = capture[0].replace(/^ *> ?/gm, "");
1054
- return {
1055
- content: parse(content, state),
1056
- };
1057
- },
1058
- react: function (node, output, state) {
1059
- return reactElement("blockquote", state.key, {
1060
- children: output(node.content, state),
1061
- });
1062
- },
1063
- html: function (node, output, state) {
1064
- return htmlTag("blockquote", output(node.content, state));
1065
- },
1066
- },
1067
- list: {
1068
- order: currOrder++,
1069
- match: function (source, state) {
1070
- // We only want to break into a list if we are at the start of a
1071
- // line. This is to avoid parsing "hi * there" with "* there"
1072
- // becoming a part of a list.
1073
- // You might wonder, "but that's inline, so of course it wouldn't
1074
- // start a list?". You would be correct! Except that some of our
1075
- // lists can be inline, because they might be inside another list,
1076
- // in which case we can parse with inline scope, but need to allow
1077
- // nested lists inside this inline scope.
1078
- var prevCaptureStr =
1079
- state.prevCapture == null ? "" : state.prevCapture[0];
1080
- var isStartOfLineCapture = LIST_LOOKBEHIND_R.exec(prevCaptureStr);
1081
- var isListBlock = state._list || !state.inline;
1082
-
1083
- if (isStartOfLineCapture && isListBlock) {
1084
- source = isStartOfLineCapture[1] + source;
1085
- return LIST_R.exec(source);
1086
- } else {
1087
- return null;
1088
- }
1089
- },
1090
- parse: function (capture, parse, state) {
1091
- var bullet = capture[2];
1092
- var ordered = bullet.length > 1;
1093
- var start = ordered ? +bullet : undefined;
1094
- // @ts-expect-error - TS2322 - Type 'RegExpMatchArray | null' is not assignable to type 'string[]'.
1095
- var items: Array<string> = capture[0]
1096
- .replace(LIST_BLOCK_END_R, "\n")
1097
- .match(LIST_ITEM_R);
1098
-
1099
- // We know this will match here, because of how the regexes are
1100
- // defined
1101
-
1102
- var lastItemWasAParagraph = false;
1103
- var itemContent = items.map(function (item: string, i: number) {
1104
- // We need to see how far indented this item is:
1105
- var prefixCapture = LIST_ITEM_PREFIX_R.exec(item);
1106
- var space = prefixCapture ? prefixCapture[0].length : 0;
1107
- // And then we construct a regex to "unindent" the subsequent
1108
- // lines of the items by that amount:
1109
- var spaceRegex = new RegExp("^ {1," + space + "}", "gm");
1110
-
1111
- // Before processing the item, we need a couple things
1112
- var content = item
1113
- // remove indents on trailing lines:
1114
- .replace(spaceRegex, "")
1115
- // remove the bullet:
1116
- .replace(LIST_ITEM_PREFIX_R, "");
1117
-
1118
- // I'm not sur4 why this is necessary again?
1119
-
1120
- // Handling "loose" lists, like:
1121
- //
1122
- // * this is wrapped in a paragraph
1123
- //
1124
- // * as is this
1125
- //
1126
- // * as is this
1127
- var isLastItem = i === items.length - 1;
1128
- var containsBlocks = content.indexOf("\n\n") !== -1;
1129
-
1130
- // Any element in a list is a block if it contains multiple
1131
- // newlines. The last element in the list can also be a block
1132
- // if the previous item in the list was a block (this is
1133
- // because non-last items in the list can end with \n\n, but
1134
- // the last item can't, so we just "inherit" this property
1135
- // from our previous element).
1136
- var thisItemIsAParagraph =
1137
- containsBlocks || (isLastItem && lastItemWasAParagraph);
1138
- lastItemWasAParagraph = thisItemIsAParagraph;
1139
-
1140
- // backup our state for restoration afterwards. We're going to
1141
- // want to set state._list to true, and state.inline depending
1142
- // on our list's looseness.
1143
- var oldStateInline = state.inline;
1144
- var oldStateList = state._list;
1145
- state._list = true;
1146
-
1147
- // Parse inline if we're in a tight list, or block if we're in
1148
- // a loose list.
1149
- var adjustedContent;
1150
- if (thisItemIsAParagraph) {
1151
- state.inline = false;
1152
- adjustedContent = content.replace(LIST_ITEM_END_R, "\n\n");
1153
- } else {
1154
- state.inline = true;
1155
- adjustedContent = content.replace(LIST_ITEM_END_R, "");
1156
- }
1157
-
1158
- var result = parse(adjustedContent, state);
1159
-
1160
- // Restore our state before returning
1161
- state.inline = oldStateInline;
1162
- state._list = oldStateList;
1163
- return result;
1164
- });
1165
-
1166
- return {
1167
- ordered: ordered,
1168
- start: start,
1169
- items: itemContent,
1170
- };
1171
- },
1172
- react: function (node, output, state) {
1173
- var ListWrapper = node.ordered ? "ol" : "ul";
1174
-
1175
- return reactElement(ListWrapper, state.key, {
1176
- start: node.start,
1177
- children: node.items.map(function (item: ASTNode, i: number) {
1178
- return reactElement("li", "" + i, {
1179
- children: output(item, state),
1180
- });
1181
- }),
1182
- });
1183
- },
1184
- html: function (node, output, state) {
1185
- var listItems = node.items
1186
- .map(function (item: ASTNode) {
1187
- return htmlTag("li", output(item, state));
1188
- })
1189
- .join("");
1190
-
1191
- var listTag = node.ordered ? "ol" : "ul";
1192
- var attributes = {
1193
- start: node.start,
1194
- };
1195
- return htmlTag(listTag, listItems, attributes);
1196
- },
1197
- },
1198
- def: {
1199
- order: currOrder++,
1200
- // TODO(aria): This will match without a blank line before the next
1201
- // block element, which is inconsistent with most of the rest of
1202
- // simple-markdown.
1203
- match: blockRegex(
1204
- /^ *\[([^\]]+)\]: *<?([^\s>]*)>?(?: +["(]([^\n]+)[")])? *\n(?: *\n)*/,
1205
- ),
1206
- parse: function (capture, parse, state) {
1207
- var def = capture[1].replace(/\s+/g, " ").toLowerCase();
1208
- var target = capture[2];
1209
- var title = capture[3];
1210
-
1211
- // Look for previous links/images using this def
1212
- // If any links/images using this def have already been declared,
1213
- // they will have added themselves to the state._refs[def] list
1214
- // (_ to deconflict with client-defined state). We look through
1215
- // that list of reflinks for this def, and modify those AST nodes
1216
- // with our newly found information now.
1217
- // Sorry :(.
1218
- if (state._refs && state._refs[def]) {
1219
- // `refNode` can be a link or an image
1220
- state._refs[def].forEach(function (refNode: RefNode) {
1221
- refNode.target = target;
1222
- refNode.title = title;
1223
- });
1224
- }
1225
-
1226
- // Add this def to our map of defs for any future links/images
1227
- // In case we haven't found any or all of the refs referring to
1228
- // this def yet, we add our def to the table of known defs, so
1229
- // that future reflinks can modify themselves appropriately with
1230
- // this information.
1231
- state._defs = state._defs || {};
1232
- state._defs[def] = {
1233
- target: target,
1234
- title: title,
1235
- };
1236
-
1237
- // return the relevant parsed information
1238
- // for debugging only.
1239
- return {
1240
- def: def,
1241
- target: target,
1242
- title: title,
1243
- };
1244
- },
1245
- react: function () {
1246
- return null;
1247
- },
1248
- html: function () {
1249
- return "";
1250
- },
1251
- },
1252
- table: {
1253
- order: currOrder++,
1254
- match: blockRegex(TABLES.TABLE_REGEX),
1255
- parse: TABLES.parseTable,
1256
- react: function (node, output, state) {
1257
- var getStyle = function (colIndex: number): {
1258
- [attr: string]: Attr;
1259
- } {
1260
- return node.align[colIndex] == null
1261
- ? {}
1262
- : {
1263
- textAlign: node.align[colIndex],
1264
- };
1265
- };
1266
-
1267
- var headers = node.header.map(function (
1268
- content: ASTNode,
1269
- i: number,
1270
- ) {
1271
- return reactElement("th", "" + i, {
1272
- style: getStyle(i),
1273
- scope: "col",
1274
- children: output(content, state),
1275
- });
1276
- });
1277
-
1278
- var rows = node.cells.map(function (
1279
- row: Array<ASTNode>,
1280
- r: number,
1281
- ) {
1282
- return reactElement("tr", "" + r, {
1283
- children: row.map(function (content: ASTNode, c: number) {
1284
- return reactElement("td", "" + c, {
1285
- style: getStyle(c),
1286
- children: output(content, state),
1287
- });
1288
- }),
1289
- });
1290
- });
1291
-
1292
- return reactElement("table", state.key, {
1293
- children: [
1294
- reactElement("thead", "thead", {
1295
- children: reactElement("tr", null, {
1296
- children: headers,
1297
- }),
1298
- }),
1299
- reactElement("tbody", "tbody", {
1300
- children: rows,
1301
- }),
1302
- ],
1303
- });
1304
- },
1305
- html: function (node, output, state) {
1306
- var getStyle = function (colIndex: number): string {
1307
- return node.align[colIndex] == null
1308
- ? ""
1309
- : "text-align:" + node.align[colIndex] + ";";
1310
- };
1311
-
1312
- var headers = node.header
1313
- .map(function (content: ASTNode, i: number) {
1314
- return htmlTag("th", output(content, state), {
1315
- style: getStyle(i),
1316
- scope: "col",
1317
- });
1318
- })
1319
- .join("");
1320
-
1321
- var rows = node.cells
1322
- .map(function (row: Array<ASTNode>) {
1323
- var cols = row
1324
- .map(function (content: ASTNode, c: number) {
1325
- return htmlTag("td", output(content, state), {
1326
- style: getStyle(c),
1327
- });
1328
- })
1329
- .join("");
1330
-
1331
- return htmlTag("tr", cols);
1332
- })
1333
- .join("");
1334
-
1335
- var thead = htmlTag("thead", htmlTag("tr", headers));
1336
- var tbody = htmlTag("tbody", rows);
1337
-
1338
- return htmlTag("table", thead + tbody);
1339
- },
1340
- },
1341
- newline: {
1342
- order: currOrder++,
1343
- match: blockRegex(/^(?:\n *)*\n/),
1344
- parse: ignoreCapture,
1345
- react: function (node, output, state) {
1346
- return "\n";
1347
- },
1348
- html: function (node, output, state) {
1349
- return "\n";
1350
- },
1351
- },
1352
- paragraph: {
1353
- order: currOrder++,
1354
- match: blockRegex(/^((?:[^\n]|\n(?! *\n))+)(?:\n *)+\n/),
1355
- parse: parseCaptureInline,
1356
- react: function (node, output, state) {
1357
- return reactElement("div", state.key, {
1358
- className: "paragraph",
1359
- children: output(node.content, state),
1360
- });
1361
- },
1362
- html: function (node, output, state) {
1363
- var attributes = {
1364
- class: "paragraph",
1365
- };
1366
- return htmlTag("div", output(node.content, state), attributes);
1367
- },
1368
- },
1369
- escape: {
1370
- order: currOrder++,
1371
- // We don't allow escaping numbers, letters, or spaces here so that
1372
- // backslashes used in plain text still get rendered. But allowing
1373
- // escaping anything else provides a very flexible escape mechanism,
1374
- // regardless of how this grammar is extended.
1375
- match: inlineRegex(/^\\([^0-9A-Za-z\s])/),
1376
- parse: function (capture, parse, state) {
1377
- return {
1378
- type: "text",
1379
- content: capture[1],
1380
- };
1381
- },
1382
- react: null,
1383
- html: null,
1384
- },
1385
- tableSeparator: {
1386
- order: currOrder++,
1387
- match: function (source, state) {
1388
- if (!state.inTable) {
1389
- return null;
1390
- }
1391
- return /^ *\| */.exec(source);
1392
- },
1393
- parse: function () {
1394
- return {type: "tableSeparator"};
1395
- },
1396
- // These shouldn't be reached, but in case they are, be reasonable:
1397
- react: function () {
1398
- return " | ";
1399
- },
1400
- html: function () {
1401
- return " &vert; ";
1402
- },
1403
- },
1404
- autolink: {
1405
- order: currOrder++,
1406
- match: inlineRegex(/^<([^: >]+:\/[^ >]+)>/),
1407
- parse: function (capture, parse, state) {
1408
- return {
1409
- type: "link",
1410
- content: [
1411
- {
1412
- type: "text",
1413
- content: capture[1],
1414
- },
1415
- ],
1416
- target: capture[1],
1417
- };
1418
- },
1419
- react: null,
1420
- html: null,
1421
- },
1422
- mailto: {
1423
- order: currOrder++,
1424
- match: inlineRegex(/^<([^ >]+@[^ >]+)>/),
1425
- parse: function (capture, parse, state) {
1426
- var address = capture[1];
1427
- var target = capture[1];
1428
-
1429
- // Check for a `mailto:` already existing in the link:
1430
- if (!AUTOLINK_MAILTO_CHECK_R.test(target)) {
1431
- target = "mailto:" + target;
1432
- }
1433
-
1434
- return {
1435
- type: "link",
1436
- content: [
1437
- {
1438
- type: "text",
1439
- content: address,
1440
- },
1441
- ],
1442
- target: target,
1443
- };
1444
- },
1445
- react: null,
1446
- html: null,
1447
- },
1448
- url: {
1449
- order: currOrder++,
1450
- match: inlineRegex(/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/),
1451
- parse: function (capture, parse, state) {
1452
- return {
1453
- type: "link",
1454
- content: [
1455
- {
1456
- type: "text",
1457
- content: capture[1],
1458
- },
1459
- ],
1460
- target: capture[1],
1461
- title: undefined,
1462
- };
1463
- },
1464
- react: null,
1465
- html: null,
1466
- },
1467
- link: {
1468
- order: currOrder++,
1469
- match: inlineRegex(
1470
- new RegExp(
1471
- "^\\[(" + LINK_INSIDE + ")\\]\\(" + LINK_HREF_AND_TITLE + "\\)",
1472
- ),
1473
- ),
1474
- parse: function (capture, parse, state) {
1475
- var link = {
1476
- content: parse(capture[1], state),
1477
- target: unescapeUrl(capture[2]),
1478
- title: capture[3],
1479
- };
1480
- return link;
1481
- },
1482
- react: function (node, output, state) {
1483
- return reactElement("a", state.key, {
1484
- href: sanitizeUrl(node.target),
1485
- title: node.title,
1486
- children: output(node.content, state),
1487
- });
1488
- },
1489
- html: function (node, output, state) {
1490
- var attributes = {
1491
- href: sanitizeUrl(node.target),
1492
- title: node.title,
1493
- };
1494
-
1495
- return htmlTag("a", output(node.content, state), attributes);
1496
- },
1497
- },
1498
- image: {
1499
- order: currOrder++,
1500
- match: inlineRegex(
1501
- new RegExp(
1502
- "^!\\[(" +
1503
- LINK_INSIDE +
1504
- ")\\]\\(" +
1505
- LINK_HREF_AND_TITLE +
1506
- "\\)",
1507
- ),
1508
- ),
1509
- parse: function (capture, parse, state) {
1510
- var image = {
1511
- alt: capture[1],
1512
- target: unescapeUrl(capture[2]),
1513
- title: capture[3],
1514
- };
1515
- return image;
1516
- },
1517
- react: function (node, output, state) {
1518
- return reactElement("img", state.key, {
1519
- src: sanitizeUrl(node.target),
1520
- alt: node.alt,
1521
- title: node.title,
1522
- });
1523
- },
1524
- html: function (node, output, state) {
1525
- var attributes = {
1526
- src: sanitizeUrl(node.target),
1527
- alt: node.alt,
1528
- title: node.title,
1529
- };
1530
-
1531
- return htmlTag("img", "", attributes, false);
1532
- },
1533
- },
1534
- reflink: {
1535
- order: currOrder++,
1536
- match: inlineRegex(
1537
- new RegExp(
1538
- // The first [part] of the link
1539
- "^\\[(" +
1540
- LINK_INSIDE +
1541
- ")\\]" +
1542
- // The [ref] target of the link
1543
- "\\s*\\[([^\\]]*)\\]",
1544
- ),
1545
- ),
1546
- parse: function (capture, parse, state) {
1547
- return parseRef(capture, state, {
1548
- type: "link",
1549
- content: parse(capture[1], state),
1550
- });
1551
- },
1552
- react: null,
1553
- html: null,
1554
- },
1555
- refimage: {
1556
- order: currOrder++,
1557
- match: inlineRegex(
1558
- new RegExp(
1559
- // The first [part] of the link
1560
- "^!\\[(" +
1561
- LINK_INSIDE +
1562
- ")\\]" +
1563
- // The [ref] target of the link
1564
- "\\s*\\[([^\\]]*)\\]",
1565
- ),
1566
- ),
1567
- parse: function (capture, parse, state) {
1568
- return parseRef(capture, state, {
1569
- type: "image",
1570
- alt: capture[1],
1571
- });
1572
- },
1573
- react: null,
1574
- html: null,
1575
- },
1576
- em: {
1577
- order: currOrder /* same as strong/u */,
1578
- match: inlineRegex(
1579
- new RegExp(
1580
- // only match _s surrounding words.
1581
- "^\\b_" +
1582
- "((?:__|\\\\[\\s\\S]|[^\\\\_])+?)_" +
1583
- "\\b" +
1584
- // Or match *s:
1585
- "|" +
1586
- // Only match *s that are followed by a non-space:
1587
- "^\\*(?=\\S)(" +
1588
- // Match at least one of:
1589
- "(?:" +
1590
- // - `**`: so that bolds inside italics don't close the
1591
- // italics
1592
- "\\*\\*|" +
1593
- // - escape sequence: so escaped *s don't close us
1594
- "\\\\[\\s\\S]|" +
1595
- // - whitespace: followed by a non-* (we don't
1596
- // want ' *' to close an italics--it might
1597
- // start a list)
1598
- "\\s+(?:\\\\[\\s\\S]|[^\\s\\*\\\\]|\\*\\*)|" +
1599
- // - non-whitespace, non-*, non-backslash characters
1600
- "[^\\s\\*\\\\]" +
1601
- ")+?" +
1602
- // followed by a non-space, non-* then *
1603
- ")\\*(?!\\*)",
1604
- ),
1605
- ),
1606
- quality: function (capture) {
1607
- // precedence by length, `em` wins ties:
1608
- return capture[0].length + 0.2;
1609
- },
1610
- parse: function (capture, parse, state) {
1611
- return {
1612
- content: parse(capture[2] || capture[1], state),
1613
- };
1614
- },
1615
- react: function (node, output, state) {
1616
- return reactElement("em", state.key, {
1617
- children: output(node.content, state),
1618
- });
1619
- },
1620
- html: function (node, output, state) {
1621
- return htmlTag("em", output(node.content, state));
1622
- },
1623
- },
1624
- strong: {
1625
- order: currOrder /* same as em */,
1626
- match: inlineRegex(/^\*\*((?:\\[\s\S]|[^\\])+?)\*\*(?!\*)/),
1627
- quality: function (capture) {
1628
- // precedence by length, wins ties vs `u`:
1629
- return capture[0].length + 0.1;
1630
- },
1631
- parse: parseCaptureInline,
1632
- react: function (node, output, state) {
1633
- return reactElement("strong", state.key, {
1634
- children: output(node.content, state),
1635
- });
1636
- },
1637
- html: function (node, output, state) {
1638
- return htmlTag("strong", output(node.content, state));
1639
- },
1640
- },
1641
- u: {
1642
- order: currOrder++ /* same as em&strong; increment for next rule */,
1643
- match: inlineRegex(/^__((?:\\[\s\S]|[^\\])+?)__(?!_)/),
1644
- quality: function (capture) {
1645
- // precedence by length, loses all ties
1646
- return capture[0].length;
1647
- },
1648
- parse: parseCaptureInline,
1649
- react: function (node, output, state) {
1650
- return reactElement("u", state.key, {
1651
- children: output(node.content, state),
1652
- });
1653
- },
1654
- html: function (node, output, state) {
1655
- return htmlTag("u", output(node.content, state));
1656
- },
1657
- },
1658
- del: {
1659
- order: currOrder++,
1660
- match: inlineRegex(
1661
- /^~~(?=\S)((?:\\[\s\S]|~(?!~)|[^\s~\\]|\s(?!~~))+?)~~/,
1662
- ),
1663
- parse: parseCaptureInline,
1664
- react: function (node, output, state) {
1665
- return reactElement("del", state.key, {
1666
- children: output(node.content, state),
1667
- });
1668
- },
1669
- html: function (node, output, state) {
1670
- return htmlTag("del", output(node.content, state));
1671
- },
1672
- },
1673
- inlineCode: {
1674
- order: currOrder++,
1675
- match: inlineRegex(/^(`+)([\s\S]*?[^`])\1(?!`)/),
1676
- parse: function (capture, parse, state) {
1677
- return {
1678
- content: capture[2].replace(
1679
- INLINE_CODE_ESCAPE_BACKTICKS_R,
1680
- "$1",
1681
- ),
1682
- };
1683
- },
1684
- react: function (node, output, state) {
1685
- return reactElement("code", state.key, {
1686
- children: node.content,
1687
- });
1688
- },
1689
- html: function (node, output, state) {
1690
- return htmlTag("code", sanitizeText(node.content));
1691
- },
1692
- },
1693
- br: {
1694
- order: currOrder++,
1695
- match: anyScopeRegex(/^ {2,}\n/),
1696
- parse: ignoreCapture,
1697
- react: function (node, output, state) {
1698
- return reactElement("br", state.key, EMPTY_PROPS);
1699
- },
1700
- html: function (node, output, state) {
1701
- return "<br>";
1702
- },
1703
- },
1704
- text: {
1705
- order: currOrder++,
1706
- // Here we look for anything followed by non-symbols,
1707
- // double newlines, or double-space-newlines
1708
- // We break on any symbol characters so that this grammar
1709
- // is easy to extend without needing to modify this regex
1710
- match: anyScopeRegex(
1711
- /^[\s\S]+?(?=[^0-9A-Za-z\s\u00c0-\uffff]|\n\n| {2,}\n|\w+:\S|$)/,
1712
- ),
1713
- parse: function (capture, parse, state) {
1714
- return {
1715
- content: capture[0],
1716
- };
1717
- },
1718
- react: function (node, output, state) {
1719
- return node.content;
1720
- },
1721
- html: function (node, output, state) {
1722
- return sanitizeText(node.content);
1723
- },
1724
- },
1725
- };
1726
-
1727
- /** (deprecated) */
1728
- var ruleOutput = function <Rule>(
1729
- rules: OutputRules<Rule>,
1730
- property: keyof Rule,
1731
- ) {
1732
- if (!property && typeof console !== "undefined") {
1733
- console.warn(
1734
- "simple-markdown ruleOutput should take 'react' or " +
1735
- "'html' as the second argument.",
1736
- );
1737
- }
1738
-
1739
- var nestedRuleOutput = function (
1740
- ast: SingleASTNode,
1741
- outputFunc: Output<any>,
1742
- state: State,
1743
- ) {
1744
- // @ts-expect-error - TS2349 - This expression is not callable.
1745
- // Type 'unknown' has no call signatures.
1746
- return rules[ast.type][property](ast, outputFunc, state);
1747
- };
1748
- return nestedRuleOutput;
1749
- };
1750
-
1751
- /** (deprecated)
1752
- */
1753
- var reactFor = function (outputFunc: ReactNodeOutput): ReactOutput {
1754
- var nestedOutput: ReactOutput = function (ast, state) {
1755
- state = state || {};
1756
- if (Array.isArray(ast)) {
1757
- var oldKey = state.key;
1758
- var result: Array<ReactElements> = [];
1759
-
1760
- // map nestedOutput over the ast, except group any text
1761
- // nodes together into a single string output.
1762
- var lastResult = null;
1763
- for (var i = 0; i < ast.length; i++) {
1764
- state.key = "" + i;
1765
- var nodeOut = nestedOutput(ast[i], state);
1766
- if (
1767
- typeof nodeOut === "string" &&
1768
- typeof lastResult === "string"
1769
- ) {
1770
- // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'null'.
1771
- lastResult = lastResult + nodeOut;
1772
- result[result.length - 1] = lastResult;
1773
- } else {
1774
- result.push(nodeOut);
1775
- // @ts-expect-error - TS2322 - Type 'ReactNode' is not assignable to type 'null'.
1776
- lastResult = nodeOut;
1777
- }
1778
- }
1779
-
1780
- state.key = oldKey;
1781
- return result;
1782
- } else {
1783
- return outputFunc(ast, nestedOutput, state);
1784
- }
1785
- };
1786
- return nestedOutput;
1787
- };
1788
-
1789
- /** (deprecated)
1790
- */
1791
- var htmlFor = function (outputFunc: HtmlNodeOutput): HtmlOutput {
1792
- var nestedOutput: HtmlOutput = function (ast, state) {
1793
- state = state || {};
1794
- if (Array.isArray(ast)) {
1795
- return ast
1796
- .map(function (node) {
1797
- return nestedOutput(node, state);
1798
- })
1799
- .join("");
1800
- } else {
1801
- return outputFunc(ast, nestedOutput, state);
1802
- }
1803
- };
1804
- return nestedOutput;
1805
- };
1806
-
1807
- var outputFor = function <Rule>(
1808
- rules: OutputRules<Rule>,
1809
- property: keyof Rule,
1810
- defaultState: State | null = {},
1811
- ) {
1812
- if (!property) {
1813
- throw new Error(
1814
- "simple-markdown: outputFor: `property` must be " +
1815
- "defined. " +
1816
- "if you just upgraded, you probably need to replace `outputFor` " +
1817
- "with `reactFor`",
1818
- );
1819
- }
1820
-
1821
- var latestState: State;
1822
- var arrayRule: ArrayRule = rules.Array || defaultRules.Array;
1823
-
1824
- // Tricks to convince tsc that this var is not null:
1825
- // @ts-expect-error - TS2538 - Type 'symbol' cannot be used as an index type.
1826
- var arrayRuleCheck = arrayRule[property];
1827
- if (!arrayRuleCheck) {
1828
- throw new Error(
1829
- "simple-markdown: outputFor: to join nodes of type `" +
1830
- // @ts-expect-error - TS2469 - The '+' operator cannot be applied to type 'symbol'.
1831
- property +
1832
- "` you must provide an `Array:` joiner rule with that type, " +
1833
- "Please see the docs for details on specifying an Array rule.",
1834
- );
1835
- }
1836
- var arrayRuleOutput = arrayRuleCheck;
1837
-
1838
- var nestedOutput: Output<any> = function (ast, state) {
1839
- state = state || latestState;
1840
- latestState = state;
1841
- if (Array.isArray(ast)) {
1842
- return arrayRuleOutput(ast, nestedOutput, state);
1843
- } else {
1844
- // @ts-expect-error - TS2349 - This expression is not callable.
1845
- // Type 'unknown' has no call signatures.
1846
- return rules[ast.type][property](ast, nestedOutput, state);
1847
- }
1848
- };
1849
-
1850
- var outerOutput: Output<any> = function (ast, state) {
1851
- latestState = populateInitialState(state, defaultState);
1852
- return nestedOutput(ast, latestState);
1853
- };
1854
- return outerOutput;
1855
- };
1856
-
1857
- // @ts-expect-error - TS2345 - Argument of type 'DefaultRules' is not assignable to parameter of type 'ParserRules'.
1858
- var defaultRawParse = parserFor(defaultRules);
1859
-
1860
- var defaultBlockParse = function (
1861
- source: string,
1862
- state?: State | null,
1863
- ): Array<SingleASTNode> {
1864
- state = state || {};
1865
- state.inline = false;
1866
- return defaultRawParse(source, state);
1867
- };
1868
-
1869
- var defaultInlineParse = function (
1870
- source: string,
1871
- state?: State | null,
1872
- ): Array<SingleASTNode> {
1873
- state = state || {};
1874
- state.inline = true;
1875
- return defaultRawParse(source, state);
1876
- };
1877
-
1878
- var defaultImplicitParse = function (
1879
- source: string,
1880
- state?: State | null,
1881
- ): Array<SingleASTNode> {
1882
- var isBlock = BLOCK_END_R.test(source);
1883
- state = state || {};
1884
- state.inline = !isBlock;
1885
- return defaultRawParse(source, state);
1886
- };
1887
-
1888
- var defaultReactOutput: ReactOutput = outputFor(defaultRules, "react");
1889
- var defaultHtmlOutput: HtmlOutput = outputFor(defaultRules, "html");
1890
-
1891
- var markdownToReact = function (
1892
- source: string,
1893
- state?: State | null,
1894
- ): ReactElements {
1895
- return defaultReactOutput(defaultBlockParse(source, state), state);
1896
- };
1897
-
1898
- var markdownToHtml = function (source: string, state?: State | null): string {
1899
- return defaultHtmlOutput(defaultBlockParse(source, state), state);
1900
- };
1901
-
1902
- // TODO: This needs definition
1903
- type Props = any;
1904
- var ReactMarkdown = function (props): React.ReactElement {
1905
- var divProps: Record<string, any> = {};
1906
-
1907
- for (var prop in props) {
1908
- if (
1909
- prop !== "source" &&
1910
- Object.prototype.hasOwnProperty.call(props, prop)
1911
- ) {
1912
- divProps[prop] = props[prop];
1913
- }
1914
- }
1915
- divProps.children = markdownToReact(props.source);
1916
-
1917
- return reactElement("div", null, divProps);
1918
- };
1919
-
1920
- type Exports = {
1921
- readonly defaultRules: DefaultRules;
1922
- readonly parserFor: (
1923
- rules: ParserRules,
1924
- defaultState?: State | null | undefined,
1925
- ) => Parser;
1926
- readonly outputFor: <Rule>(
1927
- rules: OutputRules<Rule>,
1928
- param: keyof Rule,
1929
- defaultState?: State | null | undefined,
1930
- ) => Output<any>;
1931
- readonly ruleOutput: <Rule>(
1932
- rules: OutputRules<Rule>,
1933
- param: keyof Rule,
1934
- ) => NodeOutput<any>;
1935
- readonly reactFor: (arg1: ReactNodeOutput) => ReactOutput;
1936
- readonly htmlFor: (arg1: HtmlNodeOutput) => HtmlOutput;
1937
- readonly inlineRegex: (regex: RegExp) => MatchFunction;
1938
- readonly blockRegex: (regex: RegExp) => MatchFunction;
1939
- readonly anyScopeRegex: (regex: RegExp) => MatchFunction;
1940
- readonly parseInline: (
1941
- parse: Parser,
1942
- content: string,
1943
- state: State,
1944
- ) => ASTNode;
1945
- readonly parseBlock: (
1946
- parse: Parser,
1947
- content: string,
1948
- state: State,
1949
- ) => ASTNode;
1950
- readonly markdownToReact: (
1951
- source: string,
1952
- state?: State | null | undefined,
1953
- ) => ReactElements;
1954
- readonly markdownToHtml: (
1955
- source: string,
1956
- state?: State | null | undefined,
1957
- ) => string;
1958
- readonly ReactMarkdown: (props: {
1959
- source: string;
1960
- [key: string]: any;
1961
- }) => ReactElement;
1962
- readonly defaultRawParse: (
1963
- source: string,
1964
- state?: State | null | undefined,
1965
- ) => Array<SingleASTNode>;
1966
- readonly defaultBlockParse: (
1967
- source: string,
1968
- state?: State | null | undefined,
1969
- ) => Array<SingleASTNode>;
1970
- readonly defaultInlineParse: (
1971
- source: string,
1972
- state?: State | null | undefined,
1973
- ) => Array<SingleASTNode>;
1974
- readonly defaultImplicitParse: (
1975
- source: string,
1976
- state?: State | null | undefined,
1977
- ) => Array<SingleASTNode>;
1978
- readonly defaultReactOutput: ReactOutput;
1979
- readonly defaultHtmlOutput: HtmlOutput;
1980
- readonly preprocess: (source: string) => string;
1981
- readonly sanitizeText: (text: Attr) => string;
1982
- readonly sanitizeUrl: (
1983
- url?: string | null | undefined,
1984
- ) => string | null | undefined;
1985
- readonly unescapeUrl: (url: string) => string;
1986
- readonly htmlTag: (
1987
- tagName: string,
1988
- content: string,
1989
- attributes?:
1990
- | Partial<Record<any, Attr | null | undefined>>
1991
- | null
1992
- | undefined,
1993
- isClosed?: boolean | null | undefined,
1994
- ) => string;
1995
- readonly reactElement: (
1996
- type: string,
1997
- key: string | null,
1998
- props: {
1999
- [key: string]: any;
2000
- },
2001
- ) => ReactElement;
2002
- /**
2003
- * defaultParse is deprecated, please use `defaultImplicitParse`
2004
- * @deprecated
2005
- */
2006
- readonly defaultParse: (...args: any[]) => any;
2007
- /**
2008
- * defaultOutput is deprecated, please use `defaultReactOutput`
2009
- * @deprecated
2010
- */
2011
- readonly defaultOutput: (...args: any[]) => any;
2012
- };
2013
-
2014
- export type {
2015
- // Hopefully you shouldn't have to use these, but they're here if you need!
2016
- // Top-level API:
2017
- State,
2018
- Parser,
2019
- Output,
2020
- ReactOutput,
2021
- HtmlOutput,
2022
- // Most of the following types should be considered experimental and
2023
- // subject to change or change names. Again, they shouldn't be necessary,
2024
- // but if they are I'd love to hear how so I can better support them!
2025
-
2026
- // Individual Rule fields:
2027
- Capture,
2028
- MatchFunction,
2029
- ParseFunction,
2030
- NodeOutput,
2031
- ArrayNodeOutput,
2032
- ReactNodeOutput,
2033
- // Single rules:
2034
- ParserRule,
2035
- ReactOutputRule,
2036
- HtmlOutputRule,
2037
- // Sets of rules:
2038
- ParserRules,
2039
- OutputRules,
2040
- Rules,
2041
- ReactRules,
2042
- HtmlRules,
2043
- SingleASTNode,
2044
- };
2045
-
2046
- var SimpleMarkdown: Exports = {
2047
- defaultRules: defaultRules,
2048
- parserFor: parserFor,
2049
- outputFor: outputFor,
2050
-
2051
- inlineRegex: inlineRegex,
2052
- blockRegex: blockRegex,
2053
- anyScopeRegex: anyScopeRegex,
2054
- parseInline: parseInline,
2055
- parseBlock: parseBlock,
2056
-
2057
- // default wrappers:
2058
- markdownToReact: markdownToReact,
2059
- markdownToHtml: markdownToHtml,
2060
- ReactMarkdown: ReactMarkdown,
2061
-
2062
- defaultBlockParse: defaultBlockParse,
2063
- defaultInlineParse: defaultInlineParse,
2064
- defaultImplicitParse: defaultImplicitParse,
2065
-
2066
- defaultReactOutput: defaultReactOutput,
2067
- defaultHtmlOutput: defaultHtmlOutput,
2068
-
2069
- preprocess: preprocess,
2070
- sanitizeText: sanitizeText,
2071
- sanitizeUrl: sanitizeUrl,
2072
- unescapeUrl: unescapeUrl,
2073
- htmlTag: htmlTag,
2074
- reactElement: reactElement,
2075
-
2076
- // deprecated:
2077
- defaultRawParse: defaultRawParse,
2078
- ruleOutput: ruleOutput,
2079
- reactFor: reactFor,
2080
- htmlFor: htmlFor,
2081
-
2082
- defaultParse: function (...args) {
2083
- if (typeof console !== "undefined") {
2084
- console.warn(
2085
- "defaultParse is deprecated, please use `defaultImplicitParse`",
2086
- );
2087
- }
2088
- return defaultImplicitParse.apply(null, args);
2089
- },
2090
- defaultOutput: function (...args) {
2091
- if (typeof console !== "undefined") {
2092
- console.warn(
2093
- "defaultOutput is deprecated, please use `defaultReactOutput`",
2094
- );
2095
- }
2096
- return defaultReactOutput.apply(null, args);
2097
- },
2098
- };
2099
-
2100
- export default SimpleMarkdown;