-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
api.mjs
executable file
·342 lines (291 loc) · 10.9 KB
/
api.mjs
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#!/usr/bin/env node
import test from 'tape';
import path, { join } from 'path';
import {
existsSync,
readdirSync,
readFileSync,
statSync,
} from 'fs';
import { spawn } from 'child_process';
import inspect from 'object-inspect';
import major from 'semver/functions/major.js';
import { createRequire } from 'module';
import pargs from './pargs.mjs';
const require = createRequire(import.meta.url);
const { version } = require('./package.json');
const majorV = major(version);
const help = readFileSync(join(import.meta.dirname, './help.txt'), 'utf8');
const {
positionals,
values: {
type,
'skip-shim-returns-polyfill': skipShimPolyfill,
'skip-auto-shim': skipAutoShim,
'ignore-dirs': rawIgnoreDirs,
},
// eslint-disable-next-line no-extra-parens, max-len
} = /** @type {{ positionals: string[], values: { type: 'method' | 'function' | 'property' | 'constructor' | 'multi', 'skip-shim-returns-polyfill': boolean, 'skip-auto-shim': boolean, 'ignore-dirs': string[], multi: boolean } }} */ (
pargs(help, import.meta.filename, {
allowPositionals: true,
options: {
type: {
type: 'string',
default: 'method',
},
'skip-shim-returns-polyfill': { type: 'boolean' },
'skip-auto-shim': { type: 'boolean' },
'ignore-dirs': {
type: 'string',
multiple: true,
default: [],
},
},
})
);
let isMulti = type === 'multi';
const ignoreDirs = ['node_modules', 'coverage', 'helpers', 'test', 'aos'].concat(rawIgnoreDirs.flatMap((x) => x.split(',')));
/** @type {<T extends string>(name: T) => [T, T]} */
function makeEntries(name) {
return [name, name];
}
/** @type {[string, string | [string, string]][]} */
const moduleNames = positionals.map(makeEntries);
/** @type {{ name?: string, main?: string | false, exports?: Record<string, unknown | unknown[]> }} */
let pkg;
if (moduleNames.length < 1) {
const packagePath = path.join(process.cwd(), 'package.json');
if (!existsSync(packagePath)) {
console.error('Error: No package.json found in the current directory');
console.error('at least one module name is required when not run in a directory with a package.json');
process.exit(1);
}
pkg = require(packagePath);
if (!pkg.name) {
console.error('Error: No "name" found in package.json');
process.exit(2);
}
moduleNames.push([`${pkg.name} (current directory)`, [path.join(process.cwd(), pkg.main || ''), process.cwd()]]);
const mainIsJSON = path.extname(require.resolve(process.cwd())) === '.json';
if (isMulti && !mainIsJSON) {
console.error('Error: --type=multi requires package.json main to be a JSON file');
process.exit(3);
}
if (!isMulti && mainIsJSON) {
isMulti = true;
console.error('# automatic `--type=multi` mode enabled');
}
if (
type !== 'property'
&& type !== 'method'
&& type !== 'constructor'
&& type !== 'function'
&& type !== 'multi'
) {
console.error('`type` must be one of `method`, `function`, `property`, `constructor`, or `multi`');
process.exit(4);
}
}
/** @type {(name: string) => {}} */
function requireOrEvalError(name) {
try {
return require(name);
} catch (e) {
// @ts-expect-error it's fine if this throws on a nullish exception from the module
return new EvalError(e.message);
}
}
/** @type {(t: test.Test, prefix: string, packageDir: string, asMulti: boolean) => void} */
const testAuto = function testAutoModule(t, prefix, packageDir, asMulti) {
t.test(`${prefix}auto`, (st) => {
const msg = 'auto is present';
if (skipAutoShim) {
st.comment(`# SKIP ${msg}`);
st.end();
} else {
require(path.join(packageDir, '/auto'));
st.comment(`${msg} (pass \`--skip-auto-shim\` to skip this test)`);
const proc = spawn(path.join(import.meta.dirname, asMulti ? 'multiAutoTest.js' : 'autoTest.js'), [], { cwd: packageDir, stdio: 'inherit' });
st.plan(1);
proc.on('close', (code) => {
st.equal(code, 0, 'auto invokes shim');
});
}
});
};
/** @type {(t: test.Test, packageDir: string, name: string) => undefined | EvalError} */
const doValidation = function doActualValidation(t, packageDir, name) {
const module = requireOrEvalError(name);
if (module instanceof EvalError) {
return module;
}
const implementation = requireOrEvalError(`${packageDir}/implementation`);
const shim = requireOrEvalError(`${packageDir}/shim`);
// eslint-disable-next-line no-extra-parens
const getPolyfill = /** @type {Function} */ (requireOrEvalError(`${packageDir}/polyfill`));
const prefix = isMulti ? `${path.basename(packageDir)}: ` : '';
t.test(`${prefix}export`, (st) => {
if (type === 'property') {
st.comment('# SKIP module that is a data property need not be a function');
} else if (isMulti) {
st.notEqual(typeof module, 'undefined', 'module is not `undefined`');
} else {
st.equal(typeof module, 'function', 'module is a function (pass `--type=property` to skip this test)');
}
st.test('module is NOT bound (pass `--type=method` to skip this test)', { skip: type !== 'function' && type !== 'constructor' }, (st2) => {
st2.equal(module, getPolyfill(), 'module.exports === getPolyfill()');
st2.end();
});
st.test('module is bound (pass a `--type=` other than `method` to skip this test)', { skip: type !== 'method' }, (st2) => {
st2.notEqual(module, getPolyfill(), 'module.exports !== getPolyfill()');
st2.end();
});
st.end();
});
t.test(`${prefix}implementation`, (st) => {
st.notOk(
'implementation' in module,
'module.exports lacks a `implementation` property',
{ skip: isMulti },
);
if (type === 'property') {
st.comment('# SKIP implementation that is a data property need not be a function');
} else if (isMulti) {
st.notEqual(typeof implementation, 'undefined', 'implementation is not `undefined`');
} else {
st.equal(typeof implementation, 'function', 'implementation is a function (pass `--type=property` to skip this test)');
}
st.end();
});
t.test(`${prefix}polyfill`, (st) => {
st.notOk(
'getPolyfill' in module,
'module.exports lacks a `getPolyfill` property',
{ skip: isMulti },
);
st.equal(typeof getPolyfill, 'function', 'getPolyfill is a function');
st.end();
});
t.test(`${prefix}shim`, (st) => {
st.notOk(
'shim' in module,
'module.exports lacks a `shim` property',
{ skip: isMulti },
);
st.equal(typeof shim, 'function', 'shim is a function');
if (typeof shim === 'function') {
const msg = 'shim returns polyfill (pass `--skip-shim-returns-polyfill` to skip this test)';
if (skipShimPolyfill) {
st.comment(`# SKIP ${msg}`);
} else {
const builtin = shim();
st.equal(builtin, getPolyfill(), msg);
st.test('builtin does not have own properties added', (s2t) => {
s2t.notOk('implementation' in builtin, 'has no `implementation` property');
s2t.notOk('getPolyfill' in builtin, 'has no `getPolyfill` property');
s2t.notOk('shim' in builtin, 'has no `shim` property');
s2t.end();
});
}
}
st.end();
});
testAuto(t, prefix, packageDir, false);
return void undefined;
};
/** @type {(t: test.Test, nameOrFilePaths: string | [string, string]) => EvalError | undefined} */
const validateModule = function validateAPIModule(t, nameOrFilePaths) {
const [name, packageDir] = Array.isArray(nameOrFilePaths)
? nameOrFilePaths
: [nameOrFilePaths, nameOrFilePaths];
t.test('`exports` field', { skip: !('exports' in pkg) }, (st) => {
// eslint-disable-next-line no-extra-parens
const exps = /** @type {NonNullable<typeof pkg.exports>} */ (pkg.exports);
const expectedKeys = isMulti
? ['.', './auto', './shim', './package.json']
: ['.', './auto', './polyfill', './implementation', './shim', './package.json'];
const exportsKeys = Object.keys(exps);
const keysToCheck = exportsKeys.filter((key) => expectedKeys.includes(key));
st.deepEqual(keysToCheck, expectedKeys, 'expected entrypoints are present in the proper order');
exportsKeys.forEach((key) => {
const rhs = exps[key];
// @ts-expect-error TS sucks with concat
const exists = [].concat(rhs).some(existsSync);
st.ok(exists, `entrypoint \`${key}\` points to \`${inspect(rhs)}\` which exists (or is an array with one item that exists)`);
});
st.equal(exps['./package.json'], './package.json', 'package.json is exposed');
st.end();
});
if (isMulti) {
// eslint-disable-next-line no-extra-parens
const subPackages = /** @type {string[]} */ (requireOrEvalError(name));
if (subPackages instanceof EvalError) {
return subPackages;
}
t.ok(Array.isArray(subPackages), 'main export is an array of sub packages');
subPackages.sort();
t.deepEqual(
Object.keys(subPackages),
subPackages.map((_, i) => String(i)),
'main export has no additional properties',
);
t.ok(subPackages.length > 0, 'array is not empty');
const dirs = readdirSync(packageDir).filter((d) => !d.startsWith('.') && !ignoreDirs.includes(d) && statSync(d).isDirectory());
t.deepEqual(subPackages, dirs, 'main export subpackages matches dirs in the package root');
const shim = requireOrEvalError(`${packageDir}/shim`);
t.equal(typeof shim, 'function', 'root shim is a function');
testAuto(t, 'root: ', packageDir, true);
const implementation = requireOrEvalError('./implementation');
t.ok(implementation instanceof EvalError, 'root lacks an `implementation` module');
subPackages.forEach((subPackage) => {
const subPackageDir = path.join(path.dirname(name), subPackage);
doValidation(t, subPackageDir, subPackageDir);
});
t.test('subpackages, `exports` field', { skip: !('exports' in pkg) }, (st) => {
// eslint-disable-next-line no-extra-parens
const exps = /** @type {NonNullable<typeof pkg.exports>} */ (pkg.exports);
subPackages.forEach((subPackage) => {
const subPackageLHS = [
`./${subPackage}`,
`./${subPackage}/auto`,
`./${subPackage}/polyfill`,
`./${subPackage}/implementation`,
`./${subPackage}/shim`,
];
subPackageLHS.forEach((lhs) => {
st.ok(lhs in exps, `\`${lhs}\` is in \`exports\``);
if (lhs in exps) {
// eslint-disable-next-line no-extra-parens
const rhs = /** @type {string} */ (exps[lhs]);
st.equal(typeof rhs, 'string', 'right-hand side of `exports` is a string');
const resolved = path.resolve(path.join(packageDir, rhs));
const lhsGuess = `./${path.relative(
packageDir,
path.join(
path.dirname(resolved),
path.basename(resolved, path.extname(resolved)),
),
).replace(/\/index$/, '')}`;
st.equal(lhs, lhsGuess, `subpackage \`${subPackage}\` LHS + \`${lhs}\` resolves to \`${lhsGuess}\``);
}
});
st.deepEqual(
Object.keys(exps).filter((lhs) => subPackageLHS.indexOf(lhs) > -1),
subPackageLHS,
`subpackage \`${subPackage}\` exports the expected entries in the proper order`,
);
});
st.end();
});
} else {
doValidation(t, packageDir, name);
}
return void undefined;
};
moduleNames.forEach(([name, filePath]) => {
test(`es-shim API v${majorV}: testing module: ${name}`, (t) => {
t.comment('* ----------------------------- * #');
t.error(validateModule(t, filePath), 'expected no error');
t.end();
});
});