fix: clean up rules so they can be typed (#3087)

BREAKING CHANGE: Lexer.rules object has been changed so it can be properly types. Some intermediate rules have been removed.
This commit is contained in:
Tony Brix
2023-11-28 20:56:27 -07:00
committed by GitHub
parent edae309505
commit 175fc0c321
7 changed files with 315 additions and 360 deletions
+23 -13
View File
@@ -142,11 +142,14 @@ export class Marked {
if (pack.renderer) { if (pack.renderer) {
const renderer = this.defaults.renderer || new _Renderer(this.defaults); const renderer = this.defaults.renderer || new _Renderer(this.defaults);
for (const prop in pack.renderer) { for (const prop in pack.renderer) {
const rendererFunc = pack.renderer[prop as keyof MarkedExtension['renderer']] as GenericRendererFunction; if (!(prop in renderer) || prop === 'options') {
const rendererKey = prop as keyof _Renderer; throw new Error(`renderer '${prop}' does not exist`);
const prevRenderer = renderer[rendererKey] as GenericRendererFunction; }
const rendererProp = prop as Exclude<keyof _Renderer, 'options'>;
const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;
const prevRenderer = renderer[rendererProp] as GenericRendererFunction;
// Replace renderer with func to run extension, but fall back if false // Replace renderer with func to run extension, but fall back if false
renderer[rendererKey] = (...args: unknown[]) => { renderer[rendererProp] = (...args: unknown[]) => {
let ret = rendererFunc.apply(renderer, args); let ret = rendererFunc.apply(renderer, args);
if (ret === false) { if (ret === false) {
ret = prevRenderer.apply(renderer, args); ret = prevRenderer.apply(renderer, args);
@@ -159,11 +162,15 @@ export class Marked {
if (pack.tokenizer) { if (pack.tokenizer) {
const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults); const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
for (const prop in pack.tokenizer) { for (const prop in pack.tokenizer) {
const tokenizerFunc = pack.tokenizer[prop as keyof MarkedExtension['tokenizer']] as UnknownFunction; if (!(prop in tokenizer) || ['options', 'rules', 'lexer'].includes(prop)) {
const tokenizerKey = prop as keyof _Tokenizer; throw new Error(`tokenizer '${prop}' does not exist`);
const prevTokenizer = tokenizer[tokenizerKey] as UnknownFunction; }
const tokenizerProp = prop as Exclude<keyof _Tokenizer, 'options' | 'rules' | 'lexer'>;
const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;
const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;
// Replace tokenizer with func to run extension, but fall back if false // Replace tokenizer with func to run extension, but fall back if false
tokenizer[tokenizerKey] = (...args: unknown[]) => { // @ts-expect-error cannot type tokenizer function dynamically
tokenizer[tokenizerProp] = (...args: unknown[]) => {
let ret = tokenizerFunc.apply(tokenizer, args); let ret = tokenizerFunc.apply(tokenizer, args);
if (ret === false) { if (ret === false) {
ret = prevTokenizer.apply(tokenizer, args); ret = prevTokenizer.apply(tokenizer, args);
@@ -178,11 +185,14 @@ export class Marked {
if (pack.hooks) { if (pack.hooks) {
const hooks = this.defaults.hooks || new _Hooks(); const hooks = this.defaults.hooks || new _Hooks();
for (const prop in pack.hooks) { for (const prop in pack.hooks) {
const hooksFunc = pack.hooks[prop as keyof MarkedExtension['hooks']] as UnknownFunction; if (!(prop in hooks) || prop === 'options') {
const hooksKey = prop as keyof _Hooks; throw new Error(`hook '${prop}' does not exist`);
const prevHook = hooks[hooksKey] as UnknownFunction; }
const hooksProp = prop as Exclude<keyof _Hooks, 'options'>;
const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;
const prevHook = hooks[hooksProp] as UnknownFunction;
if (_Hooks.passThroughHooks.has(prop)) { if (_Hooks.passThroughHooks.has(prop)) {
hooks[hooksKey as 'preprocess' | 'postprocess'] = (arg: string | undefined) => { hooks[hooksProp] = (arg: string | undefined) => {
if (this.defaults.async) { if (this.defaults.async) {
return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => { return Promise.resolve(hooksFunc.call(hooks, arg)).then(ret => {
return prevHook.call(hooks, ret) as string; return prevHook.call(hooks, ret) as string;
@@ -193,7 +203,7 @@ export class Marked {
return prevHook.call(hooks, ret) as string; return prevHook.call(hooks, ret) as string;
}; };
} else { } else {
hooks[hooksKey] = (...args: unknown[]) => { hooks[hooksProp] = (...args: unknown[]) => {
let ret = hooksFunc.apply(hooks, args); let ret = hooksFunc.apply(hooks, args);
if (ret === false) { if (ret === false) {
ret = prevHook.apply(hooks, args); ret = prevHook.apply(hooks, args);
+2 -4
View File
@@ -3,7 +3,6 @@ import { _defaults } from './defaults.ts';
import { block, inline } from './rules.ts'; import { block, inline } from './rules.ts';
import type { Token, TokensList, Tokens } from './Tokens.ts'; import type { Token, TokensList, Tokens } from './Tokens.ts';
import type { MarkedOptions, TokenizerExtension } from './MarkedOptions.ts'; import type { MarkedOptions, TokenizerExtension } from './MarkedOptions.ts';
import type { Rules } from './rules.ts';
/** /**
* Block Lexer * Block Lexer
@@ -22,8 +21,7 @@ export class _Lexer {
constructor(options?: MarkedOptions) { constructor(options?: MarkedOptions) {
// TokenList cannot be created in one go // TokenList cannot be created in one go
// @ts-expect-error this.tokens = [] as unknown as TokensList;
this.tokens = [];
this.tokens.links = Object.create(null); this.tokens.links = Object.create(null);
this.options = options || _defaults; this.options = options || _defaults;
this.options.tokenizer = this.options.tokenizer || new _Tokenizer(); this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
@@ -59,7 +57,7 @@ export class _Lexer {
/** /**
* Expose Rules * Expose Rules
*/ */
static get rules(): Rules { static get rules() {
return { return {
block, block,
inline inline
+65 -71
View File
@@ -5,6 +5,7 @@ import {
escape, escape,
findClosingBracket findClosingBracket
} from './helpers.ts'; } from './helpers.ts';
import type { Rules } from './rules.ts';
import type { _Lexer } from './Lexer.ts'; import type { _Lexer } from './Lexer.ts';
import type { Links, Tokens } from './Tokens.ts'; import type { Links, Tokens } from './Tokens.ts';
import type { MarkedOptions } from './MarkedOptions.ts'; import type { MarkedOptions } from './MarkedOptions.ts';
@@ -69,9 +70,8 @@ function indentCodeCompensation(raw: string, text: string) {
*/ */
export class _Tokenizer { export class _Tokenizer {
options: MarkedOptions; options: MarkedOptions;
// TODO: Fix this rules type rules!: Rules; // set by the lexer
rules: any; lexer!: _Lexer; // set by the lexer
lexer!: _Lexer;
constructor(options?: MarkedOptions) { constructor(options?: MarkedOptions) {
this.options = options || _defaults; this.options = options || _defaults;
@@ -111,7 +111,7 @@ export class _Tokenizer {
return { return {
type: 'code', type: 'code',
raw, raw,
lang: cap[2] ? cap[2].trim().replace(this.rules.inline._escapes, '$1') : cap[2], lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],
text text
}; };
} }
@@ -182,7 +182,7 @@ export class _Tokenizer {
ordered: isordered, ordered: isordered,
start: isordered ? +bull.slice(0, -1) : '', start: isordered ? +bull.slice(0, -1) : '',
loose: false, loose: false,
items: [] as Tokens.ListItem[] items: []
}; };
bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`; bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
@@ -207,10 +207,10 @@ export class _Tokenizer {
break; break;
} }
raw = cap[0] as string; raw = cap[0];
src = src.substring(raw.length); src = src.substring(raw.length);
let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t: string) => ' '.repeat(3 * t.length)) as string; let line = cap[2].split('\n', 1)[0].replace(/^\t+/, (t: string) => ' '.repeat(3 * t.length));
let nextLine = src.split('\n', 1)[0]; let nextLine = src.split('\n', 1)[0];
let indent = 0; let indent = 0;
@@ -338,7 +338,7 @@ export class _Tokenizer {
// Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
list.items[list.items.length - 1].raw = raw.trimEnd(); list.items[list.items.length - 1].raw = raw.trimEnd();
(list.items[list.items.length - 1] as Tokens.ListItem).text = itemContents.trimEnd(); (list.items[list.items.length - 1]).text = itemContents.trimEnd();
list.raw = list.raw.trimEnd(); list.raw = list.raw.trimEnd();
// Item child tokens handled here at end because we needed to have the final item to trim it first // Item child tokens handled here at end because we needed to have the final item to trim it first
@@ -384,8 +384,8 @@ export class _Tokenizer {
const cap = this.rules.block.def.exec(src); const cap = this.rules.block.def.exec(src);
if (cap) { if (cap) {
const tag = cap[1].toLowerCase().replace(/\s+/g, ' '); const tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline._escapes, '$1') : ''; const href = cap[2] ? cap[2].replace(/^<(.*)>$/, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';
const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline._escapes, '$1') : cap[3]; const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];
return { return {
type: 'def', type: 'def',
tag, tag,
@@ -398,67 +398,61 @@ export class _Tokenizer {
table(src: string): Tokens.Table | undefined { table(src: string): Tokens.Table | undefined {
const cap = this.rules.block.table.exec(src); const cap = this.rules.block.table.exec(src);
if (cap) { if (!cap) {
if (!/[:|]/.test(cap[2])) { return;
// delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading }
return;
}
const item: Tokens.Table = { if (!/[:|]/.test(cap[2])) {
type: 'table', // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading
raw: cap[0], return;
header: splitCells(cap[1]).map(c => { }
return { text: c, tokens: [] };
}),
align: cap[2].replace(/^\||\| *$/g, '').split('|'),
rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : []
};
if (item.header.length === item.align.length) { const headers = splitCells(cap[1]);
let l = item.align.length; const aligns = cap[2].replace(/^\||\| *$/g, '').split('|');
let i, j, k, row; const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, '').split('\n') : [];
for (i = 0; i < l; i++) {
const align = item.align[i];
if (align) {
if (/^ *-+: *$/.test(align)) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(align)) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(align)) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
}
l = item.rows.length; const item: Tokens.Table = {
for (i = 0; i < l; i++) { type: 'table',
item.rows[i] = splitCells(item.rows[i] as unknown as string, item.header.length).map(c => { raw: cap[0],
return { text: c, tokens: [] }; header: [],
}); align: [],
} rows: []
};
// parse child tokens inside headers and cells if (headers.length !== aligns.length) {
// header and align columns must be equal, rows can be different.
return;
}
// header child tokens for (const align of aligns) {
l = item.header.length; if (/^ *-+: *$/.test(align)) {
for (j = 0; j < l; j++) { item.align.push('right');
item.header[j].tokens = this.lexer.inline(item.header[j].text); } else if (/^ *:-+: *$/.test(align)) {
} item.align.push('center');
} else if (/^ *:-+ *$/.test(align)) {
// cell child tokens item.align.push('left');
l = item.rows.length; } else {
for (j = 0; j < l; j++) { item.align.push(null);
row = item.rows[j];
for (k = 0; k < row.length; k++) {
row[k].tokens = this.lexer.inline(row[k].text);
}
}
return item;
} }
} }
for (const header of headers) {
item.header.push({
text: header,
tokens: this.lexer.inline(header)
});
}
for (const row of rows) {
item.rows.push(splitCells(row, item.header.length).map(cell => {
return {
text: cell,
tokens: this.lexer.inline(cell)
};
}));
}
return item;
} }
lheading(src: string): Tokens.Heading | undefined { lheading(src: string): Tokens.Heading | undefined {
@@ -587,8 +581,8 @@ export class _Tokenizer {
} }
} }
return outputLink(cap, { return outputLink(cap, {
href: href ? href.replace(this.rules.inline._escapes, '$1') : href, href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,
title: title ? title.replace(this.rules.inline._escapes, '$1') : title title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title
}, cap[0], this.lexer); }, cap[0], this.lexer);
} }
} }
@@ -597,8 +591,8 @@ export class _Tokenizer {
let cap; let cap;
if ((cap = this.rules.inline.reflink.exec(src)) if ((cap = this.rules.inline.reflink.exec(src))
|| (cap = this.rules.inline.nolink.exec(src))) { || (cap = this.rules.inline.nolink.exec(src))) {
let link = (cap[2] || cap[1]).replace(/\s+/g, ' '); const linkString = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = links[link.toLowerCase()]; const link = links[linkString.toLowerCase()];
if (!link) { if (!link) {
const text = cap[0].charAt(0); const text = cap[0].charAt(0);
return { return {
@@ -612,7 +606,7 @@ export class _Tokenizer {
} }
emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined { emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {
let match = this.rules.inline.emStrong.lDelim.exec(src); let match = this.rules.inline.emStrongLDelim.exec(src);
if (!match) return; if (!match) return;
// _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
@@ -625,7 +619,7 @@ export class _Tokenizer {
const lLength = [...match[0]].length - 1; const lLength = [...match[0]].length - 1;
let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0; let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
const endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd; const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
endReg.lastIndex = 0; endReg.lastIndex = 0;
// Clip maskedSrc to same section of string as src (move to lexer?) // Clip maskedSrc to same section of string as src (move to lexer?)
@@ -761,7 +755,7 @@ export class _Tokenizer {
let prevCapZero; let prevCapZero;
do { do {
prevCapZero = cap[0]; prevCapZero = cap[0];
cap[0] = this.rules.inline._backpedal.exec(cap[0])[0]; cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';
} while (prevCapZero !== cap[0]); } while (prevCapZero !== cap[0]);
text = escape(cap[0]); text = escape(cap[0]);
if (cap[1] === 'www.') { if (cap[1] === 'www.') {
+7 -9
View File
@@ -1,5 +1,3 @@
import type { Rule } from './rules.ts';
/** /**
* Helpers * Helpers
*/ */
@@ -48,18 +46,18 @@ export function unescape(html: string) {
const caret = /(^|[^\[])\^/g; const caret = /(^|[^\[])\^/g;
export function edit(regex: Rule, opt?: string) { export function edit(regex: string | RegExp, opt?: string) {
regex = typeof regex === 'string' ? regex : regex.source; let source = typeof regex === 'string' ? regex : regex.source;
opt = opt || ''; opt = opt || '';
const obj = { const obj = {
replace: (name: string | RegExp, val: string | RegExp) => { replace: (name: string | RegExp, val: string | RegExp) => {
val = typeof val === 'object' && 'source' in val ? val.source : val; let valSource = typeof val === 'string' ? val : val.source;
val = val.replace(caret, '$1'); valSource = valSource.replace(caret, '$1');
regex = (regex as string).replace(name, val); source = source.replace(name, valSource);
return obj; return obj;
}, },
getRegex: () => { getRegex: () => {
return new RegExp(regex, opt); return new RegExp(source, opt);
} }
}; };
return obj; return obj;
@@ -74,7 +72,7 @@ export function cleanUrl(href: string) {
return href; return href;
} }
export const noopTest = { exec: () => null }; export const noopTest = { exec: () => null } as unknown as RegExp;
export function splitCells(tableRow: string, count?: number) { export function splitCells(tableRow: string, count?: number) {
// ensure that every cell-delimiting pipe has a space // ensure that every cell-delimiting pipe has a space
+215 -259
View File
@@ -1,136 +1,57 @@
import { import {
noopTest, edit, noopTest
edit
} from './helpers.ts'; } from './helpers.ts';
export type Rule = RegExp | string;
export interface Rules {
[ruleName: string]: Pick<RegExp, 'exec'> | Rule | Rules;
}
type BlockRuleNames =
| 'newline'
| 'code'
| 'fences'
| 'hr'
| 'heading'
| 'blockquote'
| 'list'
| 'html'
| 'def'
| 'lheading'
| '_paragraph'
| 'text'
| '_label'
| '_title'
| 'bullet'
| 'listItemStart'
| '_tag'
| '_comment'
| 'paragraph'
| 'uote' ;
type BlockSubRuleNames = 'normal' | 'gfm' | 'pedantic';
type InlineRuleNames =
| 'escape'
| 'autolink'
| 'tag'
| 'link'
| 'reflink'
| 'nolink'
| 'reflinkSearch'
| 'code'
| 'br'
| 'text'
| '_punctuation'
| 'punctuation'
| 'blockSkip'
| 'escapedEmSt'
| '_comment'
| '_escapes'
| '_scheme'
| '_email'
| '_attribute'
| '_label'
| '_href'
| '_title'
| 'strong'
| '_extended_email'
| '_backpedal';
type InlineSubRuleNames = 'gfm' | 'emStrong' | 'normal' | 'pedantic'| 'breaks';
/** /**
* Block-Level Grammar * Block-Level Grammar
*/ */
// Not all rules are defined in the object literal
// @ts-expect-error
export const block: Record<BlockRuleNames, Rule> & Record<BlockSubRuleNames, Rules> & Rules = {
newline: /^(?: *(?:\n|$))+/,
code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
fences: /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
html: '^ {0,3}(?:' // optional indentation
+ '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
+ '|comment[^\\n]*(\\n+|$)' // (2)
+ '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
+ '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
+ '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
+ '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
+ '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
+ '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
+ ')',
def: /^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
table: noopTest,
lheading: /^(?!bull )((?:.|\n(?!\s*?\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
// regex template, placeholders will be replaced according to different paragraph
// interruption rules of commonmark and the original markdown spec:
_paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
text: /^[^\n]+/
};
block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/; const newline = /^(?: *(?:\n|$))+/;
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
block.def = edit(block.def) const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
.replace('label', block._label) const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
.replace('title', block._title) const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
const bullet = /(?:[*+-]|\d{1,9}[.)])/;
const lheading = edit(/^(?!bull )((?:.|\n(?!\s*?\n|bull ))+?)\n {0,3}(=+|-+) *(?:\n+|$)/)
.replace(/bull/g, bullet) // lists can interrupt
.getRegex();
const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
const blockText = /^[^\n]+/;
const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/)
.replace('label', _blockLabel)
.replace('title', /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/)
.getRegex(); .getRegex();
block.bullet = /(?:[*+-]|\d{1,9}[.)])/; const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/)
block.listItemStart = edit(/^( *)(bull) */) .replace(/bull/g, bullet)
.replace('bull', block.bullet)
.getRegex(); .getRegex();
block.list = edit(block.list) const _tag = 'address|article|aside|base|basefont|blockquote|body|caption'
.replace(/bull/g, block.bullet)
.replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))')
.replace('def', '\\n+(?=' + block.def.source + ')')
.getRegex();
block._tag = 'address|article|aside|base|basefont|blockquote|body|caption'
+ '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'
+ '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'
+ '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'
+ '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr'
+ '|track|ul'; + '|track|ul';
block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/; const _comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
block.html = edit(block.html, 'i') const html = edit(
.replace('comment', block._comment) '^ {0,3}(?:' // optional indentation
.replace('tag', block._tag) + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
+ '|comment[^\\n]*(\\n+|$)' // (2)
+ '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
+ '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
+ '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
+ '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
+ '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
+ '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
+ ')', 'i')
.replace('comment', _comment)
.replace('tag', _tag)
.replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
.getRegex(); .getRegex();
block.lheading = edit(block.lheading) const paragraph = edit(_paragraph)
.replace(/bull/g, block.bullet) // lists can interrupt .replace('hr', hr)
.getRegex();
block.paragraph = edit(block._paragraph)
.replace('hr', block.hr)
.replace('heading', ' {0,3}#{1,6}(?:\\s|$)') .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
.replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
.replace('|table', '') .replace('|table', '')
@@ -138,63 +59,80 @@ block.paragraph = edit(block._paragraph)
.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)') .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
.replace('tag', block._tag) // pars can be interrupted by type (6) html blocks .replace('tag', _tag) // pars can be interrupted by type (6) html blocks
.getRegex(); .getRegex();
block.blockquote = edit(block.blockquote) const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/)
.replace('paragraph', block.paragraph) .replace('paragraph', paragraph)
.getRegex(); .getRegex();
/** /**
* Normal Block Grammar * Normal Block Grammar
*/ */
block.normal = { ...block }; const blockNormal = {
blockquote,
code: blockCode,
def,
fences,
heading,
hr,
html,
lheading,
list,
newline,
paragraph,
table: noopTest,
text: blockText
};
type BlockKeys = keyof typeof blockNormal;
/** /**
* GFM Block Grammar * GFM Block Grammar
*/ */
block.gfm = { const gfmTable = edit(
...block.normal, '^ *([^\\n ].*)\\n' // Header
table: '^ *([^\\n ].*)\\n' // Header + ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align
+ ' {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)' // Align + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)') // Cells
+ '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells .replace('hr', hr)
};
block.gfm.table = edit(block.gfm.table as Rule)
.replace('hr', block.hr)
.replace('heading', ' {0,3}#{1,6}(?:\\s|$)') .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
.replace('blockquote', ' {0,3}>') .replace('blockquote', ' {0,3}>')
.replace('code', ' {4}[^\\n]') .replace('code', ' {4}[^\\n]')
.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)') .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
.replace('tag', block._tag) // tables can be interrupted by type (6) html blocks .replace('tag', _tag) // tables can be interrupted by type (6) html blocks
.getRegex(); .getRegex();
block.gfm.paragraph = edit(block._paragraph) const blockGfm: Record<BlockKeys, RegExp> = {
.replace('hr', block.hr) ...blockNormal,
.replace('heading', ' {0,3}#{1,6}(?:\\s|$)') table: gfmTable,
.replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs paragraph: edit(_paragraph)
.replace('table', block.gfm.table as RegExp) // interrupt paragraphs with table .replace('hr', hr)
.replace('blockquote', ' {0,3}>') .replace('heading', ' {0,3}#{1,6}(?:\\s|$)')
.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n') .replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt .replace('table', gfmTable) // interrupt paragraphs with table
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)') .replace('blockquote', ' {0,3}>')
.replace('tag', block._tag) // pars can be interrupted by type (6) html blocks .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
.getRegex(); .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)')
.replace('tag', _tag) // pars can be interrupted by type (6) html blocks
.getRegex()
};
/** /**
* Pedantic grammar (original John Gruber's loose markdown specification) * Pedantic grammar (original John Gruber's loose markdown specification)
*/ */
block.pedantic = { const blockPedantic: Record<BlockKeys, RegExp> = {
...block.normal, ...blockNormal,
html: edit( html: edit(
'^ *(?:comment *(?:\\n|\\s*$)' '^ *(?:comment *(?:\\n|\\s*$)'
+ '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
+ '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
.replace('comment', block._comment) .replace('comment', _comment)
.replace(/tag/g, '(?!(?:' .replace(/tag/g, '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'
+ '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'
@@ -204,148 +142,146 @@ block.pedantic = {
heading: /^(#{1,6})(.*)(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/,
fences: noopTest, // fences not supported fences: noopTest, // fences not supported
lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
paragraph: edit(block.normal._paragraph as Rule) paragraph: edit(_paragraph)
.replace('hr', block.hr) .replace('hr', hr)
.replace('heading', ' *#{1,6} *[^\n]') .replace('heading', ' *#{1,6} *[^\n]')
.replace('lheading', block.lheading) .replace('lheading', lheading)
.replace('|table', '')
.replace('blockquote', ' {0,3}>') .replace('blockquote', ' {0,3}>')
.replace('|fences', '') .replace('|fences', '')
.replace('|list', '') .replace('|list', '')
.replace('|html', '') .replace('|html', '')
.replace('|tag', '')
.getRegex() .getRegex()
}; };
/** /**
* Inline-Level Grammar * Inline-Level Grammar
*/ */
// Not all rules are defined in the object literal
// @ts-expect-error const escape = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
export const inline: Record<InlineRuleNames, Rule> & Record<InlineSubRuleNames, Rules> & Rules = { const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, const br = /^( {2,}|\\)\n(?!\s*$)/;
autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
url: noopTest,
tag: '^comment' // list of unicode punctuation marks, plus any missing characters from CommonMark spec
const _punctuation = '\\p{P}$+<=>`^|~';
const punctuation = edit(/^((?![*_])[\spunctuation])/, 'u')
.replace(/punctuation/g, _punctuation).getRegex();
// sequences em should skip over [title](link), `code`, <html>
const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, 'u')
.replace(/punct/g, _punctuation)
.getRegex();
const emStrongRDelimAst = edit(
'^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)' // Skip orphan inside strong
+ '|[^*]+(?=[^*])' // Consume to delim
+ '|(?!\\*)[punct](\\*+)(?=[\\s]|$)' // (1) #*** can only be a Right Delimiter
+ '|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)' // (2) a***#, a*** can only be a Right Delimiter
+ '|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])' // (3) #***a, ***a can only be Left Delimiter
+ '|[\\s](\\*+)(?!\\*)(?=[punct])' // (4) ***# can only be Left Delimiter
+ '|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])' // (5) #***# can be either Left or Right Delimiter
+ '|[^punct\\s](\\*+)(?=[^punct\\s])', 'gu') // (6) a***a can be either Left or Right Delimiter
.replace(/punct/g, _punctuation)
.getRegex();
// (6) Not allowed for _
const emStrongRDelimUnd = edit(
'^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)' // Skip orphan inside strong
+ '|[^_]+(?=[^_])' // Consume to delim
+ '|(?!_)[punct](_+)(?=[\\s]|$)' // (1) #___ can only be a Right Delimiter
+ '|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)' // (2) a___#, a___ can only be a Right Delimiter
+ '|(?!_)[punct\\s](_+)(?=[^punct\\s])' // (3) #___a, ___a can only be Left Delimiter
+ '|[\\s](_+)(?!_)(?=[punct])' // (4) ___# can only be Left Delimiter
+ '|(?!_)[punct](_+)(?!_)(?=[punct])', 'gu') // (5) #___# can be either Left or Right Delimiter
.replace(/punct/g, _punctuation)
.getRegex();
const anyPunctuation = edit(/\\([punct])/, 'gu')
.replace(/punct/g, _punctuation)
.getRegex();
const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/)
.replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)
.replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)
.getRegex();
const _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();
const tag = edit(
'^comment'
+ '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
+ '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
+ '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?> + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
+ '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html> + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
+ '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', // CDATA section + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>') // CDATA section
link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, .replace('comment', _inlineComment)
reflink: /^!?\[(label)\]\[(ref)\]/, .replace('attribute', /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/)
nolink: /^!?\[(ref)\](?:\[\])?/,
reflinkSearch: 'reflink|nolink(?!\\()',
emStrong: {
lDelim: /^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,
// (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right.
// | Skip orphan inside strong | Consume to delim | (1) #*** | (2) a***#, a*** | (3) #***a, ***a | (4) ***# | (5) #***# | (6) a***a
rDelimAst: /^[^_*]*?__[^_*]*?\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\*)[punct](\*+)(?=[\s]|$)|[^punct\s](\*+)(?!\*)(?=[punct\s]|$)|(?!\*)[punct\s](\*+)(?=[^punct\s])|[\s](\*+)(?!\*)(?=[punct])|(?!\*)[punct](\*+)(?!\*)(?=[punct])|[^punct\s](\*+)(?=[^punct\s])/,
rDelimUnd: /^[^_*]*?\*\*[^_*]*?_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\s]|$)|[^punct\s](_+)(?!_)(?=[punct\s]|$)|(?!_)[punct\s](_+)(?=[^punct\s])|[\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])/ // ^- Not allowed for _
},
code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
br: /^( {2,}|\\)\n(?!\s*$)/,
del: noopTest,
text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
punctuation: /^((?![*_])[\spunctuation])/
};
// list of unicode punctuation marks, plus any missing characters from CommonMark spec
inline._punctuation = '\\p{P}$+<=>`^|~';
inline.punctuation = edit(inline.punctuation, 'u').replace(/punctuation/g, inline._punctuation).getRegex();
// sequences em should skip over [title](link), `code`, <html>
inline.blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
inline.anyPunctuation = /\\[punct]/g;
inline._escapes = /\\([punct])/g;
inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex();
inline.emStrong.lDelim = edit(inline.emStrong.lDelim as Rule, 'u')
.replace(/punct/g, inline._punctuation)
.getRegex(); .getRegex();
inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst as Rule, 'gu') const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
.replace(/punct/g, inline._punctuation)
const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/)
.replace('label', _inlineLabel)
.replace('href', /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/)
.replace('title', /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/)
.getRegex(); .getRegex();
inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd as Rule, 'gu') const reflink = edit(/^!?\[(label)\]\[(ref)\]/)
.replace(/punct/g, inline._punctuation) .replace('label', _inlineLabel)
.replace('ref', _blockLabel)
.getRegex(); .getRegex();
inline.anyPunctuation = edit(inline.anyPunctuation as Rule, 'gu') const nolink = edit(/^!?\[(ref)\](?:\[\])?/)
.replace(/punct/g, inline._punctuation) .replace('ref', _blockLabel)
.getRegex(); .getRegex();
inline._escapes = edit(inline._escapes, 'gu') const reflinkSearch = edit('reflink|nolink(?!\\()', 'g')
.replace(/punct/g, inline._punctuation) .replace('reflink', reflink)
.getRegex(); .replace('nolink', nolink)
inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
inline.autolink = edit(inline.autolink)
.replace('scheme', inline._scheme)
.replace('email', inline._email)
.getRegex();
inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
inline.tag = edit(inline.tag)
.replace('comment', inline._comment)
.replace('attribute', inline._attribute)
.getRegex();
inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
inline.link = edit(inline.link)
.replace('label', inline._label)
.replace('href', inline._href)
.replace('title', inline._title)
.getRegex();
inline.reflink = edit(inline.reflink)
.replace('label', inline._label)
.replace('ref', block._label)
.getRegex();
inline.nolink = edit(inline.nolink)
.replace('ref', block._label)
.getRegex();
inline.reflinkSearch = edit(inline.reflinkSearch, 'g')
.replace('reflink', inline.reflink)
.replace('nolink', inline.nolink)
.getRegex(); .getRegex();
/** /**
* Normal Inline Grammar * Normal Inline Grammar
*/ */
inline.normal = { ...inline }; const inlineNormal = {
_backpedal: noopTest, // only used for GFM url
anyPunctuation,
autolink,
blockSkip,
br,
code: inlineCode,
del: noopTest,
emStrongLDelim,
emStrongRDelimAst,
emStrongRDelimUnd,
escape,
link,
nolink,
punctuation,
reflink,
reflinkSearch,
tag,
text: inlineText,
url: noopTest
};
type InlineKeys = keyof typeof inlineNormal;
/** /**
* Pedantic Inline Grammar * Pedantic Inline Grammar
*/ */
inline.pedantic = { const inlinePedantic: Record<InlineKeys, RegExp> = {
...inline.normal, ...inlineNormal,
strong: {
start: /^__|\*\*/,
middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
endAst: /\*\*(?!\*)/g,
endUnd: /__(?!_)/g
},
em: {
start: /^_|\*/,
middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
endAst: /\*(?!\*)/g,
endUnd: /_(?!_)/g
},
link: edit(/^!?\[(label)\]\((.*?)\)/) link: edit(/^!?\[(label)\]\((.*?)\)/)
.replace('label', inline._label) .replace('label', _inlineLabel)
.getRegex(), .getRegex(),
reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
.replace('label', inline._label) .replace('label', _inlineLabel)
.getRegex() .getRegex()
}; };
@@ -353,28 +289,48 @@ inline.pedantic = {
* GFM Inline Grammar * GFM Inline Grammar
*/ */
inline.gfm = { const inlineGfm: Record<InlineKeys, RegExp> = {
...inline.normal, ...inlineNormal,
escape: edit(inline.escape).replace('])', '~|])').getRegex(), escape: edit(escape).replace('])', '~|])').getRegex(),
_extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, 'i')
url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)
.getRegex(),
_backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/, del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/ text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
}; };
inline.gfm.url = edit(inline.gfm.url as Rule, 'i')
.replace('email', inline.gfm._extended_email as RegExp)
.getRegex();
/** /**
* GFM + Line Breaks Inline Grammar * GFM + Line Breaks Inline Grammar
*/ */
inline.breaks = { const inlineBreaks: Record<InlineKeys, RegExp> = {
...inline.gfm, ...inlineGfm,
br: edit(inline.br).replace('{2,}', '*').getRegex(), br: edit(br).replace('{2,}', '*').getRegex(),
text: edit(inline.gfm.text as Rule) text: edit(inlineGfm.text)
.replace('\\b_', '\\b_| {2,}\\n') .replace('\\b_', '\\b_| {2,}\\n')
.replace(/\{2,\}/g, '*') .replace(/\{2,\}/g, '*')
.getRegex() .getRegex()
}; };
/**
* exports
*/
export const block = {
normal: blockNormal,
gfm: blockGfm,
pedantic: blockPedantic
};
export const inline = {
normal: inlineNormal,
gfm: inlineGfm,
breaks: inlineBreaks,
pedantic: inlinePedantic
};
export interface Rules {
block: Record<BlockKeys, RegExp>
inline: Record<InlineKeys, RegExp>
}
+2 -3
View File
@@ -1,11 +1,10 @@
/* eslint-disable */ /* eslint-disable */
import { marked } from 'marked'; import { marked } from 'marked';
import { expectType } from 'ts-expect';
// other exports // other exports
import { Lexer, Parser, Tokenizer, Renderer, TextRenderer } from 'marked'; import { Lexer, Parser, Tokenizer, Renderer, TextRenderer } from 'marked';
import type { Tokens, MarkedExtension, TokenizerAndRendererExtension, Token ,TokenizerExtension, MarkedOptions, TokensList, Rules, RendererExtension } from 'marked'; import type { Tokens, MarkedExtension, TokenizerAndRendererExtension, Token ,TokenizerExtension, MarkedOptions, TokensList, RendererExtension } from 'marked';
const tokenizer = new marked.Tokenizer(); const tokenizer = new marked.Tokenizer();
@@ -76,7 +75,7 @@ console.log(tokens3);
// verifying that the second param to inlineTokens can be ignored // verifying that the second param to inlineTokens can be ignored
const tokens3a = lexer.inlineTokens(text); const tokens3a = lexer.inlineTokens(text);
console.log(tokens3a); console.log(tokens3a);
const re: Rules = marked.Lexer.rules; const re: Record<string, Record<string, Record<string, RegExp>>> = marked.Lexer.rules;
const lexerOptions: MarkedOptions = lexer.options; const lexerOptions: MarkedOptions = lexer.options;
const renderer = new marked.Renderer(); const renderer = new marked.Renderer();
+1 -1
View File
@@ -569,7 +569,7 @@ used extension2 walked</p>
assert.ok(marked.defaults.async); assert.ok(marked.defaults.async);
}); });
it.only('should be async if any extension in use is async', () => { it('should be async if any extension in use is async', () => {
marked.use({ async: true }); marked.use({ async: true });
marked.use({ async: false }); marked.use({ async: false });