create-ts-monorepo-starter 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +531 -328
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -4,7 +4,7 @@ import { join, isAbsolute, dirname, basename, resolve, relative, sep } from 'nod
|
|
|
4
4
|
import { parseArgs, styleText, stripVTControlCharacters } from 'node:util';
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { constants, tmpdir } from 'node:os';
|
|
7
|
-
import { readFileSync, existsSync, lstatSync, readdirSync, rmSync } from 'node:fs';
|
|
7
|
+
import { readFileSync, existsSync, lstatSync, readdirSync, rmSync, rmdirSync } from 'node:fs';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import process$1, { stdout, stdin } from 'node:process';
|
|
10
10
|
import * as f$1 from 'node:readline';
|
|
@@ -98,6 +98,69 @@ function parse(argv) {
|
|
|
98
98
|
});
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
const ERROR_CODES = new Set([
|
|
102
|
+
'usage',
|
|
103
|
+
'target-not-empty',
|
|
104
|
+
'cancelled',
|
|
105
|
+
'pnpm-too-old',
|
|
106
|
+
'pnpm-switch-failed',
|
|
107
|
+
'install-failed',
|
|
108
|
+
'lockfile-changed',
|
|
109
|
+
'backup-failed',
|
|
110
|
+
'move-failed',
|
|
111
|
+
'interrupted',
|
|
112
|
+
'unexpected',
|
|
113
|
+
]);
|
|
114
|
+
const USAGE = 2;
|
|
115
|
+
const FAILURE = 1;
|
|
116
|
+
/** The machine needs fixing first (pnpm can't switch versions, or is too old); nothing was created. */
|
|
117
|
+
const TOOLCHAIN = 3;
|
|
118
|
+
const INSTALL_FAILED = 4;
|
|
119
|
+
const INTERRUPTED = 130;
|
|
120
|
+
/** The exit code for an outcome; a code this function doesn't know exits 1, never 0. */
|
|
121
|
+
function exitCode(outcome) {
|
|
122
|
+
if (outcome.ok)
|
|
123
|
+
return 0;
|
|
124
|
+
switch (outcome.error.code) {
|
|
125
|
+
case 'usage':
|
|
126
|
+
return USAGE;
|
|
127
|
+
case 'pnpm-too-old':
|
|
128
|
+
case 'pnpm-switch-failed':
|
|
129
|
+
return TOOLCHAIN;
|
|
130
|
+
case 'install-failed':
|
|
131
|
+
return INSTALL_FAILED;
|
|
132
|
+
case 'cancelled':
|
|
133
|
+
case 'interrupted':
|
|
134
|
+
return INTERRUPTED;
|
|
135
|
+
default:
|
|
136
|
+
return FAILURE;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** The error's own code if it is one of the CLI's; a Node code such as `ENOSPC` is `unexpected`. */
|
|
140
|
+
function codeOf(error) {
|
|
141
|
+
const code = error?.code;
|
|
142
|
+
return typeof code === 'string' && ERROR_CODES.has(code) ? code : 'unexpected';
|
|
143
|
+
}
|
|
144
|
+
/** A failure the CLI throws on purpose: a code, and the output lines that explain it. */
|
|
145
|
+
class CliError extends Error {
|
|
146
|
+
code;
|
|
147
|
+
lines;
|
|
148
|
+
constructor(code, message, lines = []) {
|
|
149
|
+
super(message);
|
|
150
|
+
this.code = code;
|
|
151
|
+
this.lines = lines;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Classifies an error from a step without changing it: a new error with the same message, the
|
|
156
|
+
* CLI's code, and the original as `cause`. The original keeps its own `code` (retry logic reads it).
|
|
157
|
+
*/
|
|
158
|
+
function coded(code, error) {
|
|
159
|
+
return Object.assign(new Error(error instanceof Error ? error.message : String(error), { cause: error }), {
|
|
160
|
+
code,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
101
164
|
// `../dist/` resolves to the same folder from src/ (tests) and from the bundled dist/cli.js.
|
|
102
165
|
const dist = new URL('../dist/', import.meta.url);
|
|
103
166
|
/** Dotfiles are stored renamed in the bundle because npm and pnpm drop them from packages. */
|
|
@@ -289,11 +352,9 @@ async function detectPnpm(exec = defaultExec, cwd = tmpdir()) {
|
|
|
289
352
|
return { kind: major < 10 || (major === 10 && minor < 26) ? 'old' : 'ok', version };
|
|
290
353
|
}
|
|
291
354
|
/** A toolchain problem the user has to fix before anything is created; `lines` say how. */
|
|
292
|
-
class ToolchainError extends
|
|
293
|
-
lines
|
|
294
|
-
|
|
295
|
-
super(message);
|
|
296
|
-
this.lines = lines;
|
|
355
|
+
class ToolchainError extends CliError {
|
|
356
|
+
constructor(code, message, lines) {
|
|
357
|
+
super(code, message, lines);
|
|
297
358
|
this.name = 'ToolchainError';
|
|
298
359
|
}
|
|
299
360
|
}
|
|
@@ -301,7 +362,7 @@ const PNPM_HELP = 'https://github.com/prosdevlab/create-ts-monorepo-starter#pnpm
|
|
|
301
362
|
/** The stop for a pnpm older than 10.26, which can't switch itself to the template's pnpm. */
|
|
302
363
|
function tooOld(found, spec) {
|
|
303
364
|
const version = spec.slice('pnpm@'.length);
|
|
304
|
-
return new ToolchainError(`pnpm ${found} is too old for this project`, [
|
|
365
|
+
return new ToolchainError('pnpm-too-old', `pnpm ${found} is too old for this project`, [
|
|
305
366
|
`This project needs pnpm 10.26 or newer, which switches itself to pnpm ${version}.`,
|
|
306
367
|
'Upgrade pnpm: npm install -g pnpm (or https://pnpm.io/installation)',
|
|
307
368
|
'Then run this command again. Nothing was created.',
|
|
@@ -344,7 +405,7 @@ function switchFailure(spec, found, output, installer) {
|
|
|
344
405
|
.map((line) => line.trim())
|
|
345
406
|
.filter(Boolean)
|
|
346
407
|
.slice(0, 2);
|
|
347
|
-
return new ToolchainError(`pnpm ${found} couldn't switch to pnpm ${version}, which this project needs`, [
|
|
408
|
+
return new ToolchainError('pnpm-switch-failed', `pnpm ${found} couldn't switch to pnpm ${version}, which this project needs`, [
|
|
348
409
|
...said.map((line) => `pnpm: ${line}`),
|
|
349
410
|
installer
|
|
350
411
|
? `Fix: node ${installer}`
|
|
@@ -416,6 +477,7 @@ async function initAndCommit(dir, message, exec = defaultExec) {
|
|
|
416
477
|
const MAX_NAME_LENGTH = 214;
|
|
417
478
|
class NameError extends Error {
|
|
418
479
|
name = 'NameError';
|
|
480
|
+
code = 'usage';
|
|
419
481
|
}
|
|
420
482
|
// Folder -> npm package name: last path segment, lowercased, unsafe runs collapsed to "-".
|
|
421
483
|
function packageNameFromFolder(folder, cwd = process.cwd()) {
|
|
@@ -449,220 +511,6 @@ function normalizeScope(input) {
|
|
|
449
511
|
return { ok: true, scope };
|
|
450
512
|
}
|
|
451
513
|
|
|
452
|
-
const NAMES = [...EXAMPLES, 'template-only'];
|
|
453
|
-
// Same patterns as the template's own marker check (scripts/check-examples.mjs).
|
|
454
|
-
const MARKER = {
|
|
455
|
-
html: /^<!--\s*(\/?)example:(\S+?)\s*-->$/,
|
|
456
|
-
hash: /^#\s*(\/?)example:(\S+)$/,
|
|
457
|
-
slash: /^\/\/\s*(\/?)example:(\S+)$/,
|
|
458
|
-
};
|
|
459
|
-
const SLASH_EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsonc'];
|
|
460
|
-
class MarkerError extends Error {
|
|
461
|
-
path;
|
|
462
|
-
line;
|
|
463
|
-
constructor(path, line, problem) {
|
|
464
|
-
super(`${path}:${line} ${problem}`);
|
|
465
|
-
this.path = path;
|
|
466
|
-
this.line = line;
|
|
467
|
-
this.name = 'MarkerError';
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
/** Marker comment style of a repo-relative path, or null when the file is left untouched. */
|
|
471
|
-
function commentStyle(path) {
|
|
472
|
-
const file = path.replaceAll('\\', '/');
|
|
473
|
-
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
474
|
-
const dot = name.lastIndexOf('.');
|
|
475
|
-
const ext = dot > 0 ? name.slice(dot) : '';
|
|
476
|
-
if (ext === '.md')
|
|
477
|
-
return 'html';
|
|
478
|
-
if (ext === '.yml' || ext === '.yaml')
|
|
479
|
-
return 'hash';
|
|
480
|
-
if (name === '.gitignore' || name === '_gitignore' || file.startsWith('.husky/'))
|
|
481
|
-
return 'hash';
|
|
482
|
-
if (SLASH_EXTENSIONS.includes(ext))
|
|
483
|
-
return 'slash';
|
|
484
|
-
if (/^tsconfig.*\.json$/.test(name) || name === 'turbo.json')
|
|
485
|
-
return 'slash';
|
|
486
|
-
return null;
|
|
487
|
-
}
|
|
488
|
-
/** Drops blocks named in `remove` (plus template-only) and the marker lines of the rest. */
|
|
489
|
-
function applyMarkers(text, path, remove) {
|
|
490
|
-
const style = commentStyle(path);
|
|
491
|
-
if (!style)
|
|
492
|
-
return text;
|
|
493
|
-
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
494
|
-
const out = [];
|
|
495
|
-
let open = null;
|
|
496
|
-
for (const [index, raw] of text.split(/\r?\n/).entries()) {
|
|
497
|
-
const line = index + 1;
|
|
498
|
-
const match = raw.trim().match(MARKER[style]);
|
|
499
|
-
if (!match) {
|
|
500
|
-
if (!open?.drop)
|
|
501
|
-
out.push(raw);
|
|
502
|
-
continue;
|
|
503
|
-
}
|
|
504
|
-
const [, closing, name = ''] = match;
|
|
505
|
-
if (!NAMES.includes(name))
|
|
506
|
-
throw new MarkerError(path, line, `unknown example "${name}"`);
|
|
507
|
-
if (closing) {
|
|
508
|
-
if (open?.name !== name) {
|
|
509
|
-
throw new MarkerError(path, line, `example:${name} closes without a matching opening`);
|
|
510
|
-
}
|
|
511
|
-
open = null;
|
|
512
|
-
}
|
|
513
|
-
else {
|
|
514
|
-
if (open)
|
|
515
|
-
throw new MarkerError(path, line, `example:${name} opens inside example:${open.name}`);
|
|
516
|
-
open = { name, line, drop: name === 'template-only' || remove.has(name) };
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
if (open)
|
|
520
|
-
throw new MarkerError(path, open.line, `example:${open.name} is never closed`);
|
|
521
|
-
return out.join(eol);
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
const EXAMPLE_DIRS = {
|
|
525
|
-
lib: ['packages/shared', 'packages/lib'],
|
|
526
|
-
cli: ['packages/cli'],
|
|
527
|
-
web: ['packages/web'],
|
|
528
|
-
};
|
|
529
|
-
// Files that only make sense inside the template repo itself.
|
|
530
|
-
const TEMPLATE_ONLY_FILES = ['scripts/check-examples.mjs', 'scripts/check-examples.test.ts'];
|
|
531
|
-
// pnpm rewrites the lockfile after generation, so it is never edited here.
|
|
532
|
-
const LOCKFILE = 'pnpm-lock.yaml';
|
|
533
|
-
/** Repo-relative paths (with `/`) of every file under `dir`. */
|
|
534
|
-
async function listFiles(dir, prefix = '') {
|
|
535
|
-
const entries = await readdir(join(dir, prefix), { withFileTypes: true });
|
|
536
|
-
const nested = await Promise.all(entries.map((entry) => {
|
|
537
|
-
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
538
|
-
return entry.isDirectory() ? listFiles(dir, path) : [path];
|
|
539
|
-
}));
|
|
540
|
-
return nested.flat();
|
|
541
|
-
}
|
|
542
|
-
async function isText(path) {
|
|
543
|
-
const handle = await open(path, 'r');
|
|
544
|
-
try {
|
|
545
|
-
const buffer = Buffer.alloc(8192);
|
|
546
|
-
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
547
|
-
return !buffer.subarray(0, bytesRead).includes(0);
|
|
548
|
-
}
|
|
549
|
-
finally {
|
|
550
|
-
await handle.close();
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
function identityEdits(input) {
|
|
554
|
-
const { folderName, holder, year } = input;
|
|
555
|
-
return [
|
|
556
|
-
{ file: 'package.json', from: '"name": "ts-monorepo-starter"', to: `"name": "${folderName}"` },
|
|
557
|
-
{ file: 'README.md', from: '# TypeScript Monorepo Starter', to: `# ${folderName}` },
|
|
558
|
-
{ file: 'README.md', from: /^ts-monorepo-starter\/$/m, to: `${folderName}/` },
|
|
559
|
-
{ file: 'README.md', from: 'cd ts-monorepo-starter', to: `cd ${folderName}` },
|
|
560
|
-
{
|
|
561
|
-
file: 'README.md',
|
|
562
|
-
from: 'yourusername/ts-monorepo-starter.git',
|
|
563
|
-
to: `yourusername/${folderName}.git`,
|
|
564
|
-
},
|
|
565
|
-
{
|
|
566
|
-
file: 'LICENSE',
|
|
567
|
-
from: 'Copyright (c) 2025 prosdevlab',
|
|
568
|
-
to: `Copyright (c) ${year} ${holder}`,
|
|
569
|
-
},
|
|
570
|
-
];
|
|
571
|
-
}
|
|
572
|
-
/** Writes the chosen examples of the template at `from` into `to`; touches nothing else. */
|
|
573
|
-
async function generate(input) {
|
|
574
|
-
const { from, to, scope, keep } = input;
|
|
575
|
-
await cp(from, to, { recursive: true });
|
|
576
|
-
const all = await listFiles(to);
|
|
577
|
-
for (const file of all) {
|
|
578
|
-
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
579
|
-
const renamed = DOTFILE_RENAMES[name];
|
|
580
|
-
if (renamed)
|
|
581
|
-
await rename(join(to, file), join(to, file.slice(0, -name.length) + renamed));
|
|
582
|
-
}
|
|
583
|
-
const removed = EXAMPLES.filter((example) => !keep.includes(example));
|
|
584
|
-
const doomed = [...removed.flatMap((example) => EXAMPLE_DIRS[example]), ...TEMPLATE_ONLY_FILES];
|
|
585
|
-
for (const path of doomed)
|
|
586
|
-
await rm(join(to, path), { recursive: true, force: true });
|
|
587
|
-
// The template-only files may have been all of scripts/.
|
|
588
|
-
const scripts = join(to, 'scripts');
|
|
589
|
-
const left = await readdir(scripts).catch(() => null);
|
|
590
|
-
if (left?.length === 0)
|
|
591
|
-
await rmdir(scripts);
|
|
592
|
-
const remove = new Set(removed);
|
|
593
|
-
const identity = identityEdits(input);
|
|
594
|
-
const present = await listFiles(to);
|
|
595
|
-
for (const edit of identity) {
|
|
596
|
-
if (!present.includes(edit.file)) {
|
|
597
|
-
throw new Error(`Template changed: "${typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/'}" not found in ${edit.file}`);
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
for (const file of present) {
|
|
601
|
-
if (file === LOCKFILE || !(await isText(join(to, file))))
|
|
602
|
-
continue;
|
|
603
|
-
const original = await readFile(join(to, file), 'utf8');
|
|
604
|
-
let text = commentStyle(file) ? applyMarkers(original, file, remove) : original;
|
|
605
|
-
text = text.replaceAll('@monorepo/', `${scope}/`);
|
|
606
|
-
for (const edit of identity.filter((entry) => entry.file === file)) {
|
|
607
|
-
const found = typeof edit.from === 'string' ? text.includes(edit.from) : edit.from.test(text);
|
|
608
|
-
if (!found) {
|
|
609
|
-
const shown = typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/';
|
|
610
|
-
throw new Error(`Template changed: "${shown}" not found in ${file}`);
|
|
611
|
-
}
|
|
612
|
-
text = text.replace(edit.from, () => edit.to);
|
|
613
|
-
}
|
|
614
|
-
if (text !== original)
|
|
615
|
-
await writeFile(join(to, file), text);
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
/** Thrown when an install added lockfile entries the bundled lockfile lacks. */
|
|
620
|
-
class LockfileError extends Error {
|
|
621
|
-
name = 'LockfileError';
|
|
622
|
-
}
|
|
623
|
-
const SECTIONS = ['packages', 'snapshots'];
|
|
624
|
-
function unquote(key) {
|
|
625
|
-
return key.startsWith("'") && key.endsWith("'") ? key.slice(1, -1).replaceAll("''", "'") : key;
|
|
626
|
-
}
|
|
627
|
-
/** Entries as `packages: name@version` / `snapshots: name@version`, across every YAML document. */
|
|
628
|
-
function sectionEntries(text) {
|
|
629
|
-
const found = new Set();
|
|
630
|
-
for (const doc of text.split(/^---\r?$/m)) {
|
|
631
|
-
let section = null;
|
|
632
|
-
for (const line of doc.split(/\r?\n/)) {
|
|
633
|
-
if (line.startsWith('#'))
|
|
634
|
-
continue;
|
|
635
|
-
const top = /^(\w+):\s*$/.exec(line);
|
|
636
|
-
if (top) {
|
|
637
|
-
section = SECTIONS.includes(top[1])
|
|
638
|
-
? top[1]
|
|
639
|
-
: null;
|
|
640
|
-
}
|
|
641
|
-
else if (/^\S/.test(line)) {
|
|
642
|
-
section = null;
|
|
643
|
-
}
|
|
644
|
-
else if (section) {
|
|
645
|
-
// A key ends at the first `:` followed by whitespace or end of line, so `node@runtime:1.0.0:` works.
|
|
646
|
-
const key = /^ {2}('(?:[^']|'')*'|[^\s'#].*?):(?=\s|$)/.exec(line);
|
|
647
|
-
if (key)
|
|
648
|
-
found.add(`${section}: ${unquote(key[1])}`);
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
return found;
|
|
653
|
-
}
|
|
654
|
-
/** Throws unless every entry of `generated` already exists in `bundled`. */
|
|
655
|
-
function assertLockfileSubset(bundled, generated) {
|
|
656
|
-
const have = sectionEntries(bundled);
|
|
657
|
-
const added = [...sectionEntries(generated)].filter((e) => !have.has(e));
|
|
658
|
-
if (added.length === 0)
|
|
659
|
-
return;
|
|
660
|
-
const lines = added.slice(0, 10).map((e) => `+ ${e}`);
|
|
661
|
-
if (added.length > 10)
|
|
662
|
-
lines.push(`…and ${added.length - 10} more`);
|
|
663
|
-
throw new LockfileError(`Lockfile changed during install:\n${lines.join('\n')}`);
|
|
664
|
-
}
|
|
665
|
-
|
|
666
514
|
/* MAIN */
|
|
667
515
|
const getCodePointsLength = (() => {
|
|
668
516
|
const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
|
@@ -3770,6 +3618,7 @@ function clackUi() {
|
|
|
3770
3618
|
/** Thrown when someone cancels a prompt (Ctrl-C or Escape). */
|
|
3771
3619
|
class CancelledError extends Error {
|
|
3772
3620
|
name = 'CancelledError';
|
|
3621
|
+
code = 'cancelled';
|
|
3773
3622
|
}
|
|
3774
3623
|
function answer(value) {
|
|
3775
3624
|
if (isCancel(value))
|
|
@@ -3823,26 +3672,283 @@ function createAsk(prompts = p$1) {
|
|
|
3823
3672
|
};
|
|
3824
3673
|
}
|
|
3825
3674
|
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
const
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3675
|
+
/** The failure for an error: the text `report()` printed before, and the code. */
|
|
3676
|
+
function failureFrom(error) {
|
|
3677
|
+
const code = codeOf(error);
|
|
3678
|
+
if (error instanceof CancelledError)
|
|
3679
|
+
return { code, title: CANCELLED, lines: [], fixes: [] };
|
|
3680
|
+
if (error instanceof CliError) {
|
|
3681
|
+
return { code, title: error.message, lines: error.lines, fixes: [] };
|
|
3682
|
+
}
|
|
3683
|
+
const [title = 'Something went wrong', ...lines] = String(error instanceof Error ? error.message : error).split('\n');
|
|
3684
|
+
return { code, title, lines, fixes: [] };
|
|
3833
3685
|
}
|
|
3834
|
-
/**
|
|
3835
|
-
function
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
3839
|
-
return `${target}.backup-${date}-${time}`;
|
|
3686
|
+
/** A usage error: one line on stderr, before anything else is shown. */
|
|
3687
|
+
function usageFailure(message) {
|
|
3688
|
+
const [title = '', ...lines] = message.split('\n');
|
|
3689
|
+
return { ok: false, error: { code: 'usage', title, lines, fixes: [] } };
|
|
3840
3690
|
}
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
if (
|
|
3844
|
-
|
|
3845
|
-
|
|
3691
|
+
/** Prints an outcome as text. */
|
|
3692
|
+
function renderText(outcome, ui) {
|
|
3693
|
+
if (!outcome.ok) {
|
|
3694
|
+
const { code, title, lines } = outcome.error;
|
|
3695
|
+
if (code === 'usage')
|
|
3696
|
+
process.stderr.write(`${[title, ...lines].join('\n')}\n`);
|
|
3697
|
+
else
|
|
3698
|
+
ui.fail(title, lines);
|
|
3699
|
+
return;
|
|
3700
|
+
}
|
|
3701
|
+
if (outcome.kind === 'created') {
|
|
3702
|
+
ui.outro(outcome.result, outcome.plan);
|
|
3703
|
+
return;
|
|
3704
|
+
}
|
|
3705
|
+
const version = pnpmSpec().slice('pnpm@'.length);
|
|
3706
|
+
if (outcome.pnpm.kind === 'none') {
|
|
3707
|
+
ui.warn("pnpm isn't installed", [
|
|
3708
|
+
`Creating works: the install uses a temporary pnpm ${version} (npm exec).`,
|
|
3709
|
+
`Working in the project needs pnpm 10.26 or newer: https://pnpm.io/installation`,
|
|
3710
|
+
]);
|
|
3711
|
+
}
|
|
3712
|
+
else if (outcome.pnpm.kind === 'ok') {
|
|
3713
|
+
ui.step(`Ready: pnpm ${outcome.pnpm.version} switches to pnpm ${version} for this project`);
|
|
3714
|
+
}
|
|
3715
|
+
}
|
|
3716
|
+
|
|
3717
|
+
const NAMES = [...EXAMPLES, 'template-only'];
|
|
3718
|
+
// Same patterns as the template's own marker check (scripts/check-examples.mjs).
|
|
3719
|
+
const MARKER = {
|
|
3720
|
+
html: /^<!--\s*(\/?)example:(\S+?)\s*-->$/,
|
|
3721
|
+
hash: /^#\s*(\/?)example:(\S+)$/,
|
|
3722
|
+
slash: /^\/\/\s*(\/?)example:(\S+)$/,
|
|
3723
|
+
};
|
|
3724
|
+
const SLASH_EXTENSIONS = ['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsonc'];
|
|
3725
|
+
class MarkerError extends Error {
|
|
3726
|
+
path;
|
|
3727
|
+
line;
|
|
3728
|
+
constructor(path, line, problem) {
|
|
3729
|
+
super(`${path}:${line} ${problem}`);
|
|
3730
|
+
this.path = path;
|
|
3731
|
+
this.line = line;
|
|
3732
|
+
this.name = 'MarkerError';
|
|
3733
|
+
}
|
|
3734
|
+
}
|
|
3735
|
+
/** Marker comment style of a repo-relative path, or null when the file is left untouched. */
|
|
3736
|
+
function commentStyle(path) {
|
|
3737
|
+
const file = path.replaceAll('\\', '/');
|
|
3738
|
+
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
3739
|
+
const dot = name.lastIndexOf('.');
|
|
3740
|
+
const ext = dot > 0 ? name.slice(dot) : '';
|
|
3741
|
+
if (ext === '.md')
|
|
3742
|
+
return 'html';
|
|
3743
|
+
if (ext === '.yml' || ext === '.yaml')
|
|
3744
|
+
return 'hash';
|
|
3745
|
+
if (name === '.gitignore' || name === '_gitignore' || file.startsWith('.husky/'))
|
|
3746
|
+
return 'hash';
|
|
3747
|
+
if (SLASH_EXTENSIONS.includes(ext))
|
|
3748
|
+
return 'slash';
|
|
3749
|
+
if (/^tsconfig.*\.json$/.test(name) || name === 'turbo.json')
|
|
3750
|
+
return 'slash';
|
|
3751
|
+
return null;
|
|
3752
|
+
}
|
|
3753
|
+
/** Drops blocks named in `remove` (plus template-only) and the marker lines of the rest. */
|
|
3754
|
+
function applyMarkers(text, path, remove) {
|
|
3755
|
+
const style = commentStyle(path);
|
|
3756
|
+
if (!style)
|
|
3757
|
+
return text;
|
|
3758
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
3759
|
+
const out = [];
|
|
3760
|
+
let open = null;
|
|
3761
|
+
for (const [index, raw] of text.split(/\r?\n/).entries()) {
|
|
3762
|
+
const line = index + 1;
|
|
3763
|
+
const match = raw.trim().match(MARKER[style]);
|
|
3764
|
+
if (!match) {
|
|
3765
|
+
if (!open?.drop)
|
|
3766
|
+
out.push(raw);
|
|
3767
|
+
continue;
|
|
3768
|
+
}
|
|
3769
|
+
const [, closing, name = ''] = match;
|
|
3770
|
+
if (!NAMES.includes(name))
|
|
3771
|
+
throw new MarkerError(path, line, `unknown example "${name}"`);
|
|
3772
|
+
if (closing) {
|
|
3773
|
+
if (open?.name !== name) {
|
|
3774
|
+
throw new MarkerError(path, line, `example:${name} closes without a matching opening`);
|
|
3775
|
+
}
|
|
3776
|
+
open = null;
|
|
3777
|
+
}
|
|
3778
|
+
else {
|
|
3779
|
+
if (open)
|
|
3780
|
+
throw new MarkerError(path, line, `example:${name} opens inside example:${open.name}`);
|
|
3781
|
+
open = { name, line, drop: name === 'template-only' || remove.has(name) };
|
|
3782
|
+
}
|
|
3783
|
+
}
|
|
3784
|
+
if (open)
|
|
3785
|
+
throw new MarkerError(path, open.line, `example:${open.name} is never closed`);
|
|
3786
|
+
return out.join(eol);
|
|
3787
|
+
}
|
|
3788
|
+
|
|
3789
|
+
const EXAMPLE_DIRS = {
|
|
3790
|
+
lib: ['packages/shared', 'packages/lib'],
|
|
3791
|
+
cli: ['packages/cli'],
|
|
3792
|
+
web: ['packages/web'],
|
|
3793
|
+
};
|
|
3794
|
+
// Files that only make sense inside the template repo itself.
|
|
3795
|
+
const TEMPLATE_ONLY_FILES = ['scripts/check-examples.mjs', 'scripts/check-examples.test.ts'];
|
|
3796
|
+
// pnpm rewrites the lockfile after generation, so it is never edited here.
|
|
3797
|
+
const LOCKFILE = 'pnpm-lock.yaml';
|
|
3798
|
+
/** Repo-relative paths (with `/`) of every file under `dir`. */
|
|
3799
|
+
async function listFiles(dir, prefix = '') {
|
|
3800
|
+
const entries = await readdir(join(dir, prefix), { withFileTypes: true });
|
|
3801
|
+
const nested = await Promise.all(entries.map((entry) => {
|
|
3802
|
+
const path = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
3803
|
+
return entry.isDirectory() ? listFiles(dir, path) : [path];
|
|
3804
|
+
}));
|
|
3805
|
+
return nested.flat();
|
|
3806
|
+
}
|
|
3807
|
+
async function isText(path) {
|
|
3808
|
+
const handle = await open(path, 'r');
|
|
3809
|
+
try {
|
|
3810
|
+
const buffer = Buffer.alloc(8192);
|
|
3811
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
3812
|
+
return !buffer.subarray(0, bytesRead).includes(0);
|
|
3813
|
+
}
|
|
3814
|
+
finally {
|
|
3815
|
+
await handle.close();
|
|
3816
|
+
}
|
|
3817
|
+
}
|
|
3818
|
+
function identityEdits(input) {
|
|
3819
|
+
const { folderName, holder, year } = input;
|
|
3820
|
+
return [
|
|
3821
|
+
{ file: 'package.json', from: '"name": "ts-monorepo-starter"', to: `"name": "${folderName}"` },
|
|
3822
|
+
{ file: 'README.md', from: '# TypeScript Monorepo Starter', to: `# ${folderName}` },
|
|
3823
|
+
{ file: 'README.md', from: /^ts-monorepo-starter\/$/m, to: `${folderName}/` },
|
|
3824
|
+
{ file: 'README.md', from: 'cd ts-monorepo-starter', to: `cd ${folderName}` },
|
|
3825
|
+
{
|
|
3826
|
+
file: 'README.md',
|
|
3827
|
+
from: 'yourusername/ts-monorepo-starter.git',
|
|
3828
|
+
to: `yourusername/${folderName}.git`,
|
|
3829
|
+
},
|
|
3830
|
+
{
|
|
3831
|
+
file: 'LICENSE',
|
|
3832
|
+
from: 'Copyright (c) 2025 prosdevlab',
|
|
3833
|
+
to: `Copyright (c) ${year} ${holder}`,
|
|
3834
|
+
},
|
|
3835
|
+
];
|
|
3836
|
+
}
|
|
3837
|
+
/** Writes the chosen examples of the template at `from` into `to`; touches nothing else. */
|
|
3838
|
+
async function generate(input) {
|
|
3839
|
+
const { from, to, scope, keep } = input;
|
|
3840
|
+
await cp(from, to, { recursive: true });
|
|
3841
|
+
const all = await listFiles(to);
|
|
3842
|
+
for (const file of all) {
|
|
3843
|
+
const name = file.slice(file.lastIndexOf('/') + 1);
|
|
3844
|
+
const renamed = DOTFILE_RENAMES[name];
|
|
3845
|
+
if (renamed)
|
|
3846
|
+
await rename(join(to, file), join(to, file.slice(0, -name.length) + renamed));
|
|
3847
|
+
}
|
|
3848
|
+
const removed = EXAMPLES.filter((example) => !keep.includes(example));
|
|
3849
|
+
const doomed = [...removed.flatMap((example) => EXAMPLE_DIRS[example]), ...TEMPLATE_ONLY_FILES];
|
|
3850
|
+
for (const path of doomed)
|
|
3851
|
+
await rm(join(to, path), { recursive: true, force: true });
|
|
3852
|
+
// The template-only files may have been all of scripts/.
|
|
3853
|
+
const scripts = join(to, 'scripts');
|
|
3854
|
+
const left = await readdir(scripts).catch(() => null);
|
|
3855
|
+
if (left?.length === 0)
|
|
3856
|
+
await rmdir(scripts);
|
|
3857
|
+
const remove = new Set(removed);
|
|
3858
|
+
const identity = identityEdits(input);
|
|
3859
|
+
const present = await listFiles(to);
|
|
3860
|
+
for (const edit of identity) {
|
|
3861
|
+
if (!present.includes(edit.file)) {
|
|
3862
|
+
throw new Error(`Template changed: "${typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/'}" not found in ${edit.file}`);
|
|
3863
|
+
}
|
|
3864
|
+
}
|
|
3865
|
+
for (const file of present) {
|
|
3866
|
+
if (file === LOCKFILE || !(await isText(join(to, file))))
|
|
3867
|
+
continue;
|
|
3868
|
+
const original = await readFile(join(to, file), 'utf8');
|
|
3869
|
+
let text = commentStyle(file) ? applyMarkers(original, file, remove) : original;
|
|
3870
|
+
text = text.replaceAll('@monorepo/', `${scope}/`);
|
|
3871
|
+
for (const edit of identity.filter((entry) => entry.file === file)) {
|
|
3872
|
+
const found = typeof edit.from === 'string' ? text.includes(edit.from) : edit.from.test(text);
|
|
3873
|
+
if (!found) {
|
|
3874
|
+
const shown = typeof edit.from === 'string' ? edit.from : 'ts-monorepo-starter/';
|
|
3875
|
+
throw new Error(`Template changed: "${shown}" not found in ${file}`);
|
|
3876
|
+
}
|
|
3877
|
+
text = text.replace(edit.from, () => edit.to);
|
|
3878
|
+
}
|
|
3879
|
+
if (text !== original)
|
|
3880
|
+
await writeFile(join(to, file), text);
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
|
|
3884
|
+
/** Thrown when an install added lockfile entries the bundled lockfile lacks. */
|
|
3885
|
+
class LockfileError extends Error {
|
|
3886
|
+
name = 'LockfileError';
|
|
3887
|
+
code = 'lockfile-changed';
|
|
3888
|
+
}
|
|
3889
|
+
const SECTIONS = ['packages', 'snapshots'];
|
|
3890
|
+
function unquote(key) {
|
|
3891
|
+
return key.startsWith("'") && key.endsWith("'") ? key.slice(1, -1).replaceAll("''", "'") : key;
|
|
3892
|
+
}
|
|
3893
|
+
/** Entries as `packages: name@version` / `snapshots: name@version`, across every YAML document. */
|
|
3894
|
+
function sectionEntries(text) {
|
|
3895
|
+
const found = new Set();
|
|
3896
|
+
for (const doc of text.split(/^---\r?$/m)) {
|
|
3897
|
+
let section = null;
|
|
3898
|
+
for (const line of doc.split(/\r?\n/)) {
|
|
3899
|
+
if (line.startsWith('#'))
|
|
3900
|
+
continue;
|
|
3901
|
+
const top = /^(\w+):\s*$/.exec(line);
|
|
3902
|
+
if (top) {
|
|
3903
|
+
section = SECTIONS.includes(top[1])
|
|
3904
|
+
? top[1]
|
|
3905
|
+
: null;
|
|
3906
|
+
}
|
|
3907
|
+
else if (/^\S/.test(line)) {
|
|
3908
|
+
section = null;
|
|
3909
|
+
}
|
|
3910
|
+
else if (section) {
|
|
3911
|
+
// A key ends at the first `:` followed by whitespace or end of line, so `node@runtime:1.0.0:` works.
|
|
3912
|
+
const key = /^ {2}('(?:[^']|'')*'|[^\s'#].*?):(?=\s|$)/.exec(line);
|
|
3913
|
+
if (key)
|
|
3914
|
+
found.add(`${section}: ${unquote(key[1])}`);
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
return found;
|
|
3919
|
+
}
|
|
3920
|
+
/** Throws unless every entry of `generated` already exists in `bundled`. */
|
|
3921
|
+
function assertLockfileSubset(bundled, generated) {
|
|
3922
|
+
const have = sectionEntries(bundled);
|
|
3923
|
+
const added = [...sectionEntries(generated)].filter((e) => !have.has(e));
|
|
3924
|
+
if (added.length === 0)
|
|
3925
|
+
return;
|
|
3926
|
+
const lines = added.slice(0, 10).map((e) => `+ ${e}`);
|
|
3927
|
+
if (added.length > 10)
|
|
3928
|
+
lines.push(`…and ${added.length - 10} more`);
|
|
3929
|
+
throw new LockfileError(`Lockfile changed during install:\n${lines.join('\n')}`);
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
const RETRY_CODES = new Set(['EPERM', 'EBUSY']);
|
|
3933
|
+
const RETRY_DELAYS = [100, 200, 400, 800, 1600];
|
|
3934
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
3935
|
+
/** `<parent>/.<name>.tmp-<8 hex>`, beside the target so the final rename stays on one volume. */
|
|
3936
|
+
function tempPath(target, random = () => randomBytes(4).toString('hex')) {
|
|
3937
|
+
target = resolve(target);
|
|
3938
|
+
return join(dirname(target), `.${basename(target)}.tmp-${random()}`);
|
|
3939
|
+
}
|
|
3940
|
+
/** `<target>.backup-YYYYMMDD-HHMMSS` in local time. */
|
|
3941
|
+
function backupPath(target, now) {
|
|
3942
|
+
target = resolve(target);
|
|
3943
|
+
const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`;
|
|
3944
|
+
const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
|
3945
|
+
return `${target}.backup-${date}-${time}`;
|
|
3946
|
+
}
|
|
3947
|
+
// lstat, so a dangling symlink counts as taken; only ENOENT means the name is free.
|
|
3948
|
+
const exists = (path) => lstat(path).then(() => true, (error) => {
|
|
3949
|
+
if (error.code === 'ENOENT')
|
|
3950
|
+
return false;
|
|
3951
|
+
throw error;
|
|
3846
3952
|
});
|
|
3847
3953
|
async function targetState(target) {
|
|
3848
3954
|
target = resolve(target);
|
|
@@ -3857,6 +3963,17 @@ async function targetState(target) {
|
|
|
3857
3963
|
return 'not-empty';
|
|
3858
3964
|
return (await readdir(target)).length === 0 ? 'empty' : 'not-empty';
|
|
3859
3965
|
}
|
|
3966
|
+
/** Never throws. Anything that exists and isn't a directory (a file as the target) is `not-empty`. */
|
|
3967
|
+
function probePath(path) {
|
|
3968
|
+
try {
|
|
3969
|
+
if (!lstatSync(path).isDirectory())
|
|
3970
|
+
return 'not-empty';
|
|
3971
|
+
return readdirSync(path).length === 0 ? 'empty' : 'not-empty';
|
|
3972
|
+
}
|
|
3973
|
+
catch (error) {
|
|
3974
|
+
return error.code === 'ENOENT' ? 'missing' : 'unreadable';
|
|
3975
|
+
}
|
|
3976
|
+
}
|
|
3860
3977
|
/** True when `child` is `parent` or inside it (a name that merely starts with `..` is inside). */
|
|
3861
3978
|
function isInside(parent, child) {
|
|
3862
3979
|
const rel = relative(parent, child);
|
|
@@ -3907,10 +4024,12 @@ async function backUp(target, now, deps = {}) {
|
|
|
3907
4024
|
candidate = `${base}-${n}`;
|
|
3908
4025
|
const move = retryingRename(deps);
|
|
3909
4026
|
if (!(await holdsCwd(target, deps.cwd))) {
|
|
4027
|
+
deps.onPath?.(candidate);
|
|
3910
4028
|
await move(target, candidate);
|
|
3911
4029
|
return candidate;
|
|
3912
4030
|
}
|
|
3913
4031
|
await mkdir(candidate);
|
|
4032
|
+
deps.onPath?.(candidate);
|
|
3914
4033
|
const entries = await readdir(target);
|
|
3915
4034
|
for (const [index, entry] of entries.entries()) {
|
|
3916
4035
|
try {
|
|
@@ -4007,11 +4126,9 @@ function onInterrupt(temp, deps = {}) {
|
|
|
4007
4126
|
}
|
|
4008
4127
|
|
|
4009
4128
|
/** A failure with the output lines that explain it. */
|
|
4010
|
-
class RunError extends
|
|
4011
|
-
lines
|
|
4012
|
-
|
|
4013
|
-
super(message);
|
|
4014
|
-
this.lines = lines;
|
|
4129
|
+
class RunError extends CliError {
|
|
4130
|
+
constructor(code, message, lines = []) {
|
|
4131
|
+
super(code, message, lines);
|
|
4015
4132
|
this.name = 'RunError';
|
|
4016
4133
|
}
|
|
4017
4134
|
}
|
|
@@ -4029,6 +4146,7 @@ function planFromOptions(o, cwd, now, holder) {
|
|
|
4029
4146
|
}
|
|
4030
4147
|
return {
|
|
4031
4148
|
target: resolve(cwd, o.folder),
|
|
4149
|
+
folder: o.folder,
|
|
4032
4150
|
folderName: packageNameFromFolder(o.folder, cwd),
|
|
4033
4151
|
scope,
|
|
4034
4152
|
keep: o.examples ?? [...EXAMPLES],
|
|
@@ -4042,20 +4160,20 @@ function lastLines(output) {
|
|
|
4042
4160
|
const lines = `${output.stdout}\n${output.stderr}`.split(/\r?\n/).filter((l) => l.trim());
|
|
4043
4161
|
return lines.slice(-20);
|
|
4044
4162
|
}
|
|
4163
|
+
/** What a failure or a Ctrl-C says about a temporary folder it couldn't delete. */
|
|
4164
|
+
const leftoverLine = (temp) => `Couldn't delete the temporary folder ${temp}: delete it yourself.`;
|
|
4045
4165
|
/** The line a Ctrl-C prints: "nothing was written" holds only until the backup starts. */
|
|
4046
4166
|
function cancelMessage(phase, plan, temp, outcome) {
|
|
4047
4167
|
const { target } = plan;
|
|
4048
4168
|
const leftover = [
|
|
4049
|
-
...(outcome.removed
|
|
4050
|
-
? []
|
|
4051
|
-
: [`Couldn't delete the temporary folder ${temp}: delete it yourself.`]),
|
|
4169
|
+
...(outcome.removed ? [] : [leftoverLine(temp)]),
|
|
4052
4170
|
...(outcome.stopped ? [] : ['pnpm may still be running in it.']),
|
|
4053
4171
|
];
|
|
4054
4172
|
switch (phase.at) {
|
|
4055
4173
|
case 'working':
|
|
4056
4174
|
return outcome.removed ? [CANCELLED, leftover] : ['Cancelled.', leftover];
|
|
4057
4175
|
case 'backing-up': {
|
|
4058
|
-
const backup = basename(backupPath(target, plan.now));
|
|
4176
|
+
const backup = basename(phase.backup ?? backupPath(target, plan.now));
|
|
4059
4177
|
const where = phase.inPlace
|
|
4060
4178
|
? `Your files are in ${target}, in ${backup} beside it, or split between the two.`
|
|
4061
4179
|
: `Your files are in ${target}, or in ${backup} beside it.`;
|
|
@@ -4073,6 +4191,53 @@ function cancelMessage(phase, plan, temp, outcome) {
|
|
|
4073
4191
|
return [`Cancelled after the project was created in ${target}.`, leftover];
|
|
4074
4192
|
}
|
|
4075
4193
|
}
|
|
4194
|
+
/**
|
|
4195
|
+
* What the run left behind, from the phase it was in and a synchronous read of the disk. Before
|
|
4196
|
+
* `onPath` has fired the phase has no backup path, so no backup is claimed.
|
|
4197
|
+
*/
|
|
4198
|
+
function leftBehind(phase, before, read, target) {
|
|
4199
|
+
const unknown = (backup) => {
|
|
4200
|
+
const found = backup && read(backup) === 'not-empty' ? backup : undefined;
|
|
4201
|
+
return { target: 'unknown', ...(found && { backup: found }) };
|
|
4202
|
+
};
|
|
4203
|
+
if (phase.at === 'working') {
|
|
4204
|
+
if (before === undefined)
|
|
4205
|
+
return { target: 'unknown' };
|
|
4206
|
+
return { target: before === 'not-empty' ? 'unchanged' : before };
|
|
4207
|
+
}
|
|
4208
|
+
if (phase.at === 'moved')
|
|
4209
|
+
return { target: 'complete', ...(phase.backup && { backup: phase.backup }) };
|
|
4210
|
+
const backup = phase.backup;
|
|
4211
|
+
if (phase.at === 'backing-up' && !backup)
|
|
4212
|
+
return { target: 'unchanged' };
|
|
4213
|
+
const now = read(target);
|
|
4214
|
+
if (now === 'unreadable')
|
|
4215
|
+
return unknown(backup);
|
|
4216
|
+
if (phase.at === 'moving') {
|
|
4217
|
+
// backUp has returned, so the files are there unless the disk says the folder is gone or empty.
|
|
4218
|
+
const kept = backup ? read(backup) : 'missing';
|
|
4219
|
+
const where = backup && kept !== 'missing' && kept !== 'empty' ? { backup } : {};
|
|
4220
|
+
if (now === 'missing' || now === 'empty')
|
|
4221
|
+
return { target: now, ...where };
|
|
4222
|
+
if (before === undefined)
|
|
4223
|
+
return { target: 'unknown', ...where };
|
|
4224
|
+
if (before === 'missing' || before === 'empty' || backup)
|
|
4225
|
+
return { target: 'partial', ...where };
|
|
4226
|
+
return { target: 'unchanged' };
|
|
4227
|
+
}
|
|
4228
|
+
const moved = read(backup);
|
|
4229
|
+
if (moved === 'unreadable')
|
|
4230
|
+
return unknown(backup);
|
|
4231
|
+
if (now === 'not-empty') {
|
|
4232
|
+
return moved === 'not-empty' ? { target: 'split', backup } : { target: 'unchanged' };
|
|
4233
|
+
}
|
|
4234
|
+
return moved === 'not-empty' ? { target: now, backup } : unknown();
|
|
4235
|
+
}
|
|
4236
|
+
const recorded = new WeakMap();
|
|
4237
|
+
/** The `left` that `run()` recorded for an error it threw, if any. */
|
|
4238
|
+
function leftOf(error) {
|
|
4239
|
+
return typeof error === 'object' && error !== null ? recorded.get(error) : undefined;
|
|
4240
|
+
}
|
|
4076
4241
|
const firstLine = (error) => (error instanceof Error ? error.message : String(error)).split('\n')[0] ?? '';
|
|
4077
4242
|
/** Generates, installs and commits in a temporary folder, then moves it to `plan.target`. */
|
|
4078
4243
|
async function run(plan, ui, deps = {}) {
|
|
@@ -4092,6 +4257,8 @@ async function run(plan, ui, deps = {}) {
|
|
|
4092
4257
|
const temp = tempPath(plan.target);
|
|
4093
4258
|
// What a Ctrl-C has to report changes once the user's folder is moved aside or ours moves in.
|
|
4094
4259
|
let phase = { at: 'working' };
|
|
4260
|
+
let before;
|
|
4261
|
+
const probe = deps.probe ?? probePath;
|
|
4095
4262
|
const unregister = (deps.onInterrupt ?? onInterrupt)(temp, {
|
|
4096
4263
|
onStart: () => {
|
|
4097
4264
|
interrupted = true;
|
|
@@ -4099,8 +4266,36 @@ async function run(plan, ui, deps = {}) {
|
|
|
4099
4266
|
exit: (code, outcome) => {
|
|
4100
4267
|
try {
|
|
4101
4268
|
ui.stop();
|
|
4269
|
+
const facts = {
|
|
4270
|
+
...(outcome.removed ? {} : { temp }),
|
|
4271
|
+
...(outcome.stopped ? {} : { running: true }),
|
|
4272
|
+
};
|
|
4273
|
+
let left;
|
|
4274
|
+
try {
|
|
4275
|
+
left = { ...leftBehind(phase, before, probe, plan.target), ...facts };
|
|
4276
|
+
}
|
|
4277
|
+
catch {
|
|
4278
|
+
left = { target: 'unknown', ...facts };
|
|
4279
|
+
}
|
|
4102
4280
|
const [title, lines] = cancelMessage(phase, plan, temp, outcome);
|
|
4103
|
-
|
|
4281
|
+
const interrupted = {
|
|
4282
|
+
ok: false,
|
|
4283
|
+
error: { code: 'interrupted', title, lines, fixes: [] },
|
|
4284
|
+
left,
|
|
4285
|
+
};
|
|
4286
|
+
renderText(interrupted, ui);
|
|
4287
|
+
try {
|
|
4288
|
+
deps.onOutcome?.(interrupted);
|
|
4289
|
+
}
|
|
4290
|
+
catch { }
|
|
4291
|
+
// Only an empty folder this run created: rmdir can't remove one with files in it.
|
|
4292
|
+
try {
|
|
4293
|
+
if (phase.at === 'backing-up' && phase.inPlace && phase.backup) {
|
|
4294
|
+
if (probe(phase.backup) === 'empty')
|
|
4295
|
+
rmdirSync(phase.backup);
|
|
4296
|
+
}
|
|
4297
|
+
}
|
|
4298
|
+
catch { }
|
|
4104
4299
|
}
|
|
4105
4300
|
finally {
|
|
4106
4301
|
process.exit(code);
|
|
@@ -4108,6 +4303,7 @@ async function run(plan, ui, deps = {}) {
|
|
|
4108
4303
|
},
|
|
4109
4304
|
});
|
|
4110
4305
|
try {
|
|
4306
|
+
before = await targetState(plan.target).catch(() => undefined);
|
|
4111
4307
|
// pnpm first: a pnpm that can't switch to the template's version stops the run before any file.
|
|
4112
4308
|
const spec = pnpmSpec(await readFile(join(from, 'package.json'), 'utf8'));
|
|
4113
4309
|
const pin = spec.slice('pnpm@'.length);
|
|
@@ -4171,7 +4367,7 @@ async function run(plan, ui, deps = {}) {
|
|
|
4171
4367
|
}
|
|
4172
4368
|
const seconds = Math.round((performance.now() - started) / 1000);
|
|
4173
4369
|
if (output.code !== 0) {
|
|
4174
|
-
throw new RunError(`Couldn't ${what} (pnpm exited with ${output.code})`, lastLines(output));
|
|
4370
|
+
throw new RunError('install-failed', `Couldn't ${what} (pnpm exited with ${output.code})`, lastLines(output));
|
|
4175
4371
|
}
|
|
4176
4372
|
const installed = plan.install;
|
|
4177
4373
|
ui.step(plan.install ? `Installed dependencies${using} (${seconds}s)` : 'Updated the lockfile');
|
|
@@ -4201,22 +4397,29 @@ async function run(plan, ui, deps = {}) {
|
|
|
4201
4397
|
let backup;
|
|
4202
4398
|
if (plan.replace && (await targetState(plan.target)) === 'not-empty') {
|
|
4203
4399
|
const cwd = deps.cwd ?? process.cwd();
|
|
4204
|
-
|
|
4205
|
-
|
|
4400
|
+
const inPlace = await holdsCwd(plan.target, cwd);
|
|
4401
|
+
phase = { at: 'backing-up', inPlace, backup: undefined };
|
|
4402
|
+
const onPath = (path) => {
|
|
4403
|
+
phase = { at: 'backing-up', inPlace, backup: path };
|
|
4404
|
+
};
|
|
4405
|
+
try {
|
|
4406
|
+
backup = await (deps.backUp ?? backUp)(plan.target, plan.now, { cwd, onPath });
|
|
4407
|
+
}
|
|
4408
|
+
catch (error) {
|
|
4409
|
+
throw coded('backup-failed', error);
|
|
4410
|
+
}
|
|
4206
4411
|
phase = { at: 'backed-up', backup };
|
|
4207
4412
|
ui.step(`Moved the old ${name} to ${basename(backup)}`);
|
|
4208
4413
|
}
|
|
4209
4414
|
try {
|
|
4210
4415
|
phase = { at: 'moving', ...(backup && { backup }) };
|
|
4211
4416
|
await (deps.moveIntoPlace ?? moveIntoPlace)(temp, plan.target);
|
|
4212
|
-
phase = { at: 'moved' };
|
|
4417
|
+
phase = { at: 'moved', ...(backup && { backup }) };
|
|
4213
4418
|
}
|
|
4214
4419
|
catch (error) {
|
|
4215
4420
|
if (!backup)
|
|
4216
|
-
throw error;
|
|
4217
|
-
throw new RunError(`Couldn't move the project into place: ${firstLine(error)}`, [
|
|
4218
|
-
`The old files are in ${backup}.`,
|
|
4219
|
-
]);
|
|
4421
|
+
throw coded('move-failed', error);
|
|
4422
|
+
throw new RunError('move-failed', `Couldn't move the project into place: ${firstLine(error)}`, [`The old files are in ${backup}.`]);
|
|
4220
4423
|
}
|
|
4221
4424
|
return {
|
|
4222
4425
|
pnpm,
|
|
@@ -4228,7 +4431,28 @@ async function run(plan, ui, deps = {}) {
|
|
|
4228
4431
|
};
|
|
4229
4432
|
}
|
|
4230
4433
|
catch (error) {
|
|
4231
|
-
|
|
4434
|
+
let left;
|
|
4435
|
+
try {
|
|
4436
|
+
left = leftBehind(phase, before, probe, plan.target);
|
|
4437
|
+
}
|
|
4438
|
+
catch {
|
|
4439
|
+
left = { target: 'unknown' };
|
|
4440
|
+
}
|
|
4441
|
+
try {
|
|
4442
|
+
await (deps.rm ?? rm)(temp, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
|
|
4443
|
+
}
|
|
4444
|
+
catch {
|
|
4445
|
+
// The run's own error is the one to show; `left.temp` says what stayed behind.
|
|
4446
|
+
}
|
|
4447
|
+
try {
|
|
4448
|
+
if (probe(temp) !== 'missing')
|
|
4449
|
+
left = { ...left, temp };
|
|
4450
|
+
}
|
|
4451
|
+
catch {
|
|
4452
|
+
left = { ...left, temp };
|
|
4453
|
+
}
|
|
4454
|
+
if (typeof error === 'object' && error !== null)
|
|
4455
|
+
recorded.set(error, left);
|
|
4232
4456
|
throw error;
|
|
4233
4457
|
}
|
|
4234
4458
|
finally {
|
|
@@ -4236,15 +4460,6 @@ async function run(plan, ui, deps = {}) {
|
|
|
4236
4460
|
}
|
|
4237
4461
|
}
|
|
4238
4462
|
|
|
4239
|
-
const USAGE = 2;
|
|
4240
|
-
const FAILURE = 1;
|
|
4241
|
-
/** The machine needs fixing first (pnpm can't switch versions, or is too old); nothing was created. */
|
|
4242
|
-
const TOOLCHAIN = 3;
|
|
4243
|
-
const INTERRUPTED = 130;
|
|
4244
|
-
const usage = (message) => {
|
|
4245
|
-
process.stderr.write(`${message}\n`);
|
|
4246
|
-
return USAGE;
|
|
4247
|
-
};
|
|
4248
4463
|
const nameProblem = (folder, cwd) => {
|
|
4249
4464
|
try {
|
|
4250
4465
|
packageNameFromFolder(folder, cwd);
|
|
@@ -4297,115 +4512,103 @@ async function askPlan(ask, cwd, options, now, holder) {
|
|
|
4297
4512
|
}
|
|
4298
4513
|
return { ...planFromOptions(answers, cwd, now, holder), replace };
|
|
4299
4514
|
}
|
|
4300
|
-
function report(ui, error) {
|
|
4301
|
-
if (error instanceof CancelledError) {
|
|
4302
|
-
ui.fail(CANCELLED, []);
|
|
4303
|
-
return INTERRUPTED;
|
|
4304
|
-
}
|
|
4305
|
-
if (error instanceof ToolchainError) {
|
|
4306
|
-
ui.fail(error.message, error.lines);
|
|
4307
|
-
return TOOLCHAIN;
|
|
4308
|
-
}
|
|
4309
|
-
if (error instanceof RunError) {
|
|
4310
|
-
ui.fail(error.message, error.lines);
|
|
4311
|
-
return FAILURE;
|
|
4312
|
-
}
|
|
4313
|
-
const [title = 'Something went wrong', ...lines] = String(error instanceof Error ? error.message : error).split('\n');
|
|
4314
|
-
ui.fail(title, lines);
|
|
4315
|
-
return FAILURE;
|
|
4316
|
-
}
|
|
4317
4515
|
/** `--check`: is this machine's pnpm ready for the template's? Creates nothing. */
|
|
4318
4516
|
async function check(ui, exec) {
|
|
4319
4517
|
const spec = pnpmSpec();
|
|
4320
|
-
const version = spec.slice('pnpm@'.length);
|
|
4321
4518
|
ui.intro();
|
|
4322
4519
|
const pnpm = await detectPnpm(exec);
|
|
4323
|
-
if (pnpm.kind === 'none')
|
|
4324
|
-
|
|
4325
|
-
|
|
4326
|
-
|
|
4327
|
-
]);
|
|
4328
|
-
return 0;
|
|
4329
|
-
}
|
|
4330
|
-
if (pnpm.kind === 'old') {
|
|
4331
|
-
const error = tooOld(pnpm.version, spec);
|
|
4332
|
-
ui.fail(error.message, error.lines);
|
|
4333
|
-
return TOOLCHAIN;
|
|
4334
|
-
}
|
|
4520
|
+
if (pnpm.kind === 'none')
|
|
4521
|
+
return { ok: true, kind: 'checked', pnpm, warnings: [] };
|
|
4522
|
+
if (pnpm.kind === 'old')
|
|
4523
|
+
return { ok: false, error: failureFrom(tooOld(pnpm.version, spec)) };
|
|
4335
4524
|
try {
|
|
4336
4525
|
await checkSwitch(spec, pnpm.version, exec);
|
|
4337
4526
|
}
|
|
4338
4527
|
catch (error) {
|
|
4339
4528
|
if (!(error instanceof ToolchainError))
|
|
4340
4529
|
throw error;
|
|
4341
|
-
|
|
4342
|
-
return TOOLCHAIN;
|
|
4530
|
+
return { ok: false, error: failureFrom(error) };
|
|
4343
4531
|
}
|
|
4344
|
-
|
|
4345
|
-
return 0;
|
|
4532
|
+
return { ok: true, kind: 'checked', pnpm, warnings: [] };
|
|
4346
4533
|
}
|
|
4347
|
-
|
|
4348
|
-
|
|
4534
|
+
const isInteractive = (options, io) => !options.yes && (io.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY));
|
|
4535
|
+
/** The Ui a run shows: `--check` and pipes get plain text, a terminal gets the clack screens. */
|
|
4536
|
+
const chooseUi = (options, io) => io.ui ?? (!options.check && isInteractive(options, io) ? clackUi() : plainUi());
|
|
4537
|
+
/**
|
|
4538
|
+
* Runs the command and returns how it ended, without printing the result (progress goes to the Ui).
|
|
4539
|
+
* `--help` and `--version` are `main`'s: they print text and aren't an outcome.
|
|
4540
|
+
*/
|
|
4541
|
+
async function execute(argv, io = {}) {
|
|
4349
4542
|
const parsed = parseArgv(argv);
|
|
4350
4543
|
if (!parsed.ok)
|
|
4351
|
-
return
|
|
4544
|
+
return usageFailure(parsed.message);
|
|
4352
4545
|
const { options } = parsed;
|
|
4353
|
-
if (options.help) {
|
|
4354
|
-
process.stdout.write(`${helpText()}\n`);
|
|
4355
|
-
return 0;
|
|
4356
|
-
}
|
|
4357
|
-
if (options.version) {
|
|
4358
|
-
process.stdout.write(`${versionText()}\n`);
|
|
4359
|
-
return 0;
|
|
4360
|
-
}
|
|
4361
4546
|
if (options.check)
|
|
4362
|
-
return check(io
|
|
4547
|
+
return check(chooseUi(options, io), io.exec);
|
|
4363
4548
|
const cwd = io.cwd ?? process.cwd();
|
|
4364
|
-
const interactive =
|
|
4549
|
+
const interactive = isInteractive(options, io);
|
|
4365
4550
|
// A bad flag fails at once, before any question.
|
|
4366
4551
|
if (interactive) {
|
|
4367
4552
|
const problem = (options.folder !== undefined ? nameProblem(options.folder, cwd) : undefined) ??
|
|
4368
4553
|
(options.scope !== undefined ? scopeProblem(options.scope) : undefined);
|
|
4369
4554
|
if (problem)
|
|
4370
|
-
return
|
|
4555
|
+
return usageFailure(problem);
|
|
4371
4556
|
}
|
|
4372
4557
|
const now = new Date();
|
|
4373
4558
|
const holder = (await gitIdentity(cwd)).name;
|
|
4374
4559
|
let plan;
|
|
4375
4560
|
if (!interactive) {
|
|
4376
4561
|
if (options.folder === undefined) {
|
|
4377
|
-
return
|
|
4562
|
+
return usageFailure('Pass a folder name, for example: create-ts-monorepo-starter my-tools');
|
|
4378
4563
|
}
|
|
4379
4564
|
try {
|
|
4380
4565
|
plan = planFromOptions(options, cwd, now, holder);
|
|
4381
4566
|
}
|
|
4382
4567
|
catch (error) {
|
|
4383
4568
|
if (error instanceof NameError)
|
|
4384
|
-
return
|
|
4569
|
+
return usageFailure(error.message);
|
|
4385
4570
|
throw error;
|
|
4386
4571
|
}
|
|
4387
4572
|
}
|
|
4388
|
-
const ui =
|
|
4573
|
+
const ui = chooseUi(options, io);
|
|
4389
4574
|
ui.intro();
|
|
4390
4575
|
try {
|
|
4391
4576
|
if (plan && (await targetState(plan.target)) === 'not-empty') {
|
|
4392
4577
|
if (!options.force) {
|
|
4393
|
-
const
|
|
4394
|
-
|
|
4395
|
-
return FAILURE;
|
|
4578
|
+
const title = `${options.folder} isn't empty. Use another folder, or pass --force to move it aside.`;
|
|
4579
|
+
return { ok: false, error: { code: 'target-not-empty', title, lines: [], fixes: [] } };
|
|
4396
4580
|
}
|
|
4397
4581
|
plan.replace = true;
|
|
4398
4582
|
}
|
|
4399
4583
|
plan ??= await askPlan(createAsk(io.prompts), cwd, options, now, holder);
|
|
4400
|
-
const result = await run(plan, ui);
|
|
4401
|
-
|
|
4402
|
-
return
|
|
4584
|
+
const result = await run(plan, ui, io.runDeps);
|
|
4585
|
+
const left = { target: 'complete', ...(result.backup && { backup: result.backup }) };
|
|
4586
|
+
return { ok: true, kind: 'created', plan, result, warnings: [], left };
|
|
4403
4587
|
}
|
|
4404
4588
|
catch (error) {
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4589
|
+
const left = leftOf(error);
|
|
4590
|
+
const failure = failureFrom(error);
|
|
4591
|
+
// The interrupt path says this too; a failure would otherwise leave the folder unmentioned.
|
|
4592
|
+
if (left?.temp)
|
|
4593
|
+
failure.lines = [...failure.lines, leftoverLine(left.temp)];
|
|
4594
|
+
return { ok: false, error: failure, ...(left && { left }) };
|
|
4595
|
+
}
|
|
4596
|
+
}
|
|
4597
|
+
/** Runs the command, prints how it ended, and resolves with its exit code. */
|
|
4598
|
+
async function main(argv, io = {}) {
|
|
4599
|
+
const parsed = parseArgv(argv);
|
|
4600
|
+
if (parsed.ok && parsed.options.help) {
|
|
4601
|
+
process.stdout.write(`${helpText()}\n`);
|
|
4602
|
+
return 0;
|
|
4603
|
+
}
|
|
4604
|
+
if (parsed.ok && parsed.options.version) {
|
|
4605
|
+
process.stdout.write(`${versionText()}\n`);
|
|
4606
|
+
return 0;
|
|
4408
4607
|
}
|
|
4608
|
+
const ui = parsed.ok ? chooseUi(parsed.options, io) : (io.ui ?? plainUi());
|
|
4609
|
+
const outcome = await execute(argv, { ...io, ui });
|
|
4610
|
+
renderText(outcome, ui);
|
|
4611
|
+
return exitCode(outcome);
|
|
4409
4612
|
}
|
|
4410
4613
|
|
|
4411
4614
|
// Set the exit code instead of calling process.exit(), so pending output is flushed first.
|