From 70a2eb3e3480e2ef556ec8539a67158b126be0d9 Mon Sep 17 00:00:00 2001 From: Baptiste Leproux Date: Mon, 16 Nov 2026 18:40:33 +0000 Subject: [PATCH 1/4] feat(plugins): add `external-links` plugin Amp-Thread-ID: https://ampcode.com/threads/T-01a1e59f-ac14-7116-8231-2c4fdaa3b66b --- AGENTS.md | 2 + .../4.plugins/1.built-in/external-links.md | 78 +++++++++++++++++++ docs/content/4.plugins/index.md | 4 + .../src/internal/stringify/handlers/a.ts | 2 + .../src/internal/stringify/handlers/html.ts | 2 + packages/comark/src/plugins/external-links.ts | 46 +++++++++++ packages/comark/src/types.ts | 2 + .../test/plugins/external-links.test.ts | 52 +++++++++++++ test/bundle.test.ts | 16 ++-- 9 files changed, 196 insertions(+), 8 deletions(-) create mode 100644 docs/content/4.plugins/1.built-in/external-links.md create mode 100644 packages/comark/src/plugins/external-links.ts create mode 100644 packages/comark/test/plugins/external-links.test.ts diff --git a/AGENTS.md b/AGENTS.md index 02194bff..e43c770d 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` 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..28f3b485 --- /dev/null +++ b/docs/content/4.plugins/1.built-in/external-links.md @@ -0,0 +1,78 @@ +--- +title: External Links +description: Plugin for adding a rel attribute 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. + +The `rel` is added to the document tree, so every renderer outputs it 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` to external links. + +**Parameters:** + +- `options?` - Optional configuration, see [Options](#options) + +**Returns:** `ComarkPlugin` + +A link is external when its `href` starts with `http://` or `https://`. This covers Markdown links, autolinks, bare URLs, and HTML `` tags. Links that already have a `rel`, such as `[Nuxt](https://nuxt.com){rel="sponsored"}`, are left unchanged. + +The added value is recorded in the tree as `$.autoRel`. Renderers don't output `$`, and Markdown output leaves out a `rel` that still has this value. A tree parsed with this plugin can be saved back to Markdown unchanged, while a `rel` the author wrote is kept. + +--- + +## Options + +| Option | Type | Default | Description | +|---|---|---|---| +| [`rel`](#rel) | `string` | `'nofollow'` | `rel` 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'` diff --git a/docs/content/4.plugins/index.md b/docs/content/4.plugins/index.md index 93d7acb3..35019f32 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"` 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..d448346b 100644 --- a/packages/comark/src/internal/stringify/handlers/a.ts +++ b/packages/comark/src/internal/stringify/handlers/a.ts @@ -12,6 +12,8 @@ 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` added by `external-links` isn't part of the source + if (attrs.$?.autoRel !== undefined && rest.rel === attrs.$.autoRel) delete rest.rel 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..7df6cba1 100644 --- a/packages/comark/src/internal/stringify/handlers/html.ts +++ b/packages/comark/src/internal/stringify/handlers/html.ts @@ -27,6 +27,8 @@ const blockTags = new Set([ export async function html(node: ElementNode, state: State, parent?: ElementNode) { const [tag, attr, ...children] = node const { $ = {}, ...rawAttributes } = attr + // A `rel` added by `external-links` isn't part of the source + if (!state.context.html && $.autoRel !== undefined && rawAttributes.rel === $.autoRel) delete rawAttributes.rel // 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..9f6a58f7 --- /dev/null +++ b/packages/comark/src/plugins/external-links.ts @@ -0,0 +1,46 @@ +import type { ElementNode } 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' + */ + rel?: string +} + +const EXTERNAL_LINK_RE = /^https?:\/\//i + +/** + * Adds a `rel` to external (`http://` and `https://`) links that don't set one, `nofollow` by default. + * + * `[Nuxt](https://nuxt.com)` becomes `Nuxt`. + * A `rel` the author wrote, such as `{rel="sponsored"}`, is kept. The added value is recorded + * in `$.autoRel`, so Markdown output leaves it out and the source round-trips unchanged. + * + * @example + * ```ts + * externalLinks() + * + * externalLinks({ rel: 'nofollow noopener' }) + * ``` + */ +export default defineComarkPlugin((options = {}) => { + const { rel = 'nofollow' } = 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) || attrs.rel !== undefined) return + return [tag, { ...attrs, rel, $: { ...attrs.$, autoRel: rel } }, ...children] + } + ) + }, + } +}) diff --git a/packages/comark/src/types.ts b/packages/comark/src/types.ts index 9e75bdf9..f3d85843 100644 --- a/packages/comark/src/types.ts +++ b/packages/comark/src/types.ts @@ -37,6 +37,8 @@ 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 } } 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..c5eb24c6 --- /dev/null +++ b/packages/comark/test/plugins/external-links.test.ts @@ -0,0 +1,52 @@ +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) + +[Sponsored](https://sponsor.dev){rel="sponsored"} [Nofollow](https://nofollow.dev){rel="nofollow"} + +Raw HTML link` + +describe('external-links plugin', () => { + it('adds `rel="nofollow"` to external links without a `rel`, and keeps the one the author wrote', async () => { + const tree = await parseMarkdown(LINKS, { plugins: [externalLinks()] }) + + expect(await renderHtmlForTest(tree)).toBe( + [ + '

