Debian Codegraph @

packages/babel-helper-transform-fixture-test-runner/src/index.ts

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /* eslint-env jest */
2 import * as babel from "@babel/core";
3 import {
4 buildExternalHelpers,
5 type InputOptions,
6 type FileResult,
7 } from "@babel/core";
8 import {
9 default as getFixtures,
10 resolveOptionPluginOrPreset,
11 type Test,
12 type TestFile,
13 type TaskOptions,
14 } from "@babel/helper-fixtures";
15 import { codeFrameColumns } from "@babel/code-frame";
16 import * as helpers from "./helpers";
17 import assert from "assert";
18 import fs from "fs";
19 import path from "path";
20 import vm from "vm";
21 import QuickLRU from "quick-lru";
22 import { fileURLToPath } from "url";
23
24 import { createRequire } from "module";
25 const require = createRequire(import.meta.url);
26
27 import checkDuplicateNodes from "@babel/helper-check-duplicate-nodes";
28
29 type Module = {
30 id: string;
31 exports: Record<string, unknown>;
32 };
33
34 if (!process.env.BABEL_8_BREAKING) {
35 // Introduced in Node.js 10
36 if (!assert.rejects) {
37 assert.rejects = async function (block, validateError) {
38 try {
39 await (typeof block === "function" ? block() : block);
40 return Promise.reject(new Error("Promise not rejected"));
41 } catch (error) {
42 // @ts-expect-error Fixme: validateError can be a string | object
43 // see https://nodejs.org/api/assert.html#assertrejectsasyncfn-error-message
44 if (typeof validateError === "function" && !validateError(error)) {
45 return Promise.reject(
46 new Error("Promise rejected with invalid error"),
47 );
48 }
49 }
50 };
51 }
52 }
53
54 const EXTERNAL_HELPERS_VERSION = "7.100.0";
55
56 const cachedScripts = new QuickLRU<
57 string,
58 { code: string; cachedData?: Buffer }
59 >({ maxSize: 10 });
60 const contextModuleCache = new WeakMap();
61 const sharedTestContext = createContext();
62
63 // We never want our tests to accidentally load the root
64 // babel.config.js file, so we disable config loading by
65 // default. Tests can still set `configFile: true | string`
66 // to re-enable config loading.
67 function transformWithoutConfigFile(code: string, opts: InputOptions) {
68 return babel.transformSync(code, {
69 configFile: false,
70 babelrc: false,
71 ...opts,
72 });
73 }
74 function transformAsyncWithoutConfigFile(code: string, opts: InputOptions) {
75 return babel.transformAsync(code, {
76 configFile: false,
77 babelrc: false,
78 ...opts,
79 });
80 }
81
82 function createContext() {
83 const context = vm.createContext({
84 ...helpers,
85 process: process,
86 transform: transformWithoutConfigFile,
87 transformAsync: transformAsyncWithoutConfigFile,
88 setTimeout: setTimeout,
89 setImmediate: setImmediate,
90 expect,
91 });
92 context.global = context;
93
94 const moduleCache = Object.create(null);
95 contextModuleCache.set(context, moduleCache);
96
97 // Populate the "babelHelpers" global with Babel's helper utilities.
98 runCacheableScriptInTestContext(
99 path.join(
100 path.dirname(fileURLToPath(import.meta.url)),
101 "babel-helpers-in-memory.js",
102 ),
103 buildExternalHelpers,
104 context,
105 moduleCache,
106 );
107
108 return context;
109 }
110
111 function runCacheableScriptInTestContext(
112 filename: string,
113 srcFn: () => string,
114 context: vm.Context,
115 moduleCache: any,
116 ): Module {
117 let cached = cachedScripts.get(filename);
118 if (!cached) {
119 const code = `(function (exports, require, module, __filename, __dirname) {\n${srcFn()}\n});`;
120 cached = {
121 code,
122 cachedData: undefined,
123 };
124 cachedScripts.set(filename, cached);
125 }
126
127 let script: vm.Script;
128 if (process.env.BABEL_8_BREAKING) {
129 script = new vm.Script(cached.code, {
130 filename,
131 lineOffset: -1,
132 cachedData: cached.cachedData,
133 });
134 cached.cachedData = script.createCachedData();
135 } else {
136 script = new vm.Script(cached.code, {
137 filename,
138 lineOffset: -1,
139 cachedData: cached.cachedData,
140 produceCachedData: true,
141 });
•142 // @ts-ignore
143 if (script.cachedDataProduced) {
•144 // @ts-ignore
145 cached.cachedData = script.cachedData;
146 }
147 }
148
149 const module = {
150 id: filename,
151 exports: {},
152 };
153 moduleCache[filename] = module;
154
155 const req = (id: string) =>
156 runModuleInTestContext(id, filename, context, moduleCache);
157 const dirname = path.dirname(filename);
158
159 script
160 .runInContext(context)
161 .call(module.exports, module.exports, req, module, filename, dirname);
162
163 return module;
164 }
165
166 /**
167 * A basic implementation of CommonJS so we can execute `@babel/polyfill` inside our test context.
168 * This allows us to run our unittests
169 */
170 function runModuleInTestContext(
171 id: string,
172 relativeFilename: string,
173 context: vm.Context,
174 moduleCache: any,
175 ) {
176 const filename = require.resolve(id, {
177 paths: [path.dirname(relativeFilename)],
178 });
179
180 // Expose Node-internal modules if the tests want them. Note, this will not execute inside
181 // the context's global scope.
182 if (filename === id) return require(id);
183
184 // Modules can only evaluate once per context, so the moduleCache is a
185 // stronger cache guarantee than the LRU's Script cache.
186 if (moduleCache[filename]) return moduleCache[filename].exports;
187
188 return runCacheableScriptInTestContext(
189 filename,
190 () => fs.readFileSync(filename, "utf8"),
191 context,
192 moduleCache,
193 ).exports;
194 }
195
196 /**
197 * Run the given snippet of code inside a CommonJS module.
198 *
199 * Exposed for unit tests, not for use as an API.
200 */
201 export function runCodeInTestContext(
202 code: string,
203 opts: {
204 filename: string;
205 },
206 context = sharedTestContext,
207 ) {
208 const filename = opts.filename;
209 const dirname = path.dirname(filename);
210 const moduleCache = contextModuleCache.get(context);
211 const req = (id: string) =>
212 runModuleInTestContext(id, filename, context, moduleCache);
213
214 const module: Module = {
215 id: filename,
216 exports: {},
217 };
218
219 const oldCwd = process.cwd();
220 try {
221 if (opts.filename) process.chdir(path.dirname(opts.filename));
222
223 // Expose the test options as "opts", but otherwise run the test in a CommonJS-like environment.
224 // Note: This isn't doing .call(module.exports, ...) because some of our tests currently
225 // rely on 'this === global'.
226 const src = `(function(exports, require, module, __filename, __dirname, opts) {\n${code}\n});`;
227 return vm.runInContext(src, context, {
228 filename,
229 displayErrors: true,
230 lineOffset: -1,
231 })(module.exports, req, module, filename, dirname, opts);
232 } finally {
233 process.chdir(oldCwd);
234 }
235 }
236
237 async function maybeMockConsole<R>(validateLogs: boolean, run: () => R) {
238 const actualLogs = { stdout: "", stderr: "" };
239
240 if (!validateLogs) return { result: await run(), actualLogs };
241
242 const spy1 = jest.spyOn(console, "log").mockImplementation(msg => {
243 actualLogs.stdout += `${msg}\n`;
244 });
245 const spy2 = jest.spyOn(console, "warn").mockImplementation(msg => {
246 actualLogs.stderr += `${msg}\n`;
247 });
248
249 try {
250 return { result: await run(), actualLogs };
251 } finally {
252 spy1.mockRestore();
253 spy2.mockRestore();
254 }
255 }
256
257 async function run(task: Test) {
258 const {
259 actual,
260 expect: expected,
261 exec,
262 options: opts,
263 doNotSetSourceType,
264 optionsDir,
265 validateLogs,
266 ignoreOutput,
267 stdout,
268 stderr,
269 } = task;
270
271 // todo(flow->ts) add proper return type (added any, because empty object is inferred)
272 function getOpts(self: TestFile): any {
273 const newOpts = {
274 ast: true,
275 cwd: path.dirname(self.loc),
276 filename: self.loc,
277 filenameRelative: self.filename,
278 sourceFileName: self.filename,
279 ...(doNotSetSourceType ? {} : { sourceType: "script" }),
280 babelrc: false,
281 configFile: false,
282 inputSourceMap: task.inputSourceMap || undefined,
283 ...opts,
284 };
285
286 return resolveOptionPluginOrPreset(newOpts, optionsDir);
287 }
288
289 let execCode = exec.code;
290 let result: FileResult;
291 let resultExec;
292
293 if (execCode) {
294 const context = createContext();
295 const execOpts = getOpts(exec);
296
297 // Ignore Babel logs of exec.js files.
298 // They will be validated in input/output files.
299 ({ result } = await maybeMockConsole(validateLogs, () =>
300 babel.transformAsync(execCode, execOpts),
301 ));
302
303 checkDuplicateNodes(result.ast);
304 execCode = result.code;
305
306 try {
307 resultExec = runCodeInTestContext(execCode, execOpts, context);
308 } catch (err) {
309 // Pass empty location to include the whole file in the output.
310 err.message =
311 `${exec.loc}: ${err.message}\n` + codeFrameColumns(execCode, {} as any);
312 throw err;
313 }
314 }
315
316 const inputCode = actual.code;
317 const expectedCode = expected.code;
318 if (!execCode || inputCode) {
319 let actualLogs;
320
321 ({ result, actualLogs } = await maybeMockConsole(validateLogs, () =>
322 babel.transformAsync(inputCode, getOpts(actual)),
323 ));
324
325 const outputCode = normalizeOutput(result.code);
326
327 checkDuplicateNodes(result.ast);
328 if (!ignoreOutput) {
329 if (
330 !expected.code &&
331 outputCode &&
332 !opts.throws &&
333 fs.statSync(path.dirname(expected.loc)).isDirectory() &&
334 !process.env.CI
335 ) {
336 const expectedFile = expected.loc.replace(
337 /\.m?js$/,
338 result.sourceType === "module" ? ".mjs" : ".js",
339 );
340
341 console.log(`New test file created: ${expectedFile}`);
342 fs.writeFileSync(expectedFile, `${outputCode}\n`);
343
344 if (expected.loc !== expectedFile) {
345 try {
346 fs.unlinkSync(expected.loc);
347 } catch (e) {}
348 }
349 } else {
350 validateFile(outputCode, expected.loc, expectedCode);
351
352 if (inputCode) {
353 expect(expected.loc).toMatch(
354 result.sourceType === "module" ? /\.mjs$/ : /\.js$/,
355 );
356 }
357 }
358 }
359
360 if (validateLogs) {
361 validateFile(
362 normalizeOutput(actualLogs.stdout, /* normalizePathSeparator */ true),
363 stdout.loc,
364 stdout.code,
365 );
366 validateFile(
367 normalizeOutput(actualLogs.stderr, /* normalizePathSeparator */ true),
368 stderr.loc,
369 stderr.code,
370 );
371 }
372 }
373
374 if (opts.sourceMaps === true) {
375 try {
376 expect(result.map).toEqual(task.sourceMap);
377 } catch (e) {
378 if (!process.env.OVERWRITE && task.sourceMap) throw e;
379
380 console.log(`Updated test file: ${task.sourceMapFile.loc}`);
381 fs.writeFileSync(
382 task.sourceMapFile.loc,
383 JSON.stringify(result.map, null, 2),
384 );
385 }
386 }
387
388 if (execCode && resultExec) {
389 return resultExec;
390 }
391 }
392
393 function validateFile(
394 actualCode: string,
395 expectedLoc: string,
396 expectedCode: string,
397 ) {
398 try {
399 expect(actualCode).toEqualFile({
400 filename: expectedLoc,
401 code: expectedCode,
402 });
403 } catch (e) {
404 if (!process.env.OVERWRITE) throw e;
405
406 console.log(`Updated test file: ${expectedLoc}`);
407 fs.writeFileSync(expectedLoc, `${actualCode}\n`);
408 }
409 }
410
411 function escapeRegExp(string: string) {
412 return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
413 }
414
415 function normalizeOutput(code: string, normalizePathSeparator?: boolean) {
416 const projectRoot = path.resolve(
417 path.dirname(fileURLToPath(import.meta.url)),
418 "../../../",
419 );
420 const cwdSymbol = "<CWD>";
421 let result = code
422 .trim()
423 // (non-win32) /foo/babel/packages -> <CWD>/packages
424 // (win32) C:\foo\babel\packages -> <CWD>\packages
425 .replace(new RegExp(escapeRegExp(projectRoot), "g"), cwdSymbol);
426 if (process.platform === "win32") {
427 result = result
428 // C:/foo/babel/packages -> <CWD>/packages
429 .replace(
430 new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "/")), "g"),
431 cwdSymbol,
432 )
433 // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
434 .replace(
435 new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "\\\\")), "g"),
436 cwdSymbol,
437 );
438 if (normalizePathSeparator) {
439 result = result.replace(/<CWD>[\w\\/.-]+/g, path =>
440 path.replace(/\\\\?/g, "/"),
441 );
442 }
443 }
444 return result;
445 }
446
447 expect.extend({
448 toEqualFile(actual, { filename, code }: Pick<TestFile, "filename" | "code">) {
449 if (this.isNot) {
450 throw new Error(".toEqualFile does not support negation");
451 }
452
453 const pass = actual === code;
454 return {
455 pass,
456 message: () => {
457 const diffString = this.utils.diff(code, actual, {
458 expand: false,
459 });
460 return (
461 `Expected ${filename} to match transform output.\n` +
462 `To autogenerate a passing version of this file, delete the file and re-run the tests.\n\n` +
463 `Diff:\n\n${diffString}`
464 );
465 },
466 };
467 },
468 });
469
470 declare global {
471 // eslint-disable-next-line no-redeclare,@typescript-eslint/no-unused-vars
472 namespace jest {
473 // eslint-disable-next-line @typescript-eslint/no-unused-vars
474 interface Matchers<R> {
475 toEqualFile({
476 filename,
477 code,
478 }: Pick<TestFile, "filename" | "code">): jest.CustomMatcherResult;
479 }
480 }
481 }
482
483 export type SuiteOptions = {
484 ignoreSuites?: string[];
485 ignoreTasks?: string[];
486 };
487
488 export default function (
489 fixturesLoc: string,
490 name: string,
491 suiteOpts: SuiteOptions = {},
492 taskOpts: TaskOptions = {},
493 dynamicOpts?: (options: TaskOptions, task: Test) => void,
494 ) {
495 const suites = getFixtures(fixturesLoc);
496
497 for (const testSuite of suites) {
498 if (suiteOpts.ignoreSuites?.includes(testSuite.title)) continue;
499
500 describe(name + "/" + testSuite.title, function () {
501 for (const task of testSuite.tests) {
502 if (
503 suiteOpts.ignoreTasks?.includes(task.title) ||
504 suiteOpts.ignoreTasks?.includes(testSuite.title + "/" + task.title)
505 ) {
506 continue;
507 }
508
509 const testFn = task.disabled ? it.skip : it;
510
511 testFn(
512 task.title,
513
514 async function () {
515 const runTask = () => run(task);
516
517 if ("sourceMap" in task.options) {
518 throw new Error(
519 "`sourceMap` option is deprecated. Use `sourceMaps` instead.",
520 );
521 }
522
523 if ("sourceMaps" in task.options === false) {
524 task.options.sourceMaps = !!task.sourceMap;
525 }
526
527 Object.assign(task.options, taskOpts);
528
529 if (dynamicOpts) dynamicOpts(task.options, task);
530
531 if (task.externalHelpers) {
532 (task.options.plugins ??= [])
533 // @ts-expect-error manipulating input options
534 .push([
535 "external-helpers",
536 { helperVersion: EXTERNAL_HELPERS_VERSION },
537 ]);
538 }
539
540 const throwMsg = task.options.throws;
541 if (throwMsg) {
542 // internal api doesn't have this option but it's best not to pollute
543 // the options object with useless options
544 delete task.options.throws;
545
546 await assert.rejects(runTask, function (err: Error) {
547 assert.ok(
548 throwMsg === true || err.message.includes(throwMsg),
549 `
550 Expected Error: ${throwMsg}
551 Actual Error: ${err.message}`,
552 );
553 return true;
554 });
555 } else {
556 return runTask();
557 }
558 },
559 );
560 }
561 });
562 }
563 }