/
npmProjectUtils.js
301 lines (269 loc) · 7.97 KB
/
npmProjectUtils.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
// @flow
import {searchUpDirPath} from '../fileUtils.js';
import type {FlowSpecificVer} from '../flowVersion.js';
import {fs, path} from '../node.js';
import {stringToVersion} from '../semver.js';
import type {Version} from '../semver.js';
import semver, {intersects} from 'semver';
import colors from 'colors/safe';
import glob from 'glob';
type PkgJson = {|
pathStr: string,
content: {
name: string,
version: string,
private?: boolean,
workspaces?: string[] | {packages: string[], ...},
installConfig?: {pnp?: boolean},
bundledDependencies?: {[pkgName: string]: string},
dependencies?: {[pkgName: string]: string},
devDependencies?: {[pkgName: string]: string},
optionalDependencies?: {[pkgName: string]: string},
peerDependencies?: {[pkgName: string]: string},
},
|};
export type PnpResolver = {|
resolveToUnqualified: (string, string) => string | null,
|};
const PKG_JSON_DEP_FIELDS = [
'dependencies',
'devDependencies',
'peerDependencies',
'bundledDependencies',
];
export async function findPackageJsonDepVersionStr(
pkgJson: PkgJson,
depName: string,
): Promise<null | string> {
let matchedFields = [];
const deps = PKG_JSON_DEP_FIELDS.reduce((deps, section) => {
const contentSection = pkgJson.content[section];
if (contentSection && contentSection[depName]) {
matchedFields.push(section);
deps.push(contentSection[depName]);
}
return deps;
}, []);
if (deps.length === 0) {
return null;
} else if (deps.length === 1) {
return deps.pop();
} else {
throw new Error(
`Found ${depName} listed in ${String(deps.length)} places in ` +
`${pkgJson.pathStr}!`,
);
}
}
export async function findPackageJsonPath(pathStr: string): Promise<string> {
const pkgJsonPathStr = await searchUpDirPath(
pathStr,
async p => await fs.exists(path.join(p, 'package.json')),
);
if (pkgJsonPathStr === null) {
throw new Error(`Unable to find a package.json for ${pathStr}!`);
}
return path.join(pkgJsonPathStr, 'package.json');
}
function getWorkspacePatterns(pkgJson: PkgJson): string[] {
if (Array.isArray(pkgJson.content.workspaces)) {
return pkgJson.content.workspaces;
}
if (
pkgJson.content.workspaces &&
Array.isArray(pkgJson.content.workspaces.packages)
) {
return pkgJson.content.workspaces.packages;
}
return [];
}
export async function findWorkspacesPackagePaths(
pkgJson: PkgJson,
): Promise<string[]> {
const tasks = await Promise.all(
getWorkspacePatterns(pkgJson).map(pattern => {
return new Promise((resolve, reject) => {
glob(
`${path.dirname(pkgJson.pathStr)}/${pattern}/package.json`,
{absolute: true},
(err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
},
);
});
}),
);
return tasks.flat();
}
export async function findWorkspacesPackages(
pkgJson: PkgJson,
): Promise<PkgJson[]> {
const paths = await findWorkspacesPackagePaths(pkgJson);
return Promise.all(
paths.map(async pathStr => {
const pkgJsonContent = await fs.readJson(pathStr);
return {
pathStr,
content: pkgJsonContent,
};
}),
);
}
// TODO: Write tests for this
export function getPackageJsonDependencies(
pkgJson: PkgJson,
/**
* dependency groups to ignore
*/
ignoreDeps: Array<string>,
/**
* dependencies or scopes of dependencies to be ignored
*/
ignoreDefs: Array<string>,
): {[depName: string]: string} {
const depFields = PKG_JSON_DEP_FIELDS.filter(field => {
return ignoreDeps.indexOf(field.slice(0, -12)) === -1;
});
return depFields.reduce((deps, section) => {
const contentSection = pkgJson.content[section];
if (contentSection) {
Object.keys(contentSection).forEach(pkgName => {
if (deps[pkgName]) {
console.warn(`Found ${pkgName} listed twice in package.json!`);
}
const pkgIgnored = ignoreDefs.some(cur => {
const ignoreDef = cur.trim();
if (ignoreDef === '') return false;
// if we are looking to ignore a scope dir
if (
ignoreDef.charAt(0) === '@' &&
(ignoreDef.indexOf('/') === -1 ||
ignoreDef.indexOf('/') === ignoreDef.length - 1)
) {
return pkgName.startsWith(ignoreDef);
}
return pkgName === ignoreDef;
});
if (pkgIgnored) return;
deps[pkgName] = contentSection[pkgName];
});
}
return deps;
}, {});
}
export function mergePackageJsonDependencies(
a: {[depName: string]: string},
b: {[depName: string]: string},
): {[depName: string]: string} {
const result = {...a};
for (const dep of Object.keys(b)) {
const version = b[dep];
let doesIntersect;
try {
doesIntersect = intersects(result[dep], version);
} catch (e) {
doesIntersect = result[dep] === version;
}
if (a[dep] != null && !doesIntersect) {
console.log(
colors.yellow(
"\t Conflicting versions for '%s' between '%s' and '%s'",
),
dep,
a[dep],
version,
);
} else {
result[dep] = version;
}
}
return result;
}
export async function getPackageJsonData(pathStr: string): Promise<PkgJson> {
const pkgJsonPath = await findPackageJsonPath(pathStr);
const pkgJsonContent = await fs.readJson(pkgJsonPath);
return {
pathStr: pkgJsonPath,
content: pkgJsonContent,
};
}
export async function determineFlowVersion(
pathStr: string,
): Promise<null | Version> {
const pkgJsonData = await getPackageJsonData(pathStr);
const flowBinVersionStr = await findPackageJsonDepVersionStr(
pkgJsonData,
'flow-bin',
);
if (flowBinVersionStr !== null) {
let flowVerStr;
if (semver.valid(flowBinVersionStr)) {
flowVerStr = flowBinVersionStr;
} else {
const flowVerRange = new semver.Range(flowBinVersionStr);
if (flowVerRange.set[0].length !== 2) {
const cliPkgJson = require('../../../package.json');
const cliFlowVer = cliPkgJson.devDependencies['flow-bin'];
throw new Error(
`Unable to extract flow-bin version from package.json!\n` +
`Never use a complex version range with flow-bin. Always use a ` +
`specific version (i.e. "${cliFlowVer}").`,
);
}
flowVerStr = flowVerRange.set[0][0].semver.version;
}
return stringToVersion('v' + flowVerStr);
}
return null;
}
export async function loadPnpResolver(
pkgJson: PkgJson,
): Promise<PnpResolver | null> {
if (!(pkgJson.content.installConfig && pkgJson.content.installConfig.pnp)) {
return null;
}
const pnpJsFile = path.resolve(pkgJson.pathStr, '..', '.pnp.js');
if (await fs.exists(pnpJsFile)) {
// $FlowFixMe[unsupported-syntax]
return require(pnpJsFile);
}
throw new Error(
'Unable to find Yarn PNP resolver lib: `.pnp.js`! ' +
'Did you forget to run `yarn install` before running `flow-typed install`?',
);
}
export async function findFlowSpecificVer(
startingPath: string,
): Promise<FlowSpecificVer> {
const flowSemver = await determineFlowVersion(startingPath);
if (flowSemver === null) {
throw new Error(
'Failed to find a flow-bin dependency in package.json.\n' +
'Please install flow-bin: `npm install --save-dev flow-bin`',
);
}
if (flowSemver.range !== undefined) {
throw new Error(
`Unable to extract flow-bin version from package.json!\n` +
`Never use a complex version range with flow-bin. Always use a ` +
`specific major/minor version (i.e. "^0.39").`,
);
}
const major = flowSemver.major;
if (major === 'x') {
throw new Error(
`Unable to extract flow-bin version from package.json!\n` +
`Never use a wildcard major version with flow-bin!`,
);
}
return {
major,
minor: flowSemver.minor,
patch: flowSemver.patch,
prerel: flowSemver.prerel == null ? null : flowSemver.prerel,
};
}