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
|
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFile, rm } from 'node:fs/promises';
const ROOT_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
const NODE_MODULES = join(ROOT_PATH, 'node_modules');
const INTEGRITY_FILE = join(NODE_MODULES, '.yarn-integrity');
const PACKAGE_JSON = join(ROOT_PATH, 'package.json');
function isAliasedDependency(x) {
return x.includes('@npm:');
}
function serializeAliasedDependencyPatterns(obj) {
return Object.entries(obj).map(([key, version]) => `${key}@${version}`);
}
async function readJSON(file) {
return JSON.parse(await readFile(file, { encoding: 'utf-8' }));
}
async function getPrevTopLevelPatterns() {
try {
return (await readJSON(INTEGRITY_FILE))?.topLevelPatterns?.filter(isAliasedDependency);
} catch {
return [];
}
}
async function getCurrentTopLevelPatterns() {
try {
const { dependencies, devDependencies } = await readJSON(PACKAGE_JSON);
return serializeAliasedDependencyPatterns(dependencies)
.concat(serializeAliasedDependencyPatterns(devDependencies))
.filter(isAliasedDependency);
} catch {
return [];
}
}
function arraysHaveSameItems(a1, a2) {
return JSON.stringify(a1.sort()) === JSON.stringify(a2.sort());
}
const [prevTopLevelPatterns, currentTopLevelPatterns] = await Promise.all([
getPrevTopLevelPatterns(),
getCurrentTopLevelPatterns(),
]);
/**
* Yarn seems to have problems at times, if one uses an <alias>@npm:<name>
* and those packages are being updated. In case one switches branches the
* node_modules folder seems to end up being a corrupted somehow
*/
if (!arraysHaveSameItems(prevTopLevelPatterns, currentTopLevelPatterns)) {
console.error(
'[WARNING] package.json changed significantly. Removing node_modules to be sure there are no problems.',
);
await rm(NODE_MODULES, { recursive: true, force: true });
}
|