Skip to content

Commit a13bba2

Browse files
committed
Fix npm pack JSON parsing when lifecycle scripts output to stdout
The --foreground-scripts=false flag doesn't prevent user scripts from writing directly to stdout. For example, Husky's prepare script can output text that pollutes the JSON output from npm pack --json, causing parsing failures.
1 parent 67b6aff commit a13bba2

4 files changed

Lines changed: 19 additions & 1 deletion

File tree

source/npm/util.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,11 @@ export const getFilesToBePacked = async rootDirectory => {
192192
], {cwd: rootDirectory});
193193

194194
try {
195-
const {files} = JSON.parse(stdout).at(0);
195+
// HACK: NPM lifecycle scripts can output text even with --silent and --foreground-scripts=false.
196+
// For example, Husky's prepare script outputs "> package@version prepare" and "> husky install".
197+
// We extract only the JSON portion by finding the first '[' character.
198+
// Related: https://github.com/sindresorhus/np/issues/742
199+
const {files} = JSON.parse(stdout.slice(Math.max(0, stdout.indexOf('[')))).at(0);
196200
return files.map(file => file.path);
197201
} catch (error) {
198202
throw new Error('Failed to parse output of npm pack', {cause: error});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export default function foo() {
2+
return 'bar';
3+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"name": "foo",
3+
"version": "0.0.0",
4+
"files": ["index.js"],
5+
"scripts": {
6+
"prepare": "echo '> foo@0.0.0 prepare' && echo '> test prepare script'"
7+
}
8+
}

test/npm/util/packed-files.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,6 @@ test('doesn\'t show files in .github', verifyPackedFiles, 'dot-github', [
7171
'index.js',
7272
]);
7373

74+
test('handles prepare script output (e.g., Husky)', verifyPackedFiles, 'prepare-script', [
75+
'index.js',
76+
]);

0 commit comments

Comments
 (0)