Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Commit

Permalink
fix: sanitise package.json files field (#800)
Browse files Browse the repository at this point in the history
* fix: sanitise package.json files field

* Apply suggestions from code review

Co-authored-by: Eduardo Bouças <mail@eduardoboucas.com>

Co-authored-by: Netlify Team Account 1 <netlify-team-account-1@users.noreply.github.com>
Co-authored-by: Eduardo Bouças <mail@eduardoboucas.com>
  • Loading branch information
3 people authored Nov 9, 2021
1 parent 87de250 commit 6c82ada
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/runtimes/node/utils/package_json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ interface PackageJson {
type?: string
}

const sanitiseFiles = (files: unknown): string[] | undefined => {
if (!Array.isArray(files)) {
return undefined
}

return files.filter((file) => typeof file === 'string')
}

const sanitisePackageJson = (packageJson: Record<string, unknown>): PackageJson => ({
...packageJson,
files: sanitiseFiles(packageJson.files),
})

// Retrieve the `package.json` of a specific project or module
const getPackageJson = async function (srcDir: string): Promise<PackageJson> {
const packageRoot = await pkgDir(srcDir)
Expand All @@ -25,11 +38,12 @@ const getPackageJson = async function (srcDir: string): Promise<PackageJson> {
const packageJsonPath = `${packageRoot}/package.json`
try {
// The path depends on the user's build, i.e. must be dynamic
// eslint-disable-next-line import/no-dynamic-require, node/global-require
return require(packageJsonPath)
// eslint-disable-next-line import/no-dynamic-require, node/global-require, @typescript-eslint/no-var-requires
const packageJson = require(packageJsonPath)
return sanitisePackageJson(packageJson)
} catch (error) {
throw new Error(`${packageJsonPath} is invalid JSON: ${error.message}`)
}
}

export { getPackageJson, PackageJson }
export { getPackageJson, PackageJson, sanitisePackageJson }
23 changes: 23 additions & 0 deletions tests/unit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const test = require('ava')

const { sanitisePackageJson } = require('../dist/runtimes/node/utils/package_json')

test('sanitisePackageJson', (t) => {
t.deepEqual(
sanitisePackageJson({
files: ['a.js', null, 'b.js'],
}),
{
files: ['a.js', 'b.js'],
},
)

t.deepEqual(
sanitisePackageJson({
files: { 'a.js': true, 'b.js': false },
}),
{
files: undefined,
},
)
})

1 comment on commit 6c82ada

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⏱ Benchmark results

largeDepsEsbuild: 7.5s

largeDepsNft: 46.9s

largeDepsZisi: 56.1s

Please sign in to comment.