Skip to content

Commit

Permalink
rehype-minify-url: add support for file.data.meta
Browse files Browse the repository at this point in the history
  • Loading branch information
wooorm committed Sep 6, 2021
1 parent 7fd28c3 commit 25b256a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 14 deletions.
27 changes: 19 additions & 8 deletions packages/rehype-minify-url/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,27 @@ const own = {}.hasOwnProperty
*/
export default function rehypeMinifyUrl(options) {
const {from, ...rest} = options || {}
// @ts-expect-error: checked next.
const relate = new Relate(from, rest)

try {
relate.relate('/')
} catch {
throw new Error('Missing absolute `from` in options')
}
return (tree, file) => {
const meta = /** @type {Record<string, unknown>} */ (file.data.meta || {})

/** @type {string|undefined} */
const href =
from ||
(meta.origin && meta.pathname
? // @ts-expect-error: `URL` exists.
new URL(meta.pathname, meta.origin).href
: undefined)

// @ts-expect-error: checked next.
const relate = new Relate(href, rest)

try {
relate.relate('/')
} catch {
throw new Error('Missing absolute `from` in options')
}

return (tree) => {
visit(tree, 'element', (node) => {
const props = node.properties || {}
/** @type {string} */
Expand Down
23 changes: 17 additions & 6 deletions packages/rehype-minify-url/test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {URL} from 'node:url'
import test from 'tape'
import {rehype} from 'rehype'
import {u} from 'unist-builder'
Expand All @@ -6,15 +7,11 @@ import min from './index.js'

test('rehype-minify-url', (t) => {
t.throws(() => {
rehype().use(min).freeze()
rehype().use(min).processSync('')
}, /^Error: Missing absolute `from` in options$/)

t.throws(() => {
rehype().use(min, {from: '/'}).freeze()
}, /^Error: Missing absolute `from` in options$/)

t.throws(() => {
rehype().use(min, {from: '/'}).freeze()
rehype().use(min, {from: '/'}).processSync('')
}, /^Error: Missing absolute `from` in options$/)

const options = {from: 'http://example.com/one/alpha/'}
Expand Down Expand Up @@ -90,5 +87,19 @@ test('rehype-minify-url', (t) => {
u('root', [{type: 'element', tagName: 'a', children: []}])
)

t.deepEqual(
rehype()
.use(() => (_, file) => {
const url = new URL(options.from)
file.data.meta = {origin: url.origin, pathname: url.pathname}
})
.use(min)
.runSync(
u('root', [h('a', {href: 'http://example.com/one/bravo/index.html'})])
),
u('root', [h('a', {href: '../bravo/'})]),
'should support `data.meta.{origin,pathname}`'
)

t.end()
})

0 comments on commit 25b256a

Please sign in to comment.