diff --git a/AGENTS.md b/AGENTS.md index b94ffe9a..9a822f11 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,6 +72,7 @@ packages/comark/ │ │ ├── binding.ts # Inline interpolation + shared conditional rendering rules │ │ ├── breaks.ts # Hard line breaks (`
`) from newlines │ │ ├── emoji.ts # Emoji shortcodes +│ │ ├── external-links.ts # `rel` and `target` on external links │ │ ├── footnotes.ts # GFM footnotes │ │ ├── heading-links.ts # Links headings to their own `id` │ │ ├── headings.ts # Deprecated alias → title-description (remove next major) @@ -550,6 +551,7 @@ import breaks from 'comark/plugins/breaks' import footnotes from 'comark/plugins/footnotes' import titleDescription from 'comark/plugins/title-description' // import headings from 'comark/plugins/headings' // deprecated alias → title-description +import externalLinks from 'comark/plugins/external-links' import headingLinks from 'comark/plugins/heading-links' import punctuation from 'comark/plugins/punctuation' import jsonRender from 'comark/plugins/json-render' diff --git a/docs/content/4.plugins/1.built-in/external-links.md b/docs/content/4.plugins/1.built-in/external-links.md new file mode 100644 index 00000000..93e9de8d --- /dev/null +++ b/docs/content/4.plugins/1.built-in/external-links.md @@ -0,0 +1,95 @@ +--- +title: External Links +description: Plugin for adding rel and target attributes to external links. +seo: + title: External Links Plugin +navigation: + icon: i-lucide-external-link +links: + - label: Parse API + icon: i-lucide-file-code + to: /reference/parse + color: neutral + variant: soft + - label: Document Model + icon: i-lucide-braces + to: /getting-started/document-model + color: neutral + variant: soft +--- + +The `comark/plugins/external-links` plugin adds `rel="nofollow"` to external links, which tells search engines not to pass ranking to the sites you link to. + +It can also add a `target`, such as `_blank`, to open them in a new tab. Both are added to the document tree, so the HTML, Vue, React, Svelte, and Angular renderers output them without a custom link component. + +## Usage + +```typescript +import { parseMarkdown } from 'comark' +import externalLinks from 'comark/plugins/external-links' + +const result = await parseMarkdown('[Nuxt](https://nuxt.com)', { + plugins: [externalLinks()] +}) +``` + +```html [Output] +

Nuxt

+``` + +--- + +## API + +### `externalLinks(options?)` + +Returns a `ComarkPlugin` that adds a `rel`, and optionally a `target`, to external links. + +**Parameters:** + +- `options?` - Optional configuration, see [Options](#options) + +**Returns:** `ComarkPlugin` + +A link is external when its `href` starts with `http://`, `https://`, or `//`. This covers Markdown links, autolinks, bare URLs, and HTML `` tags. A `rel` or `target` the link already has, written or bound (`:rel`, `:target`), is kept, such as in `[Nuxt](https://nuxt.com){rel="sponsored"}`. + +Added values are recorded in the tree as `$.autoRel` and `$.autoTarget`. Renderers don't output `$`, and Markdown output leaves out a `rel` or `target` that still has its added value. A tree parsed with this plugin can be saved back to Markdown unchanged, while the values the author wrote are kept. + +--- + +## Options + +| Option | Type | Default | Description | +|---|---|---|---| +| [`rel`](#rel) | `string` | `'nofollow'` | `rel` added to external links | +| [`target`](#target) | `string` | - | `target` added to external links | + +### `rel` + +`rel` added to external links that don't set one. + +```typescript +externalLinks({ rel: 'nofollow noopener' }) +``` + +```html [Output] +

Nuxt

+``` + +**Default:** `'nofollow'`, or `'nofollow noopener noreferrer'` on links that open a new tab + +### `target` + +`target` added to external links that don't set one. Not set by default, so links open in the same tab. + +```typescript +externalLinks({ target: '_blank' }) +``` + +```html [Output] +

Nuxt

