-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathinitialize.ts
More file actions
375 lines (306 loc) · 10.3 KB
/
Copy pathinitialize.ts
File metadata and controls
375 lines (306 loc) · 10.3 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import { copyFile, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
cancel,
intro,
isCancel,
log,
outro,
select,
spinner,
text,
} from "@clack/prompts";
import {
detectPackageManager,
installDependencies as nypmInstallDependencies,
type PackageManagerName,
} from "nypm";
import {
internalContentDirs,
internalContentFiles,
run,
url,
} from "./utils.js";
const supportedPackageManagers: PackageManagerName[] = [
"bun",
"npm",
"yarn",
"pnpm",
];
const cloneNextForge = (
name: string,
packageManager: PackageManagerName,
branch?: string
) => {
const exampleUrl = branch ? `${url}/tree/${branch}` : url;
run("npx", [
"create-next-app@latest",
name,
"--example",
exampleUrl,
"--disable-git",
"--skip-install",
`--use-${packageManager}`,
]);
};
const deleteInternalContent = async () => {
for (const folder of internalContentDirs) {
await rm(folder, { recursive: true, force: true });
}
for (const file of internalContentFiles) {
await rm(file, { force: true });
}
};
const installDependencies = async (packageManager: PackageManagerName) => {
await nypmInstallDependencies({
packageManager: { name: packageManager, command: packageManager },
silent: true,
});
};
const initializeGit = () => {
run("git", ["init"]);
run("git", ["add", "."]);
run("git", ["commit", "-m", "✨ Initial commit"]);
};
const setupEnvironmentVariables = async () => {
const files = [
{ source: join("apps", "api"), target: ".env.local" },
{ source: join("apps", "app"), target: ".env.local" },
{ source: join("apps", "web"), target: ".env.local" },
{ source: join("packages", "cms"), target: ".env.local" },
{ source: join("packages", "database"), target: ".env" },
{ source: join("packages", "internationalization"), target: ".env.local" },
];
for (const { source, target } of files) {
await copyFile(join(source, ".env.example"), join(source, target));
}
};
const setupOrm = (packageManager: PackageManagerName) => {
const filterCommand = packageManager === "npm" ? "--workspace" : "--filter";
run(packageManager, ["run", "build", filterCommand, "@repo/database"]);
};
const updatePackageManagerConfiguration = async (
projectDir: string,
packageManager: PackageManagerName
) => {
const packageJsonPath = join(projectDir, "package.json");
const packageJsonFile = await readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonFile);
if (packageManager === "pnpm") {
packageJson.packageManager = "pnpm@10.31.0";
} else if (packageManager === "npm") {
packageJson.packageManager = "npm@10.8.1";
} else if (packageManager === "yarn") {
packageJson.packageManager = "yarn@1.22.22";
}
const newPackageJson = JSON.stringify(packageJson, null, 2);
await writeFile(packageJsonPath, `${newPackageJson}\n`);
};
// Package managers whose scripts the template needs rewriting for, mapped to
// their "download and execute" command (the equivalent of `bunx`). Bun is the
// template default and so is intentionally absent.
const dlxCommands: Partial<Record<PackageManagerName, string>> = {
npm: "npx",
pnpm: "pnpm dlx",
// Yarn is pinned to Classic (1.22.x) in updatePackageManagerConfiguration, which has no
// `dlx` subcommand (introduced in Yarn 2/Berry). `npx` is the Yarn Classic equivalent of `bunx`.
yarn: "npx",
};
// The template ships bun-specific scripts (`bun --bun next ...`, `bunx ...`,
// `bun install`). When another package manager is selected they must be
// rewritten to that manager's equivalents, otherwise the generated project's
// scripts only work if bun is installed. See issue #733.
const rewriteBunScripts = (
scripts: Record<string, string>,
packageManager: PackageManagerName,
dlx: string
): Record<string, string> => {
const rewritten: Record<string, string> = {};
for (const [name, command] of Object.entries(scripts)) {
rewritten[name] = command
// `bun --bun next ...` runs Next.js through bun's runtime; drop the
// prefix so the selected package manager runs it directly.
.replaceAll("bun --bun ", "")
// `bunx <pkg>` -> the selected manager's "download and execute" command.
.replaceAll("bunx ", `${dlx} `)
// `bun install` -> `<pm> install`.
.replaceAll("bun install", `${packageManager} install`);
}
return rewritten;
};
const updatePackageJsonScripts = async (
path: string,
packageManager: PackageManagerName,
dlx: string
) => {
const pkgJsonFile = await readFile(path, "utf8");
const pkgJson = JSON.parse(pkgJsonFile);
if (!pkgJson.scripts) {
return;
}
pkgJson.scripts = rewriteBunScripts(pkgJson.scripts, packageManager, dlx);
await writeFile(path, `${JSON.stringify(pkgJson, null, 2)}\n`);
};
const updatePackageManagerScripts = async (
projectDir: string,
packageManager: PackageManagerName
) => {
const dlx = dlxCommands[packageManager];
// No rewrite needed for managers that share bun's defaults (e.g. bun itself).
if (!dlx) {
return;
}
const scriptPackageJsons = [
join(projectDir, "package.json"),
join(projectDir, "apps", "app", "package.json"),
join(projectDir, "apps", "web", "package.json"),
join(projectDir, "apps", "api", "package.json"),
];
for (const path of scriptPackageJsons) {
await updatePackageJsonScripts(path, packageManager, dlx);
}
};
const updateWorkspaceConfiguration = async (
projectDir: string,
packageManager: PackageManagerName
) => {
const packageJsonPath = join(projectDir, "package.json");
const packageJsonFile = await readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonFile);
if (packageManager === "pnpm") {
packageJson.workspaces = undefined;
const pnpmWorkspace = "packages:\n - 'apps/*'\n - 'packages/*'\n";
await writeFile(join(projectDir, "pnpm-workspace.yaml"), pnpmWorkspace);
}
const newPackageJson = JSON.stringify(packageJson, null, 2);
await writeFile(packageJsonPath, `${newPackageJson}\n`);
await rm("bun.lock", { force: true });
};
const updateInternalPackageDependencies = async (path: string) => {
const pkgJsonFile = await readFile(path, "utf8");
const pkgJson = JSON.parse(pkgJsonFile);
if (pkgJson.dependencies) {
const entries = Object.entries(pkgJson.dependencies);
for (const [dep, version] of entries) {
if (version === "workspace:*") {
pkgJson.dependencies[dep] = "*";
}
}
}
if (pkgJson.devDependencies) {
const entries = Object.entries(pkgJson.devDependencies);
for (const [dep, version] of entries) {
if (version === "workspace:*") {
pkgJson.devDependencies[dep] = "*";
}
}
}
const newPkgJson = JSON.stringify(pkgJson, null, 2);
await writeFile(path, `${newPkgJson}\n`);
};
const updateInternalDependencies = async (projectDir: string) => {
const rootPackageJsonPath = join(projectDir, "package.json");
await updateInternalPackageDependencies(rootPackageJsonPath);
const workspaceDirs = ["apps", "packages"];
for (const dir of workspaceDirs) {
const dirPath = join(projectDir, dir);
const packages = await readdir(dirPath);
for (const pkg of packages) {
const path = join(dirPath, pkg, "package.json");
await updateInternalPackageDependencies(path);
}
}
};
const getName = async () => {
const value = await text({
message: "What is your project named?",
placeholder: "my-app",
validate(value: string) {
if (value.length === 0) {
return "Please enter a project name.";
}
},
});
if (isCancel(value)) {
cancel("Operation cancelled.");
process.exit(0);
}
return value.toString();
};
const getPackageManager = async (): Promise<PackageManagerName> => {
const detected = await detectPackageManager(process.cwd());
if (detected) {
return detected.name;
}
const value = await select({
message: "Which package manager would you like to use?",
options: supportedPackageManagers.map((choice) => ({
value: choice,
label: choice,
})),
initialValue: "bun" as PackageManagerName,
});
if (isCancel(value)) {
cancel("Operation cancelled.");
process.exit(0);
}
return value as PackageManagerName;
};
export const initialize = async (options: {
name?: string;
packageManager?: PackageManagerName;
disableGit?: boolean;
branch?: string;
}) => {
try {
intro("Let's start a next-forge project!");
const cwd = process.cwd();
const name = options.name || (await getName());
const packageManager =
options.packageManager || (await getPackageManager());
if (!supportedPackageManagers.includes(packageManager)) {
throw new Error("Invalid package manager");
}
const s = spinner();
const projectDir = join(cwd, name);
s.start("Cloning next-forge...");
cloneNextForge(name, packageManager, options.branch);
s.message("Moving into repository...");
process.chdir(projectDir);
if (packageManager !== "bun") {
s.message("Updating package manager configuration...");
await updatePackageManagerConfiguration(projectDir, packageManager);
s.message("Updating package manager scripts...");
await updatePackageManagerScripts(projectDir, packageManager);
s.message("Updating workspace config...");
await updateWorkspaceConfiguration(projectDir, packageManager);
if (packageManager !== "pnpm") {
s.message("Updating workspace dependencies...");
await updateInternalDependencies(projectDir);
}
}
s.message("Setting up environment variable files...");
await setupEnvironmentVariables();
s.message("Deleting internal content...");
await deleteInternalContent();
s.message("Installing dependencies...");
await installDependencies(packageManager);
s.message("Setting up ORM...");
setupOrm(packageManager);
if (!options.disableGit) {
s.message("Initializing Git repository...");
initializeGit();
}
s.stop("Project initialized successfully!");
outro(
"Please make sure you install the Mintlify CLI and Stripe CLI before starting the project."
);
} catch (error) {
const message =
error instanceof Error
? error.message
: `Failed to initialize project: ${error}`;
log.error(message);
process.exit(1);
}
};