forked from t3-oss/create-t3-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
342 lines (306 loc) · 11 KB
/
index.ts
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import chalk from "chalk";
import { Command } from "commander";
import inquirer from "inquirer";
import { CREATE_T3_APP, DEFAULT_APP_NAME } from "~/consts.js";
import {
availablePackages,
type AvailablePackages,
} from "~/installers/index.js";
import { getVersion } from "~/utils/getT3Version.js";
import { getUserPkgManager } from "~/utils/getUserPkgManager.js";
import { logger } from "~/utils/logger.js";
import { validateAppName } from "~/utils/validateAppName.js";
import { validateImportAlias } from "~/utils/validateImportAlias.js";
interface CliFlags {
noGit: boolean;
noInstall: boolean;
default: boolean;
importAlias: string;
strictEslintAndPrettier: boolean;
/** @internal Used in CI. */
CI: boolean;
/** @internal Used in CI. */
tailwind: boolean;
/** @internal Used in CI. */
trpc: boolean;
/** @internal Used in CI. */
prisma: boolean;
/** @internal Used in CI. */
nextAuth: boolean;
}
interface CliResults {
appName: string;
packages: AvailablePackages[];
flags: CliFlags;
}
const defaultOptions: CliResults = {
appName: DEFAULT_APP_NAME,
packages: ["nextAuth", "prisma", "tailwind", "trpc"],
flags: {
noGit: false,
noInstall: false,
default: false,
CI: false,
tailwind: false,
trpc: false,
prisma: false,
nextAuth: false,
importAlias: "~/",
strictEslintAndPrettier: false,
},
};
export const runCli = async () => {
const cliResults = defaultOptions;
const program = new Command().name(CREATE_T3_APP);
// TODO: This doesn't return anything typesafe. Research other options?
// Emulate from: https://github.com/Schniz/soundtype-commander
program
.description("A CLI for creating web applications with the t3 stack")
.argument(
"[dir]",
"The name of the application, as well as the name of the directory to create",
)
.option(
"--noGit",
"Explicitly tell the CLI to not initialize a new git repo in the project",
false,
)
.option(
"--noInstall",
"Explicitly tell the CLI to not run the package manager's install command",
false,
)
.option(
"-y, --default",
"Bypass the CLI and use all default options to bootstrap a new t3-app",
false,
)
/** START CI-FLAGS */
/**
* @experimental Used for CI E2E tests. If any of the following option-flags are provided, we
* skip prompting.
*/
.option("--CI", "Boolean value if we're running in CI", false)
/** @experimental - Used for CI E2E tests. Used in conjunction with `--CI` to skip prompting. */
.option(
"--tailwind [boolean]",
"Experimental: Boolean value if we should install Tailwind CSS. Must be used in conjunction with `--CI`.",
(value) => !!value && value !== "false",
)
/** @experimental Used for CI E2E tests. Used in conjunction with `--CI` to skip prompting. */
.option(
"--nextAuth [boolean]",
"Experimental: Boolean value if we should install NextAuth.js. Must be used in conjunction with `--CI`.",
(value) => !!value && value !== "false",
)
/** @experimental - Used for CI E2E tests. Used in conjunction with `--CI` to skip prompting. */
.option(
"--prisma [boolean]",
"Experimental: Boolean value if we should install Prisma. Must be used in conjunction with `--CI`.",
(value) => !!value && value !== "false",
)
/** @experimental - Used for CI E2E tests. Used in conjunction with `--CI` to skip prompting. */
.option(
"--trpc [boolean]",
"Experimental: Boolean value if we should install tRPC. Must be used in conjunction with `--CI`.",
(value) => !!value && value !== "false",
)
/** @experimental - Used for CI E2E tests. Used in conjunction with `--CI` to skip prompting. */
.option(
"-i, --import-alias",
"Explicitly tell the CLI to use a custom import alias",
defaultOptions.flags.importAlias,
)
.option(
"-ep -eslint-pretteier",
"enable prettier and a strict eslint config",
defaultOptions.flags.strictEslintAndPrettier,
)
/** END CI-FLAGS */
.version(getVersion(), "-v, --version", "Display the version number")
.addHelpText(
"afterAll",
`\n The t3 stack was inspired by ${chalk
.hex("#E8DCFF")
.bold(
"@t3dotgg",
)} and has been used to build awesome fullstack applications like ${chalk
.hex("#E24A8D")
.underline("https://ping.gg")} \n`,
)
.parse(process.argv);
// FIXME: TEMPORARY WARNING WHEN USING YARN 3. SEE ISSUE #57
if (process.env.npm_config_user_agent?.startsWith("yarn/3")) {
logger.warn(` WARNING: It looks like you are using Yarn 3. This is currently not supported,
and likely to result in a crash. Please run create-t3-app with another
package manager such as pnpm, npm, or Yarn Classic.
See: https://github.com/t3-oss/create-t3-app/issues/57`);
}
// Needs to be separated outside the if statement to correctly infer the type as string | undefined
const cliProvidedName = program.args[0];
if (cliProvidedName) {
cliResults.appName = cliProvidedName;
}
cliResults.flags = program.opts();
/** @internal Used for CI E2E tests. */
let CIMode = false;
if (cliResults.flags.CI) {
CIMode = true;
cliResults.packages = [];
if (cliResults.flags.trpc) cliResults.packages.push("trpc");
if (cliResults.flags.tailwind) cliResults.packages.push("tailwind");
if (cliResults.flags.prisma) cliResults.packages.push("prisma");
if (cliResults.flags.nextAuth) cliResults.packages.push("nextAuth");
if (cliResults.flags.strictEslintAndPrettier)
cliResults.packages.push("strictEslintAndPrettier");
}
// Explained below why this is in a try/catch block
try {
if (process.env.TERM_PROGRAM?.toLowerCase().includes("mintty")) {
logger.warn(` WARNING: It looks like you are using MinTTY, which is non-interactive. This is most likely because you are
using Git Bash. If that's that case, please use Git Bash from another terminal, such as Windows Terminal. Alternatively, you
can provide the arguments from the CLI directly: https://create.t3.gg/en/installation#experimental-usage to skip the prompts.`);
const error = new Error("Non-interactive environment");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error as any).isTTYError = true;
throw error;
}
// if --CI flag is set, we are running in CI mode and should not prompt the user
// if --default flag is set, we should not prompt the user
if (!cliResults.flags.default && !CIMode) {
if (!cliProvidedName) {
cliResults.appName = await promptAppName();
}
await promptLanguage();
cliResults.packages = await promptPackages();
if (!cliResults.flags.noGit) {
cliResults.flags.noGit = !(await promptGit());
}
if (!cliResults.flags.noInstall) {
cliResults.flags.noInstall = !(await promptInstall());
}
cliResults.flags.importAlias = await promptImportAlias();
}
} catch (err) {
// If the user is not calling create-t3-app from an interactive terminal, inquirer will throw an error with isTTYError = true
// If this happens, we catch the error, tell the user what has happened, and then continue to run the program with a default t3 app
// Otherwise we have to do some fancy namespace extension logic on the Error type which feels overkill for one line
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (err instanceof Error && (err as any).isTTYError) {
logger.warn(`
${CREATE_T3_APP} needs an interactive terminal to provide options`);
const { shouldContinue } = await inquirer.prompt<{
shouldContinue: boolean;
}>({
name: "shouldContinue",
type: "confirm",
message: `Continue scaffolding a default T3 app?`,
default: true,
});
if (!shouldContinue) {
logger.info("Exiting...");
process.exit(0);
}
logger.info(`Bootstrapping a default T3 app in ./${cliResults.appName}`);
} else {
throw err;
}
}
return cliResults;
};
const promptAppName = async (): Promise<string> => {
const { appName } = await inquirer.prompt<Pick<CliResults, "appName">>({
name: "appName",
type: "input",
message: "What will your project be called?",
default: defaultOptions.appName,
validate: validateAppName,
transformer: (input: string) => {
return input.trim();
},
});
return appName;
};
const promptLanguage = async (): Promise<void> => {
const { language } = await inquirer.prompt<{ language: string }>({
name: "language",
type: "list",
message: "Will you be using TypeScript or JavaScript?",
choices: [
{ name: "TypeScript", value: "typescript", short: "TypeScript" },
{ name: "JavaScript", value: "javascript", short: "JavaScript" },
],
default: "typescript",
});
if (language === "javascript") {
logger.error("Wrong answer, using TypeScript instead...");
} else {
logger.success("Good choice! Using TypeScript!");
}
};
const promptPackages = async (): Promise<AvailablePackages[]> => {
const { packages } = await inquirer.prompt<Pick<CliResults, "packages">>({
name: "packages",
type: "checkbox",
message: "Which packages would you like to enable?",
choices: availablePackages
.filter((pkg) => pkg !== "envVariables") // don't prompt for env-vars
.map((pkgName) => ({
name: pkgName,
checked: false,
})),
});
return packages;
};
const promptGit = async (): Promise<boolean> => {
const { git } = await inquirer.prompt<{ git: boolean }>({
name: "git",
type: "confirm",
message: "Initialize a new git repository?",
default: true,
});
if (git) {
logger.success("Nice one! Initializing repository!");
} else {
logger.info("Sounds good! You can come back and run git init later.");
}
return git;
};
const promptInstall = async (): Promise<boolean> => {
const pkgManager = getUserPkgManager();
const { install } = await inquirer.prompt<{ install: boolean }>({
name: "install",
type: "confirm",
message:
`Would you like us to run '${pkgManager}` +
(pkgManager === "yarn" ? `'?` : ` install'?`),
default: true,
});
if (install) {
logger.success("Alright. We'll install the dependencies for you!");
} else {
if (pkgManager === "yarn") {
logger.info(
`No worries. You can run '${pkgManager}' later to install the dependencies.`,
);
} else {
logger.info(
`No worries. You can run '${pkgManager} install' later to install the dependencies.`,
);
}
}
return install;
};
const promptImportAlias = async (): Promise<string> => {
const { importAlias } = await inquirer.prompt<Pick<CliFlags, "importAlias">>({
name: "importAlias",
type: "input",
message: "What import alias would you like configured?",
default: defaultOptions.flags.importAlias,
validate: validateImportAlias,
transformer: (input: string) => {
return input.trim();
},
});
return importAlias;
};