/
stubUtils.js
555 lines (511 loc) · 14.5 KB
/
stubUtils.js
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/* @flow */
import colors from 'colors/safe';
import got from 'got';
import flowgen from 'flowgen';
import prettier from 'prettier';
import {determineFlowVersion} from './npm/npmProjectUtils';
import {findPackageJsonPath} from './npm/npmProjectUtils';
import {format} from 'util';
import {fs} from './node';
import globAsync from 'glob';
import {getPackageJsonData} from './npm/npmProjectUtils';
import {
getPackageJsonDependencies,
type PnpResolver,
} from './npm/npmProjectUtils';
import {mkdirp} from './fileUtils';
import {path} from './node';
import {signCode} from './codeSign';
import {verifySignedCode} from './codeSign';
import {versionToString} from './semver';
import {listItem} from './logger';
export function glob(pattern: string, options: Object): Promise<Array<string>> {
return new Promise((resolve, reject) =>
globAsync(pattern, options, (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
}),
);
}
async function resolvePkgDirPath(
pkgName: string,
pkgJsonDirPath: string,
pnpjs: PnpResolver | null,
): Promise<string> {
if (pnpjs != null) {
const pnpResolvedDirPath = pnpjs.resolveToUnqualified(
pkgName,
pkgJsonDirPath,
);
if (pnpResolvedDirPath != null) {
return pnpResolvedDirPath;
}
}
let prevNodeModulesDirPath;
let nodeModulesDirPath = path.resolve(pkgJsonDirPath, 'node_modules');
while (true) {
const pkgDirPath = path.resolve(nodeModulesDirPath, pkgName);
if (await fs.exists(pkgDirPath)) {
return pkgDirPath;
}
prevNodeModulesDirPath = nodeModulesDirPath;
nodeModulesDirPath = path.resolve(
nodeModulesDirPath,
'..',
'..',
'node_modules',
);
if (prevNodeModulesDirPath === nodeModulesDirPath) {
break;
}
}
throw new Error(
'Unable to find `' +
pkgName +
'/` install directory! ' +
'Did you forget to run `npm install` before running `flow-typed install`?',
);
}
const moduleStubTemplate = `
declare module '%s' {
declare module.exports: any;
}`.trim();
const aliasTemplate = `
declare module '%s%s' {
declare module.exports: $Exports<'%s'>;
}`.trim();
const guessedModuleStubTemplate = `
declare module '%s' {
declare module.exports: %s;
}`.trim();
function stubFor(moduleName: string, fileExt?: string): string {
const moduleStub = format(moduleStubTemplate, moduleName);
if (fileExt !== undefined) {
const aliasStub = format(aliasTemplate, moduleName, fileExt, moduleName);
return `${moduleStub}\n${aliasStub}`;
}
return moduleStub;
}
const functionTemplate = '(%s) => any';
const spaceByI = (i: number): string => ' '.repeat(i);
const keyTypeTemplate = ` %s: %s,\n`;
function objectToTypedTemplate(
obj: {...},
currentDepth: number,
maxDepth: number,
functionHeader?: string,
) {
const thisDepth = currentDepth + 1;
let formatedEntries = [];
if (functionHeader) {
formatedEntries.push(spaceByI(thisDepth + 1) + functionHeader);
}
for (let entrie of Object.entries(obj)) {
const toTypeResult = objectToType(
entrie[1],
maxDepth,
thisDepth,
thisDepth <= maxDepth,
);
formatedEntries.push(
format(
`${spaceByI(thisDepth)}${keyTypeTemplate}`,
entrie[0],
toTypeResult,
),
);
}
if (formatedEntries.length > 0) {
return `{\n${formatedEntries.join('')}${spaceByI(thisDepth)}}`;
} else {
return '{}';
}
}
function guessFunctionArguments(fun: Function): string {
let raw = fun.toString();
let args = raw.slice(raw.indexOf('(') + 1, raw.indexOf(')'));
args = args.replace(/ /g, '');
if (args.length > 0) {
args = args
.split(',')
.map((el: string) => `${el}: any`)
.join(', ');
}
return format(functionTemplate, args);
}
function functionToType(
fun: Function,
currentDepth: number,
maxDepth: number,
): string {
let output = guessFunctionArguments(fun);
let functionEntries = Object.entries(fun);
if (functionEntries.length > 0) {
return objectToTypedTemplate(
fun,
currentDepth,
maxDepth,
output.length > 0 ? output + ',\n' : undefined,
);
}
return output;
}
function objectToType(
obj: mixed,
maxDepth: number,
currentDepth: number = 0,
deep: boolean = true,
): string {
if (obj === null) return 'null';
// Every function that depends on objectToTypedTemplate need to check deep first
if (deep) {
if (typeof obj === 'object')
return objectToTypedTemplate(obj, currentDepth, maxDepth);
if (typeof obj === 'function')
return functionToType(obj, currentDepth, maxDepth);
}
if (typeof obj === 'object') return 'any';
if (typeof obj === 'function') return guessFunctionArguments(obj);
return typeof obj;
}
function guessedStubFor(
moduleName: string,
packagePath: string,
maxDepth: number = 1,
): string {
const module: {...} = (require: any)(packagePath);
const formattedTemplate: string = format(
guessedModuleStubTemplate,
moduleName,
objectToType(module, maxDepth),
);
return formattedTemplate;
}
async function writeStub(
projectRoot: string,
packageName: string,
packageVersion: string,
packageFolder: string | null,
overwrite: boolean,
files: Array<string>,
libdefDir: string,
maxDepth?: number,
typescriptTypingsPath?: string | null,
typescriptTypingsContent?: string | null,
): Promise<string> {
let flowgenOutput = null;
const flowgenTemplate = `
declare module '%s' {
%s
}
`.trim();
if (typescriptTypingsPath) {
const code = flowgen.compiler.compileDefinitionFile(typescriptTypingsPath);
try {
flowgenOutput = prettier.format(
format(flowgenTemplate, packageName, code),
{parser: 'babel-flow', singleQuote: true, semi: true},
);
} catch (e) {
if (
e.message.includes(
'`declare module` cannot be used inside another `declare module`',
)
) {
flowgenOutput = prettier.format(code, {
parser: 'babel-flow',
singleQuote: true,
semi: true,
});
} else {
flowgenOutput = format(flowgenTemplate, packageName, code);
}
}
} else if (typescriptTypingsContent) {
const code = flowgen.compiler.compileDefinitionString(
typescriptTypingsContent,
);
try {
flowgenOutput = prettier.format(
format(flowgenTemplate, packageName, code),
{parser: 'babel-flow', singleQuote: true, semi: true},
);
} catch (e) {
if (
e.message.includes(
'`declare module` cannot be used inside another `declare module`',
)
) {
flowgenOutput = prettier.format(code, {
parser: 'babel-flow',
singleQuote: true,
semi: true,
});
} else {
flowgenOutput = format(flowgenTemplate, packageName, code);
}
}
}
let output = [
'/**',
' * This is an autogenerated libdef stub for:',
' *',
` * '${packageName}'`,
' *',
' * Fill this stub out by replacing all the `any` types.',
' *',
' * Once filled out, we encourage you to share your work with the',
' * community by sending a pull request to:',
' * https://github.com/flowtype/flow-typed',
' */\n\n',
].join('\n');
if (packageFolder !== null && false) {
try {
output += guessedStubFor(packageName, packageFolder, maxDepth);
} catch (e) {
output += stubFor(packageName);
}
} else if (flowgenOutput) {
output += flowgenOutput;
} else {
output += stubFor(packageName);
}
if (files.length > 0) {
output += `
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
`;
const [fileDecls, aliases] = files.reduce(
([fileDecls, aliases], file) => {
const ext = path.extname(file);
const name = file.substr(0, file.length - ext.length);
const moduleName = `${packageName}/${name}`;
if (name === 'index') {
aliases.push(format(aliasTemplate, moduleName, '', packageName));
aliases.push(format(aliasTemplate, moduleName, ext, packageName));
} else if (path.basename(name) === 'index') {
const dirModuleName = packageName + '/' + path.dirname(file);
fileDecls.push(format(moduleStubTemplate, dirModuleName));
aliases.push(format(aliasTemplate, moduleName, '', dirModuleName));
aliases.push(format(aliasTemplate, moduleName, ext, dirModuleName));
} else {
fileDecls.push(format(moduleStubTemplate, moduleName));
aliases.push(format(aliasTemplate, moduleName, ext, moduleName));
}
return [fileDecls, aliases];
},
[[], []],
);
output += fileDecls.join('\n\n');
output += '\n\n// Filename aliases\n';
output += aliases.join('\n');
}
output += '\n'; // File should end with a newline
const filename = path.join(
projectRoot,
libdefDir,
'npm',
format('%s_vx.x.x.js', packageName),
);
await mkdirp(path.dirname(filename));
if (!overwrite) {
const exists = await fs.exists(filename);
if (exists) {
const existingStub = await fs.readFile(filename, 'utf8');
if (!verifySignedCode(existingStub)) {
throw new Error(
'Stub already exists and has been modified. ' +
'Use --overwrite to overwrite',
);
}
}
}
const flowVersionRaw = await determineFlowVersion(projectRoot);
const flowVersion = flowVersionRaw
? `/flow_${versionToString(flowVersionRaw)}`
: '';
const stubVersion = `<<STUB>>/${packageName}_v${packageVersion}${flowVersion}`;
await fs.writeFile(filename, signCode(output, stubVersion));
return filename;
}
export async function pkgHasFlowFiles(
projectRoot: string,
packageName: string,
pnpjs: PnpResolver | null,
): Promise<{|
flowTyped: boolean,
path?: string,
|}> {
try {
let pathToPackage = await resolvePkgDirPath(
packageName,
projectRoot,
pnpjs,
);
const files = await glob('**/*.flow', {
cwd: pathToPackage,
ignore: 'node_modules/**',
});
return {
flowTyped: files.length > 0,
path: pathToPackage,
};
} catch (e) {
return {
flowTyped: false,
};
}
}
async function getDefinitelyTypedPackage(
packageName: string,
explicitVersion: string | null,
) {
const parts = packageName.split('/');
const typesPackageName = packageName.startsWith('@')
? parts[0].slice(1) + '__' + parts[1]
: packageName;
const version = explicitVersion ? `@${explicitVersion}` : '';
const typing = `https://unpkg.com/@types/${typesPackageName}${version}/index.d.ts`;
return got(typing, {method: 'GET'});
}
/**
* createStub("/path/to/root", "foo") will create a file
* /path/to/root/flow-typed/npm/foo.js that contains a stub for the module foo.
*
* If foo is installed, it will read the directory that require("foo") resolves
* to and include definitions for "foo/FILE", for every FILE in the foo package
*/
export async function createStub(
projectRoot: string,
packageName: string,
explicitVersion: string | null,
overwrite: boolean,
pnpjs: PnpResolver | null,
typescript: boolean,
libdefDir?: string,
maxDepth?: number,
): Promise<boolean> {
let files = [];
let resolutionError = null;
let pathToPackage = null;
let version = explicitVersion || null;
let typescriptTypingsPath = null;
let typescriptTypingsContent = null;
const typedefDir = libdefDir || 'flow-typed';
try {
pathToPackage = await resolvePkgDirPath(packageName, projectRoot, pnpjs);
files = await glob('**/*.{js,jsx}', {
cwd: pathToPackage,
ignore: 'node_modules/**',
});
} catch (e) {
resolutionError = e;
}
// Try to deduce a version if one isn't provided
if (version == null) {
// Look at the package.json for the installed module
if (pathToPackage != null) {
try {
version = (require: any)(path.join(pathToPackage, 'package.json'))
.version;
} catch (e) {}
}
}
if (typescript) {
if (typescriptTypingsPath == null) {
// Look at the package.json for the installed module
if (pathToPackage != null) {
try {
const pkg = (require: any)(path.join(pathToPackage, 'package.json'));
const typing = pkg.typings || pkg.types;
if (typing) typescriptTypingsPath = path.join(pathToPackage, typing);
} catch (e) {}
}
}
// If that failed, try looking for index.d.ts file
if (typescriptTypingsPath == null) {
// Look at the package.json for the installed module
if (pathToPackage != null) {
const typing = path.join(pathToPackage, 'index.d.ts');
if (await fs.exists(typing)) {
typescriptTypingsPath = typing;
}
}
}
if (typescriptTypingsPath == null) {
try {
const response = await getDefinitelyTypedPackage(
packageName,
explicitVersion,
);
typescriptTypingsContent = response.body;
} catch (e) {
console.log(
colors.red("❌\t%s%s': %s"),
packageName,
version ? '@' + version : '',
e.message,
);
return false;
}
}
}
// If that failed, try looking for a package.json in the root
if (version == null) {
try {
const pkgJsonPathStr = await findPackageJsonPath(projectRoot);
const pkgJsonData = await getPackageJsonData(pkgJsonPathStr);
const rootDependencies = await getPackageJsonDependencies(
pkgJsonData,
[],
[],
);
version = rootDependencies[packageName] || null;
} catch (e) {}
}
try {
if (version === null) {
throw new Error(
'Could not deduce version from node_modules or package.json. ' +
'Please provide an explicit version',
);
}
const filename = await writeStub(
projectRoot,
packageName,
version,
pathToPackage,
overwrite,
files,
typedefDir,
maxDepth,
typescriptTypingsPath,
typescriptTypingsContent,
);
const terseFilename = path.relative(projectRoot, filename);
listItem(
`${packageName}@${version}`,
colors.red(terseFilename),
resolutionError
? colors.yellow(
`Unable to stub all files in ${packageName}, so only created a stub for the main module (${resolutionError.message})`,
)
: undefined,
);
return true;
} catch (e) {
console.log(
colors.red("❌\t%s%s': %s"),
packageName,
version ? '@' + version : '',
e.message,
);
return false;
}
}