-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (66 loc) · 2.08 KB
/
index.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
73
74
75
76
77
78
79
80
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readFileAsync = promisify(fs.readFile);
const attrs = ['src', 'href'];
const notEmpty = /.+/;
// Using default manifest file of
// https://www.npmjs.com/package/rollup-plugin-entrypoint-hashmanifest
const defaults = { manifest: './entrypoint.hashmanifest.json' };
module.exports = (opts = {}) => (tree) =>
new Promise(async (resolve, reject) => {
opts = Object.assign({}, defaults, opts);
if (typeof opts.manifest === 'string') {
// it's a file path, read it
try {
opts.manifest = JSON.parse(await readFileAsync(opts.manifest, { encoding: 'utf8' }));
} catch (e) {
reject(e.toString());
return;
}
}
opts.manifest = rebaseManifestPaths(opts);
const exp = attrs.map((attr) => {
const o = {};
o[attr] = notEmpty;
return { attrs: o };
});
tree.match(exp, (node) => {
let attrValTuple;
attrs.some((attr) => {
const value = opts.manifest[node.attrs[attr]];
if (value) {
attrValTuple = [attr, value];
return true;
}
});
if (attrValTuple) node.attrs[attrValTuple[0]] = attrValTuple[1];
return node;
});
resolve(tree);
});
function rebaseManifestPaths(opts) {
if (!opts.rebase) return opts.manifest;
return objectFromEntries(
Object.entries(opts.manifest).map((entry) => {
const origKeyPath = path.parse(entry[0]);
const origValuePath = path.parse(entry[1]);
if (opts.rebase.hasOwnProperty(origKeyPath.dir)) {
origKeyPath.dir = opts.rebase[origKeyPath.dir];
entry[0] = path.format(origKeyPath);
}
if (opts.rebase.hasOwnProperty(origValuePath.dir)) {
origValuePath.dir = opts.rebase[origValuePath.dir];
entry[1] = path.format(origValuePath);
}
return entry;
})
);
}
// Real Object.fromEntries only available in Node 12+
function objectFromEntries (iterable) {
return [...iterable].reduce((obj, [key, val]) => {
obj[key] = val
return obj
}, {})
}