+``` + +On a link that opens a new tab, from this option or a `target` the author wrote, the default `rel` adds `noopener` and `noreferrer`. The opened page can't reach your page through `window.opener` and doesn't receive it as the referrer. If you set [`rel`](#rel) yourself, include them. + +**Default:** none diff --git a/docs/content/4.plugins/index.md b/docs/content/4.plugins/index.md index 93d7acb3..51f1d489 100644 --- a/docs/content/4.plugins/index.md +++ b/docs/content/4.plugins/index.md @@ -91,6 +91,10 @@ Optional plugins you register via `plugins: [...]`. Convert emoji shortcodes like `:smile:` into emoji characters :: + ::card{icon="i-lucide-external-link" title="External Links" to="/plugins/built-in/external-links"} + Plugin for adding `rel="nofollow"`, and optionally a `target`, to external links. + :: + ::card{icon="i-lucide-footprints" title="Footnotes" to="/plugins/built-in/footnotes"} Plugin for adding footnote references and definitions to your Comark documents. :: diff --git a/packages/comark/src/internal/stringify/handlers/a.ts b/packages/comark/src/internal/stringify/handlers/a.ts index d216396c..a3d1fd23 100644 --- a/packages/comark/src/internal/stringify/handlers/a.ts +++ b/packages/comark/src/internal/stringify/handlers/a.ts @@ -12,6 +12,9 @@ export async function a(node: ElementNode, state: State, parent?: ElementNode) { if (attrs.$?.permalink === 'wrap') return state.flow(node, state, parent) const { href, ...rest } = attrs + // A `rel` or `target` added by `external-links` isn't part of the source + if (attrs.$?.autoRel !== undefined && rest.rel === attrs.$.autoRel) delete rest.rel + if (attrs.$?.autoTarget !== undefined && rest.target === attrs.$.autoTarget) delete rest.target const attrsString = Object.keys(rest).length > 0 ? comarkAttributes(rest) : '' const content = await state.flow(node, state) diff --git a/packages/comark/src/internal/stringify/handlers/html.ts b/packages/comark/src/internal/stringify/handlers/html.ts index 0a7dc61a..202d8ef7 100644 --- a/packages/comark/src/internal/stringify/handlers/html.ts +++ b/packages/comark/src/internal/stringify/handlers/html.ts @@ -27,6 +27,11 @@ const blockTags = new Set([ export async function html(node: ElementNode, state: State, parent?: ElementNode) { const [tag, attr, ...children] = node const { $ = {}, ...rawAttributes } = attr + // A `rel` or `target` added by `external-links` isn't part of the source + if (!state.context.html) { + if ($.autoRel !== undefined && rawAttributes.rel === $.autoRel) delete rawAttributes.rel + if ($.autoTarget !== undefined && rawAttributes.target === $.autoTarget) delete rawAttributes.target + } // In text/html mode, `one()` has already resolved this element's `:prefix` // bindings against the parent's render context and stored the result in diff --git a/packages/comark/src/plugins/external-links.ts b/packages/comark/src/plugins/external-links.ts new file mode 100644 index 00000000..f8e17aad --- /dev/null +++ b/packages/comark/src/plugins/external-links.ts @@ -0,0 +1,74 @@ +import type { ElementNode, ElementNodeAttributes } from 'comark' +import { defineComarkPlugin } from 'comark' +import { visit } from 'comark/utils' + +export interface ExternalLinksOptions { + /** + * `rel` added to external links that don't set one. + * @default 'nofollow', or 'nofollow noopener noreferrer' on links that open a new tab + */ + rel?: string + /** + * `target` added to external links that don't set one, such as `'_blank'`. + * @default undefined + */ + target?: string +} + +// `http://`, `https://`, and protocol-relative `//` URLs +const EXTERNAL_LINK_RE = /^(?:https?:)?\/\//i +// Targets that navigate an existing browsing context, so `window.opener` isn't set (keywords are case-insensitive) +const SAME_CONTEXT_TARGETS = new Set(['', '_self', '_parent', '_top']) + +/** + * Adds a `rel` to external (`http://`, `https://`, and `//`) links that don't set one, `nofollow` by default. + * + * `[Nuxt](https://nuxt.com)` becomes `Nuxt`. + * With `target`, links also get that `target`. On links that open a new tab, the default `rel` adds `noopener noreferrer`. + * A `rel` or `target` the author wrote, such as `{rel="sponsored"}`, is kept. Added values are recorded + * in `$.autoRel` and `$.autoTarget`, so Markdown output leaves them out and the source round-trips unchanged. + * + * @example + * ```ts + * externalLinks() + * + * externalLinks({ target: '_blank' }) + * ``` + */ +export default defineComarkPlugin((options = {}) => { + const { target, rel } = options + + return { + name: 'external-links', + post(state) { + visit( + state.tree, + (node) => Array.isArray(node) && node[0] === 'a', + (node) => { + const [tag, attrs, ...children] = node as ElementNode + if (typeof attrs.href !== 'string' || !EXTERNAL_LINK_RE.test(attrs.href)) return + // A bound `:rel` or `:target` resolves at render time, so the author set it + const addRel = attrs.rel === undefined && attrs[':rel'] === undefined + const addTarget = target !== undefined && attrs.target === undefined && attrs[':target'] === undefined + if (!addRel && !addTarget) return + + const $ = { ...attrs.$ } + const next: ElementNodeAttributes = { ...attrs, $ } + if (addRel) { + // A bound `:target` can't be checked at parse time, so it counts as a new tab + const linkTarget = addTarget ? target : (attrs.target ?? attrs[':target']) + const newContext = linkTarget !== undefined && !SAME_CONTEXT_TARGETS.has(String(linkTarget).toLowerCase()) + const linkRel = rel ?? (newContext ? 'nofollow noopener noreferrer' : 'nofollow') + next.rel = linkRel + $.autoRel = linkRel + } + if (addTarget) { + next.target = target + $.autoTarget = target + } + return [tag, next, ...children] + } + ) + }, + } +}) diff --git a/packages/comark/src/types.ts b/packages/comark/src/types.ts index 9e75bdf9..306f66cf 100644 --- a/packages/comark/src/types.ts +++ b/packages/comark/src/types.ts @@ -37,6 +37,10 @@ export type ElementNodeAttributes = { * before or after it. Markdown output leaves both out. */ permalink?: 'wrap' | 'separate' + /** The `rel` `external-links` added to a link. Markdown output leaves `rel` out while it still has this value. */ + autoRel?: string + /** The `target` `external-links` added to a link. Markdown output leaves `target` out while it still has this value. */ + autoTarget?: string } } diff --git a/packages/comark/test/plugins/external-links.test.ts b/packages/comark/test/plugins/external-links.test.ts new file mode 100644 index 00000000..00610890 --- /dev/null +++ b/packages/comark/test/plugins/external-links.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' +import { parseMarkdown } from '../../src/index' +import externalLinks from '../../src/plugins/external-links' +import { renderMarkdown } from '../../src/render' +import { renderHtmlForTest } from '../utils/render-html' + +const LINKS = `[External](https://nuxt.com) [Insecure](http://nuxt.com) [Internal](/about) [Hash](#top) [Relative](//relative.dev) + +[Sponsored](https://sponsor.dev){rel="sponsored"} [Nofollow](https://nofollow.dev){rel="nofollow"} [Blank](https://blank.dev){target="_blank"} [Upper](https://upper.dev){target="_SELF"} [Empty](https://empty.dev){target=""} + +Raw HTML link` + +describe('external-links plugin', () => { + it('adds `rel="nofollow"` to external links without a `rel`, plus `noopener noreferrer` on links that open a new tab', async () => { + const tree = await parseMarkdown(LINKS, { plugins: [externalLinks()] }) + + expect(await renderHtmlForTest(tree)).toBe( + [ + '

