create-efforge 0.1.0 → 0.2.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.
@@ -1,13 +1,15 @@
1
+ import { readdirSync } from "node:fs";
1
2
  import { dirname, join } from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
- import { Console, Context, Effect, FileSystem, Option, Path } from "effect";
4
+ import { Console, Context, Effect, Option, Path, Schema } from "effect";
4
5
  import { Argument, Command, Flag } from "effect/cli";
5
6
  import pc from "picocolors";
6
7
  import { loadAddons } from "../addon.js";
7
- import { exec } from "../exec.js";
8
+ import { exec, has } from "../exec.js";
8
9
  import { generate } from "../generate.js";
9
10
  import { askStack, DEFAULT_NAME } from "../prompts/flow.js";
10
11
  import { PromptIO } from "../prompts/navigable.js";
12
+ import { projectDirName } from "../projectName.js";
11
13
  import { generateRouteTree } from "../routeTree.js";
12
14
  import { slots } from "../slots.js";
13
15
  import { toCommand } from "../stack.js";
@@ -30,92 +32,201 @@ const silentIO = (io) => ({
30
32
  intro: () => Effect.void,
31
33
  section: () => Effect.void,
32
34
  info: () => Effect.void,
35
+ warn: () => Effect.void,
33
36
  note: () => Effect.void,
34
37
  outro: () => Effect.void,
35
38
  step: (_label, eff) => eff,
39
+ task: (_label, eff) => eff(() => { }),
36
40
  });
37
41
  /** Files `vp fmt` can format; the lockfile and dotfiles like .gitignore are left alone. */
38
42
  const formattable = /\.(?:tsx?|jsx?|json|jsonc|css|md)$/;
43
+ /** pnpm is required; checked before any prompt so nobody answers everything and then fails. */
44
+ export class PnpmMissing extends Schema.TaggedError()("PnpmMissing", {}) {
45
+ }
46
+ /** A post-write step failed: the files are on disk, `remaining` finishes the setup by hand. */
47
+ export class SetupIncomplete extends Schema.TaggedError()("SetupIncomplete", {
48
+ dir: Schema.String,
49
+ command: Schema.String,
50
+ output: Schema.String,
51
+ remaining: Schema.Array(Schema.String),
52
+ }) {
53
+ }
54
+ /** Node versions Vite+ supports; mirrors `engines` in package.json. */
55
+ const nodeSupported = (version) => {
56
+ const [major = 0, minor = 0] = version.replace(/^v/, "").split(".").map(Number);
57
+ return (major === 24 && minor >= 11) || major >= 26;
58
+ };
59
+ /** What to run after `create`, for this stack. */
60
+ export const nextSteps = (stack, o) => {
61
+ const steps = [];
62
+ if (!o.inPlace)
63
+ steps.push([`cd ${o.dirName}`]);
64
+ if (!o.installed)
65
+ steps.push(["pnpm install"]);
66
+ if (stack.infra === "alchemy") {
67
+ steps.push(["cp .env.example .env", "local values for Alchemy"]);
68
+ // D1 migrations still need wrangler.jsonc under Alchemy (a known v0.1 gap, docs/limits.md)
69
+ if (stack.database === "postgres") {
70
+ steps.push(["docker compose up -d --wait", "local Postgres"]);
71
+ steps.push(["pnpm db:migrate"]);
72
+ }
73
+ steps.push(["pnpm dev", "alchemy dev; deploying: see infra/README.md"]);
74
+ }
75
+ else {
76
+ if (stack.database === "postgres")
77
+ steps.push(["docker compose up -d --wait", "local Postgres"]);
78
+ if (stack.database !== "none")
79
+ steps.push(["pnpm db:migrate", stack.database === "d1" ? "local D1" : undefined]);
80
+ steps.push(["pnpm dev", "http://localhost:5173"]);
81
+ }
82
+ const width = Math.max(...steps.map(([c]) => c.length));
83
+ return steps
84
+ .map(([c, note]) => ` ${pc.cyan(c)}${note === undefined ? "" : ` ${" ".repeat(width - c.length)}${pc.dim(`# ${note}`)}`}`)
85
+ .join("\n");
86
+ };
39
87
  /** validate -> generate -> (dry-run | write -> git init -> pnpm install -> route tree -> format -> commit). */
