Debian Codegraph @

packages/babel-register/test/index.js

raw symbols SCIP
1 import { createRequire, Module } from "module";
2 import path from "path";
3 import fs from "fs";
4 import child from "child_process";
5 import { fileURLToPath } from "url";
6
7 const dirname = path.dirname(fileURLToPath(import.meta.url));
8 const require = createRequire(import.meta.url);
9
10 const testCacheFilename = path.join(dirname, ".index.babel");
11 const testFile = require.resolve("./fixtures/babelrc/es2015");
12 const testFileLog = require.resolve("./fixtures/babelrc/log");
13 const testFileMjs = require.resolve("./fixtures/mjs-babelrc/es2015");
14 const testFileContent = fs.readFileSync(testFile, "utf-8");
15 const testFileMjsContent = fs.readFileSync(testFileMjs, "utf-8");
16
17 const piratesPath = require.resolve("pirates");
18 const smsPath = require.resolve("source-map-support");
19
20 const defaultOptions = {
21 exts: [".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"],
22 ignoreNodeModules: false,
23 };
24
25 function cleanCache() {
26 try {
27 fs.unlinkSync(testCacheFilename);
28 } catch (e) {
29 // It is convenient to always try to clear
30 }
31 }
32
33 function resetCache() {
34 process.env.BABEL_CACHE_PATH = null;
35 }
36
37 const OLD_JEST_MOCKS = !!jest.doMock;
38
39 let USE_ESM = false;
40 try {
41 const type = fs
42 .readFileSync(new URL("../../../.module-type", import.meta.url), "utf-8")
43 .trim();
44 USE_ESM = type === "module";
45 } catch {}
46
47 describe("@babel/register", function () {
48 let currentHook, currentOptions, sourceMapSupport;
49
50 const mocks = {
51 ["pirates"]: {
52 addHook(hook, opts) {
53 currentHook = hook;
54 currentOptions = opts;
55
56 return () => {
57 currentHook = null;
58 currentOptions = null;
59 };
60 },
61 },
62
63 ["source-map-support"]: {
64 install() {
65 sourceMapSupport = true;
66 },
67 },
68 };
69
70 beforeEach(() => {
71 currentHook = null;
72 currentOptions = null;
73 sourceMapSupport = false;
74 });
75
76 let originalRequireCacheDescriptor;
77 if (OLD_JEST_MOCKS) {
78 jest.doMock("pirates", () => mocks["pirates"]);
79 jest.doMock("source-map-support", () => mocks["source-map-support"]);
80
81 afterEach(() => {
82 jest.resetModules();
83 });
84 } else {
85 beforeAll(() => {
86 originalRequireCacheDescriptor = Object.getOwnPropertyDescriptor(
87 Module,
88 "_cache",
89 );
90 });
91
92 afterAll(() => {
93 Object.defineProperty(Module, "_cache", originalRequireCacheDescriptor);
94 });
95 }
96
97 if (!USE_ESM && !process.env.BABEL_8_BREAKING) {
98 describe("babel 7", () => {
99 if (!OLD_JEST_MOCKS) {
100 beforeEach(() => {
101 const isEmptyObj = obj =>
102 Object.getPrototypeOf(obj) === null &&
103 Object.keys(obj).length === 0;
104
105 // This setter intercepts the Module._cache assignment in
106 // packages/babel-register/src/nodeWrapper.js to install in the
107 // internal isolated cache.
108 const emptyInitialCache = {};
109 Object.defineProperty(Module, "_cache", {
110 get: () => emptyInitialCache,
111 set(value) {
112 expect(isEmptyObj(value)).toBe(true);
113
114 Object.defineProperty(Module, "_cache", {
115 value,
116 enumerable: originalRequireCacheDescriptor.enumerable,
117 configurable: originalRequireCacheDescriptor.configurable,
118 writable: originalRequireCacheDescriptor.writable,
119 });
120 value[piratesPath] = { exports: mocks["pirates"] };
121 value[smsPath] = { exports: mocks["source-map-support"] };
122 },
123 enumerable: originalRequireCacheDescriptor.enumerable,
124 configurable: originalRequireCacheDescriptor.configurable,
125 });
126 });
127 }
128
129 const { setupRegister } = buildTests(require.resolve(".."));
130
131 it("does not mutate options", () => {
132 const proxyHandler = {
133 defineProperty: jest.fn(Reflect.defineProperty),
134 deleteProperty: jest.fn(Reflect.deleteProperty),
135 set: jest.fn(Reflect.set),
136 };
137
138 setupRegister(
139 new Proxy(
140 {
141 babelrc: true,
142 sourceMaps: false,
143 cwd: path.dirname(testFileMjs),
144 extensions: [".js"],
145 },
146 proxyHandler,
147 ),
148 );
149
150 currentHook(testFileContent, testFile);
151
152 expect(proxyHandler.defineProperty).not.toHaveBeenCalled();
153 expect(proxyHandler.deleteProperty).not.toHaveBeenCalled();
154 expect(proxyHandler.set).not.toHaveBeenCalled();
155 });
156 });
157 }
158
159 const nodeGte12 = (fn, ...args) => {
160 // "minNodeVersion": "8.0.0" <-- For Ctrl+F when dropping node 6-8-10
161 const testFn = /v(?:6|8|10)\./.test(process.version) ? fn.skip : fn;
162 testFn(...args);
163 };
164
165 nodeGte12(describe, "worker", () => {
166 if (!OLD_JEST_MOCKS) {
167 beforeEach(() => {
168 Object.defineProperty(Module, "_cache", {
169 ...originalRequireCacheDescriptor,
170 value: {
171 [piratesPath]: { exports: mocks["pirates"] },
172 [smsPath]: { exports: mocks["source-map-support"] },
173 },
174 });
175 });
176 }
177
178 const { setupRegister } = buildTests(
179 require.resolve("../experimental-worker"),
180 );
181
182 it("works with mjs config files", () => {
183 setupRegister({
184 babelrc: true,
185 sourceMaps: false,
186 cwd: path.dirname(testFileMjs),
187 });
188
189 const result = currentHook(testFileMjsContent, testFileMjs);
190
191 expect(result).toBe('"use strict";\n\nrequire("assert");');
192 });
193 });
194
195 function buildTests(registerFile) {
196 let babelRegister;
197
198 function setupRegister(config = { babelrc: false }) {
199 process.env.BABEL_CACHE_PATH = testCacheFilename;
200 config = {
201 cwd: path.dirname(testFile),
202 ...config,
203 };
204
205 babelRegister = require(registerFile);
206 babelRegister.default(config);
207 }
208
209 function revertRegister() {
210 if (babelRegister) {
211 babelRegister.revert();
212 delete require.cache[registerFile];
213 babelRegister = null;
214 }
215 cleanCache();
216 }
217
218 afterEach(async () => {
219 // @babel/register saves the cache on process.nextTick.
220 // We need to wait for at least one tick so that when jest
221 // tears down the testing environment @babel/register has
222 // already finished.
223 await new Promise(setImmediate);
224
225 revertRegister();
226 });
227
228 afterAll(() => {
229 resetCache();
230 });
231
232 test("registers hook correctly", () => {
233 setupRegister();
234
235 expect(typeof currentHook).toBe("function");
236 expect(currentOptions).toEqual(defaultOptions);
237 });
238
239 test("unregisters hook correctly", () => {
240 setupRegister();
241 revertRegister();
242
243 expect(currentHook).toBeNull();
244 expect(currentOptions).toBeNull();
245 });
246
247 test("installs source map support by default", () => {
248 setupRegister();
249
250 currentHook("const a = 1;", testFile);
251
252 expect(sourceMapSupport).toBe(true);
253 });
254
255 test("installs source map support when requested", () => {
256 setupRegister({
257 babelrc: false,
258 sourceMaps: true,
259 });
260
261 currentHook("const a = 1;", testFile);
262
263 expect(sourceMapSupport).toBe(true);
264 });
265
266 test("does not install source map support if asked not to", () => {
267 setupRegister({
268 babelrc: false,
269 sourceMaps: false,
270 });
271
272 currentHook("const a = 1;", testFile);
273
274 expect(sourceMapSupport).toBe(false);
275 });
276
277 describe("node auto-require", () => {
278 it("works with the -r flag", async () => {
279 const output = await spawnNodeAsync(
280 ["-r", registerFile, testFileLog],
281 path.dirname(testFileLog),
282 );
283
284 expect(output.trim()).toMatchInlineSnapshot(
285 `"It worked! function () {}"`,
286 );
287 });
288
289 it("works with the --require flag", async () => {
290 const output = await spawnNodeAsync(
291 ["--require", registerFile, testFileLog],
292 path.dirname(testFileLog),
293 );
294
295 expect(output.trim()).toMatchInlineSnapshot(
296 `"It worked! function () {}"`,
297 );
298 });
299
300 it("works with the -r flag in NODE_OPTIONS", async () => {
301 const output = await spawnNodeAsync(
302 [testFileLog],
303 path.dirname(testFileLog),
304 { NODE_OPTIONS: `-r ${registerFile}` },
305 );
306
307 expect(output.trim()).toMatchInlineSnapshot(
308 `"It worked! function () {}"`,
309 );
310 });
311
312 it("works with the --require flag in NODE_OPTIONS", async () => {
313 const output = await spawnNodeAsync(
314 [testFileLog],
315 path.dirname(testFileLog),
316 { NODE_OPTIONS: `--require ${registerFile}` },
317 );
318
319 expect(output.trim()).toMatchInlineSnapshot(
320 `"It worked! function () {}"`,
321 );
322 });
323 });
324
325 it("returns concatenatable sourceRoot and sources", async () => {
326 // The Source Maps R3 standard https://sourcemaps.info/spec.html states
327 // that `sourceRoot` is “prepended to the individual entries in the
328 // ‘source’ field.” If `sources` contains file names, and `sourceRoot`
329 // is intended to refer to a directory but doesn’t end with a trailing
330 // slash, any consumers of the source map are in for a bad day.
331 //
332 // The underlying problem seems to only get triggered if one file
333 // requires() another with @babel/register active, and I couldn’t get
334 // that working inside a test, possibly because of jest’s mocking
335 // hooks, so we spawn a separate process.
336 const output = await spawnNodeAsync([
337 "-r",
338 registerFile,
339 require.resolve("./fixtures/source-map/index"),
340 ]);
341 const sourceMap = JSON.parse(output);
342 expect(sourceMap.map.sourceRoot + sourceMap.map.sources[0]).toBe(
343 require.resolve("./fixtures/source-map/foo/bar"),
344 );
345 });
346
347 test("hook transpiles with config", () => {
348 setupRegister({
349 babelrc: false,
350 sourceMaps: false,
351 plugins: ["@babel/transform-modules-commonjs"],
352 });
353
354 const result = currentHook(testFileContent, testFile);
355
356 expect(result).toBe('"use strict";\n\nrequire("assert");');
357 });
358
359 test("hook transpiles with babelrc", () => {
360 setupRegister({
361 babelrc: true,
362 sourceMaps: false,
363 });
364
365 const result = currentHook(testFileContent, testFile);
366
367 expect(result).toBe('"use strict";\n\nrequire("assert");');
368 });
369
370 test("transforms modules used within register", async () => {
371 // Need a clean environment without `convert-source-map`
372 // already in the require cache, so we spawn a separate process
373
374 const output = await spawnNodeAsync([
375 require.resolve("./fixtures/internal-modules/index.js"),
376 ]);
377 const { convertSourceMap } = JSON.parse(output);
378 expect(convertSourceMap).toMatch("/* transformed */");
379 });
380
381 test("does not mutate options", () => {
382 const proxyHandler = {
383 defineProperty: jest.fn(Reflect.defineProperty),
384 deleteProperty: jest.fn(Reflect.deleteProperty),
385 set: jest.fn(Reflect.set),
386 };
387
388 setupRegister(
389 new Proxy(
390 {
391 babelrc: true,
392 sourceMaps: false,
393 cwd: path.dirname(testFileMjs),
394 extensions: [".js"],
395 },
396 proxyHandler,
397 ),
398 );
399
400 currentHook(testFileContent, testFile);
401
402 expect(proxyHandler.defineProperty).not.toHaveBeenCalled();
403 expect(proxyHandler.deleteProperty).not.toHaveBeenCalled();
404 expect(proxyHandler.set).not.toHaveBeenCalled();
405 });
406
407 return { setupRegister, revertRegister };
408 }
409 });
410
411 function spawnNodeAsync(args, cwd = dirname, env) {
412 const spawn = child.spawn(process.execPath, args, { cwd, env });
413
414 let output = "";
415 let callback;
416
417 for (const stream of [spawn.stderr, spawn.stdout]) {
418 stream.on("data", chunk => {
419 output += chunk;
420 });
421 }
422
423 spawn.on("close", function () {
424 callback(output);
425 });
426
427 return new Promise(resolve => {
428 callback = resolve;
429 });
430 }