External Insecure Internal Hash https://auto.dev Relative

', + '

Sponsored Nofollow Blank Upper Empty

', + '

Raw HTML link

', + ].join('\n') + ) + }) + + it('adds a custom `rel`', async () => { + const tree = await parseMarkdown('[Nuxt](https://nuxt.com)', { + plugins: [externalLinks({ rel: 'nofollow noopener' })], + }) + + expect(tree.nodes[0]).toEqual([ + 'p', + {}, + ['a', { href: 'https://nuxt.com', rel: 'nofollow noopener', $: { autoRel: 'nofollow noopener' } }, 'Nuxt'], + ]) + }) + + it('leaves the added `rel` out of Markdown output, so round-trips stay stable', async () => { + const plugins = [externalLinks()] + const once = await renderMarkdown(await parseMarkdown(LINKS, { plugins })) + + expect(once).toBe(LINKS) + expect(await renderMarkdown(await parseMarkdown(once, { plugins }))).toBe(LINKS) + }) + + it('adds a `target` with `noopener noreferrer`, and keeps the `rel` and `target` the author wrote', async () => { + const source = `[Nuxt](https://nuxt.com) [Internal](/about) [Sponsored](https://sponsor.dev){rel="sponsored"} [Self](https://self.dev){target="_self"} + +Raw HTML link` + const plugins = [externalLinks({ target: '_blank' })] + const tree = await parseMarkdown(source, { plugins }) + + expect(await renderHtmlForTest(tree)).toBe( + [ + '

Nuxt Internal Sponsored Self

', + '

Raw HTML link

', + ].join('\n') + ) + expect(await renderMarkdown(tree)).toBe(source) + }) + + it('keeps a bound `:rel`', async () => { + const source = '---\nlinkRel: sponsored\n---\n\n[Nuxt](https://nuxt.com){:rel="frontmatter.linkRel"}' + const tree = await parseMarkdown(source, { plugins: [externalLinks()] }) + + expect(await renderHtmlForTest(tree)).toBe('

Nuxt

') + }) + + it('writes a `rel` changed after parsing', async () => { + const tree = await parseMarkdown('[Nuxt](https://nuxt.com)', { plugins: [externalLinks()] }) + ;(tree.nodes[0] as any[])[2][1].rel = 'sponsored' + + expect(await renderMarkdown(tree)).toBe('[Nuxt](https://nuxt.com){rel="sponsored"}') + }) +}) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index aac8fcb8..a5137849 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -70,14 +70,14 @@ describe('package bundle size', { timeout: 60_000 }, () => { expect(report).toMatchInlineSnapshot(` { - "@comark/angular": "69.6k (59 files)", - "@comark/ansi": "41.7k (105 files)", - "@comark/html": "17.3k (65 files)", - "@comark/nuxt": "10.6k (65 files)", - "@comark/react": "42.9k (83 files)", - "@comark/svelte": "50.3k (91 files)", - "@comark/vue": "62.6k (89 files)", - "comark": "440k (171 files)", + "@comark/angular": "70.0k (61 files)", + "@comark/ansi": "41.9k (107 files)", + "@comark/html": "17.5k (67 files)", + "@comark/nuxt": "10.8k (67 files)", + "@comark/react": "43.1k (85 files)", + "@comark/svelte": "50.5k (93 files)", + "@comark/vue": "62.8k (91 files)", + "comark": "444k (173 files)", } `) })