diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 12ae8a255406d4..e14beca6015d94 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -178,7 +178,7 @@ module.exports = defineConfig({ } }, { - files: ['*.js'], + files: ['*.js', '*.mjs', '*.cjs'], rules: { '@typescript-eslint/explicit-module-boundary-types': 'off' } diff --git a/package.json b/package.json index 04df3123ff8c6d..5ecbd6f517ea1b 100644 --- a/package.json +++ b/package.json @@ -67,6 +67,7 @@ "eslint-plugin-import": "^2.26.0", "eslint-plugin-node": "^11.1.0", "execa": "^6.1.0", + "fast-glob": "^3.2.11", "fs-extra": "^10.1.0", "lint-staged": "^13.0.3", "minimist": "^1.2.6", @@ -76,8 +77,10 @@ "pnpm": "^7.9.3", "prettier": "2.7.1", "prompts": "^2.4.2", + "resolve": "^1.22.1", "rimraf": "^3.0.2", "rollup": "~2.78.0", + "rollup-plugin-license": "^2.8.1", "semver": "^7.3.7", "simple-git-hooks": "^2.8.0", "tslib": "^2.4.0", diff --git a/packages/create-vite/LICENSE b/packages/create-vite/LICENSE index 9c1b313d7b1816..4851bee9f284f3 100644 --- a/packages/create-vite/LICENSE +++ b/packages/create-vite/LICENSE @@ -1,3 +1,6 @@ +# create-vite license +create-vite is released under the MIT license: + MIT License Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors @@ -19,3 +22,274 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +# Licenses of bundled dependencies +The published create-vite artifact additionally contains code with the following licenses: +ISC, MIT + +# Bundled dependencies: +## cross-spawn +License: MIT +By: André Cruz +Repository: git@github.com:moxystudio/node-cross-spawn.git + +> The MIT License (MIT) +> +> Copyright (c) 2018 Made With MOXY Lda +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## isexe +License: ISC +By: Isaac Z. Schlueter +Repository: git+https://github.com/isaacs/isexe.git + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter and Contributors +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## kleur +License: MIT +By: Luke Edwards +Repository: lukeed/kleur + +> The MIT License (MIT) +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + +## kolorist +License: MIT +By: Marvin Hagemeister +Repository: https://github.com/marvinhagemeister/kolorist.git + +> The MIT License (MIT) +> +> Copyright (c) 2020-present Marvin Hagemeister +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## minimist +License: MIT +By: James Halliday +Repository: git://github.com/substack/minimist.git + +> This software is released under the MIT license: +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of +> this software and associated documentation files (the "Software"), to deal in +> the Software without restriction, including without limitation the rights to +> use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +> the Software, and to permit persons to whom the Software is furnished to do so, +> subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +> FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +> COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +> IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +> CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## path-key +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/path-key + +> MIT License +> +> Copyright (c) Sindre Sorhus (sindresorhus.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## prompts +License: MIT +By: Terkel Gjervig +Repository: terkelg/prompts + +> MIT License +> +> Copyright (c) 2018 Terkel Gjervig Nielsen +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## shebang-command +License: MIT +By: Kevin Mårtensson +Repository: kevva/shebang-command + +> MIT License +> +> Copyright (c) Kevin Mårtensson (github.com/kevva) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## shebang-regex +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/shebang-regex + +> MIT License +> +> Copyright (c) Sindre Sorhus (sindresorhus.com) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------------------------------------- + +## sisteransi +License: MIT +By: Terkel Gjervig +Repository: https://github.com/terkelg/sisteransi + +> MIT License +> +> Copyright (c) 2018 Terkel Gjervig Nielsen +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all +> copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +> SOFTWARE. + +--------------------------------------- + +## which +License: ISC +By: Isaac Z. Schlueter +Repository: git://github.com/isaacs/node-which.git + +> The ISC License +> +> Copyright (c) Isaac Z. Schlueter and Contributors +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/packages/create-vite/build.config.ts b/packages/create-vite/build.config.ts new file mode 100644 index 00000000000000..2c39d19d427de6 --- /dev/null +++ b/packages/create-vite/build.config.ts @@ -0,0 +1,35 @@ +import path from 'node:path' +import url from 'node:url' +import { defineBuildConfig } from 'unbuild' +import licensePlugin from '../../scripts/rollupLicensePlugin.mjs' + +const __dirname = path.dirname(url.fileURLToPath(import.meta.url)) + +export default defineBuildConfig({ + entries: ['src/index'], + clean: true, + rollup: { + inlineDependencies: true, + esbuild: { + minify: true + } + }, + alias: { + // we can always use non-transpiled code since we support 14.18.0+ + prompts: 'prompts/lib/index.js' + }, + hooks: { + 'rollup:options'(ctx, options) { + if (!options.plugins) { + options.plugins = [] + } + options.plugins.push( + licensePlugin( + path.resolve(__dirname, './LICENSE'), + 'create-vite license', + 'create-vite' + ) + ) + } + } +}) diff --git a/packages/create-vite/index.js b/packages/create-vite/index.js index d602eea2b3e57a..f5e8e064a68d9f 100755 --- a/packages/create-vite/index.js +++ b/packages/create-vite/index.js @@ -1,444 +1,3 @@ #!/usr/bin/env node -// @ts-check -import fs from 'node:fs' -import path from 'node:path' -import { fileURLToPath } from 'node:url' -import spawn from 'cross-spawn' -import minimist from 'minimist' -import prompts from 'prompts' -import { - blue, - cyan, - green, - lightGreen, - lightRed, - magenta, - red, - reset, - yellow -} from 'kolorist' - -// Avoids autoconversion to number of the project name by defining that the args -// non associated with an option ( _ ) needs to be parsed as a string. See #4606 -const argv = minimist(process.argv.slice(2), { string: ['_'] }) -const cwd = process.cwd() - -const FRAMEWORKS = [ - { - name: 'vanilla', - display: 'Vanilla', - color: yellow, - variants: [ - { - name: 'vanilla', - display: 'JavaScript', - color: yellow - }, - { - name: 'vanilla-ts', - display: 'TypeScript', - color: blue - } - ] - }, - { - name: 'vue', - display: 'Vue', - color: green, - variants: [ - { - name: 'vue', - display: 'JavaScript', - color: yellow - }, - { - name: 'vue-ts', - display: 'TypeScript', - color: blue - }, - { - name: 'custom-create-vue', - display: 'Customize with create-vue', - color: green, - customCommand: 'npm create vue@latest TARGET_DIR' - }, - { - name: 'custom-nuxt', - display: 'Nuxt', - color: lightGreen, - customCommand: 'npm exec nuxi init TARGET_DIR' - } - ] - }, - { - name: 'react', - display: 'React', - color: cyan, - variants: [ - { - name: 'react', - display: 'JavaScript', - color: yellow - }, - { - name: 'react-ts', - display: 'TypeScript', - color: blue - } - ] - }, - { - name: 'preact', - display: 'Preact', - color: magenta, - variants: [ - { - name: 'preact', - display: 'JavaScript', - color: yellow - }, - { - name: 'preact-ts', - display: 'TypeScript', - color: blue - } - ] - }, - { - name: 'lit', - display: 'Lit', - color: lightRed, - variants: [ - { - name: 'lit', - display: 'JavaScript', - color: yellow - }, - { - name: 'lit-ts', - display: 'TypeScript', - color: blue - } - ] - }, - { - name: 'svelte', - display: 'Svelte', - color: red, - variants: [ - { - name: 'svelte', - display: 'JavaScript', - color: yellow - }, - { - name: 'svelte-ts', - display: 'TypeScript', - color: blue - }, - { - name: 'custom-svelte-kit', - display: 'SvelteKit', - color: red, - customCommand: 'npm create svelte@latest TARGET_DIR' - } - ] - } -] - -const TEMPLATES = FRAMEWORKS.map( - (f) => (f.variants && f.variants.map((v) => v.name)) || [f.name] -).reduce((a, b) => a.concat(b), []) - -const renameFiles = { - _gitignore: '.gitignore' -} - -async function init() { - let targetDir = formatTargetDir(argv._[0]) - let template = argv.template || argv.t - - const defaultTargetDir = 'vite-project' - const getProjectName = () => - targetDir === '.' ? path.basename(path.resolve()) : targetDir - - let result = {} - - try { - result = await prompts( - [ - { - type: targetDir ? null : 'text', - name: 'projectName', - message: reset('Project name:'), - initial: defaultTargetDir, - onState: (state) => { - targetDir = formatTargetDir(state.value) || defaultTargetDir - } - }, - { - type: () => - !fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'confirm', - name: 'overwrite', - message: () => - (targetDir === '.' - ? 'Current directory' - : `Target directory "${targetDir}"`) + - ` is not empty. Remove existing files and continue?` - }, - { - type: (_, { overwrite } = {}) => { - if (overwrite === false) { - throw new Error(red('✖') + ' Operation cancelled') - } - return null - }, - name: 'overwriteChecker' - }, - { - type: () => (isValidPackageName(getProjectName()) ? null : 'text'), - name: 'packageName', - message: reset('Package name:'), - initial: () => toValidPackageName(getProjectName()), - validate: (dir) => - isValidPackageName(dir) || 'Invalid package.json name' - }, - { - type: template && TEMPLATES.includes(template) ? null : 'select', - name: 'framework', - message: - typeof template === 'string' && !TEMPLATES.includes(template) - ? reset( - `"${template}" isn't a valid template. Please choose from below: ` - ) - : reset('Select a framework:'), - initial: 0, - choices: FRAMEWORKS.map((framework) => { - const frameworkColor = framework.color - return { - title: frameworkColor(framework.display || framework.name), - value: framework - } - }) - }, - { - type: (framework) => - framework && framework.variants ? 'select' : null, - name: 'variant', - message: reset('Select a variant:'), - // @ts-ignore - choices: (framework) => - framework.variants.map((variant) => { - const variantColor = variant.color - return { - title: variantColor(variant.display || variant.name), - value: variant.name - } - }) - } - ], - { - onCancel: () => { - throw new Error(red('✖') + ' Operation cancelled') - } - } - ) - } catch (cancelled) { - console.log(cancelled.message) - return - } - - // user choice associated with prompts - const { framework, overwrite, packageName, variant } = result - - const root = path.join(cwd, targetDir) - - if (overwrite) { - emptyDir(root) - } else if (!fs.existsSync(root)) { - fs.mkdirSync(root, { recursive: true }) - } - - // determine template - template = variant || framework || template - - const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent) - const pkgManager = pkgInfo ? pkgInfo.name : 'npm' - const isYarn1 = pkgManager === 'yarn' && pkgInfo?.version.startsWith('1.') - - if (template.startsWith('custom-')) { - const getCustomCommand = (name) => { - for (const f of FRAMEWORKS) { - for (const v of f.variants || []) { - if (v.name === name) { - return v.customCommand - } - } - } - } - const customCommand = getCustomCommand(template) - const fullCustomCommand = customCommand - .replace('TARGET_DIR', targetDir) - .replace(/^npm create/, `${pkgManager} create`) - // Only Yarn 1.x doesn't support `@version` in the `create` command - .replace('@latest', () => (isYarn1 ? '' : '@latest')) - .replace(/^npm exec/, () => { - // Prefer `pnpm dlx` or `yarn dlx` - if (pkgManager === 'pnpm') { - return 'pnpm dlx' - } - if (pkgManager === 'yarn' && !isYarn1) { - return 'yarn dlx' - } - // Use `npm exec` in all other cases, - // including Yarn 1.x and other custom npm clients. - return 'npm exec' - }) - - const [command, ...args] = fullCustomCommand.split(' ') - const { status } = spawn.sync(command, args, { - stdio: 'inherit' - }) - process.exit(status ?? 0) - } - - console.log(`\nScaffolding project in ${root}...`) - - const templateDir = path.resolve( - fileURLToPath(import.meta.url), - '..', - `template-${template}` - ) - - const write = (file, content) => { - const targetPath = renameFiles[file] - ? path.join(root, renameFiles[file]) - : path.join(root, file) - if (content) { - fs.writeFileSync(targetPath, content) - } else { - copy(path.join(templateDir, file), targetPath) - } - } - - const files = fs.readdirSync(templateDir) - for (const file of files.filter((f) => f !== 'package.json')) { - write(file) - } - - const pkg = JSON.parse( - fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8') - ) - - pkg.name = packageName || getProjectName() - - write('package.json', JSON.stringify(pkg, null, 2)) - - console.log(`\nDone. Now run:\n`) - if (root !== cwd) { - console.log(` cd ${path.relative(cwd, root)}`) - } - switch (pkgManager) { - case 'yarn': - console.log(' yarn') - console.log(' yarn dev') - break - default: - console.log(` ${pkgManager} install`) - console.log(` ${pkgManager} run dev`) - break - } - console.log() -} - -/** - * @param {string | undefined} targetDir - */ -function formatTargetDir(targetDir) { - return targetDir?.trim().replace(/\/+$/g, '') -} - -function copy(src, dest) { - const stat = fs.statSync(src) - if (stat.isDirectory()) { - copyDir(src, dest) - } else { - fs.copyFileSync(src, dest) - } -} - -/** - * @param {string} projectName - */ -function isValidPackageName(projectName) { - return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test( - projectName - ) -} - -/** - * @param {string} projectName - */ -function toValidPackageName(projectName) { - return projectName - .trim() - .toLowerCase() - .replace(/\s+/g, '-') - .replace(/^[._]/, '') - .replace(/[^a-z0-9-~]+/g, '-') -} - -/** - * @param {string} srcDir - * @param {string} destDir - */ -function copyDir(srcDir, destDir) { - fs.mkdirSync(destDir, { recursive: true }) - for (const file of fs.readdirSync(srcDir)) { - const srcFile = path.resolve(srcDir, file) - const destFile = path.resolve(destDir, file) - copy(srcFile, destFile) - } -} - -/** - * @param {string} path - */ -function isEmpty(path) { - const files = fs.readdirSync(path) - return files.length === 0 || (files.length === 1 && files[0] === '.git') -} - -/** - * @param {string} dir - */ -function emptyDir(dir) { - if (!fs.existsSync(dir)) { - return - } - for (const file of fs.readdirSync(dir)) { - if (file === '.git') { - continue - } - fs.rmSync(path.resolve(dir, file), { recursive: true, force: true }) - } -} - -/** - * @param {string | undefined} userAgent process.env.npm_config_user_agent - * @returns object | undefined - */ -function pkgFromUserAgent(userAgent) { - if (!userAgent) return undefined - const pkgSpec = userAgent.split(' ')[0] - const pkgSpecArr = pkgSpec.split('/') - return { - name: pkgSpecArr[0], - version: pkgSpecArr[1] - } -} - -init().catch((e) => { - console.error(e) -}) +import './dist/index.mjs' diff --git a/packages/create-vite/package.json b/packages/create-vite/package.json index a52fa837d977ab..76c33bcd95e75f 100644 --- a/packages/create-vite/package.json +++ b/packages/create-vite/package.json @@ -10,9 +10,15 @@ }, "files": [ "index.js", - "template-*" + "template-*", + "dist" ], "main": "index.js", + "scripts": { + "dev": "unbuild --stub", + "build": "unbuild", + "prepublishOnly": "npm run build" + }, "engines": { "node": "^14.18.0 || >=16.0.0" }, @@ -25,7 +31,7 @@ "url": "https://github.com/vitejs/vite/issues" }, "homepage": "https://github.com/vitejs/vite/tree/main/packages/create-vite#readme", - "dependencies": { + "devDependencies": { "cross-spawn": "^7.0.3", "kolorist": "^1.5.1", "minimist": "^1.2.6", diff --git a/packages/create-vite/src/index.js b/packages/create-vite/src/index.js new file mode 100755 index 00000000000000..8e5aa02ff4a40e --- /dev/null +++ b/packages/create-vite/src/index.js @@ -0,0 +1,442 @@ +// @ts-check +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import spawn from 'cross-spawn' +import minimist from 'minimist' +import prompts from 'prompts' +import { + blue, + cyan, + green, + lightGreen, + lightRed, + magenta, + red, + reset, + yellow +} from 'kolorist' + +// Avoids autoconversion to number of the project name by defining that the args +// non associated with an option ( _ ) needs to be parsed as a string. See #4606 +const argv = minimist(process.argv.slice(2), { string: ['_'] }) +const cwd = process.cwd() + +const FRAMEWORKS = [ + { + name: 'vanilla', + display: 'Vanilla', + color: yellow, + variants: [ + { + name: 'vanilla', + display: 'JavaScript', + color: yellow + }, + { + name: 'vanilla-ts', + display: 'TypeScript', + color: blue + } + ] + }, + { + name: 'vue', + display: 'Vue', + color: green, + variants: [ + { + name: 'vue', + display: 'JavaScript', + color: yellow + }, + { + name: 'vue-ts', + display: 'TypeScript', + color: blue + }, + { + name: 'custom-create-vue', + display: 'Customize with create-vue', + color: green, + customCommand: 'npm create vue@latest TARGET_DIR' + }, + { + name: 'custom-nuxt', + display: 'Nuxt', + color: lightGreen, + customCommand: 'npm exec nuxi init TARGET_DIR' + } + ] + }, + { + name: 'react', + display: 'React', + color: cyan, + variants: [ + { + name: 'react', + display: 'JavaScript', + color: yellow + }, + { + name: 'react-ts', + display: 'TypeScript', + color: blue + } + ] + }, + { + name: 'preact', + display: 'Preact', + color: magenta, + variants: [ + { + name: 'preact', + display: 'JavaScript', + color: yellow + }, + { + name: 'preact-ts', + display: 'TypeScript', + color: blue + } + ] + }, + { + name: 'lit', + display: 'Lit', + color: lightRed, + variants: [ + { + name: 'lit', + display: 'JavaScript', + color: yellow + }, + { + name: 'lit-ts', + display: 'TypeScript', + color: blue + } + ] + }, + { + name: 'svelte', + display: 'Svelte', + color: red, + variants: [ + { + name: 'svelte', + display: 'JavaScript', + color: yellow + }, + { + name: 'svelte-ts', + display: 'TypeScript', + color: blue + }, + { + name: 'custom-svelte-kit', + display: 'SvelteKit', + color: red, + customCommand: 'npm create svelte@latest TARGET_DIR' + } + ] + } +] + +const TEMPLATES = FRAMEWORKS.map( + (f) => (f.variants && f.variants.map((v) => v.name)) || [f.name] +).reduce((a, b) => a.concat(b), []) + +const renameFiles = { + _gitignore: '.gitignore' +} + +async function init() { + let targetDir = formatTargetDir(argv._[0]) + let template = argv.template || argv.t + + const defaultTargetDir = 'vite-project' + const getProjectName = () => + targetDir === '.' ? path.basename(path.resolve()) : targetDir + + let result = {} + + try { + result = await prompts( + [ + { + type: targetDir ? null : 'text', + name: 'projectName', + message: reset('Project name:'), + initial: defaultTargetDir, + onState: (state) => { + targetDir = formatTargetDir(state.value) || defaultTargetDir + } + }, + { + type: () => + !fs.existsSync(targetDir) || isEmpty(targetDir) ? null : 'confirm', + name: 'overwrite', + message: () => + (targetDir === '.' + ? 'Current directory' + : `Target directory "${targetDir}"`) + + ` is not empty. Remove existing files and continue?` + }, + { + type: (_, { overwrite } = {}) => { + if (overwrite === false) { + throw new Error(red('✖') + ' Operation cancelled') + } + return null + }, + name: 'overwriteChecker' + }, + { + type: () => (isValidPackageName(getProjectName()) ? null : 'text'), + name: 'packageName', + message: reset('Package name:'), + initial: () => toValidPackageName(getProjectName()), + validate: (dir) => + isValidPackageName(dir) || 'Invalid package.json name' + }, + { + type: template && TEMPLATES.includes(template) ? null : 'select', + name: 'framework', + message: + typeof template === 'string' && !TEMPLATES.includes(template) + ? reset( + `"${template}" isn't a valid template. Please choose from below: ` + ) + : reset('Select a framework:'), + initial: 0, + choices: FRAMEWORKS.map((framework) => { + const frameworkColor = framework.color + return { + title: frameworkColor(framework.display || framework.name), + value: framework + } + }) + }, + { + type: (framework) => + framework && framework.variants ? 'select' : null, + name: 'variant', + message: reset('Select a variant:'), + // @ts-ignore + choices: (framework) => + framework.variants.map((variant) => { + const variantColor = variant.color + return { + title: variantColor(variant.display || variant.name), + value: variant.name + } + }) + } + ], + { + onCancel: () => { + throw new Error(red('✖') + ' Operation cancelled') + } + } + ) + } catch (cancelled) { + console.log(cancelled.message) + return + } + + // user choice associated with prompts + const { framework, overwrite, packageName, variant } = result + + const root = path.join(cwd, targetDir) + + if (overwrite) { + emptyDir(root) + } else if (!fs.existsSync(root)) { + fs.mkdirSync(root, { recursive: true }) + } + + // determine template + template = variant || framework || template + + const pkgInfo = pkgFromUserAgent(process.env.npm_config_user_agent) + const pkgManager = pkgInfo ? pkgInfo.name : 'npm' + const isYarn1 = pkgManager === 'yarn' && pkgInfo?.version.startsWith('1.') + + if (template.startsWith('custom-')) { + const getCustomCommand = (name) => { + for (const f of FRAMEWORKS) { + for (const v of f.variants || []) { + if (v.name === name) { + return v.customCommand + } + } + } + } + const customCommand = getCustomCommand(template) + const fullCustomCommand = customCommand + .replace('TARGET_DIR', targetDir) + .replace(/^npm create/, `${pkgManager} create`) + // Only Yarn 1.x doesn't support `@version` in the `create` command + .replace('@latest', () => (isYarn1 ? '' : '@latest')) + .replace(/^npm exec/, () => { + // Prefer `pnpm dlx` or `yarn dlx` + if (pkgManager === 'pnpm') { + return 'pnpm dlx' + } + if (pkgManager === 'yarn' && !isYarn1) { + return 'yarn dlx' + } + // Use `npm exec` in all other cases, + // including Yarn 1.x and other custom npm clients. + return 'npm exec' + }) + + const [command, ...args] = fullCustomCommand.split(' ') + const { status } = spawn.sync(command, args, { + stdio: 'inherit' + }) + process.exit(status ?? 0) + } + + console.log(`\nScaffolding project in ${root}...`) + + const templateDir = path.resolve( + fileURLToPath(import.meta.url), + '../..', + `template-${template}` + ) + + const write = (file, content) => { + const targetPath = renameFiles[file] + ? path.join(root, renameFiles[file]) + : path.join(root, file) + if (content) { + fs.writeFileSync(targetPath, content) + } else { + copy(path.join(templateDir, file), targetPath) + } + } + + const files = fs.readdirSync(templateDir) + for (const file of files.filter((f) => f !== 'package.json')) { + write(file) + } + + const pkg = JSON.parse( + fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8') + ) + + pkg.name = packageName || getProjectName() + + write('package.json', JSON.stringify(pkg, null, 2)) + + console.log(`\nDone. Now run:\n`) + if (root !== cwd) { + console.log(` cd ${path.relative(cwd, root)}`) + } + switch (pkgManager) { + case 'yarn': + console.log(' yarn') + console.log(' yarn dev') + break + default: + console.log(` ${pkgManager} install`) + console.log(` ${pkgManager} run dev`) + break + } + console.log() +} + +/** + * @param {string | undefined} targetDir + */ +function formatTargetDir(targetDir) { + return targetDir?.trim().replace(/\/+$/g, '') +} + +function copy(src, dest) { + const stat = fs.statSync(src) + if (stat.isDirectory()) { + copyDir(src, dest) + } else { + fs.copyFileSync(src, dest) + } +} + +/** + * @param {string} projectName + */ +function isValidPackageName(projectName) { + return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test( + projectName + ) +} + +/** + * @param {string} projectName + */ +function toValidPackageName(projectName) { + return projectName + .trim() + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/^[._]/, '') + .replace(/[^a-z0-9-~]+/g, '-') +} + +/** + * @param {string} srcDir + * @param {string} destDir + */ +function copyDir(srcDir, destDir) { + fs.mkdirSync(destDir, { recursive: true }) + for (const file of fs.readdirSync(srcDir)) { + const srcFile = path.resolve(srcDir, file) + const destFile = path.resolve(destDir, file) + copy(srcFile, destFile) + } +} + +/** + * @param {string} path + */ +function isEmpty(path) { + const files = fs.readdirSync(path) + return files.length === 0 || (files.length === 1 && files[0] === '.git') +} + +/** + * @param {string} dir + */ +function emptyDir(dir) { + if (!fs.existsSync(dir)) { + return + } + for (const file of fs.readdirSync(dir)) { + if (file === '.git') { + continue + } + fs.rmSync(path.resolve(dir, file), { recursive: true, force: true }) + } +} + +/** + * @param {string | undefined} userAgent process.env.npm_config_user_agent + * @returns object | undefined + */ +function pkgFromUserAgent(userAgent) { + if (!userAgent) return undefined + const pkgSpec = userAgent.split(' ')[0] + const pkgSpecArr = pkgSpec.split('/') + return { + name: pkgSpecArr[0], + version: pkgSpecArr[1] + } +} + +init().catch((e) => { + console.error(e) +}) diff --git a/packages/vite/package.json b/packages/vite/package.json index ceb4d2810068f4..318abeb6d233f7 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -109,7 +109,6 @@ "postcss-load-config": "^4.0.1", "postcss-modules": "^5.0.0", "resolve.exports": "^1.1.0", - "rollup-plugin-license": "^2.8.1", "sirv": "^2.0.2", "source-map-js": "^1.0.2", "source-map-support": "^0.5.21", diff --git a/packages/vite/rollup.config.ts b/packages/vite/rollup.config.ts index bf5c0e9da810a2..c333e66577f8d5 100644 --- a/packages/vite/rollup.config.ts +++ b/packages/vite/rollup.config.ts @@ -1,17 +1,13 @@ /* eslint-disable no-restricted-globals */ -import fs from 'node:fs' import path from 'node:path' import nodeResolve from '@rollup/plugin-node-resolve' import typescript from '@rollup/plugin-typescript' import commonjs from '@rollup/plugin-commonjs' import json from '@rollup/plugin-json' -import license from 'rollup-plugin-license' import MagicString from 'magic-string' -import colors from 'picocolors' -import fg from 'fast-glob' -import { sync as resolve } from 'resolve' import type { Plugin, RollupOptions } from 'rollup' import { defineConfig } from 'rollup' +import licensePlugin from '../../scripts/rollupLicensePlugin.mjs' import pkg from './package.json' const envConfig = defineConfig({ @@ -119,7 +115,12 @@ function createNodePlugins( ignore: ['bufferutil', 'utf-8-validate'] }), json(), - isProduction && licensePlugin(), + isProduction && + licensePlugin( + path.resolve(__dirname, 'LICENSE.md'), + 'Vite core license', + 'Vite' + ), cjsPatchPlugin() ] } @@ -256,115 +257,6 @@ function shimDepsPlugin(deps: Record): Plugin { } } -function licensePlugin() { - return license({ - thirdParty(dependencies) { - // https://github.com/rollup/rollup/blob/master/build-plugins/generate-license-file.js - // MIT Licensed https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md - const coreLicense = fs.readFileSync( - path.resolve(__dirname, '../../LICENSE') - ) - function sortLicenses(licenses) { - let withParenthesis = [] - let noParenthesis = [] - licenses.forEach((license) => { - if (/^\(/.test(license)) { - withParenthesis.push(license) - } else { - noParenthesis.push(license) - } - }) - withParenthesis = withParenthesis.sort() - noParenthesis = noParenthesis.sort() - return [...noParenthesis, ...withParenthesis] - } - const licenses = new Set() - const dependencyLicenseTexts = dependencies - .sort(({ name: nameA }, { name: nameB }) => - nameA > nameB ? 1 : nameB > nameA ? -1 : 0 - ) - .map( - ({ - name, - license, - licenseText, - author, - maintainers, - contributors, - repository - }) => { - let text = `## ${name}\n` - if (license) { - text += `License: ${license}\n` - } - const names = new Set() - for (const person of [author, ...maintainers, ...contributors]) { - const name = typeof person === 'string' ? person : person?.name - if (name) { - names.add(name) - } - } - if (names.size > 0) { - text += `By: ${Array.from(names).join(', ')}\n` - } - if (repository) { - text += `Repository: ${ - typeof repository === 'string' ? repository : repository.url - }\n` - } - if (!licenseText) { - try { - const pkgDir = path.dirname( - resolve(path.join(name, 'package.json'), { - preserveSymlinks: false - }) - ) - const licenseFile = fg.sync(`${pkgDir}/LICENSE*`, { - caseSensitiveMatch: false - })[0] - if (licenseFile) { - licenseText = fs.readFileSync(licenseFile, 'utf-8') - } - } catch {} - } - if (licenseText) { - text += - '\n' + - licenseText - .trim() - .replace(/(\r\n|\r)/gm, '\n') - .split('\n') - .map((line) => `> ${line}`) - .join('\n') + - '\n' - } - licenses.add(license) - return text - } - ) - .join('\n---------------------------------------\n\n') - const licenseText = - `# Vite core license\n` + - `Vite is released under the MIT license:\n\n` + - coreLicense + - `\n# Licenses of bundled dependencies\n` + - `The published Vite artifact additionally contains code with the following licenses:\n` + - `${sortLicenses(licenses).join(', ')}\n\n` + - `# Bundled dependencies:\n` + - dependencyLicenseTexts - const existingLicenseText = fs.readFileSync('LICENSE.md', 'utf8') - if (existingLicenseText !== licenseText) { - fs.writeFileSync('LICENSE.md', licenseText) - console.warn( - colors.yellow( - '\nLICENSE.md updated. You should commit the updated file.\n' - ) - ) - } - } - }) -} - /** * Inject CJS Context for each deps chunk */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f5e3a95a317cd7..e9789e8b3bd26f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -41,6 +41,7 @@ importers: eslint-plugin-import: ^2.26.0 eslint-plugin-node: ^11.1.0 execa: ^6.1.0 + fast-glob: ^3.2.11 fs-extra: ^10.1.0 lint-staged: ^13.0.3 minimist: ^1.2.6 @@ -50,8 +51,10 @@ importers: pnpm: ^7.9.3 prettier: 2.7.1 prompts: ^2.4.2 + resolve: ^1.22.1 rimraf: ^3.0.2 rollup: ~2.78.0 + rollup-plugin-license: ^2.8.1 semver: ^7.3.7 simple-git-hooks: ^2.8.0 tslib: ^2.4.0 @@ -94,6 +97,7 @@ importers: eslint-plugin-import: 2.26.0_3bh5nkk7utn7e74vrwtv6rxmt4 eslint-plugin-node: 11.1.0_eslint@8.22.0 execa: 6.1.0 + fast-glob: 3.2.11 fs-extra: 10.1.0 lint-staged: 13.0.3 minimist: 1.2.6 @@ -103,8 +107,10 @@ importers: pnpm: 7.9.3 prettier: 2.7.1 prompts: 2.4.2 + resolve: 1.22.1 rimraf: 3.0.2 rollup: 2.78.0 + rollup-plugin-license: 2.8.1_rollup@2.78.0 semver: 7.3.7 simple-git-hooks: 2.8.0 tslib: 2.4.0 @@ -122,7 +128,7 @@ importers: kolorist: ^1.5.1 minimist: ^1.2.6 prompts: ^2.4.2 - dependencies: + devDependencies: cross-spawn: 7.0.3 kolorist: 1.5.1 minimist: 1.2.6 @@ -252,7 +258,6 @@ importers: resolve: ^1.22.1 resolve.exports: ^1.1.0 rollup: ~2.78.0 - rollup-plugin-license: ^2.8.1 sirv: ^2.0.2 source-map-js: ^1.0.2 source-map-support: ^0.5.21 @@ -313,7 +318,6 @@ importers: postcss-load-config: 4.0.1_postcss@8.4.16 postcss-modules: 5.0.0_postcss@8.4.16 resolve.exports: 1.1.0 - rollup-plugin-license: 2.8.1_rollup@2.78.0 sirv: 2.0.2 source-map-js: 1.0.2 source-map-support: 0.5.21 @@ -3986,6 +3990,7 @@ packages: path-key: 3.1.1 shebang-command: 2.0.0 which: 2.0.2 + dev: true /crosspath/0.0.8: resolution: {integrity: sha512-IKlS3MpP0fhJ50M6ltyLO7Q4NzwfhafpmolMH0EDKyyaY81HutF2mH4hLpCdm3fKZ/TSTW5qPIdTy62YnefEyQ==} @@ -5039,7 +5044,7 @@ packages: is-glob: 4.0.3 minimatch: 3.1.2 object.values: 1.1.5 - resolve: 1.22.0 + resolve: 1.22.1 tsconfig-paths: 3.14.1 transitivePeerDependencies: - eslint-import-resolver-typescript @@ -5058,7 +5063,7 @@ packages: eslint-utils: 2.1.0 ignore: 5.2.0 minimatch: 3.1.2 - resolve: 1.22.0 + resolve: 1.22.1 semver: 6.3.0 dev: true @@ -6120,6 +6125,7 @@ packages: /isexe/2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + dev: true /jiti/1.14.0: resolution: {integrity: sha512-4IwstlaKQc9vCTC+qUXLM1hajy2ImiL9KnLvVYiaHOtS/v3wRjhLlGl121AmgDgx/O43uKmxownJghS5XMya2A==} @@ -6231,6 +6237,7 @@ packages: /kleur/3.0.3: resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} engines: {node: '>=6'} + dev: true /kleur/4.1.4: resolution: {integrity: sha512-8QADVssbrFjivHWQU7KkMgptGTl6WAcSdlbBPY4uNF+mWr6DGcKrvY2w4FQJoXch7+fKMjj0dRrL75vk3k23OA==} @@ -6239,7 +6246,7 @@ packages: /kolorist/1.5.1: resolution: {integrity: sha512-lxpCM3HTvquGxKGzHeknB/sUjuVoUElLlfYnXZT73K8geR9jQbroGlSCFBax9/0mpGoD3kzcMLnOlGQPJJNyqQ==} - dev: false + dev: true /launch-editor-middleware/2.6.0: resolution: {integrity: sha512-K2yxgljj5TdCeRN1lBtO3/J26+AIDDDw+04y6VAiZbWcTdBwsYN6RrZBnW5DN/QiSIdKNjKdATLUUluWWFYTIA==} @@ -7121,6 +7128,7 @@ packages: /path-key/3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} + dev: true /path-key/4.0.0: resolution: {integrity: sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==} @@ -7451,6 +7459,7 @@ packages: dependencies: kleur: 3.0.3 sisteransi: 1.0.5 + dev: true /prop-types/15.8.1: resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} @@ -8061,6 +8070,7 @@ packages: engines: {node: '>=8'} dependencies: shebang-regex: 3.0.0 + dev: true /shebang-regex/1.0.0: resolution: {integrity: sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=} @@ -8070,6 +8080,7 @@ packages: /shebang-regex/3.0.0: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + dev: true /shell-exec/1.0.2: resolution: {integrity: sha512-jyVd+kU2X+mWKMmGhx4fpWbPsjvD53k9ivqetutVW/BQ+WIZoDoP4d8vUMGezV6saZsiNoW2f9GIhg9Dondohg==} @@ -8115,6 +8126,7 @@ packages: /sisteransi/1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + dev: true /slash/3.0.0: resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} @@ -9079,6 +9091,7 @@ packages: hasBin: true dependencies: isexe: 2.0.0 + dev: true /wide-align/1.1.5: resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==} diff --git a/scripts/rollupLicensePlugin.mjs b/scripts/rollupLicensePlugin.mjs new file mode 100644 index 00000000000000..f96719e19bf9a6 --- /dev/null +++ b/scripts/rollupLicensePlugin.mjs @@ -0,0 +1,126 @@ +// @ts-check + +import fs from 'node:fs' +import path from 'node:path' +import license from 'rollup-plugin-license' +import colors from 'picocolors' +import fg from 'fast-glob' +import { sync as resolve } from 'resolve' + +/** + * @param {string} licenseFilePath + * @param {string} licenseTitle + * @param {string} packageName + */ +function licensePlugin(licenseFilePath, licenseTitle, packageName) { + return license({ + thirdParty(dependencies) { + // https://github.com/rollup/rollup/blob/master/build-plugins/generate-license-file.js + // MIT Licensed https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md + const coreLicense = fs.readFileSync( + new URL('../LICENSE', import.meta.url) + ) + function sortLicenses(licenses) { + let withParenthesis = [] + let noParenthesis = [] + licenses.forEach((license) => { + if (/^\(/.test(license)) { + withParenthesis.push(license) + } else { + noParenthesis.push(license) + } + }) + withParenthesis = withParenthesis.sort() + noParenthesis = noParenthesis.sort() + return [...noParenthesis, ...withParenthesis] + } + const licenses = new Set() + const dependencyLicenseTexts = dependencies + .sort(({ name: _nameA }, { name: _nameB }) => { + const nameA = /** @type {string} */ (_nameA) + const nameB = /** @type {string} */ (_nameB) + return nameA > nameB ? 1 : nameB > nameA ? -1 : 0 + }) + .map( + ({ + name, + license, + licenseText, + author, + maintainers, + contributors, + repository + }) => { + let text = `## ${name}\n` + if (license) { + text += `License: ${license}\n` + } + const names = new Set() + for (const person of [author, ...maintainers, ...contributors]) { + const name = typeof person === 'string' ? person : person?.name + if (name) { + names.add(name) + } + } + if (names.size > 0) { + text += `By: ${Array.from(names).join(', ')}\n` + } + if (repository) { + text += `Repository: ${ + typeof repository === 'string' ? repository : repository.url + }\n` + } + if (!licenseText && name) { + try { + const pkgDir = path.dirname( + resolve(path.join(name, 'package.json'), { + preserveSymlinks: false + }) + ) + const licenseFile = fg.sync(`${pkgDir}/LICENSE*`, { + caseSensitiveMatch: false + })[0] + if (licenseFile) { + licenseText = fs.readFileSync(licenseFile, 'utf-8') + } + } catch {} + } + if (licenseText) { + text += + '\n' + + licenseText + .trim() + .replace(/(\r\n|\r)/gm, '\n') + .split('\n') + .map((line) => `> ${line}`) + .join('\n') + + '\n' + } + licenses.add(license) + return text + } + ) + .join('\n---------------------------------------\n\n') + const licenseText = + `# ${licenseTitle}\n` + + `${packageName} is released under the MIT license:\n\n` + + coreLicense + + `\n# Licenses of bundled dependencies\n` + + `The published ${packageName} artifact additionally contains code with the following licenses:\n` + + `${sortLicenses(licenses).join(', ')}\n\n` + + `# Bundled dependencies:\n` + + dependencyLicenseTexts + const existingLicenseText = fs.readFileSync(licenseFilePath, 'utf8') + if (existingLicenseText !== licenseText) { + fs.writeFileSync(licenseFilePath, licenseText) + console.warn( + colors.yellow( + '\nLICENSE.md updated. You should commit the updated file.\n' + ) + ) + } + } + }) +} + +export default licensePlugin