UNPKG

2.49 kBJavaScriptView Raw
1#!/usr/bin/env node
2import { dirname, resolve } from 'path';
3import { fileURLToPath, pathToFileURL } from 'url';
4import { createReadStream } from 'fs';
5import { readFile } from 'fs/promises';
6import arg from 'arg';
7import globby from 'globby';
8import {
9 createDiffReporter,
10 createJSONReporter,
11 createTAPReporter,
12} from 'zora-reporters';
13
14const __filename = fileURLToPath(import.meta.url);
15const __dirname = dirname(__filename);
16
17const reporterMap = {
18 diff: createDiffReporter(),
19 tap: createTAPReporter(),
20 json: createJSONReporter(),
21 log: createJSONReporter(), // alias for "json"
22};
23
24const DEFAULT_FILE_PATTERNS = [
25 '**/test.js',
26 '**/*.spec.js',
27 '**/*.test.js',
28 '**/test/**/*.js',
29 '**/tests/**/*.js',
30 '**/__tests__/**/*.js',
31 '!**/node_modules',
32 '!node_modules',
33];
34
35const {
36 ['--reporter']: reporter = 'diff',
37 ['--only']: only = false,
38 ['--help']: help = false,
39 ['--module-loader']: moduleLoader,
40 _: filePatterns,
41} = arg({
42 ['--reporter']: String,
43 ['--only']: Boolean,
44 ['--help']: Boolean,
45 ['--module-loader']: String,
46 ['-R']: '--reporter',
47});
48
49(async () => {
50 if (help) {
51 createReadStream(resolve(__dirname, './usage.txt')).pipe(process.stdout);
52 return;
53 }
54
55 // we set the env var before loading zora
56 if (only) {
57 process.env.ZORA_ONLY = true;
58 }
59
60 // loading zora to hold the singleton -> look for loading strategy (cjs vs es)
61 const { hold, report } = await import(
62 await getZoraPackagePath({ moduleLoader })
63 );
64 hold();
65
66 const reporterInstance = reporterMap[reporter] || reporter.diff;
67 const files = await globby(
68 filePatterns.length ? filePatterns : DEFAULT_FILE_PATTERNS
69 );
70
71 if (!files.length) {
72 console.warn(`no file matching the patterns: ${filePatterns.join(', ')}`);
73 return;
74 }
75
76 await Promise.all(
77 files.map((file) => {
78 const filePath = resolve(process.cwd(), file);
79 return import(pathToFileURL(filePath));
80 })
81 );
82
83 await report({
84 reporter: reporterInstance,
85 });
86})();
87
88async function getZoraPackagePath({ moduleLoader }) {
89 // force to user choice
90 if (moduleLoader) {
91 return moduleLoader === 'cjs' ? 'zora/cjs' : 'zora';
92 }
93
94 // try to get it from package.json
95 const packageJsonPath = resolve(process.cwd(), './package.json');
96 try {
97 const file = await readFile(packageJsonPath, { encoding: 'utf-8' });
98 const { type } = JSON.parse(file);
99 return type === 'module' ? 'zora' : 'zora/cjs';
100 } catch (e) {
101 return 'zora';
102 }
103}