40
88
  export const create = (opts) => Effect.gen(function* () {
41
89
  const live = yield* PromptIO;
42
90
  const path = yield* Path.Path;
43
- const fs = yield* FileSystem.FileSystem;
44
91
  const templatesDir = yield* TemplatesDir;
45
92
  // --json must keep stdout machine-readable: it never prompts and prints no chrome.
46
93
  const quiet = opts.json;
47
94
  const yes = opts.yes || opts.json;
48
95
  const io = quiet ? silentIO(live) : live;
49
96
  if (!quiet)
50
- yield* io.intro(`${pc.bgCyan(pc.black(" create-efforge "))}${pc.dim(" Effect apps on Cloudflare, already wired")}`);
51
- const stack = yield* askStack(opts.flags, io, { yes });
97
+ yield* io.intro(`${pc.bgCyan(pc.black(" efforge "))}${pc.dim(" Effect apps on Cloudflare, already wired")}`);
98
+ // `.` scaffolds into the current directory, named after it.
99
+ const inPlace = opts.flags.name === ".";
100
+ const flags = inPlace ? { ...opts.flags, name: path.basename(process.cwd()) } : opts.flags;
101
+ let git = opts.git;
102
+ if (!opts.dryRun) {
103
+ if (!nodeSupported(process.version))
104
+ yield* io.warn(`Node ${process.version} isn't supported by the generated project (Vite+ needs Node 24.11+ or 26+).`);
105
+ if (opts.install && !(yield* has("pnpm", process.cwd())))
106
+ return yield* new PnpmMissing();
107
+ if (git && !(yield* has("git", process.cwd()))) {
108
+ yield* io.warn("git isn't installed: skipping git init and the initial commit.");
109
+ git = false;
110
+ }
111
+ }
112
+ const targetFor = (name) => inPlace ? process.cwd() : path.resolve(projectDirName(name));
113
+ const stack = yield* askStack(flags, io, {
114
+ yes,
115
+ checkName: opts.dryRun
116
+ ? undefined
117
+ : (name) => {
118
+ const dir = targetFor(name);
119
+ return isOccupied(dir)
120
+ ? `${path.relative(process.cwd(), dir) || "."} already exists and isn't empty; pick another name`
121
+ : undefined;
122
+ },
123
+ });
52
124
  const command = toCommand(stack);
53
- const dirName = stack.name.split("/").pop() ?? stack.name;
54
- const dir = path.resolve(dirName);
125
+ const dirName = projectDirName(stack.name);
126
+ const dir = targetFor(stack.name);
55
127
  // Fail before generating (and before the confirm prompt) rather than after the user answered everything.
56
- if (!opts.dryRun && (yield* fs.exists(dir)) && (yield* fs.readDirectory(dir)).length > 0) {
128
+ if (!opts.dryRun && isOccupied(dir))
57
129
  return yield* new TargetNotEmpty({ dir });
58
- }
59
130
  const addons = yield* loadAddons(templatesDir);
60
131
  const tree = yield* generate(stack, addons);
61
132
  const files = [...tree.keys()].toSorted();
133
+ const shownCommand = inPlace ? command.replace(` ${stack.name} --`, " . --") : command;
62
134
  if (opts.dryRun) {
135
+ if (!opts.json && isOccupied(dir))
136
+ yield* io.warn(`${inPlace ? "This directory" : `./${dirName}`} isn't empty, so a real run would stop here.`);
63
137
  if (opts.json) {
64
138
  yield* Console.log(JSON.stringify({ stack, command, files }, null, 2));
65
139
  }
66
140
  else {
67
141
  yield* io.note(summary(stack), "Your stack");
68
- yield* Console.log(files.join("\n"));
69
- yield* io.outro(`${pc.dim("dry run: nothing written")} ${command}`);
142
+ yield* io.note(files.join("\n"), `${files.length} files`);
143
+ yield* io.outro(`${pc.dim("dry run: nothing written.")} Run it for real:\n ${shownCommand}`);
70
144
  }
71
145
  return;
72
146
  }
73
- yield* io.note(`${summary(stack)}\n\n${pc.dim("re-run non-interactively:")}\n${command}`, "Your stack");
147
+ yield* io.note(summary(stack), "Your stack");
74
148
  if (!yes) {
75
- const ok = yield* io.confirm({ id: "confirm", message: "Create it?", initial: true });
149
+ const ok = yield* io.confirm({
150
+ id: "confirm",
151
+ message: `Create it in ${inPlace ? "this directory" : `./${dirName}`}?`,
152
+ initial: true,
153
+ });
76
154
  if (ok !== true) {
77
155
  yield* io.outro("Nothing written.");
78
156
  return;
79
157
  }
80
158
  }
81
- yield* io.step("Writing files", writeTree(dir, tree));
82
- // Init before formatting: oxfmt honors .gitignore files up the directory tree, so a project
83
- // outside any repo would otherwise pick up a parent's ignore rules (a `*` hides every file).
84
- // A failure here must not fail the scaffold.
85
- const gitReady = opts.git
86
- ? yield* io.step("Initializing git", exec("git", ["init"], dir)).pipe(Effect.as(true), Effect.catchTag("CommandFailed", (e) => io
87
- .info(`git setup skipped: ${e.command} failed. ${e.output.trim().split("\n")[0] ?? ""}`)
88
- .pipe(Effect.as(false))))
89
- : false;
90
- if (opts.install) {
91
- yield* io.step("Installing dependencies (pnpm install)", exec("pnpm", ["install"], dir));
92
- // routeTree.gen.ts isn't committed to templates: write it now, so typecheck and format see it.
93
- yield* io
94
- .step("Generating the route tree (tsr generate)", generateRouteTree(dir))
95
- .pipe(Effect.catchTag("CommandFailed", (e) => io.info(`route tree skipped: ${e.command} failed. ${e.output.trim().split("\n")[0] ?? ""}; \`pnpm typecheck\` regenerates it`)));
96
- // Transforms insert code and bindings unformatted, so tidy them now: the first `pnpm check`
97
- // passes. Without a repo of its own, a parent repo's ignore rules could hide every file, so
98
- // name the files: explicit paths bypass ignore files. Anything oxfmt can't fix is the user's to see.
99
- const targets = gitReady ? [] : files.filter((f) => formattable.test(f));
100
- yield* io
101
- .step("Formatting (vp fmt)", exec("pnpm", ["format", ...targets], dir))
102
- .pipe(Effect.catchTag("CommandFailed", () => Effect.void));
103
- }
104
- if (gitReady) {
105
- // Plain commit: whatever identity git is configured with.
106
- yield* io
107
- .step("Creating the initial commit", Effect.gen(function* () {
108
- yield* exec("git", ["add", "-A"], dir);
109
- yield* exec("git", ["commit", "-m", "Initial commit from efforge"], dir);
110
- }))
111
- .pipe(Effect.catchTag("CommandFailed", (e) => io.info(`git commit skipped: ${e.command} failed. ${e.output.trim().split("\n")[0] ?? ""}`)));
112
- }
159
+ const remaining = [];
160
+ let written = false;
161
+ const setup = Effect.gen(function* () {
162
+ yield* io.step(`Writing ${files.length} files`, writeTree(dir, tree));
163
+ written = true;
164
+ // Init before formatting: oxfmt honors .gitignore files up the directory tree, so a project
165
+ // outside any repo would otherwise pick up a parent's ignore rules (a `*` hides every file).
166
+ // A failure here must not fail the scaffold.
167
+ const gitReady = git
168
+ ? yield* io.step("Initializing git", exec("git", ["init"], dir)).pipe(Effect.as(true), Effect.catchTag("CommandFailed", (e) => io
169
+ .info(`git setup skipped: ${e.command} failed. ${e.output.trim().split("\n")[0] ?? ""}`)
170
+ .pipe(Effect.as(false))))
171
+ : false;
172
+ if (opts.install)
173
+ remaining.push("pnpm install", "pnpm format");
174
+ if (gitReady)
175
+ remaining.push("git add -A && git commit -m 'Initial commit'");
176
+ if (opts.install) {
177
+ yield* io.task("Installing dependencies (pnpm install)", (log) => exec("pnpm", ["install"], dir, log));
178
+ remaining.shift();
179
+ // routeTree.gen.ts isn't committed to templates: write it now, so typecheck and format see it.
180
+ yield* io
181
+ .step("Generating the route tree", generateRouteTree(dir))
182
+ .pipe(Effect.catchTag("CommandFailed", (e) => io.info(`route tree skipped: ${e.command} failed. ${e.output.trim().split("\n")[0] ?? ""}; \`pnpm typecheck\` regenerates it`)));
183
+ // Transforms insert code and bindings unformatted, so tidy them now: the first `pnpm check`
184
+ // passes. Without a repo of its own, a parent repo's ignore rules could hide every file, so
185
+ // name the files: explicit paths bypass ignore files. Anything oxfmt can't fix is the user's to see.
186
+ const targets = gitReady ? [] : files.filter((f) => formattable.test(f));
187
+ yield* io
188
+ .step("Formatting", exec("pnpm", ["format", ...targets], dir))
189
+ .pipe(Effect.catchTag("CommandFailed", () => Effect.void));
190
+ remaining.shift();
191
+ }
192
+ if (gitReady) {
193
+ // Plain commit: whatever identity git is configured with.
194
+ yield* io
195
+ .step("Creating the initial commit", Effect.gen(function* () {
196
+ yield* exec("git", ["add", "-A"], dir);
197
+ yield* exec("git", ["commit", "-m", "Initial commit from efforge"], dir);
198
+ }))
199
+ .pipe(Effect.catchTag("CommandFailed", (e) => io.info(`git commit skipped: ${e.command} failed. ${e.output.trim().split("\n")[0] ?? ""}${/identity|user\.(name|email)/i.test(e.output) ? " Set git config user.name and user.email, then commit." : ""}`)));
200
+ remaining.length = 0;
201
+ }
202
+ });
203
+ yield* setup.pipe(Effect.catchTag("CommandFailed", (e) => Effect.fail(new SetupIncomplete({
204
+ dir,
205
+ command: e.command,
206
+ output: e.output,
207
+ remaining: [...remaining],
208
+ }))), Effect.onInterrupt(() => io.warn(!written
209
+ ? `Stopped while writing files. Delete ${inPlace ? "what was written here" : `./${dirName}`} and run efforge again.`
210
+ : remaining.length === 0
211
+ ? `Stopped. ./${dirName} is set up; only the last step was skipped.`
212
+ : `Stopped. ./${dirName} is only partly set up: delete it, or finish with:\n ${remaining.join("\n ")}`)));
113
213
  if (opts.json) {
114
214
  yield* Console.log(JSON.stringify({ stack, command, files }, null, 2));
115
215
  return;
116
216
  }
117
- yield* io.outro(`${pc.green("Done.")}\n\n cd ${dirName}\n ${opts.install ? "" : "pnpm install\n "}pnpm dev\n\n${pc.dim("Same stack later:")} ${command}`);
217
+ yield* io.note(nextSteps(stack, { dirName, inPlace, installed: opts.install }), "Next steps");
218
+ yield* io.outro(`${pc.green("Done.")} ${pc.dim("Add more later:")} npx create-efforge list\n ${pc.dim("Same stack again:")} ${command}`);
118
219
  });
