Repository navigation
Expand file tree
/
Copy pathExplorerCommandLineParser.ts
More file actions
298 lines (253 loc) · 10.4 KB
/
Copy pathExplorerCommandLineParser.ts
File metadata and controls
298 lines (253 loc) · 10.4 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import process from 'node:process';
import * as path from 'node:path';
import type { ChildProcess } from 'node:child_process';
import express from 'express';
import yaml from 'js-yaml';
import cors from 'cors';
import { Executable, FileSystem, type IPackageJson, JsonFile } from '@rushstack/node-core-library';
import { type ITerminal, Colorize } from '@rushstack/terminal';
import {
type CommandLineFlagParameter,
CommandLineParser,
type IRequiredCommandLineStringParameter
} from '@rushstack/ts-command-line';
import {
type LfxGraph,
lfxGraphSerializer,
type IAppContext,
type IJsonLfxGraph,
type IJsonLfxWorkspace
} from '../../../build/lfx-shared';
import * as lockfilePath from '../../graph/lockfilePath';
import type { IAppState } from '../../state';
import { init } from '../../utils/init';
import { PnpmfileRunner } from '../../graph/PnpmfileRunner';
import * as lfxGraphLoader from '../../graph/lfxGraphLoader';
import { LFX_PACKAGE_NAME, LFX_VERSION } from '../../utils/constants';
import { type IPackageUpdateResult, PackageUpdateChecker } from '../../utils/PackageUpdateChecker';
const EXPLORER_TOOL_FILENAME: 'lockfile-explorer' = 'lockfile-explorer';
function printUpdateNotification(
result: { latestVersion: string; isOutdated: boolean } | undefined,
terminal: ITerminal
): void {
if (result?.isOutdated) {
terminal.writeLine(
Colorize.yellow(
`\nUpdate available: ${LFX_VERSION} → ${result.latestVersion}\n` +
`Run: npm install -g ${LFX_PACKAGE_NAME}\n`
)
);
}
}
export class ExplorerCommandLineParser extends CommandLineParser {
public readonly globalTerminal: ITerminal;
readonly #debugParameter: CommandLineFlagParameter;
readonly #subspaceParameter: IRequiredCommandLineStringParameter;
public constructor(terminal: ITerminal) {
super({
toolFilename: EXPLORER_TOOL_FILENAME,
toolDescription:
'Lockfile Explorer is a desktop app for investigating and solving version conflicts in a PNPM workspace.'
});
this.#debugParameter = this.defineFlagParameter({
parameterLongName: '--debug',
parameterShortName: '-d',
description: 'Show the full call stack if an error occurs while executing the tool'
});
this.#subspaceParameter = this.defineStringParameter({
parameterLongName: '--subspace',
argumentName: 'SUBSPACE_NAME',
description: 'Specifies an individual Rush subspace to check.',
defaultValue: 'default'
});
this.globalTerminal = terminal;
}
public get isDebug(): boolean {
return this.#debugParameter.value;
}
protected override async onExecuteAsync(): Promise<void> {
const terminal: ITerminal = this.globalTerminal;
terminal.writeLine(
Colorize.bold(`\nRush Lockfile Explorer ${LFX_VERSION}`) +
Colorize.cyan(' - https://lfx.rushstack.io/\n')
);
// Start the update check now so it runs concurrently with server setup.
// The result is awaited and displayed inside app.listen once the server is ready.
const updateChecker: PackageUpdateChecker = new PackageUpdateChecker({
packageName: LFX_PACKAGE_NAME,
currentVersion: LFX_VERSION,
// In debug mode, bypass the cache so the notice appears immediately.
forceCheck: this.isDebug
});
const updateCheckPromise: Promise<IPackageUpdateResult | undefined> = updateChecker.tryGetUpdateAsync();
const PORT: number = 8091;
// Must not have a trailing slash
const SERVICE_URL: string = `http://localhost:${PORT}`;
const appState: IAppState = init({
appVersion: LFX_VERSION,
debugMode: this.isDebug,
subspaceName: this.#subspaceParameter.value
});
const lfxWorkspace: IJsonLfxWorkspace = appState.lfxWorkspace;
// Important: This must happen after init() reads the current working directory
process.chdir(appState.lockfileExplorerProjectRoot);
const distFolderPath: string = `${appState.lockfileExplorerProjectRoot}/dist`;
const app: express.Application = express();
app.use(express.json());
app.use(cors());
// Variable used to check if the front-end client is still connected
let awaitingFirstConnect: boolean = true;
let isClientConnected: boolean = false;
let disconnected: boolean = false;
setInterval(() => {
if (!isClientConnected && !awaitingFirstConnect && !disconnected) {
terminal.writeLine(Colorize.red('The client has disconnected!'));
terminal.writeLine(`Please open a browser window at http://localhost:${PORT}/app`);
disconnected = true;
} else if (!awaitingFirstConnect) {
isClientConnected = false;
}
}, 4000);
// This takes precedence over the `/app` static route, which also has an `initappcontext.js` file.
app.get('/initappcontext.js', (req: express.Request, res: express.Response) => {
const appContext: IAppContext = {
serviceUrl: SERVICE_URL,
appVersion: appState.appVersion,
debugMode: this.isDebug
};
const sourceCode: string = [
`console.log('Loaded initappcontext.js');`,
`appContext = ${JSON.stringify(appContext)}`
].join('\n');
res.type('application/javascript').send(sourceCode);
});
app.use('/', express.static(distFolderPath));
app.use('/favicon.ico', express.static(distFolderPath, { index: 'favicon.ico' }));
app.get('/api/health', (req: express.Request, res: express.Response) => {
awaitingFirstConnect = false;
isClientConnected = true;
if (disconnected) {
disconnected = false;
terminal.writeLine(Colorize.green('The client has reconnected!'));
}
res.status(200).send();
});
app.get('/api/graph', async (req: express.Request, res: express.Response) => {
const pnpmLockfileText: string = await FileSystem.readFileAsync(appState.pnpmLockfileLocation);
const lockfile: unknown = yaml.load(pnpmLockfileText) as unknown;
const graph: LfxGraph = lfxGraphLoader.generateLockfileGraph(lockfile, lfxWorkspace);
const jsonGraph: IJsonLfxGraph = lfxGraphSerializer.serializeToJson(graph);
res.type('application/json').send(jsonGraph);
});
app.post(
'/api/package-json',
async (req: express.Request<{}, {}, { projectPath: string }, {}>, res: express.Response) => {
const { projectPath } = req.body;
const fileLocation: string = `${appState.projectRoot}/${projectPath}/package.json`;
let packageJsonText: string;
try {
packageJsonText = await FileSystem.readFileAsync(fileLocation);
} catch (e) {
if (FileSystem.isNotExistError(e)) {
return res.status(404).send({
message: `Could not load package.json file for this package. Have you installed all the dependencies for this workspace?`,
error: `No package.json in location: ${projectPath}`
});
} else {
throw e;
}
}
res.send(packageJsonText);
}
);
app.get('/api/pnpmfile', async (req: express.Request, res: express.Response) => {
const pnpmfilePath: string = lockfilePath.join(
lfxWorkspace.workspaceRootFullPath,
lfxWorkspace.rushConfig?.rushPnpmfilePath ?? lfxWorkspace.pnpmfilePath
);
let pnpmfile: string;
try {
pnpmfile = await FileSystem.readFileAsync(pnpmfilePath);
} catch (e) {
if (FileSystem.isNotExistError(e)) {
return res.status(404).send({
message: `Could not load .pnpmfile.cjs file in this repo: "${pnpmfilePath}"`,
error: `No .pnpmifile.cjs found.`
});
} else {
throw e;
}
}
res.send(pnpmfile);
});
app.post(
'/api/package-spec',
async (req: express.Request<{}, {}, { projectPath: string }, {}>, res: express.Response) => {
const { projectPath } = req.body;
const fileLocation: string = `${appState.projectRoot}/${projectPath}/package.json`;
let packageJson: IPackageJson;
try {
packageJson = await JsonFile.loadAsync(fileLocation);
} catch (e) {
if (FileSystem.isNotExistError(e)) {
return res.status(404).send({
message: `Could not load package.json file in location: ${projectPath}`
});
} else {
throw e;
}
}
let parsedPackage: IPackageJson = packageJson;
const pnpmfilePath: string = path.join(lfxWorkspace.workspaceRootFullPath, lfxWorkspace.pnpmfilePath);
if (await FileSystem.existsAsync(pnpmfilePath)) {
const pnpmFileRunner: PnpmfileRunner = new PnpmfileRunner(pnpmfilePath);
try {
parsedPackage = await pnpmFileRunner.transformPackageAsync(packageJson, fileLocation);
} finally {
await pnpmFileRunner.disposeAsync();
}
}
res.send(parsedPackage);
}
);
app.listen(PORT, async () => {
terminal.writeLine(`App launched on ${SERVICE_URL}`);
printUpdateNotification(await updateCheckPromise, terminal);
if (!appState.debugMode) {
try {
// Launch the default web browser using the platform-native open command.
let browserCmd: string;
let browserArgs: string[];
switch (process.platform) {
case 'win32': {
// "start" is a cmd.exe built-in, not a standalone executable.
// The empty string is the required [title] argument; without it,
// cmd interprets the URL as the title and ignores it.
browserCmd = 'cmd';
browserArgs = ['/c', 'start', '', SERVICE_URL];
break;
}
case 'darwin': {
browserCmd = 'open';
browserArgs = [SERVICE_URL];
break;
}
default: {
// Linux and other Unix-like systems
browserCmd = 'xdg-open';
browserArgs = [SERVICE_URL];
break;
}
}
const browserProcess: ChildProcess = Executable.spawn(browserCmd, browserArgs, { stdio: 'ignore' });
// Detach from our Node.js process so the browser stays open after we exit
browserProcess.unref();
} catch (e) {
terminal.writeError('Error launching browser: ' + e.toString());
}
}
});
}
}