-
Notifications
You must be signed in to change notification settings - Fork 76
feat: add no-reference-like-urls rule #433
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TKDev7
wants to merge
12
commits into
eslint:main
Choose a base branch
from
TKDev7:no-reference-like-url
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,446
−1
Open
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8cfbe1f
feat: add no-reference-like-url rule
TKDev7 4e2ea0a
address review feedback
TKDev7 e35922c
Merge branch 'main' into no-reference-like-url
TKDev7 a5272a5
refactor types
TKDev7 355f238
normalize urls and add more tests
TKDev7 b9a408f
fix CI
TKDev7 5ac7d7d
use regex-based parsing
TKDev7 243e831
refactor and add more tests
TKDev7 ae3713c
optimize with targeted node processing
TKDev7 06d9597
rename rule
TKDev7 22ff7fc
refactor tests
TKDev7 5aef967
simplify with ESQuery selector
TKDev7 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# no-reference-like-url | ||
|
||
Disallow URLs that match defined reference identifiers. | ||
|
||
## Background | ||
|
||
In Markdown, you can create links using either inline syntax `[text](url)` or reference syntax `[text][id]` with a separate definition `[id]: url`. This rule encourages the use of reference syntax when a link's URL matches an existing reference identifier. | ||
|
||
For example, if you have a definition like `[mercury]: https://example.com/mercury/`, then using `[text](mercury)` should be written as `[text][mercury]` instead. | ||
|
||
Please note that autofix is not performed for links or images that include a title. For example: | ||
|
||
```markdown | ||
[Mercury](mercury "The planet Mercury") | ||
 | ||
``` | ||
|
||
## Rule Details | ||
|
||
This rule flags URLs that match defined reference identifiers. | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```markdown | ||
<!-- eslint markdown/no-reference-like-url: "error" --> | ||
|
||
[**Mercury**](mercury) is the first planet from the sun. | ||
. | ||
|
||
[mercury]: https://example.com/mercury/ | ||
[venus]: https://example.com/venus.jpg | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```markdown | ||
<!-- eslint markdown/no-reference-like-url: "error" --> | ||
|
||
[**Mercury**][mercury] is the first planet from the sun. | ||
![**Venus** is a planet][venus]. | ||
|
||
[mercury]: https://example.com/mercury/ | ||
[venus]: https://example.com/venus.jpg | ||
``` | ||
|
||
## When Not to Use It | ||
|
||
If you prefer inline link syntax even when reference definitions are available, or if you're working in an environment where reference syntax is not preferred, you can safely disable this rule. | ||
|
||
## Prior Art | ||
|
||
* [remark-lint-no-reference-like-url](https://github.com/remarkjs/remark-lint/tree/main/packages/remark-lint-no-reference-like-url) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TKDev7 marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,216 @@ | ||
/** | ||
* @fileoverview Rule to enforce reference-style links when URL matches a defined identifier. | ||
* @author TKDev7 | ||
*/ | ||
|
||
//----------------------------------------------------------------------------- | ||
// Imports | ||
//----------------------------------------------------------------------------- | ||
|
||
import { normalizeIdentifier } from "micromark-util-normalize-identifier"; | ||
import { findOffsets } from "../util.js"; | ||
|
||
//----------------------------------------------------------------------------- | ||
// Type Definitions | ||
//----------------------------------------------------------------------------- | ||
|
||
/** | ||
* @import { Heading, Node, Paragraph, TableCell } from "mdast"; | ||
* @import { MarkdownRuleDefinition } from "../types.js"; | ||
* @typedef {"referenceLikeUrl"} NoReferenceLikeUrlMessageIds | ||
* @typedef {[]} NoReferenceLikeUrlOptions | ||
* @typedef {MarkdownRuleDefinition<{ RuleOptions: NoReferenceLikeUrlOptions, MessageIds: NoReferenceLikeUrlMessageIds }>} NoReferenceLikeUrlRuleDefinition | ||
*/ | ||
|
||
//----------------------------------------------------------------------------- | ||
// Helpers | ||
//----------------------------------------------------------------------------- | ||
|
||
/** Pattern to match both inline links: `[text](url)` and images: ``, with optional title */ | ||
const linkOrImagePattern = | ||
TKDev7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/(?<!\\)(?<imageBang>!)?\[(?<label>(?:\\.|[^()\\]|\([\s\S]*\))*?)\]\((?<destination>(?:<[^>]*>)|(?:[^ \t)]+))(?:[ \t]+(?<title>"[^"]*"|'[^']*'|\([^)]*\)))?\)(?!\()/gu; | ||
TKDev7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Checks if a given index is within any skip range. | ||
* @param {number} index The index to check | ||
* @param {Array<{startOffset: number, endOffset: number}>} skipRanges The skip ranges | ||
* @returns {boolean} True if index is in a skip range | ||
*/ | ||
function isInSkipRange(index, skipRanges) { | ||
return skipRanges.some( | ||
range => index >= range.startOffset && index < range.endOffset, | ||
TKDev7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
); | ||
} | ||
|
||
/** | ||
* Finds ranges of inline code and HTML nodes within a given node | ||
* @param {Heading | Paragraph | TableCell} node The node to search | ||
* @returns {Array<{startOffset: number, endOffset: number}>} Array of skip ranges | ||
*/ | ||
function findSkipRanges(node) { | ||
/** @type {Array<{startOffset: number, endOffset: number}>} */ | ||
const skipRanges = []; | ||
TKDev7 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/** | ||
* Recursively traverses the AST to find inline code and HTML nodes. | ||
* @param {Node} currentNode The current node being traversed | ||
* @returns {void} | ||
*/ | ||
function traverse(currentNode) { | ||
if (currentNode.type === "inlineCode" || currentNode.type === "html") { | ||
skipRanges.push({ | ||
startOffset: currentNode.position.start.offset, | ||
endOffset: currentNode.position.end.offset, | ||
}); | ||
return; | ||
} | ||
|
||
if ("children" in currentNode && Array.isArray(currentNode.children)) { | ||
currentNode.children.forEach(traverse); | ||
} | ||
} | ||
|
||
traverse(node); | ||
return skipRanges; | ||
} | ||
|
||
//----------------------------------------------------------------------------- | ||
// Rule Definition | ||
//----------------------------------------------------------------------------- | ||
|
||
/** @type {NoReferenceLikeUrlRuleDefinition} */ | ||
export default { | ||
meta: { | ||
type: "problem", | ||
|
||
docs: { | ||
recommended: true, | ||
description: | ||
"Disallow URLs that match defined reference identifiers", | ||
url: "https://github.com/eslint/markdown/blob/main/docs/rules/no-reference-like-url.md", | ||
}, | ||
|
||
fixable: "code", | ||
|
||
messages: { | ||
referenceLikeUrl: | ||
"Unexpected resource {{type}} ('{{prefix}}[text](url)') with URL that matches a definition identifier. Use '[text][id]' syntax instead.", | ||
}, | ||
}, | ||
|
||
create(context) { | ||
const { sourceCode } = context; | ||
/** @type {Set<string>} */ | ||
const definitionIdentifiers = new Set(); | ||
/** @type {Array<Heading | Paragraph | TableCell>} */ | ||
const relevantNodes = []; | ||
|
||
return { | ||
definition(node) { | ||
definitionIdentifiers.add(node.identifier); | ||
}, | ||
|
||
heading(node) { | ||
relevantNodes.push(node); | ||
}, | ||
|
||
paragraph(node) { | ||
relevantNodes.push(node); | ||
}, | ||
|
||
tableCell(node) { | ||
relevantNodes.push(node); | ||
}, | ||
|
||
"root:exit"() { | ||
for (const node of relevantNodes) { | ||
const text = sourceCode.getText(node); | ||
const skipRanges = findSkipRanges(node); | ||
|
||
let match; | ||
while ((match = linkOrImagePattern.exec(text)) !== null) { | ||
const { | ||
imageBang, | ||
label, | ||
destination, | ||
title: titleRaw, | ||
} = match.groups; | ||
const title = titleRaw?.slice(1, -1); | ||
const matchIndex = match.index; | ||
const matchLength = match[0].length; | ||
|
||
if ( | ||
isInSkipRange( | ||
matchIndex + node.position.start.offset, | ||
skipRanges, | ||
) | ||
) { | ||
continue; | ||
} | ||
|
||
const isImage = !!imageBang; | ||
const type = isImage ? "image" : "link"; | ||
const prefix = isImage ? "!" : ""; | ||
const url = | ||
normalizeIdentifier(destination).toLowerCase(); | ||
|
||
if (definitionIdentifiers.has(url)) { | ||
const { | ||
lineOffset: startLineOffset, | ||
columnOffset: startColumnOffset, | ||
} = findOffsets(text, matchIndex); | ||
const { | ||
lineOffset: endLineOffset, | ||
columnOffset: endColumnOffset, | ||
} = findOffsets(text, matchIndex + matchLength); | ||
|
||
const baseColumn = 1; | ||
const nodeStartLine = node.position.start.line; | ||
const nodeStartColumn = node.position.start.column; | ||
const startLine = nodeStartLine + startLineOffset; | ||
const endLine = nodeStartLine + endLineOffset; | ||
const startColumn = | ||
(startLine === nodeStartLine | ||
? nodeStartColumn | ||
: baseColumn) + startColumnOffset; | ||
const endColumn = | ||
(endLine === nodeStartLine | ||
? nodeStartColumn | ||
: baseColumn) + endColumnOffset; | ||
|
||
context.report({ | ||
loc: { | ||
start: { | ||
line: startLine, | ||
column: startColumn, | ||
}, | ||
end: { line: endLine, column: endColumn }, | ||
}, | ||
messageId: "referenceLikeUrl", | ||
data: { | ||
type, | ||
prefix, | ||
}, | ||
fix(fixer) { | ||
// The AST treats both missing and empty titles as null, so it's safe to auto-fix in both cases. | ||
if (title) { | ||
return null; | ||
} | ||
|
||
const startOffset = | ||
node.position.start.offset + matchIndex; | ||
const endOffset = startOffset + matchLength; | ||
|
||
return fixer.replaceTextRange( | ||
[startOffset, endOffset], | ||
`${prefix}[${label}][${destination}]`, | ||
); | ||
}, | ||
}); | ||
} | ||
} | ||
} | ||
}, | ||
}; | ||
}, | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.