Socket
Socket
Sign inDemoInstall

rehype-link-processor

Package Overview
Dependencies
4
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    rehype-link-processor

rehype plugin to process links adding custom css class or attributes used by external or download links


Version published
Weekly downloads
5
Maintainers
1
Install size
107 kB
Created
Weekly downloads
 

Changelog

Source

1.0.4 Patch release

feat: new 'email' builtin rule fix: force download rule to match against http* protocol

Readme

Source

rehype plugin to process links to

  • add custom css classes
  • detect external, download, same-page links
  • set attributes like rel or target
  • add custom attributes

Why

This package helps to decorate links usually in a markdown document where no extra attribute can be set.

Common scenarios:

  • set external links to open in a new page
  • decorate a link with a css class to style it, for example adding an icon next to it
  • detect external links even when the url don't start with http(s)://
  • detect download links
  • identify links under some condition to add custom attributes

When you write links in markdown, you're limited with just the url, text and title. You cannot add custom attributes, for example a css class to style that specific link as you want.

This package helps to process and transform links.

Installation

This is package is module. So an ESM compatible runtime is required (node 14+, deno, ...)

npm i rehype-link-processor
# or
pnpm add rehype-link-processor
# or
yarn add rehype-link-processor

Integration

Within a unified pipeline

Include rehype-link-processor in the pipeline:

import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeLinkProcessor from "rehype-link-processor";

const file = await unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeLinkProcessor)
  .process("...")

Within a mdx compilation

Include rehype-link-processor in the rehype plugins:

import {compile} from "@mdx-js/mdx";
import rehypeLinkProcessor from "rehype-link-processor";

const file = '[download:Get the pdf](/assets/article.pdf)';

await compile(file, { rehypePlugins: [rehypeLinkProcessor] });

In an Astro website

Include rehype-link-processor as markdown rehype plugin in the astro.config.ts:

//file: astro.config.ts
import { defineConfig } from "astro/config";
import rehypeLinkProcessor from "rehype-link-processor";

export default defineConfig({
  markdown: {
    rehypePlugins: [rehypeLinkProcessor()]
  }
);

Configuration

The processor works with rules. If a rule matches, the action is applied (the link is transformed), and the processing ends.

So the rule order is important, as the first match wins.

The rules are set via the options argument:

rehypeLinkProcessor({
  rules: [
    // add rules here
  ]
})

This package provides some builtin rules covering common scenarios. You can also add custom rules to fit you needs.

There are three rule types:

Builtin rules

All builtin rules are enabled by default.

Builtin rules can be disabled with useBuiltin set to false.

rehypeLinkProcessor({
  useBuiltin: false
})

When you disable builtin rules, you can add the ones you like manually:

rehypeLinkProcessor({
  rules: [
    "external"   // <-- enable the external link rule
  ]
})

or your use the helper R when you need a configuration:

rehypeLinkProcessor({
  rules: [
    R.download({
      skipExtension: ["html"] // exclude html to be considered a download
    })
  ]
})

The builtin rules are:

  • external

    looks for external links matching when one of:

    • the url starts with http: or https:
    • the url starts with the prefix external:
    • the text starts with the prefix external:

    if matched, the resulting a will have the attributes:

    • class = "external"
    • target = "_blank"
    • rel = "nofollow noopener"

    Examples

    Markdown:
    [Github](https://github.com)

    HTML:
    <a href="https://github.com" class="external" target="_blank" rel="nofollow noopener">Github<a>


    Markdown:
    [external:Discussion on Github](/discussion)

    HTML:
    <a href="/discussion" class="external" target="_blank" rel="nofollow noopener">Discussion on Github</a>


  • download

    looks for download links matching when one of:

    • the url starts with http: or https: and the path ends with .<ext> where ext is [1-4] chars long (excluded: html, htm, md, mdx)
    • the url starts with the prefix download:
    • the text starts with the prefix download:

    if matched, the resulting a will have the attributes:

    • class = "download"
    • download = the filename extracted or true when detected by the prefix

    Examples

    Markdown:
    [Download the pdf](/assets/my-article.pdf)

    HTML:
    <a download="my-article.pd" href="/assets/my-article.pdf" class="download">Download the pdf<a>


    Markdown:
    [download:Get the Archive](/directory?format=zip)

    HTML:
    <a download href="/directory?format=zip" class="download">Get the Archive</a>


  • email

    looks for email links matching when one of:

    • the url starts with mailto:
    • the url starts with the prefix email:
    • the text starts with the prefix email:

    if matched, the resulting a will have the attributes:

    • class = "email"

    Examples

    Markdown:
    [Contact us](support@domain.com)

    HTML:
    <a href="mailto:support@domain.com" class="email">Contact us<a>


    Markdown:
    [email:Send us a mail](info@domain.com)

    HTML:
    <a href="mailto:info@domain.com" class="email">Send us a mail<a>


  • same-page

    detect navigation within the same page, aka fragment navigation

    • checks if the url starts with #

    the resulting a will have the attributes

    • class = "same-page"

    Examples

    Markdown:
    [Chapter 2](#chapter-2)

    HTML:
    <a href="#chapter-2" class="same-page">Chapter 2<a>


Match rule

A match rule, works in two steps:

  • the match: where you identify the link you want to process
  • the action: where you specify what transformations you want to apply
rules: [
  {
    match: link => link.href.startWith("mailto:"),
    action: { className: "email" }
  }
]

If the match returns a falsy value (false, undefined, ...). The rule is skipped.

You can specify multiple actions in an Array.

You can use the A helper witch provides common actions.

// rule to correct GiThuB link casing
rules: [
  {
    match: link => link.text?.toLowerCase() === "github"
    action: [
      // add the class: the link can have preexisting class
      A.mergeClass("brand-link"),  
      // another syntax for { text: "GitHub" }
      A.set("text", "GitHub")
    ]
  }
]

The match function can also return an object. It will be assigned over the link, overwriting the common fields.

It's useful in a scenario where you want to apply a transformation right away in the matching step.

rules: [
  {
    match: link => {
      if(link.href.startsWith("http:")){
        return { href: link.href.replace("http:", "https:") };
      }
    },
    action: [
      A.set("target", "_blank"),  
    ]
  }
]

Transform rule

With a transform rule you can analyze any like directly. The transform rule provides a function based syntax to process links.

With the link as input, a transform rule can return:

  • a falsy value, to skip the rule
  • an object, to apply the patch: the object fields overwrite the link ones

You can add a transform rule like any other rule:

{
  rules: [
    link => {
      if (link.href?.includes("github.com")) {
        return { title: "GitHub: Where this code lives" };
      }
    }
  ]
}

Types

This package is built in typescript so it has full typings support.

License

MIT © Giuseppe La Torre

Keywords

FAQs

Last updated on 02 May 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc