@openelement/create 1.0.0-alpha.13 → 1.0.0-alpha.15

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.
Files changed (34) hide show
  1. package/README.md +49 -19
  2. package/package.json +1 -1
  3. package/src/cli.js +159 -76
  4. package/src/node-version.js +102 -0
  5. package/src/pm.js +143 -9
  6. package/src/template-builder.js +59 -6
  7. package/src/version.js +2 -10
  8. package/templates/.node-version +1 -0
  9. package/templates/AGENTS.md.tmpl +44 -0
  10. package/templates/README.tmpl +140 -74
  11. package/templates/app/components/page-404.css +5 -7
  12. package/templates/app/components/page-404.tsx.tmpl +16 -37
  13. package/templates/app/components/page-about.css +5 -15
  14. package/templates/app/components/page-about.tsx.tmpl +86 -82
  15. package/templates/app/components/page-home.css +5 -23
  16. package/templates/app/components/page-home.tsx.tmpl +137 -114
  17. package/templates/app/components/site-chrome.css +5 -15
  18. package/templates/app/head.tsx.tmpl +12 -23
  19. package/templates/app/islands/live-timer.css +5 -9
  20. package/templates/app/islands/live-timer.tsx.tmpl +31 -21
  21. package/templates/app/islands/my-counter.css +5 -11
  22. package/templates/app/islands/my-counter.tsx.tmpl +26 -13
  23. package/templates/app/layout.tsx.tmpl +68 -0
  24. package/templates/app/routes/404.tsx.tmpl +7 -10
  25. package/templates/app/routes/about.tsx.tmpl +4 -4
  26. package/templates/app/routes/api/ping.ts.tmpl +4 -5
  27. package/templates/app/routes/index.tsx.tmpl +4 -4
  28. package/templates/app/styles/theme.css +64 -79
  29. package/templates/openelement.config.ts.tmpl +21 -33
  30. package/templates/package.json.tmpl +14 -10
  31. package/templates/tsconfig.json.tmpl +1 -1
  32. package/templates/vite.config.ts.tmpl +9 -7
  33. package/templates/app/components/badges.css +0 -5
  34. package/templates/app/styles/recipes.css +0 -43
package/README.md CHANGED
@@ -14,7 +14,14 @@ Docs and guides: <https://openelement.org>.
14
14
  the showcase starter: a static-first landing page with two islands, a fully
15
15
  static About page, an `/api/ping` server route, and a Tailwind-ON design-token
16
16
  sheet (the `@theme` role table; one template, no variants). The generated
17
- project is a plain Node/pnpm project.
17
+ project is a plain Node project with no package-manager pin: every script is a
18
+ plain command, the manifest declares no `packageManager` field, and the
19
+ scaffold ships no `pnpm-workspace.yaml`, so the generated project installs and
20
+ runs its lifecycle scripts under npm, pnpm, yarn, or bun. (The bootstrap itself
21
+ is documented as `npm create` / `npx`; the `pnpm dlx` form names the two-bin
22
+ package explicitly.) The repository's own
23
+ development flow (Vite+ / `vp`) stays in this repository and appears nowhere in
24
+ the generated manifest or scripts.
18
25
 
19
26
  ## Usage (1.0 Alpha)
20
27
 
@@ -22,20 +29,36 @@ project is a plain Node/pnpm project.
22
29
  npm create @openelement my-app
23
30
  ```
24
31
 
25
- The CLI scaffolds, initializes git (when git is available), detects a package
26
- manager (pnpm first, then npm), installs dependencies, and prints a boxed
32
+ The CLI scaffolds, detects the first package manager on PATH (pnpm, then npm,
33
+ then yarn, then bun — failing only when none of the four exists, with a message
34
+ naming all four), installs dependencies with it, initializes git (when git is
35
+ available and the target is not already inside a repository), and prints a boxed
27
36
  handoff with the next commands. Flags (all optional):
28
37
 
29
38
  | Flag | Default | Meaning |
30
39
  | --- | --- | --- |
31
- | `-t, --template <name>` | `showcase` | the template to scaffold; skips the interactive confirmation |
32
- | `--install` / `--no-install` | install | dependency installation after scaffolding |
40
+ | `-t, --template <name>` | `showcase` | the template to scaffold (the only value; names it explicitly) |
41
+ | `--install` / `--no-install` | install | dependency installation after scaffolding; a skipped install is taught in the handoff box (the detected manager's `<pm> install`, or `npm install`) |
33
42
  | `--start` | off | start the dev server after a successful install |
34
- | `--git` / `--no-git` | git init | initialize a git repository (requires the scaffold's `.gitignore`) |
43
+ | `--git` / `--no-git` | git init | initialize a git repository, skipped with a note when the target already lives inside one (requires the scaffold's `.gitignore`) |
35
44
 
36
- On a TTY the CLI asks exactly one question — confirming the template (Enter
37
- accepts the default). Non-interactive runs (CI, packed consumers) skip the
38
- prompt and take the defaults; pass `-t` to pin the template explicitly.
45
+ The target is a new directory, an existing EMPTY directory, or `.` for the
46
+ current directory (which the same emptiness rule applies to):
47
+
48
+ ```bash
49
+ npm create @openelement my-app # new, or already empty, directory
50
+ npm create @openelement . # the current directory, which must be empty
51
+ ```
52
+
53
+ A non-empty target is refused, and the error names the entries that are in the
54
+ way — the CLI never merges into files it does not own and never advises
55
+ deleting a directory it did not create. An in-place scaffold writes the
56
+ manifest name from the directory's own name (lowercased into the npm
57
+ package-name grammar).
58
+
59
+ The template is fixed — one template, `showcase`. `-t` names it explicitly, and
60
+ without `-t` the CLI scaffolds it directly: no prompt on a TTY either.
61
+ Non-interactive runs (CI, packed consumers) behave identically.
39
62
 
40
63
  ```bash
41
64
  npx @openelement/create my-app --no-install --no-git -t showcase
@@ -52,11 +75,11 @@ verified to serve. The 1.0 line is a new baseline — not a 0.x upgrade, with no
52
75
  migration path from 0.x. Pin an exact version when reproducibility matters:
53
76
 
54
77
  ```bash
55
- npm create @openelement@<version> my-app
78
+ npm create @openelement@1.0.0-alpha.14 my-app
56
79
  ```
57
80
 
58
81
  The generated starter depends on `@openelement/*` through caret ranges over
59
- the release it was generated from, so `pnpm update` picks up later `1.0.0`
82
+ the release it was generated from, so a dependency update picks up later `1.0.0`
60
83
  prereleases without a manifest edit.
61
84
 
62
85
  The canonical install command is exported from `@openelement/create/install-command` (one builder, every documented copy derives from it).
@@ -75,8 +98,8 @@ npx @openelement/create my-app
75
98
  pnpm dlx --package=@openelement/create openelement-create my-app
76
99
  ```
77
100
 
78
- The scaffolded project itself is Node-native: Node.js 24.2+ and
79
- pnpm run its scripts.
101
+ The scaffolded project itself is Node-native: Node.js 24.2+ runs it, and any of
102
+ npm, pnpm, yarn, or bun runs its scripts.
80
103
 
81
104
  ## Stable 0.43 (maintenance line)
82
105
 
@@ -91,10 +114,14 @@ npm create @openelement@0.43 my-app
91
114
  ## Requirements
92
115
 
93
116
  - **Bootstrap:** Node.js 24.2+ with npm (or pnpm for the `pnpm dlx` variant) —
94
- the verified floor this repository exercises in CI.
117
+ the verified floor this repository exercises in CI. The generator checks the
118
+ host version before it writes anything: an older Node exits 1 with the exact
119
+ install command instead of scaffolding a project it cannot run.
95
120
  - **Generated project:** Node.js 24.2+ (the floor the packed `@openelement/*`
96
- engines declare and CI exercises; `.node-version` pins the development
97
- line) and pnpm for the lifecycle scripts.
121
+ engines declare and CI exercises) and any one of npm, pnpm, yarn, or bun for
122
+ the lifecycle scripts — nothing in the scaffold requires a specific manager.
123
+ The scaffold ships a `.node-version` pinning 24.18.0, the development line
124
+ this repository pins at its root.
98
125
  - **git (optional):** `git init` runs by default and skips silently when git
99
126
  is not on PATH.
100
127
 
@@ -102,9 +129,10 @@ npm create @openelement@0.43 my-app
102
129
 
103
130
  - `package.json` - starter dependencies (`@openelement/*` with caret ranges
104
131
  over the generated-from release)
105
- and the lifecycle scripts (`dev`/`check`/`test`/`build`/`start`; `build` and
106
- `start` run the `openelement` bin from `@openelement/router`)
107
- - `tsconfig.json` - the type-check surface for `pnpm check`: JSX authoring
132
+ and the lifecycle scripts
133
+ (`dev`/`fmt`/`lint`/`typecheck`/`test`/`build`/`start`; `dev`, `build` and
134
+ `start` run the router's `oe` bin, `fmt`/`lint` run `oxfmt`/`oxlint`)
135
+ - `tsconfig.json` - the type-check surface for `npm run typecheck`: JSX authoring
108
136
  through the element import source, whole-`app/` coverage
109
137
  - `vite.config.ts` - Vite build configuration only; framework options still
110
138
  have exactly one home:
@@ -130,6 +158,8 @@ npm create @openelement@0.43 my-app
130
158
  `prefers-color-scheme`)
131
159
  - `public/` - static assets
132
160
  - `README.md` and `.gitignore` - starter docs and ignore rules
161
+ - `.node-version` - the Node development pin (`24.18.0`; the supported floor
162
+ stays `24.2`)
133
163
 
134
164
  The generated dependency set intentionally keeps protocol and build internals
135
165
  out of the starter surface. Advanced contracts remain available through the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openelement/create",
3
- "version": "1.0.0-alpha.13",
3
+ "version": "1.0.0-alpha.15",
4
4
  "type": "module",
5
5
  "main": "./src/cli.js",
6
6
  "types": "./src/cli.d.ts",
package/src/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { CREATE_VERSION } from "./version.js";
3
- import { buildTemplates, resolveVersions, validateProjectName } from "./template-builder.js";
3
+ import { buildTemplates, inPlaceProjectName, resolveVersions, validateProjectName } from "./template-builder.js";
4
4
  import { createInstallCommand } from "./install-command.js";
5
- import { detectPackageManager } from "./pm.js";
5
+ import { assertSupportedNode } from "./node-version.js";
6
+ import { PACKAGE_MANAGERS, devCommand, installDependenciesCommand, resolvePackageManager } from "./pm.js";
6
7
  import { spawn, spawnSync } from "node:child_process";
7
8
  import { existsSync } from "node:fs";
8
- import { mkdir, stat, writeFile } from "node:fs/promises";
9
+ import { mkdir, readdir, stat, writeFile } from "node:fs/promises";
9
10
  import process from "node:process";
10
- import readline from "node:readline/promises";
11
11
  //#region src/cli.ts
12
12
  /**
13
13
  * @openelement/create - project scaffold for the openElement framework.
@@ -18,19 +18,37 @@ import readline from "node:readline/promises";
18
18
  *
19
19
  * One template (#1530): the showcase starter — a static-first landing page
20
20
  * with two islands, a fully static About page, and an /api/ping server route.
21
- * The interactive surface is one confirmation (the template) on a TTY; every
22
- * other behavior is a flag with a default, so CI and packed consumers run
23
- * without a prompt.
21
+ * There is nothing to ask: a bare run scaffolds that template, and every
22
+ * behavior is a flag with a default, so CI and packed consumers run without a
23
+ * prompt and a TTY run is identical to a piped one.
24
24
  *
25
- * Post-scaffold lifecycle: git init (default), dependency install via the
26
- * detected package manager (pnpm first, then npm — default on), an optional
27
- * dev-server start (--start), and a boxed handoff naming the next commands.
25
+ * Post-scaffold lifecycle: git init (default, skipped when the target already
26
+ * lives inside a repository), dependency install with the INVOKING package
27
+ * manager when the wrapper named one (npm create / pnpm dlx / yarn / bunx) and
28
+ * otherwise the first of pnpm, npm, yarn, bun on PATH (default on), an optional
29
+ * dev-server start (--start), and a boxed handoff naming the next commands in
30
+ * that same manager's spelling.
31
+ *
32
+ * Target: a new directory, an existing EMPTY directory, or `.` for the
33
+ * current directory (which the same emptiness rule applies to). A non-empty
34
+ * target is refused with the entries that are in the way; the CLI never
35
+ * advises deleting a directory it did not create.
36
+ *
37
+ * Manager-neutral since alpha.15: the template carries explicit version pins
38
+ * and no `packageManager` field, so no install protocol is manager-specific
39
+ * and the scaffold installs with whichever of the four the host has. The
40
+ * manager is resolved by ./pm.ts (TPL-02): the invoking wrapper first, the PATH
41
+ * probe second. Only a run with neither fails, and that message names all four.
28
42
  *
29
43
  * L9: every failure mode exits 1 with one actionable message — never a
30
44
  * runtime stack trace.
31
45
  */
32
46
  /** The one scaffold template (#1530). `-t/--template` pins it non-interactively. */
33
47
  const TEMPLATE_NAME = "showcase";
48
+ /** The positional that means "scaffold into the current directory". */
49
+ const IN_PLACE_TARGET = ".";
50
+ /** How many conflicting entries an "already occupied" error names inline. */
51
+ const MAX_LISTED_CONFLICTS = 5;
34
52
  const DOCS_URL = "https://openelement.org";
35
53
  function errorMessage(error) {
36
54
  return error instanceof Error ? error.message : String(error);
@@ -56,6 +74,24 @@ function dirnameOf(path) {
56
74
  if (idx <= 0) return ".";
57
75
  return path.slice(0, idx);
58
76
  }
77
+ /**
78
+ * The parent of an absolute-or-relative path, or `null` at a filesystem root.
79
+ * node:path is deliberately not imported (the CLI keeps its module surface to
80
+ * node: builtins it actually needs), so the walk below owns the root case:
81
+ * `/Users` → `/`, `C:\` → `null`.
82
+ */
83
+ function parentOf(path) {
84
+ const idx = path.replace(/\\+/g, "/").replace(/\/+$/, "").lastIndexOf("/");
85
+ if (idx < 0) return null;
86
+ if (idx === 0) return "/";
87
+ return path.slice(0, idx);
88
+ }
89
+ /** `a, b, c (+3 more)` — the conflicting entries an occupied target lists. */
90
+ function describeEntries(entries) {
91
+ const shown = entries.slice(0, MAX_LISTED_CONFLICTS).join(", ");
92
+ const rest = entries.length - MAX_LISTED_CONFLICTS;
93
+ return rest > 0 ? `${shown} (+${rest} more)` : shown;
94
+ }
59
95
  /** Pairwise flag reconciliation: a flag and its negation cannot both appear. */
60
96
  function setExclusiveFlag(current, incoming, pair) {
61
97
  if (current !== void 0 && current !== incoming) fail(`--${incoming ? "" : "no-"}${pair} and --${incoming ? "no-" : ""}${pair} are mutually exclusive.`);
@@ -120,6 +156,8 @@ function parseArgs(argv) {
120
156
  function printUsage() {
121
157
  console.log(`Usage (Alpha): ${createInstallCommand()}`);
122
158
  console.log("(a versionless install resolves latest — the current 1.0 line)");
159
+ console.log(` <project-name> target directory: new or empty (default template: ${TEMPLATE_NAME})`);
160
+ console.log(" \".\" scaffolds into the current directory");
123
161
  console.log(` -t, --template <name> scaffold template (default: ${TEMPLATE_NAME})`);
124
162
  console.log(" --install / --no-install");
125
163
  console.log(" install dependencies after scaffolding (default: install)");
@@ -128,37 +166,78 @@ function printUsage() {
128
166
  console.log(" -h, --help show this help");
129
167
  }
130
168
  /**
131
- * Resolve the template: a flag wins without prompting; a TTY confirms the
132
- * choice with the one scaffold question (default accepts); a non-TTY run
133
- * (CI, packed consumers) takes the default without prompting.
169
+ * Resolve the template. One template ships (#1530), so there is nothing to
170
+ * ask: `-t/--template` names it explicitly (an unknown value fails with the
171
+ * available name), and a bare run takes that same default — on a TTY exactly
172
+ * as under CI. The former TTY confirmation asked a question with one possible
173
+ * answer, which only made a first run feel like an interrogation.
134
174
  */
135
- async function resolveTemplate(flag) {
136
- if (flag !== void 0) {
137
- if (flag !== TEMPLATE_NAME) fail(`Unknown template "${flag}". The available template is: ${TEMPLATE_NAME}.`);
138
- return flag;
139
- }
140
- if (!process.stdin.isTTY || !process.stdout.isTTY) return TEMPLATE_NAME;
141
- const rl = readline.createInterface({
142
- input: process.stdin,
143
- output: process.stdout
144
- });
175
+ function resolveTemplate(flag) {
176
+ if (flag !== void 0 && flag !== TEMPLATE_NAME) fail(`Unknown template "${flag}". The available template is: ${TEMPLATE_NAME}.`);
177
+ return TEMPLATE_NAME;
178
+ }
179
+ /**
180
+ * Resolve the positional into the directory to scaffold into. A plain name is
181
+ * validated exactly as before (npm package-name grammar, no traversal); `.`
182
+ * means the current directory, whose name the host chose — so the manifest
183
+ * name is DERIVED from it (inPlaceProjectName) instead of validated, and the
184
+ * in-place run can never fail on a directory called `My App`.
185
+ */
186
+ function planTarget(name) {
187
+ const cwd = process.cwd().replace(/\/+$/, "") || "/";
188
+ if (name === IN_PLACE_TARGET) return {
189
+ directory: cwd,
190
+ label: IN_PLACE_TARGET,
191
+ projectName: inPlaceProjectName(cwd),
192
+ inPlace: true
193
+ };
194
+ const invalid = validateProjectName(name);
195
+ if (invalid) fail(`Invalid project name "${name}". ${invalid}`);
196
+ if (name.includes("..") || name.includes("/") || name.includes("\\") || /^[a-zA-Z]:/.test(name) || name.startsWith("/")) fail(`Refusing to create project outside the current directory: ${name}`);
197
+ return {
198
+ directory: `${cwd}/${name}`,
199
+ label: name,
200
+ projectName: name,
201
+ inPlace: false
202
+ };
203
+ }
204
+ /**
205
+ * Refuse a target the scaffold would have to merge into. A directory that does
206
+ * not exist yet and an existing EMPTY directory are both legal (a user may have
207
+ * made the directory already, and `.` is the current directory); a directory
208
+ * holding anything — including a foreign `.git` — is not, because the scaffold
209
+ * would silently mix with files it does not own. The error names what is in the
210
+ * way and never tells the user to delete a directory the CLI did not create.
211
+ */
212
+ async function assertScaffoldableTarget(plan) {
213
+ let info;
145
214
  try {
146
- for (;;) {
147
- const answer = (await rl.question(`Template to scaffold (${TEMPLATE_NAME}): `)).trim();
148
- if (answer === "") return TEMPLATE_NAME;
149
- if (answer === TEMPLATE_NAME) return answer;
150
- console.info(` unknown template "${answer}" — available: ${TEMPLATE_NAME}`);
151
- }
152
- } finally {
153
- rl.close();
215
+ info = await stat(plan.directory);
216
+ } catch (error) {
217
+ if (isNotFound(error)) return;
218
+ throw new Error(`Could not inspect target directory "${plan.label}": ${errorMessage(error)}`);
154
219
  }
220
+ if (!info.isDirectory()) fail(`"${plan.label}" exists and is not a directory. Choose a new or empty directory.`);
221
+ const entries = (await readdir(plan.directory)).toSorted();
222
+ if (entries.length === 0) return;
223
+ fail(`Directory "${plan.label}" is not empty — it holds ${entries.length} ${entries.length === 1 ? "entry" : "entries"}: ${describeEntries(entries)}. Scaffold into a new or empty directory (a bare name creates one; "." uses the current directory, which must be empty too).`);
155
224
  }
156
225
  /**
157
- * `git init` in the scaffolded project. Git unavailable (ENOENT) is a silent
158
- * skip (the ask's contract); any other failure prints one note line and keeps
159
- * the scaffold successful — the repository is a convenience, not the product.
226
+ * `git init` in the scaffolded project, unless the target already lives inside
227
+ * a repository. A scaffold dropped into a checkout is a subdirectory of it,
228
+ * not a new repository: a nested `.git` would make the project's own history
229
+ * and its parent's disagree. The skip is a note, never a question — the run
230
+ * stays non-interactive, and `git init` inside the project is the one command
231
+ * that overrides it. Git unavailable (ENOENT) is a silent skip (the ask's
232
+ * contract); any other failure prints one note line and keeps the scaffold
233
+ * successful — the repository is a convenience, not the product.
160
234
  */
161
- function initGitRepository(targetDir, relativeTarget) {
235
+ function initGitRepository(targetDir, label) {
236
+ const enclosing = findEnclosingRepository(targetDir);
237
+ if (enclosing !== null) {
238
+ console.info(` note: ${label} is inside the git repository at ${enclosing}; skipping git init (run \`git init\` inside the project to give it its own repository).`);
239
+ return;
240
+ }
162
241
  const result = spawnSync("git", ["init"], {
163
242
  cwd: targetDir,
164
243
  stdio: "ignore"
@@ -169,30 +248,29 @@ function initGitRepository(targetDir, relativeTarget) {
169
248
  return;
170
249
  }
171
250
  if (result.status !== 0) {
172
- console.info(` note: git init exited ${result.status ?? "unknown"} in ${relativeTarget}; skipping.`);
251
+ console.info(` note: git init exited ${result.status ?? "unknown"} in ${label}; skipping.`);
173
252
  return;
174
253
  }
175
254
  console.info(" initialized git repository (with .gitignore)");
176
255
  }
177
256
  /**
178
- * The boxed end-of-run handoff: where to go, what to run, where to read, and
179
- * which generator version produced the scaffold. The version line is load
180
- * bearing: a cached `npm exec` / `npx` run resolves whatever copy it first
181
- * downloaded, so the box is the one place a stale generator announces itself
182
- * (#1634). The framework's packed-starter qualification asserts the line on
183
- * the packed artifact.
257
+ * The nearest ancestor of `startDir` (or `startDir` itself) that is a git
258
+ * working tree: a `.git` directory, or a `.git` file as used by worktrees and
259
+ * submodules. `null` when the walk reaches the filesystem root without one.
184
260
  */
185
- function printHandoff(relativeTarget, pm, startRequested) {
186
- const devCommand = pm ? `${pm} run dev` : "pnpm run dev";
261
+ function findEnclosingRepository(startDir) {
262
+ for (let dir = startDir; dir !== null; dir = parentOf(dir)) if (existsSync(joinPosix(dir, ".git"))) return dir;
263
+ return null;
264
+ }
265
+ function printHandoff(plan, pm, { installSkipped, startRequested }) {
187
266
  const lines = [
188
267
  "openElement project ready",
189
268
  `(@openelement/create ${CREATE_VERSION})`,
190
- "",
191
- `cd ${relativeTarget}`,
192
- `${devCommand} # start the dev server`,
193
- "",
194
- `Docs: ${DOCS_URL}`
269
+ ""
195
270
  ];
271
+ if (!plan.inPlace) lines.push(`cd ${plan.label}`);
272
+ if (installSkipped) lines.push(`${installDependenciesCommand(pm)} # install dependencies`);
273
+ lines.push(`${devCommand(pm)} # start the dev server`, "", `Docs: ${DOCS_URL}`);
196
274
  if (startRequested) lines.push("", "The dev server is starting — press Ctrl-C to stop it.");
197
275
  const width = Math.max(...lines.map((line) => line.length));
198
276
  console.info(`┌─${"─".repeat(width)}─┐`);
@@ -200,7 +278,14 @@ function printHandoff(relativeTarget, pm, startRequested) {
200
278
  console.info(`└─${"─".repeat(width)}─┘`);
201
279
  }
202
280
  async function main() {
203
- const flags = parseArgs(process.argv.slice(2));
281
+ const argv = process.argv.slice(2);
282
+ if (!argv.some((arg) => [
283
+ "-h",
284
+ "--help",
285
+ "-v",
286
+ "--version"
287
+ ].includes(arg))) assertSupportedNode(process.versions.node);
288
+ const flags = parseArgs(argv);
204
289
  if (flags.help) {
205
290
  printUsage();
206
291
  process.exit(0);
@@ -213,54 +298,52 @@ async function main() {
213
298
  printUsage();
214
299
  process.exit(1);
215
300
  }
216
- const invalid = validateProjectName(name);
217
- if (invalid) fail(`Invalid project name "${name}". ${invalid}`);
218
- const targetDir = `${process.cwd().replace(/\/+$/, "")}/${name}`;
219
- const relativeTarget = name;
220
- if (!relativeTarget || relativeTarget.includes("..") || relativeTarget.includes("/") || relativeTarget.includes("\\") || /^[a-zA-Z]:/.test(relativeTarget) || relativeTarget.startsWith("/")) fail(`Refusing to create project outside the current directory: ${name}`);
221
- try {
222
- await stat(targetDir);
223
- fail(`Directory "${name}" already exists. Choose a different name or remove the existing directory.`);
224
- } catch (error) {
225
- if (!isNotFound(error)) throw new Error(`Could not inspect target directory "${name}": ${errorMessage(error)}`);
226
- }
227
- const template = await resolveTemplate(flags.template);
301
+ const plan = planTarget(name);
302
+ await assertScaffoldableTarget(plan);
303
+ const template = resolveTemplate(flags.template);
228
304
  const v = resolveVersions();
229
305
  try {
230
- await mkdir(targetDir, { recursive: true });
231
- const TPL = await buildTemplates(v, name);
306
+ await mkdir(plan.directory, { recursive: true });
307
+ const TPL = await buildTemplates(v, plan.projectName);
232
308
  for (const [path, content] of Object.entries(TPL)) {
233
- const fullPath = joinPosix(targetDir, path);
309
+ const fullPath = joinPosix(plan.directory, path);
234
310
  await mkdir(dirnameOf(fullPath), { recursive: true });
235
311
  await writeFile(fullPath, content, "utf8");
236
312
  console.info(` created ${path}`);
237
313
  }
238
314
  } catch (error) {
239
- const detail = isPermissionDenied(error) ? `Permission denied. Check write permissions for ${targetDir}.` : errorMessage(error);
240
- throw new Error(`Failed to write project files in "${name}": ${detail} Remove the partially created directory before retrying.`);
315
+ const detail = isPermissionDenied(error) ? `Permission denied. Check write permissions for ${plan.directory}.` : errorMessage(error);
316
+ throw new Error(`Failed to write project files in "${plan.label}": ${detail} Remove the partially created directory before retrying.`);
241
317
  }
242
- console.info(`\nopenElement project created at ./${relativeTarget}/ (template: ${template})`);
318
+ const location = plan.inPlace ? "the current directory" : `./${plan.label}/`;
319
+ const cdPrefix = plan.inPlace ? "" : `cd ${plan.label} && `;
320
+ console.info(plan.inPlace ? `\nopenElement project created in the current directory (template: ${template})` : `\nopenElement project created at ./${plan.label}/ (template: ${template})`);
243
321
  if (flags.git !== false) {
244
- if (!existsSync(joinPosix(targetDir, ".gitignore"))) fail("The scaffold did not write .gitignore; refusing to initialize a repository that would track build output. Remove the directory and retry.");
245
- initGitRepository(targetDir, relativeTarget);
322
+ if (!existsSync(joinPosix(plan.directory, ".gitignore"))) fail("The scaffold did not write .gitignore; refusing to initialize a repository that would track build output. Remove the directory and retry.");
323
+ initGitRepository(plan.directory, plan.label);
246
324
  }
247
325
  let pm = null;
248
326
  if (flags.install !== false) {
249
- pm = detectPackageManager();
327
+ const detected = resolvePackageManager();
328
+ if (detected === null) fail(`No package manager found: this project installs with any of ${PACKAGE_MANAGERS.join(", ")}, and none of them is on PATH. Install one of them, then run its install command in ${location} (for example: ${cdPrefix}npm install). The project files are already complete there.`);
329
+ pm = detected;
250
330
  console.info(`\nInstalling dependencies with ${pm}...`);
251
331
  const install = spawnSync(pm, ["install"], {
252
- cwd: targetDir,
332
+ cwd: plan.directory,
253
333
  stdio: "inherit",
254
334
  shell: process.platform === "win32"
255
335
  });
256
- if (install.error !== void 0) fail(`Could not run ${pm} (${errorMessage(install.error)}). The project files are complete at ./${relativeTarget}/ — install manually with: cd ${relativeTarget} && ${pm} install`);
257
- if (install.status !== 0) fail(`${pm} install exited ${install.status ?? "unknown"}. The project files are complete at ./${relativeTarget}/ — inspect the output above, then retry manually with: cd ${relativeTarget} && ${pm} install`);
336
+ if (install.error !== void 0) fail(`Could not run ${pm} (${errorMessage(install.error)}). The project files are complete in ${location} — install manually with: ${cdPrefix}${pm} install`);
337
+ if (install.status !== 0) fail(`${pm} install exited ${install.status ?? "unknown"}. The project files are complete in ${location} — inspect the output above, then retry manually with: ${cdPrefix}${pm} install`);
258
338
  }
259
- printHandoff(relativeTarget, pm, flags.start);
339
+ printHandoff(plan, flags.install === false ? resolvePackageManager() : pm, {
340
+ installSkipped: flags.install === false,
341
+ startRequested: flags.start
342
+ });
260
343
  if (flags.start) {
261
344
  if (pm === null) fail("--start needs a package manager; installation was skipped.");
262
345
  const dev = spawn(pm, ["run", "dev"], {
263
- cwd: targetDir,
346
+ cwd: plan.directory,
264
347
  stdio: "inherit",
265
348
  shell: process.platform === "win32"
266
349
  });
@@ -0,0 +1,102 @@
1
+ import "node:process";
2
+ //#region src/node-version.ts
3
+ /**
4
+ * The Node.js floor, checked by every CLI entry before it does any work.
5
+ *
6
+ * The packed manifests declare `engines.node >= 24.2`, but an engine range is
7
+ * advisory: npm warns and installs anyway. The CLIs' own dispatch gate is a
8
+ * runtime flag — the Router entries run their main block only when
9
+ * `import.meta.main` is true, and Node added that flag in 24.2.0. On an older
10
+ * host it is `undefined`, so `undefined === true` is false and the packed CLI
11
+ * terminates successfully having done nothing at all: the silent success this
12
+ * module exists to prevent. An engine range cannot close that window from
13
+ * inside the artifact; this check can, because every entry runs it before the
14
+ * dispatch and before any filesystem work.
15
+ *
16
+ * ONE implementation, TWO verbatim placements: this file (the Create scaffold
17
+ * CLI, source of truth) and the Router CLI's copy beside its bin entries. A
18
+ * packed package may not import a source module outside its own root — a
19
+ * relative declaration edge that escapes the package root fails the release,
20
+ * and a runtime specifier that escapes the tarball cannot resolve for a
21
+ * consumer — so the two copies ship side by side, and the Create suite fails
22
+ * if they ever drift. Edit here, mirror the file byte-for-byte, run the
23
+ * Create suite.
24
+ */
25
+ /**
26
+ * The supported Node.js floor: 24.2.0, the first release with
27
+ * `import.meta.main` (the flag every Router bin entry dispatches on).
28
+ */
29
+ const MINIMUM_NODE_VERSION = "24.2.0";
30
+ /** Where a consumer reads how to install a supported Node line. */
31
+ const NODE_FLOOR_DOCS_URL = "https://openelement.org/docs/guide/getting-started";
32
+ /** The download page the install hint points at. */
33
+ const NODE_DOWNLOAD_URL = "https://nodejs.org/en/download";
34
+ /**
35
+ * `MINIMUM_NODE_VERSION` in comparable form. Derived, never restated, so the
36
+ * published constant and the comparison cannot drift apart.
37
+ */
38
+ const FLOOR = (() => {
39
+ const parsed = parseNodeVersion(MINIMUM_NODE_VERSION);
40
+ if (parsed === null) throw new Error(`node-version: unreadable floor "${MINIMUM_NODE_VERSION}"`);
41
+ return parsed;
42
+ })();
43
+ /** True when `version` names the same release as `floor`, or a newer one. */
44
+ function atLeast(version, floor) {
45
+ if (version.major !== floor.major) return version.major > floor.major;
46
+ if (version.minor !== floor.minor) return version.minor > floor.minor;
47
+ return version.patch >= floor.patch;
48
+ }
49
+ /**
50
+ * Parse `24.2.0`, `v24.2`, `24.2.0-nightly…` into its numeric parts. Returns
51
+ * null when the string carries no major.minor pair; the caller treats that as
52
+ * unsupported, so an unreadable host fails closed instead of passing by
53
+ * accident. A prerelease suffix is ignored: the floor is the numeric triple.
54
+ */
55
+ function parseNodeVersion(version) {
56
+ const match = /^v?(\d+)\.(\d+)(?:\.(\d+))?/.exec(version.trim());
57
+ if (match === null) return null;
58
+ const [, major, minor, patch] = match;
59
+ return {
60
+ major: Number(major),
61
+ minor: Number(minor),
62
+ patch: Number(patch ?? 0)
63
+ };
64
+ }
65
+ /**
66
+ * The one actionable message an unsupported host gets, or null when the host
67
+ * is supported. Pure — no process state, no I/O — so every CLI and every test
68
+ * reads the same sentence: required floor, current version, install command,
69
+ * why, and the docs link. Deliberately not a stack trace.
70
+ */
71
+ function nodeFloorProblem(version) {
72
+ const parsed = parseNodeVersion(version);
73
+ if (parsed !== null && atLeast(parsed, FLOOR)) return null;
74
+ return [
75
+ `This CLI requires Node.js ${MINIMUM_NODE_VERSION} or newer, but this host reports ${version}.`,
76
+ `Install Node.js ${MINIMUM_NODE_VERSION} or newer (${NODE_DOWNLOAD_URL}) and re-run the command.`,
77
+ "The packed CLI dispatches on `import.meta.main`, which Node added in 24.2.0; on an older host it would exit 0 without doing anything.",
78
+ `Docs: ${NODE_FLOOR_DOCS_URL}`
79
+ ].join("\n");
80
+ }
81
+ /** Raised by `assertSupportedNode`; `message` is the one actionable text. */
82
+ var UnsupportedNodeError = class extends Error {
83
+ /** The host version string that failed the check. */
84
+ version;
85
+ constructor(version, message) {
86
+ super(message);
87
+ this.name = "UnsupportedNodeError";
88
+ this.version = version;
89
+ }
90
+ };
91
+ /**
92
+ * Fail closed when `version` is below the floor. The Create CLI calls this
93
+ * before parsing flags, choosing a template, or touching the filesystem; its
94
+ * module-scope catch renders the message as one `error:` line and exits 1 (the
95
+ * scaffold's L9 rule: never a runtime stack trace).
96
+ */
97
+ function assertSupportedNode(version) {
98
+ const problem = nodeFloorProblem(version);
99
+ if (problem !== null) throw new UnsupportedNodeError(version, problem);
100
+ }
101
+ //#endregion
102
+ export { MINIMUM_NODE_VERSION, NODE_FLOOR_DOCS_URL, UnsupportedNodeError, assertSupportedNode, nodeFloorProblem, parseNodeVersion };