-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
JsPackageManager.ts
341 lines (299 loc) · 10.1 KB
/
JsPackageManager.ts
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
import chalk from 'chalk';
import { gt, satisfies } from '@storybook/semver';
import { sync as spawnSync } from 'cross-spawn';
import { commandLog } from '../helpers';
import { PackageJson, PackageJsonWithDepsAndDevDeps } from './PackageJson';
import { readPackageJson, writePackageJson } from './PackageJsonHelper';
import storybookPackagesVersions from '../versions';
const logger = console;
/**
* Extract package name and version from input
*
* @param pkg A string like `@storybook/cli`, `react` or `react@^16`
* @return A tuple of 2 elements: [packageName, packageVersion]
*/
export function getPackageDetails(pkg: string): [string, string?] {
const idx = pkg.lastIndexOf('@');
// If the only `@` is the first character, it is a scoped package
// If it isn't in the string, it will be -1
if (idx <= 0) {
return [pkg, undefined];
}
const packageName = pkg.slice(0, idx);
const packageVersion = pkg.slice(idx + 1);
return [packageName, packageVersion];
}
export abstract class JsPackageManager {
public abstract readonly type: 'npm' | 'yarn1' | 'yarn2';
public abstract initPackageJson(): void;
public abstract getRunStorybookCommand(): string;
public abstract getRunCommand(command: string): string;
/**
* Install dependencies listed in `package.json`
*/
public installDependencies(): void {
let done = commandLog('Preparing to install dependencies');
done();
logger.log();
logger.log();
done = commandLog('Installing dependencies');
try {
this.runInstall();
} catch (e) {
done('An error occurred while installing dependencies.');
process.exit(1);
}
done();
}
/**
* Read the `package.json` file available in the directory the command was call from
* If there is no `package.json` it will create one.
*/
public retrievePackageJson(): PackageJsonWithDepsAndDevDeps {
let packageJson;
try {
packageJson = readPackageJson();
} catch (err) {
this.initPackageJson();
packageJson = readPackageJson();
}
return {
...packageJson,
dependencies: { ...packageJson.dependencies },
devDependencies: { ...packageJson.devDependencies },
};
}
/**
* Add dependencies to a project using `yarn add` or `npm install`.
*
* @param {Object} options contains `skipInstall`, `packageJson` and `installAsDevDependencies` which we use to determine how we install packages.
* @param {Array} dependencies contains a list of packages to add.
* @example
* addDependencies(options, [
* `@storybook/react@${storybookVersion}`,
* `@storybook/addon-actions@${actionsVersion}`,
* `@storybook/addon-links@${linksVersion}`,
* `@storybook/addons@${addonsVersion}`,
* ]);
*/
public addDependencies(
options: {
skipInstall?: boolean;
installAsDevDependencies?: boolean;
packageJson?: PackageJson;
},
dependencies: string[]
): void {
const { skipInstall } = options;
if (skipInstall) {
const { packageJson } = options;
const dependenciesMap = dependencies.reduce((acc, dep) => {
const [packageName, packageVersion] = getPackageDetails(dep);
return { ...acc, [packageName]: packageVersion };
}, {});
if (options.installAsDevDependencies) {
packageJson.devDependencies = {
...packageJson.devDependencies,
...dependenciesMap,
};
} else {
packageJson.dependencies = {
...packageJson.dependencies,
...dependenciesMap,
};
}
writePackageJson(packageJson);
} else {
try {
this.runAddDeps(dependencies, options.installAsDevDependencies);
} catch (e) {
logger.error('An error occurred while installing dependencies.');
logger.log(e.message);
process.exit(1);
}
}
}
/**
* Remove dependencies from a project using `yarn remove` or `npm uninstall`.
*
* @param {Object} options contains `skipInstall`, `packageJson` and `installAsDevDependencies` which we use to determine how we install packages.
* @param {Array} dependencies contains a list of packages to remove.
* @example
* removeDependencies(options, [
* `@storybook/react`,
* `@storybook/addon-actions`,
* ]);
*/
public removeDependencies(
options: {
skipInstall?: boolean;
packageJson?: PackageJson;
},
dependencies: string[]
): void {
const { skipInstall } = options;
if (skipInstall) {
const { packageJson } = options;
dependencies.forEach((dep) => {
if (packageJson.devDependencies) {
delete packageJson.devDependencies[dep];
}
if (packageJson.dependencies) {
delete packageJson.dependencies[dep];
}
});
writePackageJson(packageJson);
} else {
try {
this.runRemoveDeps(dependencies);
} catch (e) {
logger.error('An error occurred while removing dependencies.');
logger.log(e.message);
process.exit(1);
}
}
}
/**
* Return an array of strings matching following format: `<package_name>@<package_latest_version>`
*
* @param packages
*/
public getVersionedPackages(packages: string[]): Promise<string[]> {
return Promise.all(
packages.map(async (pkg) => {
const [packageName, packageVersion] = getPackageDetails(pkg);
return `${packageName}@${await this.getVersion(packageName, packageVersion)}`;
})
);
}
/**
* Return an array of string standing for the latest version of the input packages.
* To be able to identify which version goes with which package the order of the input array is keep.
*
* @param packageNames
*/
public getVersions(...packageNames: string[]): Promise<string[]> {
return Promise.all(
packageNames.map((packageName) => {
return this.getVersion(packageName);
})
);
}
/**
* Return the latest version of the input package available on npmjs registry.
* If constraint are provided it return the latest version matching the constraints.
*
* For `@storybook/*` packages the latest version is retrieved from `cli/src/versions.json` file directly
*
* @param packageName The name of the package
* @param constraint A valid semver constraint, example: '1.x || >=2.5.0 || 5.0.0 - 7.2.3'
*/
public async getVersion(packageName: string, constraint?: string): Promise<string> {
let current: string;
if (/(@storybook|^sb$|^storybook$)/.test(packageName)) {
// @ts-ignore
current = storybookPackagesVersions[packageName];
}
let latest;
try {
latest = await this.latestVersion(packageName, constraint);
} catch (e) {
if (current) {
logger.warn(`\n ${chalk.yellow(e.message)}`);
return current;
}
logger.error(`\n ${chalk.red(e.message)}`);
process.exit(1);
}
const versionToUse =
current && (!constraint || satisfies(current, constraint)) && gt(current, latest)
? current
: latest;
return `^${versionToUse}`;
}
/**
* Get the latest version of the package available on npmjs.com.
* If constraint is set then it returns a version satisfying it, otherwise the latest version available is returned.
*
* @param packageName Name of the package
* @param constraint Version range to use to constraint the returned version
*/
public async latestVersion(packageName: string, constraint?: string): Promise<string> {
if (!constraint) {
return this.runGetVersions(packageName, false);
}
const versions = await this.runGetVersions(packageName, true);
// Get the latest version satisfying the constraint
return versions.reverse().find((version) => satisfies(version, constraint));
}
public addStorybookCommandInScripts(options?: {
port: number;
staticFolder?: string;
preCommand?: string;
}) {
const sbPort = options?.port ?? 6006;
const storybookCmd = options?.staticFolder
? `npx storybook dev -p ${sbPort} -s ${options.staticFolder}`
: `npx storybook dev -p ${sbPort}`;
const buildStorybookCmd = options?.staticFolder
? `npx storybook build -s ${options.staticFolder}`
: `npx storybook build`;
const preCommand = options?.preCommand ? this.getRunCommand(options.preCommand) : undefined;
this.addScripts({
storybook: [preCommand, storybookCmd].filter(Boolean).join(' && '),
'build-storybook': [preCommand, buildStorybookCmd].filter(Boolean).join(' && '),
});
}
public addESLintConfig() {
const packageJson = this.retrievePackageJson();
writePackageJson({
...packageJson,
eslintConfig: {
...packageJson.eslintConfig,
overrides: [
...(packageJson.eslintConfig?.overrides || []),
{
files: ['**/*.stories.*'],
rules: {
'import/no-anonymous-default-export': 'off',
},
},
],
},
});
}
public addScripts(scripts: Record<string, string>) {
const packageJson = this.retrievePackageJson();
writePackageJson({
...packageJson,
scripts: {
...packageJson.scripts,
...scripts,
},
});
}
protected abstract runInstall(): void;
protected abstract runAddDeps(dependencies: string[], installAsDevDependencies: boolean): void;
protected abstract runRemoveDeps(dependencies: string[]): void;
/**
* Get the latest or all versions of the input package available on npmjs.com
*
* @param packageName Name of the package
* @param fetchAllVersions Should return
*/
protected abstract runGetVersions<T extends boolean>(
packageName: string,
fetchAllVersions: T
): // Use generic and conditional type to force `string[]` if fetchAllVersions is true and `string` if false
Promise<T extends true ? string[] : string>;
public executeCommand(command: string, args: string[], stdio?: 'pipe' | 'inherit'): string {
const commandResult = spawnSync(command, args, {
stdio: stdio ?? 'pipe',
encoding: 'utf-8',
});
if (commandResult.status !== 0) {
throw new Error(commandResult.stderr ?? '');
}
return commandResult.stdout ?? '';
}
}