Repository navigation
Expand file tree
/
Copy pathinstaller.ts
More file actions
629 lines (573 loc) · 17.4 KB
/
Copy pathinstaller.ts
File metadata and controls
629 lines (573 loc) · 17.4 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
import lodash from "lodash";
const { isEmpty } = lodash;
import path from "path";
import fs from "fs";
import pc from "picocolors";
import os from "os";
import semver from "semver";
import { execFileSync } from "child_process";
// Use dynamic import for simple-git to avoid bundlers injecting unsupported dynamic requires in ESM
import type { SimpleGit, SimpleGitOptions } from "simple-git";
import {
shouldUseYarn,
checkThatNpmCanReadCwd,
checkNpmVersion,
checkIfOnline,
shouldUsePnpm,
shouldUseBun,
} from "./helpers.js";
import { loadPackages } from "./package.js";
import type { TemplateOrExtension } from "./loaders.js";
import { loadFiles } from "./loaders.js";
import { resolveExecutable } from "./executable.js";
import { assertDirectoryIsEmpty } from "./config.js";
import { ScaffoldAbortedError } from "./errors.js";
/**
* Print a one-line step indicator during scaffolding so users can tell the
* CLI is making progress through long silent phases (resolve, copy).
* Uses picocolors (already a dependency) — no spinner library needed.
*/
export const logStep = (message: string) => {
console.log(pc.cyan(`${message}...`));
};
const install = async (
root: string,
useYarn = false,
usePnpm = false,
useBun = false,
dependencies: string[] = [],
verbose = false,
isOnline = true,
isDevDependencies = false,
) => {
let command: string;
let args: string[];
if (useYarn) {
command = "yarnpkg";
args = ["add", "--ignore-workspace-root-check"];
if (!isOnline) {
args.push("--offline");
}
if (isDevDependencies) {
args.push("--dev");
}
args.push(...dependencies);
args.push("--cwd");
args.push(root);
if (!isOnline) {
console.log(pc.yellow("You appear to be offline."));
console.log(pc.yellow("Falling back to the local Yarn cache."));
console.log();
}
} else if (usePnpm) {
command = "pnpm";
args = ["install", "--ignore-workspace", "--loglevel", "error"];
if (isDevDependencies) {
args.push("--save-dev");
} else {
args.push("--save");
}
args.push(...dependencies);
} else if (useBun) {
command = "bun";
if (dependencies.length > 0) {
args = ["add"];
if (isDevDependencies) {
args.push("--dev");
}
args.push(...dependencies);
} else {
args = ["install"];
}
} else {
command = "npm";
args = ["install", "--loglevel", "error"];
if (isDevDependencies) {
args.push("--save-dev");
} else {
args.push("--save");
}
args.push(...dependencies);
}
if (verbose) {
args.push("--verbose");
}
try {
execFileSync(resolveExecutable(command), args, {
cwd: root,
stdio: "inherit",
});
} catch {
throw new Error(buildInstallFailureMessage(command, args, usePnpm));
}
};
export const buildInstallFailureMessage = (
command: string,
args: string[],
usePnpm = false,
) => {
if (usePnpm) {
return (
`${command} ${args.join(" ")}\n` +
"If pnpm reports ERR_PNPM_IGNORED_BUILDS, run `pnpm approve-builds` inside the generated project and retry your install command."
);
}
return `${command} ${args.join(" ")}`;
};
export type RunOptions = {
root: string;
appName: string;
originalDirectory: string;
verbose?: boolean;
useYarn?: boolean;
usePnpm?: boolean;
useBun?: boolean;
templatesOrExtensions?: TemplateOrExtension[];
dependencies?: string[];
devDependencies?: string[];
installDependencies?: boolean;
runCommand: string;
installCommand: string;
offline?: boolean;
cacheDir?: string;
refresh?: import("./git.js").RefreshMode;
refreshAfterHours?: number;
} & {
[key: string]: unknown;
};
const runCommandInProjectDir = async (
root: string,
command: string,
args: string[] = [],
successMessage = "Operation completed successfully.",
errorMessage = "Operation failed.",
) => {
const [executable, ...baseArgs] =
command === "npm run"
? ["npm", "run"]
: command === "pnpm run"
? ["pnpm", "run"]
: command === "bun run"
? ["bun", "run"]
: [command];
try {
execFileSync(resolveExecutable(executable), [...baseArgs, ...args], {
cwd: root,
stdio: "ignore",
});
console.log(pc.green(successMessage));
} catch {
console.log();
console.log(pc.red(errorMessage));
console.log();
process.exitCode = 1;
}
};
export function extractNameAndVersion(dependencyString: string) {
// extract the name and version from the dependency string separated by @
// e.g. @types/react@^16
// => name: @types/react
// => version: ^16
// e.g. react@^16
// => name: react
// => version: ^16
// Find the last "@" symbol to split the string
const lastIndex = dependencyString.lastIndexOf("@");
if (lastIndex !== -1) {
// Split the string into name and version parts
const name = dependencyString.substring(0, lastIndex); // Name
const version = dependencyString.substring(lastIndex + 1); // Version
return { name, version };
} else {
// If "@" is not present, treat the whole string as the name
return { name: dependencyString, version: "" };
}
}
/**
* Executes the full app creation pipeline - scaffolding, dependency
* installation, and git initialization - inside the target project directory.
*
* @param options Run options (see {@link RunOptions})
* @param options.root Absolute path to the app directory
* @param options.appName App name (basename of the directory)
* @param options.originalDirectory CWD at the time `createApp` was called
* @param [options.verbose] Enable verbose output from the package manager (default: `false`)
* @param [options.useYarn] Use Yarn as the package manager (default: `false`)
* @param [options.usePnpm] Use pnpm as the package manager (default: `false`)
* @param [options.useBun] Use Bun as the package manager (default: `false`)
* @param [options.templatesOrExtensions] Templates or extensions to apply
* @param [options.dependencies] Production dependencies to install
* @param [options.devDependencies] Development dependencies to install
* @param [options.installDependencies] Whether to install dependencies automatically (default: `true`)
* @param options.runCommand Script run command (e.g. `"npm run"`, `"yarn"`)
* @param options.installCommand Dependency install command (e.g. `"npm install"`)
* @param [options.offline] Run in offline mode
* @param [options.cacheDir] Path to the cache directory
* @param [options.refresh] Git cache refresh mode
* @param [options.refreshAfterHours] Cache refresh interval in hours
*/
const run = async ({
root,
appName,
originalDirectory,
verbose = false,
useYarn = false,
usePnpm = false,
useBun = false,
templatesOrExtensions = [],
dependencies = [],
devDependencies = [],
installDependencies = true,
runCommand = "",
installCommand = "",
offline,
cacheDir,
refresh,
refreshAfterHours,
...customOptions
}: RunOptions) => {
const isOnline = useYarn ? await checkIfOnline(useYarn) : true;
if (isEmpty(templatesOrExtensions)) {
console.log();
console.log(
pc.yellow(
"No templates or extensions specified to bootstrap application.",
),
);
console.log();
process.exit(0);
}
console.log();
console.log("Scaffolding project in " + root + "...");
logStep("Copying files");
await loadFiles({
root,
templatesOrExtensions,
appName,
originalDirectory,
verbose,
useYarn,
usePnpm,
useBun,
runCommand,
installCommand,
...(offline !== undefined ? { offline } : {}),
...(cacheDir !== undefined ? { cacheDir } : {}),
...(refresh !== undefined ? { refresh } : {}),
...(refreshAfterHours !== undefined ? { refreshAfterHours } : {}),
...customOptions,
});
console.log();
console.log(pc.green("Successfully scaffolded project."));
console.log();
if (installDependencies) {
console.log(
pc.green("Installing packages. This might take a couple of minutes."),
);
console.log(pc.green("Installing dependencies..."));
console.log();
// Install dependencies
await install(
root,
useYarn,
usePnpm,
useBun,
dependencies,
verbose,
isOnline,
false,
);
if (devDependencies.length > 0) {
console.log();
console.log(pc.green("Installing devDependencies..."));
console.log();
// Install devDependencies
await install(
root,
useYarn,
usePnpm,
useBun,
devDependencies,
verbose,
isOnline,
true,
);
}
} else {
console.log(pc.yellow("Skip package installation."));
const packageJson = JSON.parse(
fs.readFileSync(`${root}/package.json`, "utf8"),
);
const updateDependencies = (deps: string[]) => {
return deps.reduce(
(dep, elem) => {
const nextDep = dep;
const lastAt = elem.lastIndexOf("@");
if (
lastAt > 0 &&
/^[\^~]?[0-9a-zA-Z.-]+$/.test(elem.slice(lastAt + 1))
) {
const { name, version } = extractNameAndVersion(elem);
nextDep[name] = version;
} else {
nextDep[elem] = "*";
}
return nextDep;
},
{} as { [key: string]: string },
);
};
packageJson.dependencies = updateDependencies(dependencies);
packageJson.devDependencies = updateDependencies(devDependencies);
fs.writeFileSync(
path.join(root, "package.json"),
JSON.stringify(packageJson, null, 2) + os.EOL,
);
console.log();
console.log(pc.green("Successfully updated package.json."));
console.log(pc.yellow(`Run ${pc.cyan(installCommand)} to install.`));
}
console.log();
console.log("Initializing git repository...");
try {
const { simpleGit } = (await import("simple-git")) as unknown as {
simpleGit: (
baseDir?: string,
options?: Partial<SimpleGitOptions>,
) => SimpleGit;
};
const git = simpleGit(root);
await git.init();
console.log(pc.green("Successfully initialized git repository."));
} catch {
console.log();
console.log(
pc.red(
"Failed to initialize git repository. Run `git init` to initialize git repository after the process is completed.",
),
);
console.log();
process.exitCode = 1;
}
if (installDependencies && isOnline) {
const packageJson = JSON.parse(
fs.readFileSync(`${root}/package.json`, "utf8"),
);
const runFormat = async () => {
try {
await runCommandInProjectDir(
root,
runCommand,
["format"],
"Successfully formatted code.",
`Failed to format code. Run \`${runCommand} format\` to format code after the process is completed.`,
);
} catch {
// ignore
}
};
const runLintFix = async () => {
try {
await runCommandInProjectDir(
root,
runCommand,
["lint:fix"],
"Successfully fixed linting errors.",
`Failed to fix linting errors. Run \`${runCommand} lint:fix\` to fix linting errors after the process is completed.`,
);
} catch {
// ignore
}
};
if (packageJson.scripts && packageJson.scripts["format"]) {
await runFormat();
}
if (packageJson.scripts && packageJson.scripts["lint:fix"]) {
await runLintFix();
}
}
// Print out instructions
console.log();
console.log(pc.green("Successfully created project " + appName + "."));
console.log();
console.log("Done! Now run:");
console.log();
console.log(pc.cyan(` cd ${appName}`));
console.log(pc.cyan(` ${installCommand}`));
const packageJson = JSON.parse(
fs.readFileSync(`${root}/package.json`, "utf8"),
);
const lookForScripts = ["compose:up", "sls:offline", "dev", "start"];
for (const script of lookForScripts) {
if (packageJson.scripts && packageJson.scripts[script]) {
console.log(pc.cyan(` ${runCommand} ${script}`));
break;
}
}
console.log();
console.log(pc.green("Happy hacking!"));
};
export type CreateAppOptions = {
name: string;
verbose?: boolean;
force?: boolean;
packageManager?: string;
templatesOrExtensions?: TemplateOrExtension[];
installDependencies?: boolean;
ignorePackage?: boolean;
offline?: boolean;
cacheDir?: string;
refresh?: import("./git.js").RefreshMode;
refreshAfterHours?: number;
} & {
[key: string]: unknown;
};
/**
* Entry point for creating a new Node.js app.
*
* Creates a directory with the given name, resolves the package manager,
* then delegates to `run()` to copy template files, install dependencies,
* and initialize a git repository.
*
* @param options - App creation options (see {@link CreateAppOptions})
* @param options.name Name of the app (used as the directory name)
* @param [options.verbose] Enable verbose output from the package manager (default: `false`)
* @param [options.force] Proceed even if the target directory is not empty (default: `false`)
* @param [options.packageManager] Package manager to use
* @param [options.templatesOrExtensions] Template or extensions to apply
* @param [options.installDependencies] Whether to install dependencies automatically (default: `true`)
* @param [options.ignorePackage] Skip package.json merge logic (default: `false`)
* @param [options.offline] Run in offline mode
* @param [options.cacheDir] Path to the cache directory
* @param [options.refresh] Git cache refresh mode
* @param [options.refreshAfterHours] Cache refresh interval in hours
* @returns The return value of `run()` (`undefined` on success)
*/
export const createApp = async ({
name,
verbose = false,
force = false,
templatesOrExtensions = [],
installDependencies = true,
ignorePackage = false,
offline,
cacheDir,
refresh,
refreshAfterHours,
...customOptions
}: CreateAppOptions) => {
const root = path.resolve(name);
const appName = path.basename(root);
fs.mkdirSync(name, {
recursive: true,
});
if (!force) {
assertDirectoryIsEmpty(root);
}
const onSignal = (signal: string) => {
const error = new ScaffoldAbortedError(root);
console.error(pc.red(error.message));
error.cleanup();
process.exit(128 + (signal === "SIGINT" ? 2 : 15));
};
process.once("SIGINT", () => onSignal("SIGINT"));
process.once("SIGTERM", () => onSignal("SIGTERM"));
console.log(`Creating a new Node app in ${pc.green(root)}.`);
console.log();
const useYarn = customOptions.packageManager === "yarn" && shouldUseYarn();
const usePnpm = customOptions.packageManager === "pnpm" && shouldUsePnpm();
const useBun = customOptions.packageManager === "bun" && shouldUseBun();
const runCommand = useYarn
? "yarn"
: usePnpm
? "pnpm run"
: useBun
? "bun run"
: "npm run";
const installCommand = useYarn
? "yarn"
: usePnpm
? "pnpm install"
: useBun
? "bun install"
: "npm install";
logStep("Resolving template");
const { packageJson, dependencies, devDependencies } = await loadPackages({
templatesOrExtensions,
appName,
usePnpm,
useYarn,
useBun,
runCommand,
ignorePackage,
...(offline !== undefined ? { offline } : {}),
...(cacheDir !== undefined ? { cacheDir } : {}),
...(refresh !== undefined ? { refresh } : {}),
...(refreshAfterHours !== undefined ? { refreshAfterHours } : {}),
});
fs.writeFileSync(
path.join(root, "package.json"),
JSON.stringify(packageJson, null, 2) + os.EOL,
);
const originalDirectory = process.cwd();
// Prepend \\?\ to bypass MAX_PATH (260 char) limit on Windows
const chdirTarget =
process.platform === "win32" &&
root.length > 200 &&
!root.startsWith("\\\\?\\")
? "\\\\?\\" + root
: root;
process.chdir(chdirTarget);
try {
if (!useYarn && !useBun && !checkThatNpmCanReadCwd()) {
process.exit(1);
}
if (!semver.satisfies(process.version, ">=18.0.0")) {
console.log(
pc.yellow(
`You are using Node ${process.version} so the project will be bootstrapped with an old unsupported version of tools.\n\n` +
`Please update to Node 18 or higher for a better, fully supported experience.\n`,
),
);
}
if (!useYarn && !useBun) {
const npmInfo = checkNpmVersion();
if (!npmInfo.hasMinNpm) {
if (npmInfo.npmVersion) {
console.log(
pc.yellow(
`You are using npm ${npmInfo.npmVersion} so the project will be bootstrapped with an old unsupported version of tools.\n\n` +
`Please update to npm 3 or higher for a better, fully supported experience.\n`,
),
);
}
}
}
// Note: yarn registry detection used to live here. The cached
// `yarn.lock.cached` file was never shipped and the
// `yarnUsesDefaultRegistry` check was guarded by `if (false)`,
// so the block was effectively dead. Removed in #189.
return await run({
root,
appName,
originalDirectory,
verbose,
useYarn,
usePnpm,
useBun,
templatesOrExtensions,
dependencies,
devDependencies,
installDependencies,
runCommand,
installCommand,
...(offline !== undefined ? { offline } : {}),
...(cacheDir !== undefined ? { cacheDir } : {}),
...(refresh !== undefined ? { refresh } : {}),
...(refreshAfterHours !== undefined ? { refreshAfterHours } : {}),
...customOptions,
});
} finally {
process.chdir(originalDirectory);
}
};