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

fix: sanitise package.json files field #800

Merged
merged 2 commits into from
Nov 9, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 = (pack: Record<string, unknown>): PackageJson => ({
netlify-team-account-1 marked this conversation as resolved.
Show resolved Hide resolved
...pack,
netlify-team-account-1 marked this conversation as resolved.
Show resolved Hide resolved
files: sanitiseFiles(pack.files),
netlify-team-account-1 marked this conversation as resolved.
Show resolved Hide resolved
})

// 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 pack = require(packageJsonPath)
netlify-team-account-1 marked this conversation as resolved.
Show resolved Hide resolved
return sanitisePackageJson(pack)
netlify-team-account-1 marked this conversation as resolved.
Show resolved Hide resolved
} 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,
},
)
})