This repository was archived by the owner on Dec 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathabsolute.js
72 lines (61 loc) · 1.84 KB
/
absolute.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var through = require('through3')
, ast = require('mkast')
, Node = ast.Node
, walker = ast.NodeWalker.walk
, pattern = /^[\/]/
, greedy = /^[\/#\?]/;
/**
* Makes relative link destinations absolute.
*
* @module {constructor} Absolute
* @param {Object} [opts] stream options.
*
* @option {String} [base] prepend path for relative links.
* @option {Boolean=false} [images] also handle images.
* @option {String} [imageBase] prepend path for relative image URLs.
* @option {Boolean=false} [greedy] convert # and ? link destinations.
*/
function Absolute(opts) {
opts = opts || {};
// noop with no base path
this.base = opts.base || '';
// default to false for backwards compatibility
this.images = opts.images ?? Boolean(opts.imageBase);
// default to `base` if not set
this.imageBase = opts.imageBase || this.base;
this.pattern = opts.greedy ? greedy : pattern;
}
/**
* Stream transform.
*
* @private {function} transform
* @member Absolute
*
* @param {Array} node input AST node.
* @param {String} encoding character encoding.
* @param {Function} callback function.
*/
function transform(chunk, encoding, cb) {
var base = this.base
, images = this.images
, imageBase = this.imageBase
, ptn = this.pattern;
function linkify(node) {
/* istanbul ignore next: must have a string value for re.test() */
var dest = node.destination || '';
if(Node.is(node, Node.LINK) || (Node.is(node, Node.IMAGE) && images && !imageBase)) {
if(ptn.test(dest)) {
node.destination = base + dest;
}
} else if(Node.is(node, Node.IMAGE) && images && imageBase) {
if(ptn.test(dest)) {
node.destination = imageBase + dest;
}
}
}
linkify(chunk);
walker(chunk, linkify);
this.push(chunk);
cb();
}
module.exports = through.transform(transform, {ctor: Absolute})