External Insecure Internal Hash https://auto.dev

', + '

Sponsored Nofollow

', + '

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('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 b0d64568..4254956f 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": "439k (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": "441k (173 files)", } `) }) From f1203549620a756278846d175c76fd04b8e8d75d Mon Sep 17 00:00:00 2001 From: Baptiste Leproux Date: Mon, 16 Nov 2026 18:55:56 +0000 Subject: [PATCH 2/4] fix(plugins): keep a bound `:rel` in `external-links` Amp-Thread-ID: https://ampcode.com/threads/T-01a1e59f-ac14-7116-8231-2c4fdaa3b66b --- docs/content/4.plugins/1.built-in/external-links.md | 4 ++-- packages/comark/src/plugins/external-links.ts | 4 +++- packages/comark/test/plugins/external-links.test.ts | 7 +++++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/content/4.plugins/1.built-in/external-links.md b/docs/content/4.plugins/1.built-in/external-links.md index 28f3b485..f5d5f6a5 100644 --- a/docs/content/4.plugins/1.built-in/external-links.md +++ b/docs/content/4.plugins/1.built-in/external-links.md @@ -20,7 +20,7 @@ links: 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. -The `rel` is added to the document tree, so every renderer outputs it without a custom link component. +The `rel` is added to the document tree, so the HTML, Vue, React, Svelte, and Angular renderers output it without a custom link component. ## Usage @@ -51,7 +51,7 @@ Returns a `ComarkPlugin` that adds a `rel` to external links. **Returns:** `ComarkPlugin` -A link is external when its `href` starts with `http://` or `https://`. This covers Markdown links, autolinks, bare URLs, and HTML `` tags. Links that already have a `rel`, such as `[Nuxt](https://nuxt.com){rel="sponsored"}`, are left unchanged. +A link is external when its `href` starts with `http://` or `https://`. This covers Markdown links, autolinks, bare URLs, and HTML `` tags. Links that already have a `rel` or a bound `:rel`, such as `[Nuxt](https://nuxt.com){rel="sponsored"}`, are left unchanged. The added value is recorded in the tree as `$.autoRel`. Renderers don't output `$`, and Markdown output leaves out a `rel` that still has this value. A tree parsed with this plugin can be saved back to Markdown unchanged, while a `rel` the author wrote is kept. diff --git a/packages/comark/src/plugins/external-links.ts b/packages/comark/src/plugins/external-links.ts index 9f6a58f7..56b01df0 100644 --- a/packages/comark/src/plugins/external-links.ts +++ b/packages/comark/src/plugins/external-links.ts @@ -37,7 +37,9 @@ export default defineComarkPlugin((options = {}) => { (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) || attrs.rel !== undefined) return + if (typeof attrs.href !== 'string' || !EXTERNAL_LINK_RE.test(attrs.href)) return + // A bound `:rel` resolves to `rel` at render time, so the author set it + if (attrs.rel !== undefined || attrs[':rel'] !== undefined) return return [tag, { ...attrs, rel, $: { ...attrs.$, autoRel: rel } }, ...children] } ) diff --git a/packages/comark/test/plugins/external-links.test.ts b/packages/comark/test/plugins/external-links.test.ts index c5eb24c6..117d77d7 100644 --- a/packages/comark/test/plugins/external-links.test.ts +++ b/packages/comark/test/plugins/external-links.test.ts @@ -43,6 +43,13 @@ describe('external-links plugin', () => { expect(await renderMarkdown(await parseMarkdown(once, { plugins }))).toBe(LINKS) }) + 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' From 3acd6476525acbe4ddbfcfa00fe64a3b7784a43d Mon Sep 17 00:00:00 2001 From: Baptiste Leproux Date: Tue, 17 Nov 2026 15:01:58 +0000 Subject: [PATCH 3/4] feat(plugins): add `target` option to `external-links` Amp-Thread-ID: https://ampcode.com/threads/T-01a1e59f-ac14-7116-8231-2c4fdaa3b66b --- AGENTS.md | 2 +- .../4.plugins/1.built-in/external-links.md | 29 ++++++++--- docs/content/4.plugins/index.md | 2 +- .../src/internal/stringify/handlers/a.ts | 3 +- .../src/internal/stringify/handlers/html.ts | 7 ++- packages/comark/src/plugins/external-links.ts | 48 ++++++++++++++----- packages/comark/src/types.ts | 2 + .../test/plugins/external-links.test.ts | 26 ++++++++-- test/bundle.test.ts | 2 +- 9 files changed, 93 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e43c770d..7185c7bd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,7 +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` on external links +│ │ ├── 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) diff --git a/docs/content/4.plugins/1.built-in/external-links.md b/docs/content/4.plugins/1.built-in/external-links.md index f5d5f6a5..93e9de8d 100644 --- a/docs/content/4.plugins/1.built-in/external-links.md +++ b/docs/content/4.plugins/1.built-in/external-links.md @@ -1,6 +1,6 @@ --- title: External Links -description: Plugin for adding a rel attribute to external links. +description: Plugin for adding rel and target attributes to external links. seo: title: External Links Plugin navigation: @@ -20,7 +20,7 @@ links: 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. -The `rel` is added to the document tree, so the HTML, Vue, React, Svelte, and Angular renderers output it without a custom link component. +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 @@ -43,7 +43,7 @@ const result = await parseMarkdown('[Nuxt](https://nuxt.com)', { ### `externalLinks(options?)` -Returns a `ComarkPlugin` that adds a `rel` to external links. +Returns a `ComarkPlugin` that adds a `rel`, and optionally a `target`, to external links. **Parameters:** @@ -51,9 +51,9 @@ Returns a `ComarkPlugin` that adds a `rel` to external links. **Returns:** `ComarkPlugin` -A link is external when its `href` starts with `http://` or `https://`. This covers Markdown links, autolinks, bare URLs, and HTML `` tags. Links that already have a `rel` or a bound `:rel`, such as `[Nuxt](https://nuxt.com){rel="sponsored"}`, are left unchanged. +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"}`. -The added value is recorded in the tree as `$.autoRel`. Renderers don't output `$`, and Markdown output leaves out a `rel` that still has this value. A tree parsed with this plugin can be saved back to Markdown unchanged, while a `rel` the author wrote is kept. +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. --- @@ -62,6 +62,7 @@ The added value is recorded in the tree as `$.autoRel`. Renderers don't output ` | Option | Type | Default | Description | |---|---|---|---| | [`rel`](#rel) | `string` | `'nofollow'` | `rel` added to external links | +| [`target`](#target) | `string` | - | `target` added to external links | ### `rel` @@ -75,4 +76,20 @@ externalLinks({ rel: 'nofollow noopener' })

Nuxt

``` -**Default:** `'nofollow'` +**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 35019f32..51f1d489 100644 --- a/docs/content/4.plugins/index.md +++ b/docs/content/4.plugins/index.md @@ -92,7 +92,7 @@ Optional plugins you register via `plugins: [...]`. :: ::card{icon="i-lucide-external-link" title="External Links" to="/plugins/built-in/external-links"} - Plugin for adding `rel="nofollow"` to 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"} diff --git a/packages/comark/src/internal/stringify/handlers/a.ts b/packages/comark/src/internal/stringify/handlers/a.ts index d448346b..a3d1fd23 100644 --- a/packages/comark/src/internal/stringify/handlers/a.ts +++ b/packages/comark/src/internal/stringify/handlers/a.ts @@ -12,8 +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` added by `external-links` isn't part of the source + // 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 7df6cba1..202d8ef7 100644 --- a/packages/comark/src/internal/stringify/handlers/html.ts +++ b/packages/comark/src/internal/stringify/handlers/html.ts @@ -27,8 +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` added by `external-links` isn't part of the source - if (!state.context.html && $.autoRel !== undefined && rawAttributes.rel === $.autoRel) delete rawAttributes.rel + // 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 index 56b01df0..422e0c31 100644 --- a/packages/comark/src/plugins/external-links.ts +++ b/packages/comark/src/plugins/external-links.ts @@ -1,33 +1,42 @@ -import type { ElementNode } from 'comark' +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' + * @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 } -const EXTERNAL_LINK_RE = /^https?:\/\//i +// `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 +const SAME_CONTEXT_TARGETS = new Set(['_self', '_parent', '_top']) /** - * Adds a `rel` to external (`http://` and `https://`) links that don't set one, `nofollow` by default. + * Adds a `rel` to external (`http://`, `https://`, and `//`) links that don't set one, `nofollow` by default. * * `[Nuxt](https://nuxt.com)` becomes `Nuxt`. - * A `rel` the author wrote, such as `{rel="sponsored"}`, is kept. The added value is recorded - * in `$.autoRel`, so Markdown output leaves it out and the source round-trips unchanged. + * 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({ rel: 'nofollow noopener' }) + * externalLinks({ target: '_blank' }) * ``` */ export default defineComarkPlugin((options = {}) => { - const { rel = 'nofollow' } = options + const { target, rel } = options return { name: 'external-links', @@ -38,9 +47,26 @@ export default defineComarkPlugin((options = {}) => { (node) => { const [tag, attrs, ...children] = node as ElementNode if (typeof attrs.href !== 'string' || !EXTERNAL_LINK_RE.test(attrs.href)) return - // A bound `:rel` resolves to `rel` at render time, so the author set it - if (attrs.rel !== undefined || attrs[':rel'] !== undefined) return - return [tag, { ...attrs, rel, $: { ...attrs.$, autoRel: rel } }, ...children] + // 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)) + 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 f3d85843..306f66cf 100644 --- a/packages/comark/src/types.ts +++ b/packages/comark/src/types.ts @@ -39,6 +39,8 @@ export type ElementNodeAttributes = { 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 index 117d77d7..95ca17d2 100644 --- a/packages/comark/test/plugins/external-links.test.ts +++ b/packages/comark/test/plugins/external-links.test.ts @@ -4,20 +4,20 @@ 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) +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"} +[Sponsored](https://sponsor.dev){rel="sponsored"} [Nofollow](https://nofollow.dev){rel="nofollow"} [Blank](https://blank.dev){target="_blank"} Raw HTML link` describe('external-links plugin', () => { - it('adds `rel="nofollow"` to external links without a `rel`, and keeps the one the author wrote', async () => { + 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

', - '

Sponsored Nofollow

', + '

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

', + '

Sponsored Nofollow Blank

', '

Raw HTML link

', ].join('\n') ) @@ -43,6 +43,22 @@ describe('external-links plugin', () => { 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()] }) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 4254956f..b9f0e2c8 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -77,7 +77,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/react": "43.1k (85 files)", "@comark/svelte": "50.5k (93 files)", "@comark/vue": "62.8k (91 files)", - "comark": "441k (173 files)", + "comark": "443k (173 files)", } `) }) From 8f7bf96eb40c88e331def85393c818aaeeee6fea Mon Sep 17 00:00:00 2001 From: Baptiste Leproux Date: Tue, 17 Nov 2026 15:23:09 +0000 Subject: [PATCH 4/4] fix(plugins): treat empty and mixed-case same-tab targets as same-tab in `external-links` Amp-Thread-ID: https://ampcode.com/threads/T-01a1e59f-ac14-7116-8231-2c4fdaa3b66b --- packages/comark/src/plugins/external-links.ts | 6 +++--- packages/comark/test/plugins/external-links.test.ts | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/comark/src/plugins/external-links.ts b/packages/comark/src/plugins/external-links.ts index 422e0c31..f8e17aad 100644 --- a/packages/comark/src/plugins/external-links.ts +++ b/packages/comark/src/plugins/external-links.ts @@ -17,8 +17,8 @@ export interface ExternalLinksOptions { // `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 -const SAME_CONTEXT_TARGETS = new Set(['_self', '_parent', '_top']) +// 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. @@ -57,7 +57,7 @@ export default defineComarkPlugin((options = {}) => { 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)) + const newContext = linkTarget !== undefined && !SAME_CONTEXT_TARGETS.has(String(linkTarget).toLowerCase()) const linkRel = rel ?? (newContext ? 'nofollow noopener noreferrer' : 'nofollow') next.rel = linkRel $.autoRel = linkRel diff --git a/packages/comark/test/plugins/external-links.test.ts b/packages/comark/test/plugins/external-links.test.ts index 95ca17d2..00610890 100644 --- a/packages/comark/test/plugins/external-links.test.ts +++ b/packages/comark/test/plugins/external-links.test.ts @@ -6,7 +6,7 @@ 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"} +[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` @@ -17,7 +17,7 @@ describe('external-links plugin', () => { expect(await renderHtmlForTest(tree)).toBe( [ '

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

', - '

Sponsored Nofollow Blank

', + '

Sponsored Nofollow Blank Upper Empty

', '

Raw HTML link

', ].join('\n') )