npm/workspaces/libnpmpack/lib/index.js

70 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-02-16 14:45:21 +08:00
'use strict'
const pacote = require('pacote')
const npa = require('npm-package-arg')
const runScript = require('@npmcli/run-script')
const path = require('path')
const util = require('util')
2024-05-07 14:59:55 +08:00
const Arborist = require('@npmcli/arborist')
2023-02-16 14:45:21 +08:00
const writeFile = util.promisify(require('fs').writeFile)
module.exports = pack
async function pack (spec = 'file:.', opts = {}) {
// gets spec
spec = npa(spec)
const manifest = await pacote.manifest(spec, opts)
// Default to true if no log options passed, set to false if we're in silent
// mode
2024-05-07 14:59:55 +08:00
const banner = !opts.silent
2023-02-16 14:45:21 +08:00
2024-05-07 14:59:55 +08:00
const stdio = opts.foregroundScripts ? 'inherit' : 'pipe'
if (spec.type === 'directory' && !opts.ignoreScripts) {
2023-02-16 14:45:21 +08:00
// prepack
await runScript({
...opts,
event: 'prepack',
path: spec.fetchSpec,
2024-05-07 14:59:55 +08:00
stdio,
2023-02-16 14:45:21 +08:00
pkg: manifest,
banner,
})
}
// packs tarball
const tarball = await pacote.tarball(manifest._resolved, {
...opts,
2024-05-07 14:59:55 +08:00
Arborist,
2023-02-16 14:45:21 +08:00
integrity: manifest._integrity,
})
// check for explicit `false` so the default behavior is to skip writing to disk
if (opts.dryRun === false) {
const filename = `${manifest.name}-${manifest.version}.tgz`
.replace(/^@/, '').replace(/\//, '-')
const destination = path.resolve(opts.packDestination, filename)
await writeFile(destination, tarball)
}
2024-05-07 14:59:55 +08:00
if (spec.type === 'directory' && !opts.ignoreScripts) {
2023-02-16 14:45:21 +08:00
// postpack
await runScript({
...opts,
event: 'postpack',
path: spec.fetchSpec,
2024-05-07 14:59:55 +08:00
stdio,
2023-02-16 14:45:21 +08:00
pkg: manifest,
banner,
env: {
npm_package_from: tarball.from,
npm_package_resolved: tarball.resolved,
npm_package_integrity: tarball.integrity,
},
})
}
return tarball
}