eslint-plugin-mdx
Version:
ESLint Plugin for MDX
3,393 lines • 103 kB
JavaScript
'use strict';
var eslintMdx = require('eslint-mdx');
var node_module = require('node:module');
var fs = require('node:fs');
var path = require('node:path');
var collapseWhiteSpace = require('collapse-white-space');
var micromarkUtilNormalizeIdentifier = require('micromark-util-normalize-identifier');
var prettierLinterHelpers = require('prettier-linter-helpers');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var eslintMdx__namespace = /*#__PURE__*/_interopNamespaceDefault(eslintMdx);
var mdx = /*#__PURE__*/Object.freeze({
__proto__: null,
get DEFAULT_LANGUAGE_MAPPER () { return DEFAULT_LANGUAGE_MAPPER; },
get base () { return base; },
get blockquoteIndentation () { return blockquoteIndentation; },
get checkboxCharacterStyle () { return checkboxCharacterStyle; },
get cjsRequire () { return cjsRequire; },
get codeBlockStyle () { return codeBlockStyle; },
get codeBlocks () { return codeBlocks; },
get configs () { return configs; },
get createRemarkProcessor () { return createRemarkProcessor; },
get definitionCase () { return definitionCase; },
get definitionSpacing () { return definitionSpacing; },
get emphasisMarker () { return emphasisMarker; },
get fencedCodeFlag () { return fencedCodeFlag; },
get fencedCodeMarker () { return fencedCodeMarker; },
get finalDefinition () { return finalDefinition; },
get finalNewline () { return finalNewline; },
get flat () { return flat; },
get flatCodeBlocks () { return flatCodeBlocks; },
get getGlobals () { return getGlobals; },
get getShortLang () { return getShortLang; },
get hardBreakSpaces () { return hardBreakSpaces; },
get headingIncrement () { return headingIncrement; },
get headingStyle () { return headingStyle; },
get linkTitleStyle () { return linkTitleStyle; },
get listItemBulletIndent () { return listItemBulletIndent; },
get listItemContentIndent () { return listItemContentIndent; },
get listItemIndent () { return listItemIndent; },
get listItemSpacing () { return listItemSpacing; },
get maximumHeadingLength () { return maximumHeadingLength; },
get maximumLineLength () { return maximumLineLength; },
get meta () { return meta; },
get native () { return native; },
get noBlockquoteWithoutMarker () { return noBlockquoteWithoutMarker; },
get noConsecutiveBlankLines () { return noConsecutiveBlankLines; },
get noDuplicateDefinitions () { return noDuplicateDefinitions; },
get noDuplicateHeadings () { return noDuplicateHeadings; },
get noDuplicateHeadingsInSection () { return noDuplicateHeadingsInSection; },
get noEmphasisAsHeading () { return noEmphasisAsHeading; },
get noFileNameArticles () { return noFileNameArticles; },
get noFileNameConsecutiveDashes () { return noFileNameConsecutiveDashes; },
get noFileNameIrregularCharacters () { return noFileNameIrregularCharacters; },
get noFileNameMixedCase () { return noFileNameMixedCase; },
get noFileNameOuterDashes () { return noFileNameOuterDashes; },
get noHeadingContentIndent () { return noHeadingContentIndent; },
get noHeadingPunctuation () { return noHeadingPunctuation; },
get noLiteralUrls () { return noLiteralUrls; },
get noMultipleToplevelHeadings () { return noMultipleToplevelHeadings; },
get noShellDollars () { return noShellDollars; },
get noShortcutReferenceImage () { return noShortcutReferenceImage; },
get noShortcutReferenceLink () { return noShortcutReferenceLink; },
get noTableIndentation () { return noTableIndentation; },
get noUndefinedReferences () { return noUndefinedReferences; },
get noUnusedDefinitions () { return noUnusedDefinitions; },
get orderedListMarkerStyle () { return orderedListMarkerStyle; },
get orderedListMarkerValue () { return orderedListMarkerValue; },
get overrides () { return overrides$1; },
get processorOptions () { return processorOptions; },
get processors () { return processors; },
get recommended () { return recommended; },
get remark () { return remark; },
get ruleStyle () { return ruleStyle; },
get rules () { return rules; },
get strongMarker () { return strongMarker; },
get tableCellPadding () { return tableCellPadding; },
get tablePipeAlignment () { return tablePipeAlignment; },
get tablePipes () { return tablePipes; },
get unorderedListMarkerStyle () { return unorderedListMarkerStyle; }
});
const base = {
parser: "eslint-mdx",
parserOptions: {
sourceType: "module",
ecmaVersion: "latest",
ecmaFeatures: {
jsx: true
}
},
plugins: ["mdx"],
processor: "mdx/remark",
rules: {
"mdx/remark": "warn",
"no-unused-expressions": "error"
}
};
const codeBlocks = {
parserOptions: {
ecmaFeatures: {
// Adding a "use strict" directive at the top of
// every code block is tedious and distracting, so
// opt into strict mode parsing without the
// directive.
impliedStrict: true
}
},
rules: {
// ESLint deprecated `eol-last` and `padded-blocks` in v8.53.0 in favour of
// @stylistic/eslint-plugin, which carries them under its own prefix, so both
// names are switched off here. An entry naming a rule the installed ESLint
// no longer has is bypassed while it is "off", and the @stylistic entries
// keep the same rules muted for the users who run the plugin.
"eol-last": "off",
"@stylistic/eol-last": "off",
// In code snippets and examples, these rules are often
// counterproductive to clarity and brevity.
"no-undef": "off",
"no-unused-expressions": "off",
"mdx/no-file-name-articles": "off",
"mdx/no-file-name-consecutive-dashes": "off",
"mdx/no-file-name-irregular-characters": "off",
"mdx/no-file-name-mixed-case": "off",
"mdx/no-file-name-outer-dashes": "off",
"mdx/blockquote-indentation": "off",
"mdx/checkbox-character-style": "off",
"mdx/code-block-style": "off",
"mdx/definition-case": "off",
"mdx/definition-spacing": "off",
"mdx/emphasis-marker": "off",
"mdx/fenced-code-flag": "off",
"mdx/fenced-code-marker": "off",
"mdx/final-definition": "off",
"mdx/final-newline": "off",
"mdx/hard-break-spaces": "off",
"mdx/heading-increment": "off",
"mdx/heading-style": "off",
"mdx/link-title-style": "off",
"mdx/list-item-bullet-indent": "off",
"mdx/list-item-content-indent": "off",
"mdx/list-item-indent": "off",
"mdx/list-item-spacing": "off",
"mdx/maximum-heading-length": "off",
"mdx/maximum-line-length": "off",
"mdx/no-blockquote-without-marker": "off",
"mdx/no-consecutive-blank-lines": "off",
"mdx/no-duplicate-definitions": "off",
"mdx/no-duplicate-headings-in-section": "off",
"mdx/no-duplicate-headings": "off",
"mdx/no-emphasis-as-heading": "off",
"mdx/no-heading-content-indent": "off",
"mdx/no-heading-punctuation": "off",
"mdx/no-literal-urls": "off",
"mdx/no-multiple-toplevel-headings": "off",
"mdx/no-shell-dollars": "off",
"mdx/no-shortcut-reference-image": "off",
"mdx/no-shortcut-reference-link": "off",
"mdx/no-table-indentation": "off",
"mdx/no-undefined-references": "off",
"mdx/no-unused-definitions": "off",
"mdx/ordered-list-marker-style": "off",
"mdx/ordered-list-marker-value": "off",
"mdx/rule-style": "off",
"mdx/strong-marker": "off",
"mdx/table-cell-padding": "off",
"mdx/table-pipe-alignment": "off",
"mdx/table-pipes": "off",
"mdx/unordered-list-marker-style": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "off",
"padded-blocks": "off",
"@stylistic/padded-blocks": "off",
// Adding a "use strict" directive at the top of every
// code block is tedious and distracting. The config
// opts into strict mode parsing without the directive.
strict: "off",
// The processor will not receive a Unicode Byte Order
// Mark from the Markdown parser.
"unicode-bom": "off"
}
};
const getGlobals = (sources, initialGlobals = {}) => (Array.isArray(sources) ? (
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
sources
) : Object.keys(sources)).reduce(
(globals, source) => Object.assign(globals, {
[source]: false
}),
initialGlobals
);
const importMetaUrl = (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href));
const cjsRequire = importMetaUrl ? node_module.createRequire(importMetaUrl) : require;
const pkg = cjsRequire("../package.json");
const meta = { name: pkg.name, version: pkg.version };
const DEFAULT_LANGUAGE_MAPPER = {
ecmascript: "js",
javascript: "js",
javascriptreact: "jsx",
typescript: "ts",
typescriptreact: "tsx",
markdown: "md",
markdownjsx: "mdx",
markdownreact: "mdx",
mdown: "md",
mkdn: "md"
};
function getShortLang(filename, languageMapper) {
const language = filename.split(".").at(-1);
if (languageMapper === false) {
return language;
}
languageMapper = languageMapper ? { ...DEFAULT_LANGUAGE_MAPPER, ...languageMapper } : DEFAULT_LANGUAGE_MAPPER;
const mapped = languageMapper[language];
if (mapped) {
return mapped;
}
const lang = language.toLowerCase();
return languageMapper[lang] || lang;
}
const UNSATISFIABLE_RULES = /* @__PURE__ */ new Set([
"eol-last",
// The Markdown parser strips trailing newlines in code fences
"unicode-bom"
// Code blocks will begin in the middle of Markdown files
]);
const SUPPORTS_AUTOFIX = true;
const BOM = "\uFEFF";
const blocksCache = /* @__PURE__ */ new Map();
function traverse(node, callbacks) {
if (callbacks[node.type]) {
callbacks[node.type](node);
} else {
callbacks["*"]();
}
const parent = node;
if ("children" in parent) {
for (const child of parent.children) {
traverse(child, callbacks);
}
}
}
const COMMENTS = [
[
/^<!-{2,}/,
// eslint-disable-next-line sonarjs/super-linear-regex
/-{2,}>$/
],
[
/^\/\*+/,
// eslint-disable-next-line sonarjs/super-linear-regex
/\*+\/$/
]
];
const eslintCommentRegex = /^(?:eslint\b|global\s)/u;
function getComment(value, isMdx = false) {
const [commentStart, commentEnd] = COMMENTS[+isMdx];
const commentStartMatched = commentStart.exec(value);
const commentEndMatched = commentEnd.exec(value);
if (commentStartMatched == null || commentEndMatched == null) {
return "";
}
const comment = value.slice(commentStartMatched[0].length, -commentEndMatched[0].length).trim();
if (!eslintCommentRegex.test(comment)) {
return "";
}
return comment;
}
const leadingWhitespaceRegex = /^[>\s]*/u;
function getBeginningOfLineOffset(node) {
return node.position.start.offset - node.position.start.column + 1;
}
function getIndentText(text, node) {
return leadingWhitespaceRegex.exec(
text.slice(getBeginningOfLineOffset(node))
)[0];
}
function getBlockRangeMap(text, node, comments) {
const startOffset = getBeginningOfLineOffset(node);
const code = text.slice(startOffset, node.position.end.offset);
const lines = code.split("\n");
const baseIndent = getIndentText(text, node).length;
const commentLength = comments.reduce(
(len, comment) => len + comment.length + 1,
0
);
const rangeMap = [
{
indent: baseIndent,
js: 0,
md: 0
}
];
let jsOffset = commentLength;
let mdOffset = startOffset + lines[0].length + 1;
for (let i = 0; i + 1 < lines.length; i++) {
const line = lines[i + 1];
const leadingWhitespaceLength = leadingWhitespaceRegex.exec(line)[0].length;
const trimLength = Math.min(baseIndent, leadingWhitespaceLength);
rangeMap.push({
indent: trimLength,
js: jsOffset,
// Advance `trimLength` character from the beginning of the Markdown
// line to the beginning of the equivalent JS line, then compute the
// delta.
md: mdOffset + trimLength - jsOffset
});
mdOffset += line.length + 1;
jsOffset += line.length - trimLength + 1;
}
return rangeMap;
}
const codeBlockFileNameRegex = /filename=(?<quote>["'])(?<filename>.*?)\k<quote>/u;
function fileNameFromMeta(block) {
return codeBlockFileNameRegex.exec(block.meta)?.groups.filename.replaceAll(/\s+/gu, "_");
}
function getOnDiskFilepath(filepath) {
let fallback;
try {
if (!fs.statSync(filepath, { throwIfNoEntry: false })) {
fallback = true;
}
} catch (err) {
if (err.code === "ENOTDIR") {
fallback = true;
}
}
return fallback ? getOnDiskFilepath(path.dirname(filepath)) : filepath;
}
function preprocess(sourceText, filename, syncOptions) {
const text = sourceText.startsWith(BOM) ? sourceText.slice(1) : sourceText;
const { root } = eslintMdx.performSyncWork({
filePath: getOnDiskFilepath(filename),
code: text,
// FIXME: how to read `extensions` and `markdownExtensions` parser options?
isMdx: filename.endsWith(".mdx"),
...syncOptions
});
const blocks = [];
blocksCache.set(filename, blocks);
let allComments = [];
function mdxExpression(node) {
const comment = getComment(node.value, true);
if (comment) {
allComments.push(comment);
} else {
allComments = [];
}
}
traverse(root, {
"*"() {
allComments = [];
},
/**
* Visit a code node.
*
* @param node The visited node.
*/
code(node) {
if (!node.lang) {
return;
}
const comments = [];
for (const comment of allComments) {
if (comment === "eslint-skip") {
allComments = [];
return;
}
comments.push(`/* ${comment} */`);
}
allComments = [];
blocks.push({
...node,
baseIndentText: getIndentText(text, node),
comments,
rangeMap: getBlockRangeMap(text, node, comments)
});
},
/**
* Visit an HTML node.
*
* @param node The visited node.
*/
html(node) {
const comment = getComment(node.value);
if (comment) {
allComments.push(comment);
} else {
allComments = [];
}
},
mdxFlowExpression: mdxExpression,
mdxTextExpression: mdxExpression
});
return blocks.map((block, index) => {
const [language] = block.lang.trim().split(" ");
return {
filename: fileNameFromMeta(block) ?? `${index}.${language}`,
text: [...block.comments, block.value, ""].join("\n")
};
});
}
function adjustFix(block, fix) {
return {
range: fix.range.map((range) => {
let i = 1;
while (i < block.rangeMap.length && block.rangeMap[i].js <= range) {
i++;
}
return range + block.rangeMap[i - 1].md;
}),
text: fix.text.replaceAll("\n", `
${block.baseIndentText}`)
};
}
function adjustBlock(block) {
const leadingCommentLines = block.comments.reduce(
(count, comment) => count + comment.split("\n").length,
0
);
const blockStart = block.position.start.line;
return function adjustMessage(message) {
if (!Number.isInteger(message.line)) {
return {
...message,
line: blockStart,
column: block.position.start.column
};
}
const lineInCode = message.line - leadingCommentLines;
if (lineInCode < 1 || lineInCode >= block.rangeMap.length) {
return null;
}
const out = {
line: lineInCode + blockStart,
column: message.column + block.rangeMap[lineInCode].indent
};
if (Number.isInteger(message.endLine)) {
out.endLine = message.endLine - leadingCommentLines + blockStart;
}
if (Array.isArray(message.suggestions)) {
out.suggestions = message.suggestions.map((suggestion) => ({
...suggestion,
fix: adjustFix(block, suggestion.fix)
}));
}
const adjustedFix = {};
if (message.fix) {
adjustedFix.fix = adjustFix(block, message.fix);
}
return { ...message, ...out, ...adjustedFix };
};
}
function excludeUnsatisfiableRules(message) {
return message && !UNSATISFIABLE_RULES.has(message.ruleId);
}
function postprocess(messages, filename) {
const blocks = blocksCache.get(filename);
blocksCache.delete(filename);
return messages.flatMap((group, i) => {
const adjust = adjustBlock(blocks[i]);
return group.map(adjust).filter(excludeUnsatisfiableRules);
});
}
const markdownProcessor = {
meta: {
name: "mdx/markdown",
version: meta.version
},
preprocess,
postprocess,
supportsAutofix: SUPPORTS_AUTOFIX
};
const processorOptions = {};
const linterPath = Object.keys(cjsRequire.cache).find(
(path) => /([/\\])eslint\1lib(?:\1linter){2}\.js$/.test(path)
);
const ESLinter = cjsRequire(linterPath || "eslint").Linter;
const { verify } = ESLinter.prototype;
ESLinter.prototype.verify = function(code, config, options) {
const settings = (config.extractConfig?.(
// eslint-disable-next-line unicorn-x/no-typeof-undefined
typeof options === "undefined" || typeof options === "string" ? options : options.filename
) ?? config).settings ?? {};
processorOptions.lintCodeBlocks = settings["mdx/code-blocks"];
processorOptions.languageMapper = settings["mdx/language-mapper"];
processorOptions.ignoreRemarkConfig = settings["mdx/ignore-remark-config"];
processorOptions.remarkConfigPath = settings["mdx/remark-config-path"];
return verify.call(this, code, config, options);
};
const createRemarkProcessor = ({
languageMapper,
lintCodeBlocks,
...syncOptions
} = processorOptions) => ({
meta: {
name: "mdx/remark",
version: meta.version
},
supportsAutofix: true,
preprocess(text, filename) {
if (!lintCodeBlocks) {
return [text];
}
return [
text,
...markdownProcessor.preprocess(text, filename, syncOptions).map(({ text: text2, filename: filename2 }) => ({
text: text2,
filename: filename2.slice(0, filename2.lastIndexOf(".")) + "." + getShortLang(filename2, languageMapper)
}))
];
},
postprocess([mdxMessages, ...markdownMessages], filename) {
return [
...mdxMessages,
...markdownProcessor.postprocess(markdownMessages, filename)
].sort((a, b) => a.line - b.line || a.column - b.column).map((lintMessage) => {
const {
message,
ruleId: eslintRuleId,
severity: eslintSeverity
} = lintMessage;
if (eslintRuleId !== "mdx/remark") {
return lintMessage;
}
const { source, ruleId, reason, severity } = JSON.parse(
message
);
return {
...lintMessage,
ruleId: `${source}-${ruleId}`,
message: reason,
severity: Math.max(
eslintSeverity,
severity
)
};
});
}
});
const remark$1 = createRemarkProcessor();
const flat = {
name: "mdx/flat",
files: ["**/*.{md,mdx}"],
languageOptions: {
parser: eslintMdx__namespace,
parserOptions: {
ecmaFeatures: {
jsx: true
}
},
globals: {
React: false
}
},
plugins: {
mdx
},
processor: remark$1,
rules: {
"mdx/remark": "warn",
"no-unused-expressions": "error",
"react/react-in-jsx-scope": "off"
}
};
const { parserOptions, ...restConfig } = codeBlocks;
const flatCodeBlocks = {
name: "mdx/flat-code-blocks",
files: ["**/*.{md,mdx}/**"],
languageOptions: {
parserOptions
},
...restConfig
};
const native = {
rules: {
"mdx/emphasis-marker": "warn",
"mdx/final-newline": "warn",
"mdx/fenced-code-marker": "warn",
"mdx/heading-increment": "warn",
"mdx/heading-style": "warn",
"mdx/definition-case": "warn",
"mdx/definition-spacing": "warn",
"mdx/no-consecutive-blank-lines": "warn",
"mdx/no-duplicate-definitions": "warn",
"mdx/no-duplicate-headings": "warn",
"mdx/no-duplicate-headings-in-section": "warn",
"mdx/no-file-name-articles": "warn",
"mdx/no-file-name-consecutive-dashes": "warn",
"mdx/no-file-name-irregular-characters": "warn",
"mdx/no-file-name-mixed-case": "warn",
"mdx/no-file-name-outer-dashes": "warn",
"mdx/no-emphasis-as-heading": "warn",
"mdx/maximum-heading-length": "warn",
"mdx/no-heading-content-indent": "warn",
"mdx/link-title-style": "warn",
"mdx/no-heading-punctuation": "warn",
"mdx/ordered-list-marker-style": "warn",
"mdx/no-literal-urls": "warn",
"mdx/no-multiple-toplevel-headings": "warn",
"mdx/no-unused-definitions": "warn",
"mdx/rule-style": "warn",
"mdx/no-shell-dollars": "warn",
"mdx/no-table-indentation": "warn",
"mdx/no-shortcut-reference-image": "warn",
"mdx/no-shortcut-reference-link": "warn",
"mdx/strong-marker": "warn",
"mdx/unordered-list-marker-style": "warn",
"mdx/blockquote-indentation": "warn",
"mdx/checkbox-character-style": "warn",
"mdx/code-block-style": "warn",
"mdx/fenced-code-flag": "warn",
"mdx/final-definition": "warn",
"mdx/hard-break-spaces": "warn",
"mdx/list-item-bullet-indent": "warn",
"mdx/list-item-content-indent": "warn",
"mdx/list-item-indent": "warn",
"mdx/list-item-spacing": "warn",
"mdx/maximum-line-length": "warn",
"mdx/no-blockquote-without-marker": "warn",
"mdx/no-undefined-references": "warn",
"mdx/ordered-list-marker-value": "warn",
"mdx/table-cell-padding": "warn",
"mdx/table-pipe-alignment": "warn",
"mdx/table-pipes": "warn",
"mdx/remark": ["warn", { native: true }]
}
};
let isReactPluginAvailable = false;
try {
cjsRequire.resolve("eslint-plugin-react");
isReactPluginAvailable = true;
} catch {
}
const overrides$1 = {
...base,
globals: {
React: false
},
plugins: eslintMdx.arrayify(
base.plugins,
/* istanbul ignore next */
isReactPluginAvailable ? "react" : null
),
rules: {
"react/jsx-no-undef": (
/* istanbul ignore next */
isReactPluginAvailable ? [
2,
{
allowGlobals: true
}
] : 0
),
"react/react-in-jsx-scope": 0
}
};
const overrides = [
{
files: ["*.md", "*.mdx"],
extends: "plugin:mdx/overrides",
...base
},
{
files: "**/*.{md,mdx}/**",
extends: "plugin:mdx/code-blocks"
}
];
const recommended = {
overrides
};
const addPrettierRules = () => {
try {
cjsRequire.resolve("prettier");
const { meta } = cjsRequire("eslint-plugin-prettier");
const version = meta?.version || "";
const [major, minor, patch] = version.split(".");
if (
/* istanbul ignore next */
+major > 5 || +major === 5 && (+minor > 1 || +minor === 1 && Number.parseInt(patch) >= 2)
) {
return;
}
overrides.push(
{
files: "*.md",
rules: {
"prettier/prettier": [
"error",
{
parser: "markdown"
}
]
}
},
{
files: "*.mdx",
rules: {
"prettier/prettier": [
"error",
{
parser: "mdx"
}
]
}
}
);
} catch {
}
};
addPrettierRules();
const configs = {
base,
"code-blocks": codeBlocks,
codeBlocks,
flat,
flatCodeBlocks,
native,
overrides: overrides$1,
recommended
};
const processors = { remark: remark$1 };
const ANY_OPTION_SCHEMA = {};
const ENABLED_OPTION_SCHEMA = {
additionalProperties: false,
properties: { enabled: { const: true } },
required: ["enabled"],
type: "object"
};
const getParserOptions = (context) => {
const options = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
// @ts-ignore -- ESLint v10 removed
...context.parserOptions,
...context.languageOptions?.parserOptions
};
return options;
};
const isMdxFile = (filename, extensions) => [...eslintMdx.DEFAULT_EXTENSIONS, ...eslintMdx.arrayify(extensions)].includes(
path.extname(filename)
);
const isMarkdownFile = (filename, markdownExtensions) => [...eslintMdx.MARKDOWN_EXTENSIONS, ...eslintMdx.arrayify(markdownExtensions)].includes(
path.extname(filename)
);
const NATIVE_REMARK_RULES = /* @__PURE__ */ new Set([
"emphasis-marker",
"final-newline",
"fenced-code-marker",
"heading-increment",
"heading-style",
"definition-case",
"definition-spacing",
"no-consecutive-blank-lines",
"no-duplicate-definitions",
"no-duplicate-headings",
"no-duplicate-headings-in-section",
"no-file-name-articles",
"no-file-name-consecutive-dashes",
"no-file-name-irregular-characters",
"no-file-name-mixed-case",
"no-file-name-outer-dashes",
"no-emphasis-as-heading",
"maximum-heading-length",
"no-heading-content-indent",
"link-title-style",
"no-heading-punctuation",
"ordered-list-marker-style",
"no-literal-urls",
"no-multiple-toplevel-headings",
"no-unused-definitions",
"rule-style",
"no-shell-dollars",
"no-table-indentation",
"no-shortcut-reference-image",
"no-shortcut-reference-link",
"strong-marker",
"unordered-list-marker-style",
"blockquote-indentation",
"checkbox-character-style",
"code-block-style",
"fenced-code-flag",
"final-definition",
"hard-break-spaces",
"list-item-bullet-indent",
"list-item-content-indent",
"list-item-indent",
"list-item-spacing",
"maximum-line-length",
"no-blockquote-without-marker",
"no-undefined-references",
"ordered-list-marker-value",
"table-cell-padding",
"table-pipe-alignment",
"table-pipes"
]);
const getRuleConfig = (context, name) => {
const {
remarkConfig
// type-coverage:ignore-next-line -- bad typings
} = context.sourceCode.parserServices;
if (!remarkConfig) {
return null;
}
const { ruleOptions } = remarkConfig;
const eslintOptions = context.options;
const hasEslintOption = eslintOptions.length > 0;
const hasRemarkOption = name in ruleOptions;
if (!hasEslintOption && !hasRemarkOption) {
return null;
}
return {
options: hasEslintOption ? eslintOptions[0] : ruleOptions[name]
};
};
const getNodeText = (node) => {
if (node.type === "MDHtml") {
return "";
}
if (node.value != null) {
return node.value;
}
if (node.alt) {
return node.alt;
}
return (node.children ?? []).map((child) => getNodeText(child)).join("");
};
const pluralize$4 = (count) => count === 1 ? "space" : "spaces";
const blockquoteIndentation = {
meta: {
type: "layout",
docs: { description: "Enforce blockquote indentation" },
schema: [{ type: ["number", "string"] }]
},
create(context) {
const config = getRuleConfig(context, "blockquote-indentation");
if (!config) {
return {};
}
let expected = typeof config.options === "number" ? config.options : void 0;
return {
MDBlockquote(node) {
const [child] = node.children;
if (!child) {
return;
}
const actual = child.loc.start.column - node.loc.start.column;
expected ??= actual;
if (actual !== expected) {
const difference = expected - actual;
context.report({
loc: child.loc,
message: `Unexpected \`${actual}\` ${pluralize$4(actual)} between block quote marker and content, expected \`${expected}\` ${pluralize$4(expected)}, ${difference > 0 ? "add" : "remove"} \`${Math.abs(difference)}\` ${pluralize$4(Math.abs(difference))}`
});
}
}
};
}
};
const checkboxCharacterStyle = {
meta: {
type: "layout",
docs: { description: "Enforce checkbox character style" },
schema: [
{
anyOf: [
{ enum: ["consistent"], type: "string" },
{
additionalProperties: false,
properties: {
checked: { enum: ["consistent", "X", "x"], type: "string" },
unchecked: { enum: [" ", " ", "consistent"], type: "string" }
},
type: "object"
}
]
}
]
},
create(context) {
const config = getRuleConfig(context, "checkbox-character-style");
if (!config) {
return {};
}
const options = typeof config.options === "object" ? config.options : void 0;
let checkedExpected = options?.checked === "x" || options?.checked === "X" ? options.checked : void 0;
let uncheckedExpected = options?.unchecked === " " || options?.unchecked === " " ? options.unchecked : void 0;
return {
MDListItem(node) {
if (typeof node.checked !== "boolean") {
return;
}
const match = /^\s*(?:[-*+]|\d+[.)])\s+\[([ x\t])\]/iu.exec(node.raw);
const actual = match[1];
const expected = node.checked ? checkedExpected : uncheckedExpected;
if (!expected) {
if (node.checked) {
checkedExpected = actual;
} else {
uncheckedExpected = actual;
}
return;
}
if (actual !== expected) {
const actualText = actual === " " ? String.raw`\t` : actual;
const expectedText = expected === " " ? String.raw`\t` : expected;
const checked = node.checked ? "" : "un";
const checkboxLoc = context.sourceCode.getLocFromIndex(
node.range[0] + match[0].length - 1
);
context.report({
loc: {
start: checkboxLoc,
end: { ...checkboxLoc, column: checkboxLoc.column + 1 }
},
message: `Unexpected ${checked}checked checkbox value \`${actualText}\`, expected \`${expectedText}\``
});
}
}
};
}
};
const codeBlockStyle = {
meta: {
type: "layout",
docs: { description: "Enforce code block style" },
schema: [{ enum: ["consistent", "fenced", "indented"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "code-block-style");
if (!config) {
return {};
}
let expected = config.options === "fenced" || config.options === "indented" ? config.options : void 0;
return {
MDCode(node) {
const actual = /^ {0,3}(?:`{3,}|~{3,})/u.test(node.raw) ? "fenced" : "indented";
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected ${actual} code block, expected ${expected} code blocks`
});
}
};
}
};
const definitionCase = {
meta: {
type: "problem",
docs: {
description: "Enforce lowercase definition labels"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "definition-case");
if (!config) {
return {};
}
const check = (node, footnote) => {
if (node.label && node.label !== node.label.toLowerCase()) {
context.report({
loc: node.loc,
message: `Unexpected uppercase characters in ${footnote ? "footnote " : ""}definition label, expected lowercase`
});
}
};
return {
MDDefinition(node) {
check(node, false);
},
MDFootnoteDefinition(node) {
check(node, true);
}
};
}
};
const definitionSpacing = {
meta: {
type: "layout",
docs: {
description: "Enforce spacing in definition labels"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "definition-spacing");
if (!config) {
return {};
}
return {
MDDefinition(node) {
const match = / {2,}/u.exec(node.label);
if (match) {
context.report({
loc: node.loc,
message: `Unexpected \`${match[0].length}\` consecutive spaces in definition label, expected \`1\` space, remove \`${match[0].length - 1}\` spaces`
});
}
}
};
}
};
const emphasisMarker = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent emphasis marker"
},
fixable: "code",
schema: [{ enum: ["_", "*", "consistent"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "emphasis-marker");
if (!config) {
return {};
}
const { options } = config;
const sourceText = context.sourceCode.getText();
let expected = options === "*" || options === "_" ? options : void 0;
return {
MDEmphasis(node) {
const [start, end] = node.range;
const actual = sourceText.charAt(start);
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected emphasis marker \`${actual}\`, expected \`${expected}\``,
fix: (fixer) => [
fixer.replaceTextRange([start, start + 1], expected),
fixer.replaceTextRange([end - 1, end], expected)
]
});
}
};
}
};
const fence = /^ {0,3}([~`])\1{2,}/u;
const listFormat = new Intl.ListFormat("en", { type: "disjunction" });
const unitFormat = new Intl.ListFormat("en", { type: "unit" });
const formatFlags = (flags) => {
const quoted = flags.map((flag) => `\`${flag}\``);
return flags.length > 3 ? unitFormat.format([...quoted.slice(0, 3), "\u2026"]) : listFormat.format(quoted);
};
const fencedCodeFlag = {
meta: {
type: "problem",
docs: { description: "Enforce fenced code language flags" },
schema: [
{
anyOf: [
{ items: { type: "string" }, type: "array" },
{
additionalProperties: false,
properties: {
allowEmpty: { type: "boolean" },
flags: { items: { type: "string" }, type: "array" }
},
type: "object"
}
]
}
]
},
create(context) {
const config = getRuleConfig(context, "fenced-code-flag");
if (!config) {
return {};
}
const options = config.options;
let allowEmpty = false;
let flags;
if (Array.isArray(options)) {
flags = options;
} else if (options && typeof options === "object") {
const settings = options;
allowEmpty = settings.allowEmpty === true;
flags = settings.flags;
}
const expected = flags ? formatFlags(flags) : "keyword";
return {
MDCode(node) {
if (!fence.test(node.raw)) {
return;
}
if (!node.lang) {
if (!allowEmpty) {
context.report({
loc: node.loc,
message: `Unexpected missing fenced code language flag in info string, expected ${expected}`
});
}
return;
}
if (flags && !flags.includes(node.lang)) {
context.report({
loc: node.loc,
message: `Unexpected fenced code language flag \`${node.lang}\` in info string, expected ${expected}`
});
}
}
};
}
};
const markerText = (marker) => marker === "`" ? "`` ` ``" : "`~`";
const fencedCodeMarker = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent fenced code marker"
},
schema: [{ enum: ["`", "~", "consistent"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "fenced-code-marker");
if (!config) {
return {};
}
let expected = config.options === "`" || config.options === "~" ? config.options : void 0;
return {
MDCode(node) {
const raw = node.raw;
let actual;
if (raw.startsWith("```")) {
actual = "`";
} else if (raw.startsWith("~~~")) {
actual = "~";
}
if (!actual) {
return;
}
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected fenced code marker ${markerText(actual)}, expected ${markerText(expected)}`
});
}
};
}
};
const finalDefinition = {
meta: {
type: "layout",
docs: { description: "Require definitions at the end" },
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "final-definition");
if (!config) {
return {};
}
return {
Program() {
const body = context.sourceCode.ast.body;
const definition = body.find(
(node) => node.type === "MDDefinition" || node.type === "MDFootnoteDefinition"
);
const index = definition ? body.indexOf(definition) : -1;
if (definition && body.slice(index + 1).some(
(node) => node.type !== "MDDefinition" && node.type !== "MDFootnoteDefinition"
)) {
context.report({
loc: definition.loc,
message: "Unexpected definition before last content, expected definitions after last content"
});
}
}
};
}
};
const finalNewline = {
meta: {
type: "layout",
docs: {
description: "Require a final newline"
},
fixable: "code",
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "final-newline");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
return {
Program() {
if (sourceText.length > 0 && !sourceText.endsWith("\n")) {
context.report({
loc: {
start: {
line: context.sourceCode.getLocFromIndex(sourceText.length).line,
column: context.sourceCode.getLocFromIndex(sourceText.length).column
},
end: {
line: context.sourceCode.getLocFromIndex(sourceText.length).line,
column: context.sourceCode.getLocFromIndex(sourceText.length).column
}
},
message: "Unexpected missing final newline character, expected line feed (`\\n`) at end of file",
fix: (fixer) => fixer.insertTextAfterRange([0, sourceText.length], "\n")
});
}
}
};
}
};
const hardBreakSpaces = {
meta: {
type: "layout",
docs: { description: "Enforce hard break spaces" },
schema: [
{
additionalProperties: false,
properties: { allowSpaces: { type: "boolean" } },
type: "object"
}
]
},
create(context) {
const config = getRuleConfig(context, "hard-break-spaces");
if (!config) {
return {};
}
const allowSpaces = config.options?.allowSpaces !== false;
return {
MDBreak(node) {
const raw = node.raw;
const size = raw.length - 1;
if (raw.startsWith(" ") && !allowSpaces || raw.startsWith(" ") && size !== 2) {
context.report({
loc: node.loc,
message: allowSpaces ? `Unexpected \`${size}\` spaces for hard break, expected \`2\` spaces` : `Unexpected \`${size}\` spaces for hard break, expected escape`
});
}
}
};
}
};
const headingIncrement = {
meta: {
type: "problem",
docs: {
description: "Warn when heading ranks increment by more than one"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "heading-increment");
if (!config) {
return {};
}
let previous = 0;
return {
MDHeading(node) {
const depth = node.depth;
const expected = previous + 1;
if (previous > 0 && depth > expected) {
context.report({
loc: node.loc,
message: `Unexpected heading rank \`${depth}\`, exected rank \`${expected}\``
});
}
previous = depth;
}
};
}
};
const styleName = (style) => {
switch (style) {
case "setext": {
return "setext";
}
case "atx-closed": {
return "ATX (closed)";
}
default: {
return "ATX";
}
}
};
const consolidate = (depth, relative) => {
if (depth < 3) {
return "atx";
}
if (relative === "atx" || relative === "setext") {
return relative;
}
};
const getHeadingStyle = (node, relative) => {
const position = node.loc.end;
const last = node.children.at(-1);
const final = last?.loc?.end;
const { depth } = node;
if (!last) {
if (position.column <= depth * 2) {
return consolidate(depth, relative);
}
return "atx-closed";
}
if (final && final.line + 1 === position.line) {
return "setext";
}
if (final && final.column + depth < position.column) {
return "atx-closed";
}
return consolidate(depth, relative);
};
const headingStyle = {
meta: {
type: "layout",
docs: {
description: "Enforce a heading style"
},
schema: [
{ enum: ["atx-closed", "atx", "consistent", "setext"], type: "string" }
]
},
create(context) {
const config = getRuleConfig(context, "heading-style");
if (!config) {
return {};
}
let expected = config.options === "atx" || config.options === "atx-closed" || config.options === "setext" ? config.options : void 0;
return {
MDHeading(node) {
const actual = getHeadingStyle(node, expected);
if (!actual) {
return;
}
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected ${styleName(actual)} heading, expected ${styleName(expected)}`
});
}
};
}
};
const linkTitleStyle = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent link title style"
},
fixable: "code",
schema: [{ enum: ['"', "'", "()", "consistent"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "link-title-style");
if (!config) {
return {};
}
let expected = config.options === '"' || config.options === "'" || config.options === "()" ? config.options : void 0;
return {
MDLink(node) {
if (!node.title) {
return;
}
const raw = new Set(node.raw);
let actual;
if (raw.has('"')) {
actual = '"';
} else if (raw.has("'")) {
actual = "'";
} else {
actual = "()";
}
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected title markers \`${actual}\`, expected \`${expected}\``
});
}
};
}
};
const listItemBulletIndent = {
meta: {
type: "layout",
docs: { description: "Disallow indented list bullets" },
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "list-item-bullet-indent");
if (!config) {
return {};
}
return {
Program(node) {
for (const child of node.body) {
if (child.type !== "MDList") {
continue;
}
for (const item of child.children) {
const actual = item.loc.start.column;
if (actual > 0) {
context.report({
loc: item.loc,
message: `Unexpected \`${actual}\` ${actual === 1 ? "space" : "spaces"} before list item, expected \`0\` spaces, remove them`
});
}
}
}
}
};
}
};
const pluralize$3 = (count) => count === 1 ? "space" : "spaces";
const listItemContentIndent = {
meta: {
type: "layout",
docs: { description: "Enforce list item content indentation" },
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "list-item-content-indent");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
return {
MDListItem(node) {
const children = node.children.filter((child) => child.loc);
const [first] = children;
if (!first) {
return;
}
let expected = first.loc.start.column;
if (typeof node.checked === "boolean") {
const checkboxStart = sourceText.lastIndexOf("[", first.range[0] - 1);
expected -= first.range[0] - checkboxStart;
}
for (const child of children.slice(1)) {
const actual = child.loc.start.column;
if (actual !== expected) {
const difference = expected - actual;
context.report({
loc: child.loc,
message: `Unexpected unaligned list item child, expected to align with first child, ${difference > 0 ? "add" : "remove"} \`${Math.abs(difference)}\` ${pluralize$3(Math.abs(difference))}`
});
}
}
}
};
}
};
const CHARS_PER_TAB = 4;
const pluralize$2 = (count) => count === 1 ? "space" : "spaces";
const getListKind = (style, loose) => {
if (style !== "mixed") {
return "";
}
return loose ? " in loose list" : " in tight list";
};
const listItemIndent = {
meta: {
type: "layout",
docs: { description: "Enforce list item indentation" },
schema: [{ enum: ["mixed", "one", "tab"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "list-item-indent");
if (!config) {
return {};
}
const configured = config.options === "mixed" || config.options === "one" || config.options === "tab" ? config.options : void 0;
const style = configured ?? "one";
const checkItem = (item, loose) => {
const head = item.children[0];
if (!head) {
return;
}
let slice = item.raw.slice(0, head.range[0] - item.range[0]);
const checkbox = slice.indexOf("[");
if (checkbox !== -1) {
slice = slice.slice(0, checkbox);
}
let end = slice.length;
while (end > 0 && (slice[end - 1] === " " || slice[end - 1] === " ")) {
end--;
}
let expectedIndent = end + 1;
if (style === "tab" || style === "mixed" && loose) {
expectedIndent = Math.ceil(expectedIndent / CHARS_PER_TAB) * CHARS_PER_TAB;
}
const expectedSpaces = expectedIndent - end;
const actualSpaces = slice.length - end;
if (actualSpaces !== expectedSpaces) {
const difference = expectedSpaces - actualSpaces;
const listKind = getListKind(style, loose);
const direction = difference > 0 ? "add" : "remove";
context.report({
loc: head.loc,
message: `Unexpected \`${actualSpaces}\` ${pluralize$2(actualSpaces)} between list item marker and content${listKind}, expected \`${expectedSpaces}\` ${pluralize$2(expectedSpaces)}, ${direction} \`${Math.abs(difference)}\` ${pluralize$2(Math.abs(difference))}`
});
}
};
return {
MDList(list) {
const loose = list.spread || list.children.some((item) => "spread" in item && item.spread);
for (const item of list.children) {
checkItem(item, loose);
}
}
};
}
};
const pluralize$1 = (count) => count === 1 ? "line" : "lines";
const listItemSpacing = {
meta: {
type: "layout",
docs: { description: "Enforce list item spacing" },
schema: [
{
additionalProperties: false,
properties: { checkBlanks: { type: "boolean" } },
type: "object"
}
]
},
create(context) {
const config = getRuleConfig(context, "list-item-spacing");
if (!config) {
return {};
}
return {
MDList(node) {
const spaced = node.children.some((item) => {
if (config.options?.checkBlanks) {
return item.spread;
}
const tail = item.children.at(-1);
return !!tail?.loc && tail.loc.end.line - item.loc.start.line > 0;
});
const expected = spaced ? 1 : 0;
let previous;
for (const item of node.children) {
if (previous?.loc) {
const actual = item.loc.start.line - previous.loc.end.line - 1;
if (actual !== expected) {
const difference = expected - actual;
const direction = difference > 0 ? "add" : "remove";
const differenceAbsolute = Math.abs(difference);
context.report({
loc: { start: previous.loc.end, end: item.loc.start },
message: `Unexpected \`${actual}\` blank ${pluralize$1(actual)} between list items, expected \`${expected}\` blank ${pluralize$1(expected)}, ${direction} \`${differenceAbsolute}\` blank ${pluralize$1(differenceAbsolute)}`
});
}
}
previous = item;
}
}
};
}
};
const maximumHeadingLength = {
meta: {
type: "problem",
docs: {
description: "Enforce a maximum heading length"
},
schema: [
{
anyOf: [
{ type: "number" },
{
additionalProperties: false,
properties: {
size: { type: ["number", "null"] },
stringLength: ANY_OPTION_SCHEMA
},
type: "object"
}
]
}
]
},
create(context) {
const config = getRuleConfig(context, "maximum-heading-length");
if (!config) {
return {};
}
const size = typeof config.options === "object" ? config.options.size : config.options;
const expected = typeof size === "number" ? size : 60;
const report = (node) => {
const actual = [...getNodeText(node)].length;
if (actual > expected) {
context.report({
loc: node.loc,
message: `Unexpected \`${actual}\` characters in heading, expected at most \`${expected}\` characters`
});
}
};
return {
MDHeading(node) {
report(node);
},
JSXElement(node) {
const name = node.openingElement.name;
if (name.type !== "JSXIdentifier" || !/^h[1-6]$/u.test(name.name)) {
return;
}
report(node);
}
};
}
};
const IGNORED_TYPES = /* @__PURE__ */ new Set([
"MDCode",
"MDDefinition",
"MDHeading",
"MDHtml",
"MDMath",
"MDTable",
"MDToml",
"MDXFlowExpression",
"MDXTextExpression",
"MDYaml",
"JSXExpressionContainer"
]);
const INLINE_TYPES = /* @__PURE__ */ new Set(["MDImage", "MDInlineCode", "MDLink"]);
const maximumLineLength = {
meta: {
type: "problem",
docs: { description: "Enforce maximum line length" },
schema: [
{
anyOf: [
{ type: "number" },
{
additionalProperties: false,
properties: { size: { type: ["number", "null"] } },
type: "object"
}
]
}
]
},
create(context) {
const config = getRuleConfig(context, "maximum-line-length");
if (!config) {
return {};
}
const size = typeof config.options === "object" && config.options !== null ? config.options.size : config.options;
const expected = typeof size === "number" ? size : 80;
const sourceText = context.sourceCode.getText();
const lines = sourceText.split(/\r?\n/u);
const blankLines = (node) => {
for (let line = node.loc.start.line - 1; line < node.loc.end.line; line++) {
lines[line] = "";
}
};
const visit = (node, parent, index) => {
if (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration") {
blankLines(node);
return;
}
if (IGNORED_TYPES.has(node.type)) {
blankLines(node);
return;
}
if (INLINE_TYPES.has(node.type) && node.loc && parent?.children) {
const startLine = node.loc.start.line;
const startColumn = node.loc.start.column + 1;
const endColumn = node.loc.end.column + 1;
const next = parent.children[index + 1];
const nextStart = next?.loc?.start;
if (startColumn <= expected && endColumn >= expected) {
const hasBreakOpportunity = nextStart?.line === startLine && (next.value == null || /^[^\r\n]*[ \t]/u.test(next.value));
if (!hasBreakOpportunity) {
blankLines(node);
}
}
}
if (node.expression) {
visit(node.expression, node, 0);
}
for (const [childIndex, child] of (node.children ?? []).entries()) {
visit(child, node, childIndex);
}
};
return {
Program(node) {
for (const [index, child] of node.body.entries()) {
visit(child, void 0, index);
}
for (const [index, line] of lines.entries()) {
const actual = [...line].length;
const difference = actual - expected;
if (difference > 0) {
context.report({
loc: {
start: { line: index + 1, column: line.length },
end: { line: index + 1, column: line.length }
},
message: `Unexpected \`${actual}\` character line, expected at most \`${expected}\` characters, remove \`${difference}\` ${difference === 1 ? "character" : "characters"}`
});
}
}
}
};
}
};
const plural = (count) => count === 1 ? "marker" : "markers";
const countMarkers = (line) => {
let count = 0;
for (const char of line) {
if (char === ">") {
count++;
} else if (char !== " " && char !== " ") {
break;
}
}
return count;
};
const noBlockquoteWithoutMarker = {
meta: {
type: "problem",
docs: { description: "Disallow blockquotes without markers" },
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-blockquote-without-marker");
if (!config) {
return {};
}
let depth = 0;
return {
MDBlockquote() {
depth++;
},
"MDBlockquote:exit"() {
depth--;
},
MDParagraph(node) {
if (depth === 0) {
return;
}
const lines = node.raw.split("\n");
for (const [index, line] of lines.entries()) {
if (index === 0 || !line.trim()) {
continue;
}
const actual = countMarkers(line);
const expected = depth;
if (actual !== expected) {
const difference = expected - actual;
context.report({
loc: {
start: {
line: node.loc.start.line + index,
column: 0
},
end: {
line: node.loc.start.line + index,
column: line.length
}
},
message: `Unexpected \`${actual}\` block quote ${plural(actual)} before paragraph line, expected \`${expected}\` ${plural(expected)}, ${["remove", "remove", "add"][Math.sign(difference) + 1]} \`${Math.abs(difference)}\` ${plural(Math.abs(difference))}`
});
}
}
}
};
}
};
const noConsecutiveBlankLines = {
meta: {
type: "layout",
docs: {
description: "Disallow consecutive blank lines"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-consecutive-blank-lines");
if (!config) {
return {};
}
const check = (children) => {
let previousLoc;
for (const current of children) {
const currentLoc = current.loc;
const difference = previousLoc ? currentLoc.start.line - previousLoc.end.line - 2 : 0;
if (difference > 0) {
const actual = difference + 1;
context.report({
loc: currentLoc,
message: `Unexpected \`${actual}\` blank lines before node, expected up to \`1\` blank line, remove \`${difference}\` blank line`
});
}
previousLoc = currentLoc;
}
};
return {
Program(node) {
check(node.body);
},
MDBlockquote(node) {
check(node.children);
},
MDList(node) {
check(node.children);
},
MDListItem(node) {
check(node.children);
}
};
}
};
const noDuplicateDefinitions = {
meta: {
type: "problem",
docs: {
description: "Disallow duplicate definitions"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-duplicate-definitions");
if (!config) {
return {};
}
const definitions = /* @__PURE__ */ new Set();
const footnoteDefinitions = /* @__PURE__ */ new Set();
const check = (node, footnote) => {
const identifiers = footnote ? footnoteDefinitions : definitions;
if (identifiers.has(node.identifier)) {
const prefix = footnote ? "footnote " : "";
context.report({
loc: node.loc,
message: `Unexpected ${prefix}definition with an already defined identifier (\`${node.identifier}\`), expected unique identifiers`
});
}
identifiers.add(node.identifier);
};
return {
MDDefinition(node) {
check(node, false);
},
MDFootnoteDefinition(node) {
check(node, true);
}
};
}
};
const noDuplicateHeadingsInSection = {
meta: {
type: "problem",
docs: {
description: "Disallow duplicate headings within a section"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-duplicate-headings-in-section");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
const stack = [];
return {
MDHeading(node) {
const rank = node.depth;
const value = sourceText.slice(node.range[0], node.range[1]).replace(/^\s*#{1,6}\s*/u, "").trim().toLowerCase();
const map = stack[rank - 1] ?? /* @__PURE__ */ new Map();
stack[rank - 1] = map;
if (map.has(value)) {
context.report({
loc: node.loc,
message: "Unexpected heading with equivalent text in section, expected unique headings"
});
}
map.set(value, node);
stack.length = rank;
}
};
}
};
const noDuplicateHeadings = {
meta: {
type: "problem",
docs: {
description: "Disallow duplicate headings"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-duplicate-headings");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
const headings = /* @__PURE__ */ new Set();
return {
MDHeading(node) {
const text = sourceText.slice(node.range[0], node.range[1]).replace(/^\s*#{1,6}\s*/u, "").trim().toLowerCase();
if (headings.has(text)) {
context.report({
loc: node.loc,
message: "Unexpected heading with equivalent text, expected unique headings"
});
}
headings.add(text);
}
};
}
};
const isParagraph = (node) => node?.type === "MDParagraph";
const noEmphasisAsHeading = {
meta: {
type: "problem",
docs: {
description: "Disallow emphasis used as a heading"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-emphasis-as-heading");
if (!config) {
return {};
}
return {
MDParagraph(node) {
const parent = node.parent;
const children = parent?.children ?? parent?.body;
const index = children.indexOf(node);
const next = children[index + 1];
if (!isParagraph(next)) {
return;
}
const [head] = node.children;
if (node.children.length !== 1 || head?.type !== "MDEmphasis" && head?.type !== "MDStrong") {
return;
}
context.report({
loc: node.loc,
message: `Unexpected ${head.type === "MDStrong" ? "strong" : "emphasis"} introducing a section, expected a heading instead`
});
}
};
}
};
const noFileNameArticles = {
meta: {
type: "problem",
docs: {
description: "Disallow articles at the start of file names"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-file-name-articles");
if (!config) {
return {};
}
const stem = path.basename(context.filename, path.extname(context.filename));
const match = /^(?:the|teh|an?)\b/iu.exec(stem);
if (match) {
context.report({
loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
message: `Unexpected file name starting with \`${match[0]}\`, remove it`
});
}
return {};
}
};
const noFileNameConsecutiveDashes = {
meta: {
type: "problem",
docs: {
description: "Disallow consecutive dashes in file names"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-file-name-consecutive-dashes");
if (!config) {
return {};
}
const stem = path.basename(context.filename, path.extname(context.filename));
if (/-{2,}/u.test(stem)) {
context.report({
loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
message: "Unexpected consecutive dashes in a file name, expected `-`"
});
}
return {};
}
};
const noFileNameIrregularCharacters = {
meta: {
type: "problem",
docs: {
description: "Disallow irregular characters in file names"
},
schema: [{ type: ["string", "object", "null"] }]
},
create(context) {
const config = getRuleConfig(context, "no-file-name-irregular-characters");
if (!config) {
return {};
}
const expected = config.options == null ? /[^-.\dA-Za-z]/u : typeof config.options === "string" ? new RegExp(`[^${config.options}]`, "u") : config.options;
const stem = path.basename(context.filename, path.extname(context.filename));
const match = expected.exec(stem);
if (match) {
context.report({
loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
message: `Unexpected character \`${match[0]}\` in file name`
});
}
return {};
}
};
const noFileNameMixedCase = {
meta: {
type: "problem",
docs: {
description: "Disallow mixed case in file names"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-file-name-mixed-case");
if (!config) {
return {};
}
const stem = path.basename(context.filename, path.extname(context.filename));
if (stem && stem !== stem.toLowerCase() && stem !== stem.toUpperCase()) {
context.report({
loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
message: "Unexpected mixed case in file name, expected either lowercase or uppercase"
});
}
return {};
}
};
const noFileNameOuterDashes = {
meta: {
type: "problem",
docs: {
description: "Disallow initial or final dashes in file names"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-file-name-outer-dashes");
if (!config) {
return {};
}
const stem = path.basename(context.filename, path.extname(context.filename));
if (/^-|-$/u.test(stem)) {
context.report({
loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
message: "Unexpected initial or final dashes in file name, expected dashes to join words"
});
}
return {};
}
};
const noHeadingContentIndent = {
meta: {
type: "layout",
docs: {
description: "Enforce one space between heading markers and content"
},
fixable: "code",
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-heading-content-indent");
if (!config) {
return {};
}
return {
MDHeading(node) {
const spaceMatch = /^(#+)([ \t]+)/u.exec(node.raw);
if (!spaceMatch) {
return;
}
const size = spaceMatch[2].length;
if (size <= 1) {
return;
}
const start = node.range[0] + spaceMatch[1].length;
context.report({
loc: {
start: {
line: node.loc.start.line,
column: node.loc.start.column + start - node.range[0]
},
end: {
line: node.loc.start.line,
column: node.loc.start.column + start - node.range[0] + size
}
},
message: `Unexpected \`${size}\` spaces between hashes and content, expected \`1\` space, remove \`${size - 1}\` spaces`,
fix: (fixer) => fixer.replaceTextRange([start, start + size], " ")
});
}
};
}
};
const noHeadingPunctuation = {
meta: {
type: "problem",
docs: {
description: "Disallow punctuation at the end of headings"
},
schema: [{ type: ["string", "object", "null"] }]
},
create(context) {
const config = getRuleConfig(context, "no-heading-punctuation");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
const expected = config.options == null ? /[!,.:;?]/u : typeof config.options === "string" ? new RegExp(`[${config.options}]`, "u") : config.options;
return {
MDHeading(node) {
const text = sourceText.slice(node.range[0], node.range[1]).replace(/^\s*#{1,6}\s*/u, "").trim();
const tail = [...text].at(-1);
if (tail && expected.test(tail)) {
context.report({
loc: node.loc,
message: `Unexpected character \`${tail}\` at end of heading, remove it`
});
}
}
};
}
};
const defaultHttp = "http://";
const defaultMailto = "mailto:";
const noLiteralUrls = {
meta: {
type: "problem",
docs: {
description: "Disallow literal URLs"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-literal-urls");
if (!config) {
return {};
}
const isMdx = isMdxFile(
context.filename,
getParserOptions(context).extensions
);
return {
MDLink(node) {
const raw = node.raw;
if (raw.startsWith("[")) {
return;
}
let protocol;
switch (true) {
case raw === node.url: {
break;
}
case defaultHttp + raw === node.url: {
protocol = defaultHttp;
break;
}
case defaultMailto + raw === node.url: {
protocol = defaultMailto;
break;
}
default: {
return;
}
}
const expectedKind = isMdx ? "regular link" : "regular autolink";
const marker = protocol ?? "";
const suggestion = isMdx ? "use `[text](url)` instead" : `add \`<${marker}\` before and \`>\` after`;
context.report({
loc: node.loc,
message: `Unexpected GFM autolink literal, expected ${expectedKind}, ${suggestion}`
});
}
};
}
};
const noMultipleToplevelHeadings = {
meta: {
type: "problem",
docs: {
description: "Disallow multiple top-level headings"
},
schema: [{ type: "number" }]
},
create(context) {
const config = getRuleConfig(context, "no-multiple-toplevel-headings");
if (!config) {
return {};
}
const rank = config.options || 1;
let seen = false;
return {
MDHeading(node) {
if (node.depth !== rank) {
return;
}
if (seen) {
context.report({
loc: node.loc,
message: `Unexpected duplicate toplevel heading, exected a single heading with rank \`${rank}\``
});
}
seen = true;
}
};
}
};
const shellLanguages = /* @__PURE__ */ new Set([
"bash",
"bats",
"command",
"csh",
"ebuild",
"eclass",
"ksh",
"sh",
"sh.in",
"tcsh",
"tmux",
"tool",
"zsh",
"zsh-theme",
"abuild",
"alpine-abuild",
"apkbuild",
"gentoo-ebuild",
"gentoo-eclass",
"openrc",
"openrc-runscript",
"shell",
"shell-script"
]);
const noShellDollars = {
meta: {
type: "problem",
docs: {
description: "Disallow shell code prefixed by dollar signs"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-shell-dollars");
if (!config) {
return {};
}
return {
MDCode(node) {
if (!node.lang || !shellLanguages.has(node.lang)) {
return;
}
const lines = node.value.split("\n").map((line) => line.trim()).filter(Boolean);
if (lines.length > 0 && lines.every((line) => line.startsWith("$"))) {
context.report({
loc: node.loc,
message: "Unexpected shell code with every line prefixed by `$`, expected different code for input and output"
});
}
}
};
}
};
const noShortcutReferenceImage = {
meta: {
type: "problem",
docs: {
description: "Disallow shortcut reference images"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-shortcut-reference-image");
if (!config) {
return {};
}
return {
MDImageReference(node) {
if (node.referenceType === "shortcut") {
context.report({
loc: node.loc,
message: "Unexpected shortcut reference image (`![text]`), expected collapsed reference (`![text][]`)"
});
}
}
};
}
};
const noShortcutReferenceLink = {
meta: {
type: "problem",
docs: {
description: "Disallow shortcut reference links"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-shortcut-reference-link");
if (!config) {
return {};
}
return {
MDLinkReference(node) {
if (node.referenceType === "shortcut") {
context.report({
loc: node.loc,
message: "Unexpected shortcut reference link (`[text]`), expected collapsed reference (`[text][]`)"
});
}
}
};
}
};
const noTableIndentation = {
meta: {
type: "layout",
docs: {
description: "Disallow indentation before table rows"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-table-indentation");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
return {
MDTable(node) {
const [first, ...rest] = node.children;
const lineStart = sourceText.lastIndexOf("\n", first.range[0] - 1) + 1;
const prefix = sourceText.slice(lineStart, first.range[0]);
const leading = /^\s+$/u.test(prefix) ? prefix.length : 0;
if (leading > 0) {
const spaces = leading === 1 ? "space" : "spaces";
context.report({
loc: first.loc,
message: `Unexpected \`${leading}\` extra ${spaces} before table row, remove \`${leading}\` ${spaces}`
});
}
const expected = first.loc.start.column;
for (const row of rest) {
const actual = row.loc.start.column - expected;
if (actual > 0) {
const spaces = actual === 1 ? "space" : "spaces";
context.report({
loc: row.loc,
message: `Unexpected \`${actual}\` extra ${spaces} before table row, remove \`${actual}\` ${spaces}`
});
}
}
}
};
}
};
const FULL_REFERENCE_LENGTH = 4;
const labelFor = (before, after) => {
if (before === "!") {
return "image";
}
return after === "^" ? "footnote" : "link";
};
const noUndefinedReferences = {
meta: {
type: "problem",
docs: { description: "Disallow undefined references" },
schema: [
{
additionalProperties: false,
properties: {
allow: {
items: { type: ["string", "object"] },
type: "array"
},
allowShortcutLink: { type: "boolean" }
},
type: "object"
}
]
},
create(context) {
const config = getRuleConfig(context, "no-undefined-references");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
const options = config.options;
const allowShortcutLink = options?.allowShortcutLink === true;
const allowStrings = /* @__PURE__ */ new Set();
const allowRegexes = [];
for (const value of options?.allow ?? []) {
if (typeof value === "string") {
allowStrings.add(micromarkUtilNormalizeIdentifier.normalizeIdentifier(value));
} else {
allowRegexes.push(new RegExp(value.source, value.flags ?? "i"));
}
}
const definitions = /* @__PURE__ */ new Set();
const footnoteDefinitions = /* @__PURE__ */ new Set();
const report = (range, node) => {
if (range.length === 2 && range[0] + 2 === range[1]) {
return;
}
const startOffset = node.range[0];
const before = sourceText[startOffset + range[0] - 1];
const after = sourceText[startOffset + range[0] + 1];
const label = labelFor(before, after);
const offset = range.length === FULL_REFERENCE_LENGTH && range[2] + 2 !== range[3] ? 2 : 0;
let identifier = micromarkUtilNormalizeIdentifier.normalizeIdentifier(
collapseWhiteSpace.collapseWhiteSpace(
sourceText.slice(
startOffset + range[offset] + 1,
startOffset + range[offset + 1] - 1
),
{ style: "html", trim: true }
)
);
let defined = definitions;
if (label === "footnote") {
if (identifier.includes(" ")) {
return;
}
defined = footnoteDefinitions;
identifier = identifier.slice(1);
}
if (allowShortcutLink && range.length === 2 || defined.has(identifier) || allowStrings.has(identifier) || allowRegexes.some((regex) => regex.test(identifier))) {
return;
}
context.report({
loc: {
end: context.sourceCode.getLocFromIndex(startOffset + range.at(-1)),
start: context.sourceCode.getLocFromIndex(startOffset + range[0])
},
message: `Unexpected reference to undefined definition, expected corresponding definition (\`${identifier.toLowerCase()}\`) for ${label === "image" ? "an" : "a"} ${label} or escaped opening bracket (\`\\[\`) for regular text`
});
};
const scan = (value, node) => {
const ranges = [];
let index = 0;
while (index < value.length) {
const char = value[index];
switch (char) {
case "[": {
ranges.push([index]);
index++;
break;
}
case "\\": {
const next = value[index + 1];
index++;
if (next === "[" || next === "]") {
index++;
}
break;
}
case "]": {
const range = ranges.at(-1);
if (!range) {
index++;
} else if (value[index + 1] === "[" && range.length !== 3) {
index++;
range.push(index, index);
index++;
} else {
index++;
range.push(index);
report(range, node);
ranges.pop();
}
break;
}
default: {
index++;
}
}
}
};
return {
MDDefinition(node) {
definitions.add(micromarkUtilNormalizeIdentifier.normalizeIdentifier(node.identifier));
},
MDFootnoteDefinition(node) {
footnoteDefinitions.add(micromarkUtilNormalizeIdentifier.normalizeIdentifier(node.identifier));
},
MDText(node) {
scan(node.raw, node);
}
};
}
};
const noUnusedDefinitions = {
meta: {
type: "problem",
docs: {
description: "Disallow unused definitions"
},
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "no-unused-definitions");
if (!config) {
return {};
}
const definitions = /* @__PURE__ */ new Map();
const used = /* @__PURE__ */ new Set();
const markUsed = (identifier) => {
used.add(identifier);
};
return {
MDDefinition(node) {
definitions.set(node.identifier, {
identifier: node.identifier,
node
});
},
MDFootnoteDefinition(node) {
definitions.set(node.identifier, {
identifier: node.identifier,
node
});
},
MDImageReference(node) {
markUsed(node.identifier);
},
MDLinkReference(node) {
markUsed(node.identifier);
},
MDFootnoteReference(node) {
markUsed(node.identifier);
},
"Program:exit"() {
for (const { identifier, node } of definitions.values()) {
if (used.has(identifier)) {
continue;
}
const prefix = node.type === "MDFootnoteDefinition" ? "footnote " : "";
context.report({
loc: node.loc,
message: `Unexpected unused ${prefix}definition, expected no definition or one or more ${prefix}references to \`${identifier}\``
});
}
}
};
}
};
const orderedListMarkerStyle = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent ordered list marker style"
},
fixable: "code",
schema: [{ enum: [".", ")", "consistent"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "ordered-list-marker-style");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
let expected = config.options === "." || config.options === ")" ? config.options : void 0;
const checkItem = (item) => {
const start = item.range[0];
const raw = sourceText.slice(start, item.range[1]);
const match = /^\d+([.)])/u.exec(raw);
const actual = match[1];
expected ??= actual;
if (actual === expected) {
return;
}
const markerIndex = start + match[0].length - 1;
const markerStart = context.sourceCode.getLocFromIndex(markerIndex);
context.report({
loc: { start: markerStart, end: markerStart },
message: `Unexpected ordered list marker \`${actual}\`, expected \`${expected}\``,
fix: (fixer) => fixer.replaceTextRange([markerIndex, markerIndex + 1], expected)
});
};
return {
MDList(list) {
if (!list.ordered) {
return;
}
for (const item of list.children) {
checkItem(item);
}
}
};
}
};
const configuredStyle = (option) => {
if (option === "one" || option === "ordered" || option === "single") {
return option;
}
};
const inferStyle = (first, second) => {
if (second != null && second === first) {
return "single";
}
return "ordered";
};
const expectedValue = (style, first, index) => {
if (style === "one") {
return 1;
}
return style === "single" ? first : first + index;
};
const markerValue = (item) => {
const match = /^(\d+)[.)]/u.exec(item.raw);
return Number(match[1]);
};
const orderedListMarkerValue = {
meta: {
type: "layout",
docs: { description: "Enforce ordered list marker values" },
schema: [{ enum: ["one", "ordered", "single"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "ordered-list-marker-value");
if (!config) {
return {};
}
return {
MDList(node) {
if (!node.ordered) {
return;
}
const values = node.children.map((item) => markerValue(item));
const first = values[0];
const second = values[1];
const style = configuredStyle(config.options) ?? inferStyle(first, second);
for (const [index, actual] of values.entries()) {
const expected = expectedValue(style, first, index);
if (actual !== expected) {
const item = node.children[index];
const marker = /^\d+[.)]/u.exec(item.raw)[0];
const markerStart = context.sourceCode.getLocFromIndex(
item.range[0] + marker.length - 1
);
context.report({
loc: { start: markerStart, end: markerStart },
message: `Unexpected ordered list item value \`${actual}\`, expected \`${expected}\``
});
}
}
}
};
}
};
const LARGE_DOCUMENT_THRESHOLD = 64 * 1024;
const MAX_FIXED_TEXT_RATIO = 2;
let warnedAboutDeprecatedFix = false;
const warnDeprecatedFix = (enabled) => {
if (!enabled || warnedAboutDeprecatedFix) {
return;
}
warnedAboutDeprecatedFix = true;
process.emitWarning(
"Stringify-based autofixes from mdx/remark are deprecated and will be removed in a future major release. Enable the native config for targeted fixes; reporting remains supported.",
{
code: "ESLINT_MDX_DEPRECATED_REMARK_FIX",
type: "DeprecationWarning"
}
);
};
const normalizeDifference = (difference) => ({
deleteText: "",
insertText: "",
...difference
});
const getDifferences = (sourceText, fixedText) => prettierLinterHelpers.generateDifferences(sourceText, fixedText).map(normalizeDifference);
const getFixesForPlace = (differences, place) => {
if (place == null) {
return null;
}
const start = "start" in place ? place.start : place;
const end = "start" in place ? place.end : place;
if (start.offset == null || end.offset == null) {
return null;
}
const fixes = differences.filter(
({ deleteText, offset }) => offset <= end.offset && offset + deleteText.length >= start.offset
).map(({ deleteText, insertText, offset }) => ({
range: [offset, offset + deleteText.length],
text: insertText
}));
return fixes.length > 0 ? fixes : null;
};
const remark = {
meta: {
type: "layout",
docs: {
description: "Linter integration with remark plugins",
// eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
// @ts-ignore -- ESLint v10 removed
category: "Stylistic Issues",
recommended: true
},
fixable: "code",
schema: [
{
additionalProperties: false,
properties: {
deprecationWarnings: { type: "boolean" },
native: { type: "boolean" }
},
type: "object"
}
]
},
create(context) {
const nativeOption = context.options[0];
const native = nativeOption?.native === true;
const filename = context.filename ?? // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
// @ts-ignore -- ESLint v10 removed
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
/* istanbul ignore next */
context.getFilename();
const sourceCode = context.sourceCode ?? // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
// @ts-ignore -- ESLint v10 removed
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
/* istanbul ignore next */
context.getSourceCode();
const {
extensions,
markdownExtensions,
ignoreRemarkConfig,
remarkConfigPath
} = getParserOptions(context);
const isMdx = isMdxFile(filename, extensions);
const isMarkdown = isMarkdownFile(filename, markdownExtensions);
return {
Program(node) {
if (!isMdx && !isMarkdown) {
return;
}
const sourceText = sourceCode.getText(node);
const { messages, content: fixedText } = eslintMdx.performSyncWork({
filePath: eslintMdx.getPhysicalFilename(filename),
code: sourceText,
cwd: context.cwd ?? // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
// @ts-ignore -- ESLint v10 removed
// eslint-disable-next-line @typescript-eslint/no-unsafe-call -- ESLint v10 removed
/* istanbul ignore next */
context.getCwd(),
isMdx,
process: true,
ignoreRemarkConfig,
ignoreRemarkRules: native ? NATIVE_REMARK_RULES : /* @__PURE__ */ new Set(),
remarkConfigPath
});
let differences;
let wholeDocumentFixed = false;
const getDifferencesOnce = () => differences ??= getDifferences(sourceText, fixedText);
for (const {
source,
reason,
ruleId,
fatal,
line,
column,
place
} of messages) {
const severity = fatal ? 2 : fatal == null ? 0 : 1;
if (!severity) {
continue;
}
const message = {
reason,
source,
ruleId,
severity
};
const point = {
line,
// ! eslint ast column is 0-indexed, but unified is 1-indexed
column: column - 1
};
context.report({
// related to https://github.com/eslint/eslint/issues/14198
message: JSON.stringify(message),
loc: (
/* istanbul ignore next */
place && "start" in place ? {
...point,
start: { ...place.start, column: place.start.column - 1 },
end: { ...place.end, column: place.end.column - 1 }
} : point
),
node,
fix: () => {
warnDeprecatedFix(nativeOption?.deprecationWarnings !== false);
if (fixedText == null || fixedText === sourceText) {
return null;
}
if (fixedText.length > sourceText.length * MAX_FIXED_TEXT_RATIO) {
return null;
}
if (sourceText.length > LARGE_DOCUMENT_THRESHOLD) {
if (wholeDocumentFixed) {
return null;
}
wholeDocumentFixed = true;
return [
{
range: [0, sourceText.length],
text: fixedText
}
];
}
return getFixesForPlace(getDifferencesOnce(), place);
}
});
}
}
};
}
};
const ruleStyle = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent thematic rule style"
},
fixable: "code",
schema: [{ type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "rule-style");
if (!config) {
return {};
}
let expected = typeof config.options === "string" && config.options !== "consistent" ? config.options : void 0;
return {
MDThematicBreak(node) {
const actual = node.raw;
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected thematic rule \`${actual}\`, expected \`${expected}\``,
fix: (fixer) => fixer.replaceTextRange(node.range, expected)
});
}
};
}
};
const strongMarker = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent strong marker"
},
fixable: "code",
schema: [{ enum: ["_", "*", "consistent"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "strong-marker");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
let expected = config.options === "*" || config.options === "_" ? config.options : void 0;
return {
MDStrong(node) {
const [start, end] = node.range;
const actual = sourceText.charAt(start);
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected strong marker \`${actual}\`, expected \`${expected}\``,
fix: (fixer) => [
fixer.replaceTextRange([start, start + 2], expected.repeat(2)),
fixer.replaceTextRange([end - 2, end], expected.repeat(2))
]
});
}
};
}
};
const tableCellPadding = {
meta: {
type: "layout",
docs: { description: "Enforce table cell padding" },
schema: [{ enum: ["compact", "consistent", "padded"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "table-cell-padding");
if (!config) {
return {};
}
return {
MDTable(node) {
let expected = config.options === "padded" || config.options === "compact" ? config.options : void 0;
for (const row of node.children) {
const raw = row.raw;
const padded = /^\|\s/u.test(raw) && /\s\|$/u.test(raw);
expected ??= padded ? "padded" : "compact";
if (expected === "padded" !== padded) {
context.report({
loc: row.loc,
message: `Unexpected table cell padding, expected ${expected} cells`
});
}
}
}
};
}
};
const PIPE = 124;
const SPACE = 32;
const CARRIAGE_RETURN = 13;
const LINE_FEED = 10;
const TAB = 9;
const GREATER_THAN = 62;
const pluralize = (count) => count === 1 ? "space" : "spaces";
const tablePipeAlignment = {
meta: {
type: "layout",
docs: { description: "Enforce table pipe alignment" },
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "table-pipe-alignment");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
const inferSize = (startOffset, endOffset, tailCell) => {
let leftIndex = startOffset;
let left;
if (sourceText.codePointAt(leftIndex) === PIPE) {
left = 0;
leftIndex++;
while (sourceText.codePointAt(leftIndex) === SPACE) {
left++;
leftIndex++;
}
}
let rightIndex = endOffset;
let right;
if (tailCell) {
while (sourceText.codePointAt(rightIndex - 1) === SPACE) {
rightIndex--;
}
if (rightIndex > leftIndex && sourceText.codePointAt(rightIndex - 1) === PIPE) {
rightIndex--;
} else {
rightIndex = endOffset;
}
}
const rightEdgeIndex = rightIndex;
if (sourceText.codePointAt(rightIndex) === PIPE) {
right = 0;
while (rightIndex - 1 > leftIndex && sourceText.codePointAt(rightIndex - 1) === SPACE) {
right++;
rightIndex--;
}
}
return {
left,
leftOffset: leftIndex,
middle: rightIndex - leftIndex,
right,
rightOffset: rightEdgeIndex
};
};
const inferAlignRow = (table) => {
const header = table.children[0];
let index = header.range[1];
if (sourceText.codePointAt(index) === CARRIAGE_RETURN) {
index++;
}
if (sourceText.codePointAt(index) !== LINE_FEED) {
return [];
}
index++;
let code = sourceText.codePointAt(index);
while (code === TAB || code === SPACE || code === GREATER_THAN) {
index++;
code = sourceText.codePointAt(index);
}
let lineEndOffset = sourceText.indexOf("\n", index);
if (lineEndOffset === -1) {
lineEndOffset = sourceText.length;
}
if (sourceText.codePointAt(lineEndOffset - 1) === CARRIAGE_RETURN) {
lineEndOffset--;
}
let column = 0;
let cellStart = index;
let cellEnd = sourceText.indexOf("|", index + (code === PIPE ? 1 : 0));
if (cellEnd === -1 || cellEnd > lineEndOffset) {
cellEnd = lineEndOffset;
}
const entries = [];
while (cellStart !== cellEnd) {
let nextCellEnd = sourceText.indexOf("|", cellEnd + 1);
if (nextCellEnd === -1 || nextCellEnd > lineEndOffset) {
nextCellEnd = lineEndOffset;
}
if (nextCellEnd === lineEndOffset) {
let maybeEnd = lineEndOffset;
let trail = sourceText.codePointAt(maybeEnd - 1);
while (trail === TAB || trail === SPACE) {
maybeEnd--;
trail = sourceText.codePointAt(maybeEnd - 1);
}
if (cellEnd + 1 === maybeEnd) {
cellEnd = lineEndOffset;
}
}
entries.push({
align: table.align?.[column] ?? null,
column,
contentStart: index,
size: inferSize(cellStart, cellEnd, cellEnd === lineEndOffset)
});
cellStart = cellEnd;
cellEnd = nextCellEnd;
column++;
}
return entries;
};
const inferTable = (table) => {
const entries = [];
for (const [row, rowNode] of table.children.entries()) {
for (const [column, cell] of rowNode.children.entries()) {
entries.push({
align: table.align?.[column] ?? null,
column,
row,
size: inferSize(
cell.range[0],
cell.range[1],
column === rowNode.children.length - 1
)
});
}
if (row === 0) {
entries.push(...inferAlignRow(table));
}
}
return entries;
};
return {
MDTable(table) {
const entries = inferTable(table);
const sizes = [];
for (const entry of entries) {
const size = entry.size;
const total = size.middle + (size.left ?? 0) + (size.right ?? 0);
if (sizes[entry.column] === void 0 || total > sizes[entry.column]) {
sizes[entry.column] = total;
}
}
const warn = (entry, add, offset) => {
if (add === 0) {
return;
}
const absolute = context.sourceCode.getLocFromIndex(offset);
const position = entry.contentStart === void 0 ? absolute : {
line: absolute.line,
column: offset - entry.contentStart
};
context.report({
loc: { start: position, end: position },
message: `Unexpected unaligned cell, expected aligned pipes, add \`${add}\` ${pluralize(add)}${entry.row === void 0 ? " (or add `-` to pad alignment row cells)" : ""}`
});
};
for (const entry of entries) {
const size = entry.size;
const total = size.middle + (size.left ?? 0) + (size.right ?? 0);
const difference = sizes[entry.column] - total;
let left = 0;
let right = 0;
if (entry.align === "center" && entry.size.middle && difference > 0) {
const max = Math.floor(
(sizes[entry.column] - entry.size.middle) / 2
);
if (entry.size.right !== void 0 && max > entry.size.right) {
right = max - entry.size.right;
}
left = difference - right;
} else if (entry.align === "right") {
left = difference;
} else {
right = difference;
}
warn(entry, left, entry.size.leftOffset);
if (entry.size.right !== void 0) {
warn(entry, right, entry.size.rightOffset);
}
}
}
};
}
};
const tablePipes = {
meta: {
type: "layout",
docs: { description: "Enforce table pipes" },
schema: [ENABLED_OPTION_SCHEMA]
},
create(context) {
const config = getRuleConfig(context, "table-pipes");
if (!config) {
return {};
}
return {
MDTable(node) {
for (const row of node.children) {
const trimmed = row.raw.trim();
if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) {
context.report({
loc: row.loc,
message: "Unexpected table row without leading or trailing pipe"
});
}
}
}
};
}
};
const unorderedListMarkerStyle = {
meta: {
type: "layout",
docs: {
description: "Enforce a consistent unordered list marker"
},
fixable: "code",
schema: [{ enum: ["-", "*", "+", "consistent"], type: "string" }]
},
create(context) {
const config = getRuleConfig(context, "unordered-list-marker-style");
if (!config) {
return {};
}
const sourceText = context.sourceCode.getText();
let expected = config.options === "*" || config.options === "+" || config.options === "-" ? config.options : void 0;
return {
MDListItem(node) {
if (node.parent?.type !== "MDList" || node.parent.ordered) {
return;
}
const [start] = node.range;
const actual = sourceText.charAt(start);
expected ??= actual;
if (actual === expected) {
return;
}
context.report({
loc: node.loc,
message: `Unexpected unordered list marker \`${actual}\`, expected \`${expected}\``,
fix: (fixer) => fixer.replaceTextRange([start, start + 1], expected)
});
}
};
}
};
const rules = {
"emphasis-marker": emphasisMarker,
"final-newline": finalNewline,
"fenced-code-marker": fencedCodeMarker,
"heading-increment": headingIncrement,
"heading-style": headingStyle,
"maximum-heading-length": maximumHeadingLength,
"code-block-style": codeBlockStyle,
"list-item-indent": listItemIndent,
"list-item-spacing": listItemSpacing,
"ordered-list-marker-value": orderedListMarkerValue,
"blockquote-indentation": blockquoteIndentation,
"no-blockquote-without-marker": noBlockquoteWithoutMarker,
"checkbox-character-style": checkboxCharacterStyle,
"list-item-bullet-indent": listItemBulletIndent,
"list-item-content-indent": listItemContentIndent,
"table-pipes": tablePipes,
"table-pipe-alignment": tablePipeAlignment,
"table-cell-padding": tableCellPadding,
"final-definition": finalDefinition,
"no-undefined-references": noUndefinedReferences,
"definition-case": definitionCase,
"fenced-code-flag": fencedCodeFlag,
"hard-break-spaces": hardBreakSpaces,
"maximum-line-length": maximumLineLength,
"definition-spacing": definitionSpacing,
"no-consecutive-blank-lines": noConsecutiveBlankLines,
"no-duplicate-definitions": noDuplicateDefinitions,
"no-duplicate-headings": noDuplicateHeadings,
"no-duplicate-headings-in-section": noDuplicateHeadingsInSection,
"no-emphasis-as-heading": noEmphasisAsHeading,
"no-file-name-articles": noFileNameArticles,
"no-file-name-consecutive-dashes": noFileNameConsecutiveDashes,
"no-file-name-irregular-characters": noFileNameIrregularCharacters,
"no-file-name-mixed-case": noFileNameMixedCase,
"no-file-name-outer-dashes": noFileNameOuterDashes,
"no-heading-content-indent": noHeadingContentIndent,
"link-title-style": linkTitleStyle,
"no-heading-punctuation": noHeadingPunctuation,
"ordered-list-marker-style": orderedListMarkerStyle,
"no-literal-urls": noLiteralUrls,
"no-multiple-toplevel-headings": noMultipleToplevelHeadings,
"no-shell-dollars": noShellDollars,
"no-table-indentation": noTableIndentation,
"no-shortcut-reference-image": noShortcutReferenceImage,
"no-unused-definitions": noUnusedDefinitions,
"rule-style": ruleStyle,
"no-shortcut-reference-link": noShortcutReferenceLink,
"strong-marker": strongMarker,
"unordered-list-marker-style": unorderedListMarkerStyle,
remark
};
exports.DEFAULT_LANGUAGE_MAPPER = DEFAULT_LANGUAGE_MAPPER;
exports.base = base;
exports.blockquoteIndentation = blockquoteIndentation;
exports.checkboxCharacterStyle = checkboxCharacterStyle;
exports.cjsRequire = cjsRequire;
exports.codeBlockStyle = codeBlockStyle;
exports.codeBlocks = codeBlocks;
exports.configs = configs;
exports.createRemarkProcessor = createRemarkProcessor;
exports.definitionCase = definitionCase;
exports.definitionSpacing = definitionSpacing;
exports.emphasisMarker = emphasisMarker;
exports.fencedCodeFlag = fencedCodeFlag;
exports.fencedCodeMarker = fencedCodeMarker;
exports.finalDefinition = finalDefinition;
exports.finalNewline = finalNewline;
exports.flat = flat;
exports.flatCodeBlocks = flatCodeBlocks;
exports.getGlobals = getGlobals;
exports.getShortLang = getShortLang;
exports.hardBreakSpaces = hardBreakSpaces;
exports.headingIncrement = headingIncrement;
exports.headingStyle = headingStyle;
exports.linkTitleStyle = linkTitleStyle;
exports.listItemBulletIndent = listItemBulletIndent;
exports.listItemContentIndent = listItemContentIndent;
exports.listItemIndent = listItemIndent;
exports.listItemSpacing = listItemSpacing;
exports.maximumHeadingLength = maximumHeadingLength;
exports.maximumLineLength = maximumLineLength;
exports.meta = meta;
exports.native = native;
exports.noBlockquoteWithoutMarker = noBlockquoteWithoutMarker;
exports.noConsecutiveBlankLines = noConsecutiveBlankLines;
exports.noDuplicateDefinitions = noDuplicateDefinitions;
exports.noDuplicateHeadings = noDuplicateHeadings;
exports.noDuplicateHeadingsInSection = noDuplicateHeadingsInSection;
exports.noEmphasisAsHeading = noEmphasisAsHeading;
exports.noFileNameArticles = noFileNameArticles;
exports.noFileNameConsecutiveDashes = noFileNameConsecutiveDashes;
exports.noFileNameIrregularCharacters = noFileNameIrregularCharacters;
exports.noFileNameMixedCase = noFileNameMixedCase;
exports.noFileNameOuterDashes = noFileNameOuterDashes;
exports.noHeadingContentIndent = noHeadingContentIndent;
exports.noHeadingPunctuation = noHeadingPunctuation;
exports.noLiteralUrls = noLiteralUrls;
exports.noMultipleToplevelHeadings = noMultipleToplevelHeadings;
exports.noShellDollars = noShellDollars;
exports.noShortcutReferenceImage = noShortcutReferenceImage;
exports.noShortcutReferenceLink = noShortcutReferenceLink;
exports.noTableIndentation = noTableIndentation;
exports.noUndefinedReferences = noUndefinedReferences;
exports.noUnusedDefinitions = noUnusedDefinitions;
exports.orderedListMarkerStyle = orderedListMarkerStyle;
exports.orderedListMarkerValue = orderedListMarkerValue;
exports.overrides = overrides$1;
exports.processorOptions = processorOptions;
exports.processors = processors;
exports.recommended = recommended;
exports.remark = remark;
exports.ruleStyle = ruleStyle;
exports.rules = rules;
exports.strongMarker = strongMarker;
exports.tableCellPadding = tableCellPadding;
exports.tablePipeAlignment = tablePipeAlignment;
exports.tablePipes = tablePipes;
exports.unorderedListMarkerStyle = unorderedListMarkerStyle;