-
Notifications
You must be signed in to change notification settings - Fork 208
/
npm.ts
230 lines (196 loc) · 6 KB
/
npm.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
import * as path from 'path';
import * as fs from 'fs';
import * as cp from 'child_process';
import parseSemver from 'parse-semver';
import { CancellationToken, log, nonnull } from './util';
const exists = (file: string) =>
fs.promises.stat(file).then(
_ => true,
_ => false
);
interface IOptions {
cwd?: string;
stdio?: any;
customFds?: any;
env?: any;
timeout?: number;
maxBuffer?: number;
killSignal?: string;
}
function parseStdout({ stdout }: { stdout: string }): string {
return stdout.split(/[\r\n]/).filter(line => !!line)[0];
}
function exec(
command: string,
options: IOptions = {},
cancellationToken?: CancellationToken
): Promise<{ stdout: string; stderr: string }> {
return new Promise((c, e) => {
let disposeCancellationListener: Function | null = null;
const child = cp.exec(command, { ...options, encoding: 'utf8' } as any, (err, stdout: string, stderr: string) => {
if (disposeCancellationListener) {
disposeCancellationListener();
disposeCancellationListener = null;
}
if (err) {
return e(err);
}
c({ stdout, stderr });
});
if (cancellationToken) {
disposeCancellationListener = cancellationToken.subscribe((err: any) => {
child.kill();
e(err);
});
}
});
}
async function checkNPM(cancellationToken?: CancellationToken): Promise<void> {
const { stdout } = await exec('npm -v', {}, cancellationToken);
const version = stdout.trim();
if (/^3\.7\.[0123]$/.test(version)) {
throw new Error(`npm@${version} doesn't work with vsce. Please update npm: npm install -g npm`);
}
}
function getNpmDependencies(cwd: string): Promise<string[]> {
return checkNPM()
.then(() =>
exec('npm list --production --parseable --depth=99999 --loglevel=error', { cwd, maxBuffer: 5000 * 1024 })
)
.then(({ stdout }) => stdout.split(/[\r\n]/).filter(dir => path.isAbsolute(dir)));
}
interface YarnTreeNode {
name: string;
children: YarnTreeNode[];
}
export interface YarnDependency {
name: string;
path: string;
children: YarnDependency[];
}
function asYarnDependency(prefix: string, tree: YarnTreeNode, prune: boolean): YarnDependency | null {
if (prune && /@[\^~]/.test(tree.name)) {
return null;
}
let name: string;
try {
const parseResult = parseSemver(tree.name);
name = parseResult.name;
} catch (err) {
name = tree.name.replace(/^([^@+])@.*$/, '$1');
}
const dependencyPath = path.join(prefix, name);
const children: YarnDependency[] = [];
for (const child of tree.children || []) {
const dep = asYarnDependency(path.join(prefix, name, 'node_modules'), child, prune);
if (dep) {
children.push(dep);
}
}
return { name, path: dependencyPath, children };
}
function selectYarnDependencies(deps: YarnDependency[], packagedDependencies: string[]): YarnDependency[] {
const index = new (class {
private data: { [name: string]: YarnDependency } = Object.create(null);
constructor() {
for (const dep of deps) {
if (this.data[dep.name]) {
throw Error(`Dependency seen more than once: ${dep.name}`);
}
this.data[dep.name] = dep;
}
}
find(name: string): YarnDependency {
let result = this.data[name];
if (!result) {
throw new Error(`Could not find dependency: ${name}`);
}
return result;
}
})();
const reached = new (class {
values: YarnDependency[] = [];
add(dep: YarnDependency): boolean {
if (this.values.indexOf(dep) < 0) {
this.values.push(dep);
return true;
}
return false;
}
})();
const visit = (name: string) => {
let dep = index.find(name);
if (!reached.add(dep)) {
// already seen -> done
return;
}
for (const child of dep.children) {
visit(child.name);
}
};
packagedDependencies.forEach(visit);
return reached.values;
}
async function getYarnProductionDependencies(cwd: string, packagedDependencies?: string[]): Promise<YarnDependency[]> {
const raw = await new Promise<string>((c, e) =>
cp.exec(
'yarn list --prod --json',
{ cwd, encoding: 'utf8', env: { DISABLE_V8_COMPILE_CACHE: "1", ...process.env }, maxBuffer: 5000 * 1024 },
(err, stdout) => (err ? e(err) : c(stdout))
)
);
const match = /^{"type":"tree".*$/m.exec(raw);
if (!match || match.length !== 1) {
throw new Error('Could not parse result of `yarn list --json`');
}
const usingPackagedDependencies = Array.isArray(packagedDependencies);
const trees = JSON.parse(match[0]).data.trees as YarnTreeNode[];
let result = trees
.map(tree => asYarnDependency(path.join(cwd, 'node_modules'), tree, !usingPackagedDependencies))
.filter(nonnull);
if (usingPackagedDependencies) {
result = selectYarnDependencies(result, packagedDependencies!);
}
return result;
}
async function getYarnDependencies(cwd: string, packagedDependencies?: string[]): Promise<string[]> {
const result = new Set([cwd]);
const deps = await getYarnProductionDependencies(cwd, packagedDependencies);
const flatten = (dep: YarnDependency) => {
result.add(dep.path);
dep.children.forEach(flatten);
};
deps.forEach(flatten);
return [...result];
}
export async function detectYarn(cwd: string): Promise<boolean> {
for (const name of ['yarn.lock', '.yarnrc', '.yarnrc.yaml', '.pnp.cjs', '.yarn']) {
if (await exists(path.join(cwd, name))) {
if (!process.env['VSCE_TESTS']) {
log.info(
`Detected presence of ${name}. Using 'yarn' instead of 'npm' (to override this pass '--no-yarn' on the command line).`
);
}
return true;
}
}
return false;
}
export async function getDependencies(
cwd: string,
dependencies: 'npm' | 'yarn' | 'none' | undefined,
packagedDependencies?: string[]
): Promise<string[]> {
if (dependencies === 'none') {
return [cwd];
} else if (dependencies === 'yarn' || (dependencies === undefined && (await detectYarn(cwd)))) {
return await getYarnDependencies(cwd, packagedDependencies);
} else {
return await getNpmDependencies(cwd);
}
}
export function getLatestVersion(name: string, cancellationToken?: CancellationToken): Promise<string> {
return checkNPM(cancellationToken)
.then(() => exec(`npm show ${name} version`, {}, cancellationToken))
.then(parseStdout);
}