Debian Codegraph @

packages/babel-helper-fixtures/src/index.ts

raw symbols SCIP
1 import semver from "semver";
2 import path from "path";
3 import fs from "fs";
4 import { fileURLToPath } from "url";
5 import { createRequire } from "module";
6 import type { InputOptions } from "@babel/core";
7 import type { EncodedSourceMap } from "@jridgewell/gen-mapping";
8
9 const require = createRequire(import.meta.url);
10
11 const nodeVersion = semver.clean(process.version.slice(1));
12
13 function humanize(val: string, noext?: boolean) {
14 if (noext) val = path.basename(val, path.extname(val));
15 return val.replace(/-/g, " ");
16 }
17
18 interface TestIO {
19 loc: string;
20 code: string;
21 }
22
23 export interface TestFile extends TestIO {
24 filename: string;
25 }
26
27 export interface Test {
28 taskDir: string;
29 title: string;
30 disabled: boolean;
31 options: TaskOptions;
32 optionsDir: string;
33 doNotSetSourceType: boolean;
34 externalHelpers: boolean;
35 ignoreOutput: boolean;
36 stdout: TestIO;
37 stderr: TestIO;
38 exec: TestFile;
39 actual: TestFile;
40 expect: TestFile;
41 inputSourceMap?: EncodedSourceMap;
42 sourceMap: string;
43 sourceMapFile: TestFile;
44 validateLogs: boolean;
45 }
46
47 export interface TaskOptions extends InputOptions {
48 BABEL_8_BREAKING?: boolean;
49 DO_NOT_SET_SOURCE_TYPE?: boolean;
50 externalHelpers?: boolean;
51 ignoreOutput?: boolean;
52 minNodeVersion?: string;
53 sourceMap?: boolean;
54 os?: string | string[];
55 validateLogs?: boolean;
56 throws?: boolean | string;
57 }
58
59 type Suite = {
60 options: TaskOptions;
61 tests: Array<Test>;
62 title: string;
63 filename: string;
64 };
65
66 function tryResolve(module: string) {
67 try {
68 return require.resolve(module);
69 } catch (e) {
70 return null;
71 }
72 }
73 function assertDirectory(loc: string) {
74 if (!fs.statSync(loc).isDirectory()) {
75 throw new Error(`Expected ${loc} to be a directory.`);
76 }
77 }
78
79 function shouldIgnore(name: string, ignore?: Array<string>) {
80 if (ignore && ignore.indexOf(name) >= 0) {
81 return true;
82 }
83
84 const ext = path.extname(name);
85 const base = path.basename(name, ext);
86
87 return (
88 name[0] === "." ||
89 ext === ".md" ||
90 base === "LICENSE" ||
91 base === "options" ||
92 name === "package.json"
93 );
94 }
95
96 const EXTENSIONS = [".js", ".mjs", ".ts", ".tsx", ".cts", ".mts"];
97
98 function findFile(filepath: string, allowJSON?: boolean) {
99 const matches = [];
100
101 for (const ext of EXTENSIONS.concat(allowJSON ? ".json" : [])) {
102 const name = filepath + ext;
103
104 if (fs.existsSync(name)) matches.push(name);
105 }
106
107 if (matches.length > 1) {
108 throw new Error(`Found conflicting file matches: ${matches.join(", ")}`);
109 }
110
111 return matches[0];
112 }
113
114 function pushTask(
115 taskName: string,
116 taskDir: string,
117 suite: Suite,
118 suiteName: string,
119 ) {
120 const taskDirStats = fs.statSync(taskDir);
121 let actualLoc = findFile(taskDir + "/input");
122 let execLoc = findFile(taskDir + "/exec");
123
124 // If neither input nor exec is present it is not a real testcase
125 if (taskDirStats.isDirectory() && !actualLoc && !execLoc) {
126 if (fs.readdirSync(taskDir).length > 0) {
127 console.warn(`Skipped test folder with invalid layout: ${taskDir}`);
128 }
129 return;
130 } else if (!actualLoc) {
131 actualLoc = taskDir + "/input.js";
132 } else if (!execLoc) {
133 execLoc = taskDir + "/exec.js";
134 }
135
136 const expectLoc =
137 findFile(taskDir + "/output", true /* allowJSON */) ||
138 findFile(`${taskDir}/output.extended`, true) ||
139 taskDir + "/output.js";
140 const stdoutLoc = taskDir + "/stdout.txt";
141 const stderrLoc = taskDir + "/stderr.txt";
142
143 const actualLocAlias =
144 suiteName + "/" + taskName + "/" + path.basename(actualLoc);
145 const expectLocAlias =
146 suiteName + "/" + taskName + "/" + path.basename(actualLoc);
147 let execLocAlias =
148 suiteName + "/" + taskName + "/" + path.basename(actualLoc);
149
150 if (taskDirStats.isFile()) {
151 const ext = path.extname(taskDir);
152 if (EXTENSIONS.indexOf(ext) === -1) return;
153
154 execLoc = taskDir;
155 execLocAlias = suiteName + "/" + taskName;
156 }
157
158 const taskOpts: TaskOptions = JSON.parse(JSON.stringify(suite.options));
159
160 const taskOptsLoc = tryResolve(taskDir + "/options");
161 if (taskOptsLoc) Object.assign(taskOpts, require(taskOptsLoc));
162
163 const test: Test = {
164 taskDir,
165 optionsDir: taskOptsLoc ? path.dirname(taskOptsLoc) : null,
166 title: humanize(taskName, true),
167 disabled:
168 taskName[0] === "." ||
169 (process.env.BABEL_8_BREAKING
170 ? taskOpts.BABEL_8_BREAKING === false
171 : taskOpts.BABEL_8_BREAKING === true),
172 options: taskOpts,
173 doNotSetSourceType: taskOpts.DO_NOT_SET_SOURCE_TYPE,
174 externalHelpers:
175 taskOpts.externalHelpers ??
176 !!tryResolve("@babel/plugin-external-helpers"),
177 validateLogs: taskOpts.validateLogs,
178 ignoreOutput: taskOpts.ignoreOutput,
179 stdout: { loc: stdoutLoc, code: readFile(stdoutLoc) },
180 stderr: { loc: stderrLoc, code: readFile(stderrLoc) },
181 exec: {
182 loc: execLoc,
183 code: readFile(execLoc),
184 filename: execLocAlias,
185 },
186 actual: {
187 loc: actualLoc,
188 code: readFile(actualLoc),
189 filename: actualLocAlias,
190 },
191 expect: {
192 loc: expectLoc,
193 code: readFile(expectLoc),
194 filename: expectLocAlias,
195 },
196 sourceMap: undefined,
197 sourceMapFile: undefined,
198 inputSourceMap: undefined,
199 };
200
201 delete taskOpts.BABEL_8_BREAKING;
202 delete taskOpts.DO_NOT_SET_SOURCE_TYPE;
203
204 // If there's node requirement, check it before pushing task
205 if (taskOpts.minNodeVersion) {
206 const minimumVersion = semver.clean(taskOpts.minNodeVersion);
207
208 if (minimumVersion == null) {
209 throw new Error(
210 `'minNodeVersion' has invalid semver format: ${taskOpts.minNodeVersion}`,
211 );
212 }
213
214 if (semver.lt(nodeVersion, minimumVersion)) {
215 return;
216 }
217
218 // Delete to avoid option validation error
219 delete taskOpts.minNodeVersion;
220 }
221
222 if (taskOpts.os) {
223 let os = taskOpts.os;
224
225 if (!Array.isArray(os) && typeof os !== "string") {
226 throw new Error(
227 `'os' should be either string or string array: ${taskOpts.os}`,
228 );
229 }
230
231 if (typeof os === "string") {
232 os = [os];
233 }
234
235 if (!os.includes(process.platform)) {
236 return;
237 }
238
239 delete taskOpts.os;
240 }
241
242 // traceur checks
243
244 if (test.exec.code.indexOf("// Async.") >= 0) {
245 return;
246 }
247
248 suite.tests.push(test);
249
250 const sourceMapLoc = taskDir + "/source-map.json";
251 if (fs.existsSync(sourceMapLoc)) {
252 test.sourceMap = JSON.parse(readFile(sourceMapLoc));
253 }
254 test.sourceMapFile = {
255 loc: sourceMapLoc,
256 code: test.sourceMap,
257 filename: "",
258 };
259
260 const inputMapLoc = taskDir + "/input-source-map.json";
261 if (fs.existsSync(inputMapLoc)) {
262 test.inputSourceMap = JSON.parse(readFile(inputMapLoc));
263 }
264
265 if (taskOpts.throws) {
266 if (test.expect.code) {
267 throw new Error(
268 "Test cannot throw and also return output code: " + expectLoc,
269 );
270 }
271 if (test.sourceMap) {
272 throw new Error(
273 "Test cannot throw and also return sourcemaps: " + sourceMapLoc,
274 );
275 }
276 }
277
278 if (!test.validateLogs && (test.stdout.code || test.stderr.code)) {
279 throw new Error(
280 "stdout.txt and stderr.txt are only allowed when the 'validateLogs' option is enabled: " +
281 (test.stdout.code ? stdoutLoc : stderrLoc),
282 );
283 }
284 if (test.ignoreOutput) {
285 if (test.expect.code) {
286 throw new Error(
287 "Test cannot ignore its output and also validate it: " + expectLoc,
288 );
289 }
290 if (!test.validateLogs) {
291 throw new Error(
292 "ignoreOutput can only be used when validateLogs is true: " +
293 taskOptsLoc,
294 );
295 }
296 }
297
298 // Delete to avoid option validation error
299 delete test.options.validateLogs;
300 delete test.options.ignoreOutput;
301 delete test.options.externalHelpers;
302 }
303
304 function wrapPackagesArray(
305 type: "plugin" | "preset",
306 names: (string | [string, object?, string?])[],
307 optionsDir: string,
308 ) {
309 return names.map(function (val) {
310 if (typeof val === "string") val = [val];
311
312 // relative path (outside of monorepo)
313 if (val[0][0] === ".") {
314 if (!optionsDir) {
315 throw new Error(
316 "Please provide an options.json in test dir when using a " +
317 "relative plugin path.",
318 );
319 }
320
321 val[0] = path.resolve(optionsDir, val[0]);
322 } else {
323 let name = val[0];
324 const match = name.match(/^(@babel\/(?:plugin-|preset-)?)(.*)$/);
325 if (match) {
326 name = match[2];
327 }
328
329 const monorepoPath = path.join(
330 path.dirname(fileURLToPath(import.meta.url)),
331 "../../..",
332 name.startsWith("codemod") ? "codemods" : "packages",
333 `babel-${type}-${name}/lib/index.js`,
334 );
335
336 if (fs.existsSync(monorepoPath)) {
337 if (match) {
338 throw new Error(
339 `Remove the "${match[1]}" prefix from "${val[0]}", to load it from the monorepo`,
340 );
341 }
342
343 val[0] = monorepoPath;
344 }
345 }
346
347 return val;
348 });
349 }
350
351 /**
352 * Resolve plugins/presets defined in options.json
353 *
354 * @export
355 * @param {{}} options the imported options.json
356 * @param {string} optionsDir the direcotry where options.json is placed
357 * @returns {{}} options whose plugins/presets are resolved
358 */
359 export function resolveOptionPluginOrPreset(
360 options: any,
361 optionsDir: string,
362 ): {} {
363 if (options.plugins) {
364 options.plugins = wrapPackagesArray("plugin", options.plugins, optionsDir);
365 }
366 if (options.presets) {
367 options.presets = wrapPackagesArray(
368 "preset",
369 options.presets,
370 optionsDir,
371 ).map(function (val) {
372 if (val.length > 3) {
373 throw new Error(
374 "Unexpected extra options " +
375 JSON.stringify(val.slice(3)) +
376 " passed to preset.",
377 );
378 }
379
380 return val;
381 });
382 }
383 return options;
384 }
385
386 export default function get(entryLoc: string): Array<Suite> {
387 const suites = [];
388
389 let rootOpts: TaskOptions = {};
390 const rootOptsLoc = tryResolve(entryLoc + "/options");
391 if (rootOptsLoc) rootOpts = require(rootOptsLoc);
392
393 for (const suiteName of fs.readdirSync(entryLoc)) {
394 if (shouldIgnore(suiteName)) continue;
395
396 const suite = {
397 options: { ...rootOpts },
398 tests: [] as Test[],
399 title: humanize(suiteName),
400 filename: entryLoc + "/" + suiteName,
401 };
402
403 assertDirectory(suite.filename);
404 suites.push(suite);
405
406 const suiteOptsLoc = tryResolve(suite.filename + "/options");
407 if (suiteOptsLoc) {
408 suite.options = resolveOptionPluginOrPreset(
409 require(suiteOptsLoc),
410 suite.filename,
411 );
412 }
413
414 for (const taskName of fs.readdirSync(suite.filename)) {
415 pushTask(taskName, suite.filename + "/" + taskName, suite, suiteName);
416 }
417 }
418
419 return suites;
420 }
421
422 export function multiple(entryLoc: string, ignore?: Array<string>) {
423 const categories: Record<string, unknown> = {};
424
425 for (const name of fs.readdirSync(entryLoc)) {
426 if (shouldIgnore(name, ignore)) continue;
427
428 const loc = path.join(entryLoc, name);
429 assertDirectory(loc);
430
431 categories[name] = get(loc);
432 }
433
434 return categories;
435 }
436
437 export function readFile(filename: string) {
438 if (fs.existsSync(filename)) {
439 let file = fs.readFileSync(filename, "utf8").trimRight();
440 file = file.replace(/\r\n/g, "\n");
441 return file;
442 } else {
443 return "";
444 }
445 }