/
index.js
271 lines (219 loc) · 7.15 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { createRequire, Module } from "module";
import path from "path";
import fs from "fs";
import child from "child_process";
import { fileURLToPath } from "url";
const dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const registerFile = require.resolve("../lib/index");
const testCacheFilename = path.join(dirname, ".index.babel");
const testFile = require.resolve("./fixtures/babelrc/es2015");
const testFileContent = fs.readFileSync(testFile);
const piratesPath = require.resolve("pirates");
const smsPath = require.resolve("source-map-support");
const defaultOptions = {
exts: [".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"],
ignoreNodeModules: false,
};
function cleanCache() {
try {
fs.unlinkSync(testCacheFilename);
} catch (e) {
// It is convenient to always try to clear
}
}
function resetCache() {
process.env.BABEL_CACHE_PATH = null;
}
const OLD_JEST_MOCKS = !!jest.doMock;
describe("@babel/register", function () {
let currentHook, currentOptions, sourceMapSupport;
const mocks = {
["pirates"]: {
addHook(hook, opts) {
currentHook = hook;
currentOptions = opts;
return () => {
currentHook = null;
currentOptions = null;
};
},
},
["source-map-support"]: {
install() {
sourceMapSupport = true;
},
},
};
let babelRegister;
function setupRegister(config = { babelrc: false }) {
process.env.BABEL_CACHE_PATH = testCacheFilename;
config = {
cwd: path.dirname(testFile),
...config,
};
babelRegister = require(registerFile);
babelRegister.default(config);
}
function revertRegister() {
if (babelRegister) {
babelRegister.revert();
delete require.cache[registerFile];
babelRegister = null;
}
cleanCache();
}
beforeEach(() => {
currentHook = null;
currentOptions = null;
sourceMapSupport = false;
});
afterEach(async () => {
// @babel/register saves the cache on process.nextTick.
// We need to wait for at least one tick so that when jest
// tears down the testing environment @babel/register has
// already finished.
await new Promise(setImmediate);
revertRegister();
});
afterAll(() => {
resetCache();
});
if (OLD_JEST_MOCKS) {
jest.doMock("pirates", () => mocks["pirates"]);
jest.doMock("source-map-support", () => mocks["source-map-support"]);
afterEach(() => {
jest.resetModules();
});
} else {
let originalRequireCacheDescriptor;
beforeAll(() => {
originalRequireCacheDescriptor = Object.getOwnPropertyDescriptor(
Module,
"_cache",
);
});
beforeEach(() => {
const isEmptyObj = obj =>
Object.getPrototypeOf(obj) === null && Object.keys(obj).length === 0;
// This setter intercepts the Module._cache assignment in
// packages/babel-register/src/nodeWrapper.js to install in the
// internal isolated cache.
const emptyInitialCache = {};
Object.defineProperty(Module, "_cache", {
get: () => emptyInitialCache,
set(value) {
expect(isEmptyObj(value)).toBe(true);
Object.defineProperty(Module, "_cache", {
value,
enumerable: originalRequireCacheDescriptor.enumerable,
configurable: originalRequireCacheDescriptor.configurable,
writable: originalRequireCacheDescriptor.writable,
});
value[piratesPath] = { exports: mocks["pirates"] };
value[smsPath] = { exports: mocks["source-map-support"] };
},
enumerable: originalRequireCacheDescriptor.enumerable,
configurable: originalRequireCacheDescriptor.configurable,
});
});
afterAll(() => {
Object.defineProperty(Module, "_cache", originalRequireCacheDescriptor);
});
}
test("registers hook correctly", () => {
setupRegister();
expect(typeof currentHook).toBe("function");
expect(currentOptions).toEqual(defaultOptions);
});
test("unregisters hook correctly", () => {
setupRegister();
revertRegister();
expect(currentHook).toBeNull();
expect(currentOptions).toBeNull();
});
test("installs source map support by default", () => {
setupRegister();
currentHook("const a = 1;", testFile);
expect(sourceMapSupport).toBe(true);
});
test("installs source map support when requested", () => {
setupRegister({
babelrc: false,
sourceMaps: true,
});
currentHook("const a = 1;", testFile);
expect(sourceMapSupport).toBe(true);
});
test("does not install source map support if asked not to", () => {
setupRegister({
babelrc: false,
sourceMaps: false,
});
currentHook("const a = 1;", testFile);
expect(sourceMapSupport).toBe(false);
});
it("returns concatenatable sourceRoot and sources", async () => {
// The Source Maps R3 standard https://sourcemaps.info/spec.html states
// that `sourceRoot` is “prepended to the individual entries in the
// ‘source’ field.” If `sources` contains file names, and `sourceRoot`
// is intended to refer to a directory but doesn’t end with a trailing
// slash, any consumers of the source map are in for a bad day.
//
// The underlying problem seems to only get triggered if one file
// requires() another with @babel/register active, and I couldn’t get
// that working inside a test, possibly because of jest’s mocking
// hooks, so we spawn a separate process.
const output = await spawnNodeAsync([
"-r",
registerFile,
require.resolve("./fixtures/source-map/index"),
]);
const sourceMap = JSON.parse(output);
expect(sourceMap.map.sourceRoot + sourceMap.map.sources[0]).toBe(
require.resolve("./fixtures/source-map/foo/bar"),
);
});
test("hook transpiles with config", () => {
setupRegister({
babelrc: false,
sourceMaps: false,
plugins: ["@babel/transform-modules-commonjs"],
});
const result = currentHook(testFileContent, testFile);
expect(result).toBe('"use strict";\n\nrequire("assert");');
});
test("hook transpiles with babelrc", () => {
setupRegister({
babelrc: true,
sourceMaps: false,
});
const result = currentHook(testFileContent, testFile);
expect(result).toBe('"use strict";\n\nrequire("assert");');
});
test("transforms modules used within register", async () => {
// Need a clean environment without `convert-source-map`
// already in the require cache, so we spawn a separate process
const output = await spawnNodeAsync([
require.resolve("./fixtures/internal-modules/index.js"),
]);
const { convertSourceMap } = JSON.parse(output);
expect(convertSourceMap).toMatch("/* transformed */");
});
});
function spawnNodeAsync(args) {
const spawn = child.spawn(process.execPath, args, { cwd: dirname });
let output = "";
let callback;
for (const stream of [spawn.stderr, spawn.stdout]) {
stream.on("data", chunk => {
output += chunk;
});
}
spawn.on("close", function () {
callback(output);
});
return new Promise(resolve => {
callback = resolve;
});
}