| 1 |
const fs = require('node:fs/promises') |
| 2 |
const { existsSync } = require('node:fs') |
| 3 |
const { join, resolve, sep, extname, relative, delimiter } = require('node:path') |
| 4 |
const which = require('which') |
| 5 |
const spawn = require('@npmcli/promise-spawn') |
| 6 |
const MockRegistry = require('@npmcli/mock-registry') |
| 7 |
const http = require('node:http') |
| 8 |
const { createProxy } = require('proxy') |
| 9 |
|
| 10 |
const { SMOKE_PUBLISH_TARBALL, CI, PATH, Path } = process.env |
| 11 |
|
| 12 |
const DEFAULT_REGISTRY = new URL('https://registry.npmjs.org/') |
| 13 |
const MOCK_REGISTRY = new URL('http://smoke-test-registry.club/') |
| 14 |
|
| 15 |
const NODE_PATH = process.execPath |
| 16 |
const CLI_ROOT = resolve(process.cwd(), '..') |
| 17 |
const CLI_JS_BIN = join('bin', 'npm-cli.js') |
| 18 |
const NPM_PATH = join(CLI_ROOT, CLI_JS_BIN) |
| 19 |
|
| 20 |
const WINDOWS = process.platform === 'win32' |
| 21 |
const GLOBAL_BIN = WINDOWS ? '' : 'bin' |
| 22 |
const GLOBAL_NODE_MODULES = join(WINDOWS ? '' : 'lib', 'node_modules') |
| 23 |
|
| 24 |
const getOpts = (...a) => { |
| 25 |
const [opts, args] = a.reduce((acc, arg) => { |
| 26 |
acc[typeof arg === 'object' ? 0 : 1].push(arg) |
| 27 |
return acc |
| 28 |
}, [[], []]) |
| 29 |
return [Object.assign({}, ...opts), args] |
| 30 |
} |
| 31 |
|
| 32 |
const normalizePath = path => path.replace(/[A-Z]:/, '').replace(/\\/g, '/') |
| 33 |
|
| 34 |
const testdirHelper = (obj) => { |
| 35 |
for (const [key, value] of Object.entries(obj)) { |
| 36 |
if (extname(key) === '.json') { |
| 37 |
obj[key] = JSON.stringify(value, null, 2) |
| 38 |
} else if (typeof value === 'object') { |
| 39 |
obj[key] = testdirHelper(value) |
| 40 |
} else { |
| 41 |
obj[key] = value |
| 42 |
} |
| 43 |
} |
| 44 |
return obj |
| 45 |
} |
| 46 |
|
| 47 |
const getNpmRoot = (r) => { |
| 48 |
return r.stdout |
| 49 |
.split('\n') |
| 50 |
.slice(-1)[0] |
| 51 |
.match(/^npm@.*?\s(.*)$/) |
| 52 |
?.[1] |
| 53 |
} |
| 54 |
|
| 55 |
const getCleanPaths = async () => { |
| 56 |
const cliBin = join('bin', 'npm') |
| 57 |
const npmLinks = await which('npm', { all: true }) |
| 58 |
const npmPaths = await Promise.all(npmLinks.map(npm => fs.realpath(npm))) |
| 59 |
|
| 60 |
const cleanNpmPaths = [...new Set([ |
| 61 |
CLI_ROOT, |
| 62 |
join(CLI_ROOT, cliBin), |
| 63 |
join(CLI_ROOT, CLI_JS_BIN), |
| 64 |
...npmLinks, |
| 65 |
...npmPaths, |
| 66 |
...npmPaths.map(n => n.replace(sep + cliBin, '')), |
| 67 |
...npmPaths.map(n => n.replace(sep + CLI_JS_BIN, '')), |
| 68 |
])] |
| 69 |
|
| 70 |
return Object.entries({ |
| 71 |
NODE: NODE_PATH, |
| 72 |
NPM: cleanNpmPaths, |
| 73 |
}) |
| 74 |
} |
| 75 |
|
| 76 |
module.exports = async (t, { |
| 77 |
testdir = {}, debug, mockRegistry = true, strictRegistryNock = true, useProxy = false, |
| 78 |
} = {}) => { |
| 79 |
const debugLog = debug || CI ? (...a) => t.comment(...a) : () => {} |
| 80 |
debugLog({ SMOKE_PUBLISH_TARBALL, CI }) |
| 81 |
|
| 82 |
const cleanPaths = await getCleanPaths() |
| 83 |
|
| 84 |
// setup fixtures |
| 85 |
const root = t.testdir({ |
| 86 |
cache: {}, |
| 87 |
project: { '.npmrc': '' }, |
| 88 |
global: { '.npmrc': '' }, |
| 89 |
home: { '.npmrc': '' }, |
| 90 |
...testdirHelper(testdir), |
| 91 |
}) |
| 92 |
const paths = { |
| 93 |
root, |
| 94 |
project: join(root, 'project'), |
| 95 |
global: join(root, 'global'), |
| 96 |
home: join(root, 'home'), |
| 97 |
userConfig: join(root, 'home', '.npmrc'), |
| 98 |
globalConfig: join(root, 'global', '.npmrc'), |
| 99 |
cache: join(root, 'cache'), |
| 100 |
globalBin: join(root, 'global', GLOBAL_BIN), |
| 101 |
globalNodeModules: join(root, 'global', GLOBAL_NODE_MODULES), |
| 102 |
} |
| 103 |
|
| 104 |
const registry = !mockRegistry ? DEFAULT_REGISTRY : new MockRegistry({ |
| 105 |
tap: t, |
| 106 |
registry: MOCK_REGISTRY, |
| 107 |
debug, |
| 108 |
strict: strictRegistryNock, |
| 109 |
}) |
| 110 |
|
| 111 |
const proxyEnv = {} |
| 112 |
if (useProxy || mockRegistry) { |
| 113 |
useProxy = true |
| 114 |
const proxyServer = createProxy(http.createServer()) |
| 115 |
await new Promise(res => proxyServer.listen(0, res)) |
| 116 |
t.teardown(() => proxyServer.close()) |
| 117 |
proxyEnv.HTTP_PROXY = new URL(`http://localhost:${proxyServer.address().port}`) |
| 118 |
} |
| 119 |
|
| 120 |
// update notifier should never be written |
| 121 |
t.afterEach((t) => { |
| 122 |
t.equal(existsSync(join(paths.cache, '_update-notifier-last-checked')), false) |
| 123 |
}) |
| 124 |
|
| 125 |
const cleanOutput = s => { |
| 126 |
// sometimes we print normalized paths in snapshots regardless of |
| 127 |
// platform so replace those first then replace platform style paths |
| 128 |
for (const [key, value] of cleanPaths) { |
| 129 |
const values = [].concat(value) |
| 130 |
for (const v of values) { |
| 131 |
s = s.split(normalizePath(v)).join(`{${key}}`) |
| 132 |
} |
| 133 |
} |
| 134 |
for (const [key, value] of cleanPaths) { |
| 135 |
const values = [].concat(value) |
| 136 |
for (const v of values) { |
| 137 |
s = s.split(v).join(`{${key}}`) |
| 138 |
} |
| 139 |
} |
| 140 |
return s |
| 141 |
.split(relative(CLI_ROOT, t.testdirName)).join('{TESTDIR}') |
| 142 |
.split(registry.origin).join('{REGISTRY}') |
| 143 |
.replace(/\\+/g, '/') |
| 144 |
.replace(/\r\n/g, '\n') |
| 145 |
.replace(/ \(in a browser\)/g, '') |
| 146 |
.replace(/^npm@.* /gm, 'npm ') |
| 147 |
.replace(/[0-9TZ_-]*debug-[0-9]+.log$/gm, '{LOG}') |
| 148 |
.replace(/in \d+[ms]+$/gm, 'in {TIME}') |
| 149 |
} |
| 150 |
const log = (...a) => debugLog(cleanOutput(a.join(' '))) |
| 151 |
t.cleanSnapshot = cleanOutput |
| 152 |
|
| 153 |
const getPath = () => `${paths.globalBin}${delimiter}${Path || PATH}` |
| 154 |
const getEnvPath = () => ({ [Path ? 'Path' : 'PATH']: getPath() }) |
| 155 |
|
| 156 |
const baseSpawn = async (spawnCmd, spawnArgs, { |
| 157 |
cwd = paths.project, |
| 158 |
env, |
| 159 |
...opts } = {} |
| 160 |
) => { |
| 161 |
log(`CWD: ${cwd}`) |
| 162 |
log(`${spawnCmd} ${spawnArgs.join(' ')}`) |
| 163 |
log('-'.repeat(40)) |
| 164 |
|
| 165 |
const p = spawn(spawnCmd, spawnArgs, { |
| 166 |
cwd, |
| 167 |
env: { |
| 168 |
...getEnvPath(), |
| 169 |
HOME: paths.root, |
| 170 |
ComSpec: process.env.ComSpec, |
| 171 |
...env, |
| 172 |
}, |
| 173 |
...opts, |
| 174 |
}) |
| 175 |
|
| 176 |
// In debug mode, stream stdout and stderr to console so we can debug hanging processes |
| 177 |
p.process.stdout.on('data', (c) => log(c.toString().trim())) |
| 178 |
p.process.stderr.on('data', (c) => log(c.toString().trim())) |
| 179 |
|
| 180 |
const { stdout, stderr } = await p |
| 181 |
log('='.repeat(40)) |
| 182 |
|
| 183 |
return { stderr, stdout } |
| 184 |
} |
| 185 |
|
| 186 |
const baseNpm = async (...a) => { |
| 187 |
const [{ cwd, cmd, argv = [], proxy = useProxy, ...opts }, args] = getOpts(...a) |
| 188 |
|
| 189 |
const isGlobal = args.some(arg => ['-g', '--global', '--global=true'].includes(arg)) |
| 190 |
|
| 191 |
const defaultFlags = [ |
| 192 |
`--registry=${registry.origin}`, |
| 193 |
`--cache=${paths.cache}`, |
| 194 |
`--prefix=${isGlobal ? paths.global : cwd}`, |
| 195 |
`--userconfig=${paths.userConfig}`, |
| 196 |
`--globalconfig=${paths.globalConfig}`, |
| 197 |
'--no-audit', |
| 198 |
'--no-update-notifier', |
| 199 |
'--loglevel=silly', |
| 200 |
'--fetch-retries=0', |
| 201 |
].filter(Boolean) |
| 202 |
|
| 203 |
const cliArgv = args.reduce((acc, arg) => { |
| 204 |
if (arg.startsWith('-')) { |
| 205 |
acc[1].push(arg) |
| 206 |
} else { |
| 207 |
acc[0].push(arg) |
| 208 |
} |
| 209 |
return acc |
| 210 |
}, [[], defaultFlags]).reduce((acc, i) => acc.concat(i), []) |
| 211 |
|
| 212 |
return baseSpawn(cmd, [...argv, ...cliArgv], { |
| 213 |
cwd, |
| 214 |
env: { |
| 215 |
...opts.env, |
| 216 |
...proxy ? proxyEnv : {}, |
| 217 |
}, |
| 218 |
...opts, |
| 219 |
}) |
| 220 |
} |
| 221 |
|
| 222 |
const npmLocal = async (...args) => { |
| 223 |
const [{ force = false }] = getOpts(...args) |
| 224 |
if (SMOKE_PUBLISH_TARBALL && !force) { |
| 225 |
throw new Error('npmLocal cannot be called during smoke-publish') |
| 226 |
} |
| 227 |
return baseNpm({ |
| 228 |
cwd: CLI_ROOT, |
| 229 |
cmd: process.execPath, |
| 230 |
argv: ['.'], |
| 231 |
proxy: false, |
| 232 |
}, ...args) |
| 233 |
} |
| 234 |
|
| 235 |
const npmPath = async (...args) => baseNpm({ |
| 236 |
cwd: paths.project, |
| 237 |
cmd: 'npm', |
| 238 |
shell: true, |
| 239 |
}, ...args) |
| 240 |
|
| 241 |
const npm = async (...args) => baseNpm({ |
| 242 |
cwd: paths.project, |
| 243 |
cmd: process.execPath, |
| 244 |
argv: [NPM_PATH], |
| 245 |
}, ...args) |
| 246 |
|
| 247 |
// helpers for reading/writing files and their source |
| 248 |
const readFile = async (f) => { |
| 249 |
const file = await fs.readFile(join(paths.project, f), 'utf-8') |
| 250 |
return extname(f) === '.json' ? JSON.parse(file) : file |
| 251 |
} |
| 252 |
|
| 253 |
return { |
| 254 |
npmPath, |
| 255 |
npmLocal, |
| 256 |
npm: SMOKE_PUBLISH_TARBALL ? npmPath : npm, |
| 257 |
spawn: baseSpawn, |
| 258 |
readFile, |
| 259 |
getPath, |
| 260 |
paths, |
| 261 |
registry, |
| 262 |
npmLocalTarball: async () => SMOKE_PUBLISH_TARBALL ?? |
| 263 |
npmLocal('pack', `--pack-destination=${root}`).then(r => { |
| 264 |
const output = r.stdout.trim().split('\n') |
| 265 |
return join(root, output[output.length - 1]) |
| 266 |
}), |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
module.exports.testdir = testdirHelper |
| 271 |
module.exports.getNpmRoot = getNpmRoot |
| 272 |
module.exports.CLI_ROOT = CLI_ROOT |
| 273 |
module.exports.WINDOWS = WINDOWS |
| 274 |
module.exports.SMOKE_PUBLISH = !!SMOKE_PUBLISH_TARBALL |
| 275 |
module.exports.SMOKE_PUBLISH_TARBALL = SMOKE_PUBLISH_TARBALL |
| 276 |
module.exports.MOCK_REGISTRY = MOCK_REGISTRY |