forked from sveltejs/kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin.js
executable file
·277 lines (235 loc) · 6.8 KB
/
bin.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { bold, cyan, gray, green, red } from 'kleur/colors';
import prompts from 'prompts';
import { mkdirp, copy } from './utils.js';
// prettier-ignore
const disclaimer = `
${bold(cyan('Welcome to SvelteKit!'))}
${bold(red('This is beta software; expect bugs and missing features.'))}
If you encounter a problem, open an issue on ${cyan('https://github.com/sveltejs/kit/issues')} if none exists already.
`;
const { version } = JSON.parse(fs.readFileSync(new URL('package.json', import.meta.url), 'utf-8'));
async function main() {
console.log(gray(`\ncreate-svelte version ${version}`));
console.log(disclaimer);
const cwd = process.argv[2] || '.';
if (fs.existsSync(cwd)) {
if (fs.readdirSync(cwd).length > 0) {
const response = await prompts({
type: 'confirm',
name: 'value',
message: 'Directory not empty. Continue?',
initial: false
});
if (!response.value) {
process.exit(1);
}
}
} else {
mkdirp(cwd);
}
const options = /** @type {import('./types/internal').Options} */ (
await prompts([
{
type: 'select',
name: 'template',
message: 'Which Svelte app template?',
choices: fs.readdirSync(dist('templates')).map((dir) => {
const meta_file = dist(`templates/${dir}/meta.json`);
const meta = JSON.parse(fs.readFileSync(meta_file, 'utf8'));
return {
title: meta.description,
value: dir
};
})
},
{
type: 'toggle',
name: 'typescript',
message: 'Use TypeScript?',
initial: false,
active: 'Yes',
inactive: 'No'
},
{
type: 'toggle',
name: 'eslint',
message: 'Add ESLint for code linting?',
initial: false,
active: 'Yes',
inactive: 'No'
},
{
type: 'toggle',
name: 'prettier',
message: 'Add Prettier for code formatting?',
initial: false,
active: 'Yes',
inactive: 'No'
}
])
);
const name = path.basename(path.resolve(cwd));
write_template_files(options.template, options.typescript, name, cwd);
write_common_files(cwd, options, name);
console.log(bold(green('✔ Copied project files')));
if (options.typescript) {
console.log(
bold(
green(
'✔ Added TypeScript support. ' +
'To use it inside Svelte components, add lang="ts" to the attributes of a script tag.'
)
)
);
}
if (options.eslint) {
console.log(
bold(
green(
'✔ Added ESLint.\n' +
'Readme for ESLint and Svelte: https://github.com/sveltejs/eslint-plugin-svelte3'
)
)
);
}
if (options.prettier) {
console.log(
bold(
green(
'✔ Added Prettier.\n' +
'General formatting options: https://prettier.io/docs/en/options.html\n' +
'Svelte-specific formatting options: https://github.com/sveltejs/prettier-plugin-svelte#options'
)
)
);
}
console.log(
'\nWant to add other parts to your code base? ' +
'Visit https://github.com/svelte-add/svelte-adders, a community project of commands ' +
'to add particular functionality to Svelte projects\n'
);
console.log('\nNext steps:');
let i = 1;
const relative = path.relative(process.cwd(), cwd);
if (relative !== '') {
console.log(` ${i++}: ${bold(cyan(`cd ${relative}`))}`);
}
console.log(` ${i++}: ${bold(cyan('npm install'))} (or pnpm install, etc)`);
// prettier-ignore
console.log(` ${i++}: ${bold(cyan('git init && git add -A && git commit -m "Initial commit"'))} (optional step)`);
console.log(` ${i++}: ${bold(cyan('npm run dev -- --open'))}`);
console.log(`\nTo close the dev server, hit ${bold(cyan('Ctrl-C'))}`);
console.log('\nStuck? Visit us at https://svelte.dev/chat\n');
}
/**
* @param {string} template
* @param {boolean} typescript
* @param {string} name
* @param {string} cwd
*/
function write_template_files(template, typescript, name, cwd) {
const dir = dist(`templates/${template}`);
copy(`${dir}/assets`, cwd, (name) => name.replace('gitignore', '.gitignore'));
copy(`${dir}/package.json`, `${cwd}/package.json`);
const manifest = `${dir}/files.${typescript ? 'ts' : 'js'}.json`;
const files = /** @type {import('./types/internal').File[]} */ (
JSON.parse(fs.readFileSync(manifest, 'utf-8'))
);
files.forEach((file) => {
const dest = path.join(cwd, file.name);
mkdirp(path.dirname(dest));
fs.writeFileSync(dest, file.contents.replace(/~TODO~/g, name));
});
}
/**
*
* @param {string} cwd
* @param {import('./types/internal').Options} options
* @param {string} name
*/
function write_common_files(cwd, options, name) {
const shared = dist('shared.json');
const { files } = /** @type {import('./types/internal').Common} */ (
JSON.parse(fs.readFileSync(shared, 'utf-8'))
);
const pkg_file = path.join(cwd, 'package.json');
const pkg = /** @type {any} */ (JSON.parse(fs.readFileSync(pkg_file, 'utf-8')));
files.forEach((file) => {
const include = file.include.every((condition) => matchesCondition(condition, options));
const exclude = file.exclude.some((condition) => matchesCondition(condition, options));
if (exclude || !include) return;
if (file.name === 'package.json') {
const new_pkg = JSON.parse(file.contents);
merge(pkg, new_pkg);
} else {
const dest = path.join(cwd, file.name);
mkdirp(path.dirname(dest));
fs.writeFileSync(dest, file.contents);
}
});
pkg.dependencies = sort_keys(pkg.dependencies);
pkg.devDependencies = sort_keys(pkg.devDependencies);
pkg.name = toValidPackageName(name);
fs.writeFileSync(pkg_file, JSON.stringify(pkg, null, ' '));
}
/**
* @param {import('./types/internal').Condition} condition
* @param {import('./types/internal').Options} options
* @returns {boolean}
*/
function matchesCondition(condition, options) {
return condition === 'default' || condition === 'skeleton'
? options.template === condition
: options[condition];
}
/**
* @param {any} target
* @param {any} source
*/
function merge(target, source) {
for (const key in source) {
if (key in target) {
const target_value = target[key];
const source_value = source[key];
if (
typeof source_value !== typeof target_value ||
Array.isArray(source_value) !== Array.isArray(target_value)
) {
throw new Error('Mismatched values');
}
merge(target_value, source_value);
} else {
target[key] = source[key];
}
}
}
/** @param {Record<string, any>} obj */
function sort_keys(obj) {
if (!obj) return;
/** @type {Record<string, any>} */
const sorted = {};
Object.keys(obj)
.sort()
.forEach((key) => {
sorted[key] = obj[key];
});
return sorted;
}
/** @param {string} path */
function dist(path) {
return fileURLToPath(new URL(`./dist/${path}`, import.meta.url).href);
}
/** @param {string} name */
function toValidPackageName(name) {
return name
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z0-9~.-]+/g, '-');
}
main();