-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathindex.ts
More file actions
219 lines (177 loc) · 5.5 KB
/
index.ts
File metadata and controls
219 lines (177 loc) · 5.5 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
/**
* Verify that the published contents of your node package will pass a basic smoke test.
*
* @example
* ```sh
* node --test
* ```
*
* ```js
* // test/pack.test.mjs
* import { testPack } from '@csstools/pack-test';
*
* await testPack("your-module-name");
* ```
*
* @packageDocumentation
*/
import url from 'node:url';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { platform } from 'node:process';
import { spawn } from 'node:child_process';
const PACKAGE_DIR_NAME = 'package';
export async function testPack(moduleName: string): Promise<void> {
if (platform.startsWith('win')) {
// eslint-disable-next-line no-console
console.log('Skipping test on Windows');
return;
}
if (!('resolve' in import.meta)) {
// eslint-disable-next-line no-console
console.log('Skipping test on platform without `import.meta.resolve` support');
return;
}
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'csstools-pack-test-'));
try {
const moduleURL = new URL(import.meta.resolve(moduleName));
// eslint-disable-next-line no-console
console.log(`Testing module: ${moduleName}`);
const modulePath = url.fileURLToPath(moduleURL);
const packageJsonPath = await findPackageJsonFromDir(path.dirname(modulePath));
const moduleRoot = path.dirname(packageJsonPath);
const packFile = await pack(moduleRoot, tempDir);
const packagePath = await unpack(packFile, tempDir);
const packageInfo = await getPackageInfo(path.join(packagePath, 'package.json'));
await eraseDevDependenciesInfo(path.join(packagePath, 'package.json'));
await createRootPackage(tempDir, packageInfo);
await runNPMInstall(tempDir);
await runTest(tempDir);
} finally {
await fs.rm(tempDir, { recursive: true });
}
}
async function findPackageJsonFromDir(dir: string, ceil = 10): Promise<string> {
const packageJsonPath = path.join(dir, 'package.json');
try {
await fs.access(packageJsonPath);
return packageJsonPath;
} catch {
if (dir === '/' || ceil <= 0) {
throw new Error('Could not find package.json');
}
}
return findPackageJsonFromDir(path.dirname(dir), ceil - 1);
}
async function pack(moduleDir: string, tmpDir: string): Promise<string> {
const packDir = await fs.mkdir(path.join(tmpDir, 'pack'), { recursive: true });
// run `npm pack --pack-destination <dir>`
const npm = spawn('npm', ['pack', '--pack-destination', packDir], {
cwd: moduleDir,
shell: platform === 'win32',
});
const packFile = await new Promise<string>((resolve, reject) => {
let stdoutBuffer = '';
let stderrBuffer = '';
npm.stdout.on('data', (data: Buffer | string) => {
stdoutBuffer += data.toString();
});
npm.stderr.on('data', (data: Buffer | string) => {
stderrBuffer += data.toString();
});
npm.on('close', (code) => {
if (code === 0) {
resolve(stdoutBuffer.trim());
} else {
// eslint-disable-next-line no-console
console.error(stderrBuffer);
reject(new Error(`npm pack exited with code ${code}`));
}
});
});
return path.join(packDir, packFile);
}
async function unpack(packFile: string, tmpDir: string): Promise<string> {
const packagePath = path.join(tmpDir, PACKAGE_DIR_NAME);
await fs.mkdir(packagePath, { recursive: true });
// run `tar -xf <dir>`
const tar = spawn('tar', ['-xf', packFile, '-C', PACKAGE_DIR_NAME, '--strip-components', '1'], {
cwd: tmpDir,
});
await new Promise<void>((resolve, reject) => {
tar.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`tar exited with code ${code}`));
}
});
});
return packagePath;
}
type packageInfo = { name: string, peerDependencies?: Record<string, string> };
// Because NPM/Node is broken all over...
async function eraseDevDependenciesInfo(packageJSONPath: string): Promise<void> {
const packageInfo = JSON.parse(await fs.readFile(packageJSONPath, 'utf8')) as Record<string, unknown>;
delete packageInfo.devDependencies;
await fs.writeFile(packageJSONPath, JSON.stringify(packageInfo, null, '\t'));
}
async function getPackageInfo(packageJSONPath: string): Promise<packageInfo> {
return JSON.parse(await fs.readFile(packageJSONPath, 'utf8')) as packageInfo;
}
async function createRootPackage(rootDir: string, packageInfo: packageInfo): Promise<void> {
await fs.writeFile(
path.join(rootDir, 'package.json'),
JSON.stringify({
"name": "@csstools/pack-test--root",
"private": true,
"type": "module",
"version": "1.0.0",
"description": "",
"workspaces": [
PACKAGE_DIR_NAME
],
"dependencies": packageInfo.peerDependencies ?? {},
"scripts": {
"test": "node --test"
}
}, null, '\t')
);
await fs.writeFile(
path.join(rootDir, 'index.mjs'),
`import '${packageInfo.name}';`
);
}
async function runNPMInstall(rootDir: string): Promise<void> {
const npm = spawn('npm', ['install', '--ignore-scripts', '--omit', 'dev', '--engine-strict', 'false'], {
cwd: rootDir,
stdio: 'inherit',
shell: platform === 'win32',
});
await new Promise<void>((resolve, reject) => {
npm.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`npm install exited with code ${code}`));
}
});
});
}
async function runTest(rootDir: string): Promise<void> {
const npm = spawn('node', ['index.mjs'], {
cwd: rootDir,
stdio: 'inherit',
shell: platform === 'win32',
});
await new Promise<void>((resolve, reject) => {
npm.on('close', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`npm install exited with code ${code}`));
}
});
});
}