220
+ /** Exists and has something in it besides `.git` and OS clutter. */
221
+ export const isOccupied = (dir) => {
222
+ try {
223
+ return readdirSync(dir).some((f) => !ignorable.has(f));
224
+ }
225
+ catch {
226
+ return false;
227
+ }
228
+ };
229
+ const ignorable = new Set([".git", ".DS_Store", "Thumbs.db"]);
119
230
  // --- CLI -----------------------------------------------------------------------
120
231
  const slotFlag = (id) => {
121
232
  const slot = slots.find((s) => s.id === id);
@@ -161,26 +272,48 @@ export const toCreateOptions = (input) => ({
161
272
  install: input.install,
162
273
  git: input.git,
163
274
  });
275
+ const flagHint = (id, options) => id === "name"
276
+ ? "pass a project name"
277
+ : id === "confirm"
278
+ ? "pass --yes to create without confirming"
279
+ : `pass --${id}=${options.join("|")}${id === "extras" ? " (comma-separated, or --extras= for none)" : ""}`;
164
280
  const describe = (e) => {
165
281
  switch (e._tag) {
166
- case "IncompatibleStack":
167
- return `--${String(e.slot)}=${String(e.value)} isn't available with the other choices. Options: ${e.allowed.join(", ")}${typeof e.reason === "string" ? `. ${e.reason}` : ""}`;
282
+ case "IncompatibleStack": {
283
+ const slot = slots.find((x) => x.id === e.slot);
284
+ const known = slot?.options.some((o) => o.id === e.value) ?? false;
285
+ const allowed = e.allowed.join(", ");
286
+ return known
287
+ ? `--${String(e.slot)}=${String(e.value)} can't be used here${typeof e.reason === "string" ? `: ${e.reason}.` : `. Options: ${allowed}`}`
288
+ : `Unknown --${String(e.slot)}=${String(e.value)}. Options: ${allowed}`;
289
+ }
290
+ case "InvalidProjectName":
291
+ return String(e.message);
168
292
  case "TargetNotEmpty":
169
- return `${String(e.dir)} already exists and is not empty. Pick another name or remove it.`;
170
- case "CommandFailed":
171
- return `\`${String(e.command)}\` failed. The project was written; run it yourself.\n${String(e.output).trim()}`;
293
+ return `${String(e.dir)} already exists and isn't empty. Pick another name or remove it.`;
294
+ case "NeedsInput":
295
+ return `No terminal to ask for "${String(e.id)}": ${flagHint(String(e.id), e.options)}, or --yes to accept the defaults.`;
296
+ case "PnpmMissing":
297
+ return "efforge projects use pnpm, and it isn't on your PATH. Install it (corepack enable pnpm, or https://pnpm.io/installation) and re-run, or pass --no-install.";
298
+ case "SetupIncomplete": {
299
+ const rest = e.remaining;
300
+ return `\`${String(e.command)}\` failed. The files are in ${String(e.dir)}${rest.length > 0 ? `; to finish, run there:\n ${rest.join("\n ")}` : "."}\n\n${String(e.output).trim().split("\n").slice(-15).join("\n")}`;
301
+ }
172
302
  default:
173
303
  return e.message ?? e._tag;
174
304
  }
175
305
  };
176
- /** Command handler: reports failures as one clear line and exit code 1; cancelling exits 0. */
306
+ /** Command handler: one clear error and exit code 1; cancelling exits 130 like any Ctrl-C. */
177
307
  export const createHandler = (input) => create(toCreateOptions(input)).pipe(Effect.catch((e) => Effect.gen(function* () {
178
308
  const io = yield* PromptIO;
179
- if (e._tag === "Cancelled")
180
- return yield* io.outro("Cancelled.");
181
- yield* Console.error(pc.red(describe(e)));
309
+ const cancelled = e._tag === "Cancelled";
182
310
  yield* Effect.sync(() => {
183
- process.exitCode = 1;
311
+ process.exitCode = cancelled ? 130 : 1;
184
312
  });
313
+ if (cancelled)
314
+ return yield* io.outro("Cancelled. Nothing written.");
315
+ if (input.json)
316
+ return yield* Console.log(JSON.stringify({ error: { code: e._tag, message: describe(e) } }, null, 2));
317
+ yield* Console.error(pc.red(describe(e)));
185
318
  })));
186
319
  export const createCommand = Command.make("create", createConfig, createHandler).pipe(Command.withDescription("Create a new app"));
@@ -0,0 +1,80 @@
1
+ import { Console, Effect, Path } from "effect";
2
+ import { Command, Flag } from "effect/cli";
3
+ import pc from "picocolors";
4
+ import { loadAddons } from "../addon.js";
5
+ import { slots } from "../slots.js";
6
+ import { readManifest } from "./add.js";
7
+ import { TemplatesDir } from "./create.js";
8
+ /** Every option of every slot, with its add-on description; `none` and single-option slots are left out. */
9
+ export const listAddons = (cwd) => Effect.gen(function* () {
10
+ const addons = yield* loadAddons(yield* TemplatesDir);
11
+ // outside a project, list everything; a --cwd that doesn't exist is a mistake worth reporting
12
+ const stack = yield* readManifest(cwd).pipe(Effect.map((m) => m.stack), Effect.catchTag("NotAnEfforgeProject", (e) => e.reason === "efforge.jsonc not found" ? Effect.succeed(undefined) : Effect.fail(e)));
13
+ const out = [];
14
+ for (const slot of slots) {
15
+ if (slot.options.length <= 1)
16
+ continue;
17
+ for (const o of slot.options) {
18
+ if (o.id === "none")
19
+ continue;
20
+ const id = `${slot.id}/${o.id}`;
21
+ const m = addons.get(id)?.manifest;
22
+ const installed = stack === undefined
23
+ ? undefined
24
+ : slot.id === "extras"
25
+ ? stack.extras.includes(o.id)
26
+ : stack[slot.id] === o.id;
27
+ out.push({
28
+ id,
29
+ slot: slot.id,
30
+ option: o.id,
31
+ title: m?.title ?? o.label,
32
+ description: m?.description ?? o.hint ?? "",
33
+ ...(installed === undefined ? {} : { installed }),
34
+ });
35
+ }
36
+ }
37
+ return { project: stack !== undefined, addons: out };
38
+ });
39
+ /** First clause of a description, cut to fit the terminal. */
40
+ const short = (s, room) => {
41
+ const clause = s.split(/[:;]\s|\.(?:\s|$)/)[0] ?? s;
42
+ return clause.length <= room ? clause : `${clause.slice(0, Math.max(10, room - 1)).trimEnd()}…`;
43
+ };
44
+ export const listCommand = Command.make("list", {
45
+ json: Flag.Boolean("json").pipe(Flag.withDescription("Print the add-ons as JSON on stdout"), Flag.withDefault(false)),
46
+ cwd: Flag.String("cwd").pipe(Flag.withDescription("Mark what this efforge project already has (default: current directory)"), Flag.withDefault(".")),
47
+ }, (input) => Effect.gen(function* () {
48
+ const path = yield* Path.Path;
49
+ const { project, addons } = yield* listAddons(path.resolve(input.cwd));
50
+ if (input.json)
51
+ return yield* Console.log(JSON.stringify(addons, null, 2));
52
+ const width = Math.max(...addons.map((a) => a.id.length));
53
+ // cut descriptions to the terminal; piped output keeps them whole, a very narrow one drops them
54
+ const room = process.stdout.isTTY ? (process.stdout.columns || 80) - width - 6 : undefined;
55
+ const lines = [];
56
+ let slot = "";
57
+ for (const a of addons) {
58
+ if (a.slot !== slot) {
59
+ slot = a.slot;
60
+ const def = slots.find((s) => s.id === slot);
61
+ lines.push("", pc.bold(def?.title ?? slot));
62
+ }
63
+ const mark = a.installed === true ? pc.green("✓") : " ";
64
+ if (room !== undefined && room < 20) {
65
+ lines.push(`${mark} ${a.installed === true ? pc.dim(a.id) : pc.cyan(a.id)}`);
66
+ continue;
67
+ }
68
+ lines.push(`${mark} ${a.installed === true ? pc.dim(a.id.padEnd(width)) : pc.cyan(a.id.padEnd(width))} ${pc.dim(room === undefined ? a.description : short(a.description, room))}`);
69
+ }
70
+ lines.push("", pc.dim(project
71
+ ? "✓ already in this project. Add one with: npx create-efforge add <id>"
72
+ : "Pick them in npm create efforge, or add one later with: npx create-efforge add <id>"));
73
+ yield* Console.log(lines.join("\n").replace(/^\n/, ""));
74
+ }).pipe(Effect.catch((e) => Effect.gen(function* () {
75
+ const err = e;
76
+ yield* Console.error(pc.red(err.message ?? err._tag));
77
+ yield* Effect.sync(() => {
78
+ process.exitCode = 1;
79
+ });
80
+ })))).pipe(Command.withDescription("List the add-ons you can pick or add later"));
package/dist/exec.js CHANGED
@@ -6,15 +6,28 @@ export class CommandFailed extends Schema.TaggedError()("CommandFailed", {
6
6
  output: Schema.String,
7
7
  }) {
8
8
  }
9
- /** Runs `cmd args` in `cwd`, returning combined output; a non-zero exit fails with `CommandFailed`. */
10
- export const exec = (cmd, args, cwd) => {
9
+ /**
10
+ * Runs `cmd args` in `cwd`, returning combined output; a non-zero exit fails with `CommandFailed`.
11
+ * `onLine` sees each output line as it arrives (for live progress).
12
+ */
13
+ export const exec = (cmd, args, cwd, onLine) => {
11
14
  const command = [cmd, ...args].join(" ");
12
15
  return Effect.gen(function* () {
13
16
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
14
17
  const handle = yield* spawner.spawn(ChildProcess.make(cmd, [...args], { cwd }));
15
- const [output, code] = yield* Effect.all([handle.all.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode], { concurrency: 2 });
18
+ const lines = [];
19
+ const [, code] = yield* Effect.all([
20
+ handle.all.pipe(Stream.decodeText(), Stream.splitLines, Stream.runForEach((line) => Effect.sync(() => {
21
+ lines.push(line);
22
+ onLine?.(line);
23
+ }))),
24
+ handle.exitCode,
25
+ ], { concurrency: 2 });
26
+ const output = lines.join("\n");
16
27
  if (code !== 0)
17
28
  return yield* new CommandFailed({ command, exitCode: code, output });
18
29
  return output;
19
30
  }).pipe(Effect.scoped, Effect.catchTag("PlatformError", (e) => new CommandFailed({ command, output: e.message })));
20
31
  };
32
+ /** True when `cmd --version` runs; used to check for pnpm and git before writing anything. */
33
+ export const has = (cmd, cwd) => exec(cmd, ["--version"], cwd).pipe(Effect.as(true), Effect.catchTag("CommandFailed", () => Effect.succeed(false)));
@@ -1,16 +1,24 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { IncompatibleStack, validate } from "../rules.js";
3
- import { available, slots } from "../slots.js";
3
+ import { available, slots, whyUnavailable } from "../slots.js";
4
4
  import { ProjectName } from "../stack.js";
5
5
  import { GoBack } from "./navigable.js";
6
6
  export class InvalidProjectName extends Schema.TaggedError()("InvalidProjectName", { name: Schema.String, message: Schema.String }) {
7
7
  }
8
8
  export const DEFAULT_NAME = "my-app";
9
+ /** Names npm refuses, or that would shadow a well-known directory. */
10
+ const reserved = new Set(["node_modules", "favicon.ico", "test", "tests", "src", "dist"]);
9
11
  const nameError = (name) => {
12
+ if (name.length > 214)
13
+ return `the name is ${name.length} characters; npm allows 214`;
14
+ if (reserved.has(name))
15
+ return `"${name}" is a reserved or confusing package name; pick another`;
10
16
  const r = Schema.decodeUnknownExit(ProjectName)(name);
11
17
  return r._tag === "Success"
12
18
  ? undefined
13
- : "Use a valid npm package name: lowercase letters, digits, - . _ ~ (optionally @scope/name), no '..'";
19
+ : name.includes("/") && !name.startsWith("@")
20
+ ? `"${name}" is a path; run efforge from the parent directory and pass just the name`
21
+ : `"${name}" isn't a valid npm package name: use lowercase letters, digits, - . _ ~ (optionally @scope/name)`;
14
22
  };
15
23
  const defaultFor = (slot, options) => {
16
24
  if (slot.multi)
@@ -35,7 +43,7 @@ export const askStack = (flags, io, opts = {}) => Effect.gen(function* () {
35
43
  message: "Project name",
36
44
  placeholder: DEFAULT_NAME,
37
45
  defaultValue: DEFAULT_NAME,
38
- validate: nameError,
46
+ validate: (n) => nameError(n) ?? opts.checkName?.(n),
39
47
  });
40
48
  name = answer === GoBack ? DEFAULT_NAME : answer;
41
49
  }
@@ -58,10 +66,13 @@ export const askStack = (flags, io, opts = {}) => Effect.gen(function* () {
58
66
  const values = typeof flag === "string" ? [flag] : flag;
59
67
  for (const value of values) {
60
68
  if (!ids.includes(value)) {
61
- return yield* new IncompatibleStack({ slot: slot.id, value, allowed: ids });
69
+ const reason = whyUnavailable(slot.id, value, draft);
70
+ return yield* new IncompatibleStack(reason === undefined
71
+ ? { slot: slot.id, value, allowed: ids }
72
+ : { slot: slot.id, value, allowed: ids, reason });
62
73
  }
63
74
  }
64
- draft[slot.id] = slot.multi ? values : flag;
75
+ draft[slot.id] = slot.multi ? [...new Set(values)] : flag;
65
76
  i++;
66
77
  continue;
67
78
  }