forked from chromeos/create-vite-pwa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
262 lines (234 loc) · 6.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#!/usr/bin/env node
/**
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const inquirer = require("inquirer");
const chalk = require("chalk");
const {
emptyDirSync,
ensureDirSync,
copySync,
moveSync,
writeJsonSync,
} = require("fs-extra");
const argv = require("minimist")(process.argv.slice(2), {
string: ["_"],
boolean: true,
});
const posthtml = require("posthtml");
const fs = require("fs");
const path = require("path");
// Add Search List as prompt type
inquirer.registerPrompt("search-list", require("inquirer-search-list"));
// Set up frameworks and colors
const frameworks = Object.entries({
vanilla: "yellow",
vue: "green",
react: "cyan",
preact: "magenta",
"lit-element": "blue",
svelte: "red",
}).map(([name, color]) => ({
name: chalk[color](name),
value: name,
color,
}));
// Get default args
let targetDir = argv._[0];
let framework = argv.f;
let typescript = argv.ts;
let overwrite = argv.overwrite;
const defaultProjectName = !targetDir ? "vite-pwa" : targetDir;
if (argv.js) {
typescript = false;
}
if (targetDir === undefined) {
overwrite = false;
}
// Start the inquisition!
inquirer
.prompt([
{
type: "input",
name: "dir",
message: "Project name:",
default: defaultProjectName,
when: () => defaultProjectName === "vite-pwa",
},
{
type: "confirm",
name: "overwrite",
default: false,
message: ({ dir }) =>
(dir === "."
? "Current directory"
: `Target directory "${dir || targetDir}"`) +
" is not empty. Remove existing files and continue?",
when: ({ dir }) => !isEmpty(dir) && overwrite !== true,
},
{
type: "input",
name: "package",
message: "Package name:",
default: ({ dir }) =>
dir ? toValidPackageName(dir) : toValidPackageName(targetDir),
validate: (package) =>
isValidPackageName(package) ? true : "Invalid package name",
when: (answers) =>
continuePrompts(answers) &&
(answers.dir
? !isValidPackageName(answers.dir)
: !isValidPackageName(targetDir)),
},
{
type: "search-list",
name: "framework",
message: "Select a framework:",
default: () =>
framework
? isAvailableFramework(framework)?.value
: frameworks[0].value,
choices: frameworks,
when: (answers) =>
continuePrompts(answers) &&
(framework ? !isAvailableFramework(framework) : true),
},
{
type: "confirm",
name: "typescript",
default: typescript === undefined ? false : true,
message: "Use TypeScript?",
when: continuePrompts && typescript === undefined,
},
])
.then((answers) => {
if (continuePrompts(answers) === false) {
throw new Error(chalk.red("✖") + " Operation cancelled");
}
const options = Object.assign(
{
dir: targetDir,
framework: framework ? framework.toLowerCase() : "",
package: targetDir,
typescript,
overwrite,
},
Object.assign({ package: answers.dir }, answers)
);
// Processing files
const cwd = process.cwd();
const createViteDir = path.dirname(require.resolve("create-vite"));
const renameFiles = {
_gitignore: ".gitignore",
};
const root = path.join(cwd, options.dir);
if (options.overwrite) {
emptyDirSync(root);
} else {
ensureDirSync(root);
}
const { color } = isAvailableFramework(options.framework);
console.log(
`\nScaffolding ${chalk[color](options.framework)} project${
options.typescript ? chalk.bold(" with TypeScript") : ""
} in:\n${root}`
);
const template = options.framework + (options.typescript ? "-ts" : "");
// Copy files in
copySync(path.join(createViteDir, `template-${template}`), root);
copySync(path.join(__dirname, "templates"), root);
for (const [oldName, newName] of Object.entries(renameFiles)) {
moveSync(path.join(root, oldName), path.join(root, newName));
}
// Update package file
const pkg = require(path.join(root, "package.json"));
pkg.name = options.package;
writeJsonSync(
path.join(root, "package.json"),
require("./lib/update-package")(pkg, options.typescript),
{ spaces: 2 }
);
// Update index.html to include PWA stuff
const indexHTML = fs.readFileSync(path.join(root, "index.html"), "utf-8");
const updatedHTML = posthtml()
.use(require("./lib/posthtml-add-pwa.js")())
.process(indexHTML, { sync: true }).html;
fs.writeFileSync(path.join(root, "index.html"), updatedHTML);
// Update Vite Config
require("./lib/update-vite-config")(root, options.typescript);
// Close out
const pkgManager = getPkgManager();
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();
})
.catch((e) => {
console.error(e.message);
});
// Prompt Helper Functions
function continuePrompts({ dir, overwrite }) {
if (
!(
fs.existsSync(dir || targetDir) &&
fs.readdirSync(dir || targetDir).length === 0
) &&
overwrite === false
) {
return false;
}
return true;
}
function isEmpty(dir) {
if (!fs.existsSync(dir || targetDir)) return true;
return fs.readdirSync(dir || targetDir).length === 0;
}
function isValidPackageName(projectName) {
return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(
projectName
);
}
function toValidPackageName(projectName) {
return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/^[._]/, "")
.replace(/[^a-z0-9-~]+/g, "-");
}
function isAvailableFramework(fr) {
return frameworks.find((f) => f.value === fr.toLowerCase());
}
/**
* @param {string | undefined} userAgent process.env.npm_config_user_agent
* @returns object | undefined
*/
function getPkgManager(userAgent = process.env.npm_config_user_agent) {
if (!userAgent) return "npm";
const pkgSpec = userAgent.split(" ")[0];
const pkgSpecArr = pkgSpec.split("/");
return pkgSpecArr[0] || "npm";
}