Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(create-app): improved package name validation #2772

Merged
merged 4 commits into from
Mar 30, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 32 additions & 11 deletions packages/create-app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,42 @@ async function init() {
let targetDir = argv._[0]
if (!targetDir) {
/**
* @type {{ name: string }}
* @type {{ projectName: string }}
*/
const { name } = await prompt({
const { projectName } = await prompt({
type: 'input',
name: 'name',
name: 'projectName',
message: `Project name:`,
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
initial: 'vite-project'
})
targetDir = name
targetDir = projectName
}
let packageName
const packageNameRegExp = /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/
if (packageNameRegExp.test(targetDir)) {
packageName = targetDir
} else {
const suggestPkgName = targetDir
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z0-9-~]+/g, '-')

/**
* @type {{ inputPackageName: string }}
*/
const { inputPackageName } = await prompt({
type: 'input',
name: 'inputPackageName',
message: `Name for package.json:`,
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
initial: suggestPkgName,
validate: (input) =>
packageNameRegExp.test(input)
? true
: 'Name contains illegal characters'
})
packageName = inputPackageName
}

const root = path.join(cwd, targetDir)
Expand Down Expand Up @@ -122,13 +149,7 @@ async function init() {

const pkg = require(path.join(templateDir, `package.json`))
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved

pkg.name = path
.basename(root)
// #2360 ensure packgae.json name is valid
.trim()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[~)('!*]+/g, '-')
pkg.name = packageName
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved

write('package.json', JSON.stringify(pkg, null, 2))

Expand Down