-
Notifications
You must be signed in to change notification settings - Fork 187
/
replace.js
81 lines (69 loc) · 2.25 KB
/
replace.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
81
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./replace.d.ts" />
// originally from: https://github.com/vitejs/vite/blob/51e9c83458e30e3ce70abead14e02a7b353322d9/src/node/build/buildPluginReplace.ts
const { default: MagicString } = await import('magic-string');
/** @typedef {import("rollup").TransformResult} TransformResult */
/** @typedef {import("rollup").Plugin} RollupPlugin */
/**
* @param {(id: string) => boolean} test
* @param {Record<string, string>} replacements
* @param {boolean} sourcemap
*
* @returns {RollupPlugin}
*/
export function createReplacePlugin(test, replacements, sourcemap) {
const pattern = new RegExp(
'\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[$()*+\-./?[\\\]^{|}]/gu, '\\$&');
})
.join('|') +
')\\b',
'g'
);
return {
name: 'starbeam:replace',
/**
* @param {string} code
* @param {string} id
* @returns {import("rollup").TransformResult}
*/
transform(code, id) {
if (test(id)) {
const s = new MagicString(code);
let hasReplaced = false;
/** @type {RegExpMatchArray | null} */
let match;
while ((match = pattern.exec(code))) {
hasReplaced = true;
const start = /** @type {number} */ (match.index);
const [wholeMatch, partialMatch] = /** @type {[string, string]} */ (match);
const end = start + wholeMatch.length;
const replacement = replacements[partialMatch];
if (replacement === undefined) {
throw new Error(
`Unexpected missing replacement for "${partialMatch}".\n\nReplacements were ${JSON.stringify(
replacements,
null,
2
)}`
);
}
s.overwrite(start, end, replacement);
}
if (!hasReplaced) {
return null;
}
/** @type {TransformResult} */
const result = { code: s.toString() };
if (sourcemap) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
result.map = s.generateMap({ hires: true });
}
return result;
}
},
};
}