@cellajs/create-cella 0.5.0 → 0.5.1

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/index.js CHANGED
@@ -1,1009 +1,1054 @@
1
1
  #!/usr/bin/env tsx
2
-
3
- // src/create-cella-cli.ts
4
- import { existsSync as existsSync2 } from "fs";
5
- import { rm as rm2 } from "fs/promises";
6
- import { basename as basename2, resolve as resolve3 } from "path";
2
+ import fs, { existsSync } from "node:fs";
3
+ import fs$1, { cp, mkdir, readFile, readdir, rm } from "node:fs/promises";
4
+ import path, { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
7
5
  import { input, select } from "@inquirer/prompts";
8
- import pc6 from "picocolors";
9
-
10
- // src/constants.ts
11
6
  import pc from "picocolors";
12
-
7
+ import git from "isomorphic-git";
8
+ import { Command, InvalidArgumentError } from "commander";
9
+ import validate from "validate-npm-package-name";
10
+ import http from "isomorphic-git/http/node";
11
+ import ignore from "ignore";
12
+ import ora from "ora";
13
+ import { connect } from "node:net";
13
14
  // package.json
14
- var package_default = {
15
- name: "@cellajs/create-cella",
16
- version: "0.5.0",
17
- private: false,
18
- license: "MIT",
19
- description: "Cella is a TypeScript template to create web apps with sync and offline capabilities.",
20
- publishConfig: {
21
- access: "public"
22
- },
23
- repository: {
24
- type: "git",
25
- url: "https://github.com/cellajs/create-cella"
26
- },
27
- homepage: "https://cellajs.com",
28
- author: "CellaJS <info@cellajs.com>",
29
- engines: {
30
- node: "26.x"
31
- },
32
- type: "module",
33
- main: "./dist/index.js",
34
- files: [
35
- "dist",
36
- "index.js",
37
- "README.md"
38
- ],
39
- imports: {
40
- "#/*": "./src/*"
41
- },
42
- bin: {
43
- "create-cella": "index.js"
44
- },
45
- scripts: {
46
- start: "tsx ./src/create-cella-cli.ts",
47
- try: "tsx ./src/create-cella-cli.ts ../cella-try-app",
48
- clean: "rimraf ./dist",
49
- build: "tsup",
50
- "test-build": "pnpm run build && node index.js",
51
- prepublishOnly: "pnpm run test:release",
52
- check: "pnpm ts && pnpm biome check --write .",
53
- ts: "tsgo --pretty",
54
- lint: "biome check .",
55
- "lint:fix": "biome check --write .",
56
- test: "vitest run",
57
- "test:release": "pnpm run build && vitest run --config vitest.release.config.ts",
58
- "test:watch": "vitest",
59
- prepare: "lefthook install"
60
- },
61
- dependencies: {
62
- "@inquirer/prompts": "^8.7.2",
63
- commander: "^15.0.0",
64
- ignore: "^7.0.11",
65
- "isomorphic-git": "^1.42.5",
66
- ora: "^9.4.1",
67
- picocolors: "^1.1.1",
68
- "validate-npm-package-name": "^8.0.0"
69
- },
70
- devDependencies: {
71
- "@biomejs/biome": "^2.5.15",
72
- "@commitlint/cli": "^21.2.3",
73
- "@commitlint/config-conventional": "^21.2.3",
74
- "@evilmartians/lefthook": "^2.1.15",
75
- "@types/node": "26.6.3",
76
- "@types/validate-npm-package-name": "^4.0.2",
77
- "@typescript/native-preview": "7.0.0-dev.20260707.2",
78
- rimraf: "^6.1.3",
79
- tsup: "^8.5.1",
80
- tsx: "^4.23.15",
81
- typescript: "6.0.3",
82
- vitest: "^5.0.3"
83
- },
84
- packageManager: "pnpm@11.28.7",
85
- commitlint: {
86
- extends: [
87
- "@commitlint/config-conventional"
88
- ],
89
- rules: {
90
- "type-enum": [
91
- 2,
92
- "always",
93
- [
94
- "feat",
95
- "fix",
96
- "perf",
97
- "refactor",
98
- "revert",
99
- "docs",
100
- "chore",
101
- "build",
102
- "ci",
103
- "style",
104
- "test"
105
- ]
106
- ]
107
- }
108
- }
109
- };
110
-
15
+ var version = "0.5.1";
16
+ var description = "Cella is a TypeScript template to create web apps with sync and offline capabilities.";
17
+ var homepage = "https://cellajs.com";
111
18
  // src/constants.ts
112
- var NAME = "create cella";
113
- var DIVIDER = "\u2500".repeat(60);
114
- var TEMPLATE_URL = "github:cellajs/cella";
115
- var TEMPLATE_REPOSITORY = "cellajs/cella";
116
- var TEMPLATE_GIT_URL = `https://github.com/${TEMPLATE_REPOSITORY}.git`;
117
- var SYNC_CONFIG = "cella/cella.config.ts";
118
- var CELLA_REMOTE_URL = TEMPLATE_GIT_URL;
119
- var CELLA_REMOTE_NAME = "cella-upstream";
120
- var DESCRIPTION = package_default.description;
121
- var VERSION = package_default.version;
122
- var WEBSITE = package_default.homepage;
19
+ /** Name of this CLI tool */
20
+ const NAME = "create cella";
21
+ /** Thin line divider for console output (60 chars wide) */
22
+ const DIVIDER = "─".repeat(60);
23
+ /** URL of the template repository */
24
+ const TEMPLATE_URL = "github:cellajs/cella";
25
+ /** Canonical owner/repo for template metadata fetched from the GitHub API. */
26
+ const TEMPLATE_REPOSITORY = "cellajs/cella";
27
+ /** HTTPS git URL of the template, for reading its release tags without the GitHub API. */
28
+ const TEMPLATE_GIT_URL = `https://github.com/${TEMPLATE_REPOSITORY}.git`;
29
+ /** The app's sync config, which the template ships with its own settings. */
30
+ const SYNC_CONFIG = "cella/cella.config.ts";
31
+ /** Upstream remote of a new app: HTTPS, so reading a public template needs no SSH key. */
32
+ const CELLA_REMOTE_URL = TEMPLATE_GIT_URL;
33
+ /**
34
+ * Git remote name pointing at upstream cella. Matches the name the sync CLI
35
+ * (`pnpm cella`) expects, so scaffolds don't end up with a duplicate remote.
36
+ */
37
+ const CELLA_REMOTE_NAME = "cella-upstream";
38
+ /** Export details from package.json */
39
+ const DESCRIPTION = description;
40
+ const VERSION = version;
41
+ const WEBSITE = homepage;
123
42
  function getHeaderLine() {
124
- const leftText = `\u29C8 ${NAME} \xB7 ${VERSION}`;
125
- const left = `${pc.cyan(`\u29C8 ${NAME}`)} ${pc.dim(`\xB7 ${VERSION}`)}`;
126
- const right = pc.cyan(WEBSITE);
127
- const padding = Math.max(1, 60 - leftText.length - WEBSITE.length);
128
- return `${left}${" ".repeat(padding)}${right}`;
129
- }
130
- var TO_REMOVE = ["./infra/Pulumi.production.yaml", "./infra/Pulumi.staging.yaml"];
131
- var TO_CLEAN = ["./backend/drizzle"];
132
- var TO_COPY = {
133
- "./frontend/.env.example": "./frontend/.env"
134
- };
135
- var QUICKSTART = "./cella/QUICKSTART.md";
136
- var AGENT_FILES = {
137
- "AGENTS.md": "# Agent guidelines\n\nThis app is built from the cella template. Read [cella/AGENTS.md](./cella/AGENTS.md) before changing code: it holds the project rules. Skills, such as `add-entity`, live in [cella/skills](./cella/skills).\n",
138
- "CLAUDE.md": "@cella/AGENTS.md\n"
43
+ const leftText = `⧈ ${NAME} · ${VERSION}`;
44
+ const left = `${pc.cyan(`⧈ ${NAME}`)} ${pc.dim(`· ${VERSION}`)}`;
45
+ const right = pc.cyan(WEBSITE);
46
+ const padding = Math.max(1, 60 - leftText.length - WEBSITE.length);
47
+ return `${left}${" ".repeat(padding)}${right}`;
48
+ }
49
+ const TO_REMOVE = ["./infra/Pulumi.production.yaml", "./infra/Pulumi.staging.yaml"];
50
+ const TO_CLEAN = ["./backend/drizzle"];
51
+ const TO_COPY = { "./frontend/.env.example": "./frontend/.env" };
52
+ /** The template's quickstart, which becomes the new app's README. */
53
+ const QUICKSTART = "./cella/QUICKSTART.md";
54
+ /** Entry points a coding agent reads from the repo root; the rules and skills live in the template's `cella/` folder. */
55
+ const AGENT_FILES = {
56
+ "AGENTS.md": "# Agent guidelines\n\nThis app is built from the cella template. Read [cella/AGENTS.md](./cella/AGENTS.md) before changing code: it holds the project rules. Skills, such as `add-entity`, live in [cella/skills](./cella/skills).\n",
57
+ "CLAUDE.md": "@cella/AGENTS.md\n"
139
58
  };
140
- var frontendPort = (appIndex) => 3e3 + appIndex;
59
+ /** Frontend dev port of an app number. */
60
+ const frontendPort = (appIndex) => 3e3 + appIndex;
61
+ /**
62
+ * The quickstart as the README of a new app: at the repo root, with this app's port and without the step that just ran.
63
+ * Its links are relative to `cella/` in the template, so `./x` becomes `./cella/x` and `../x` becomes `./x`.
64
+ */
141
65
  function quickstartToReadme(source, displayName, appIndex) {
142
- return source.replace(/^# .*$/m, `# ${displayName}`).replace(/^## Create\n[\s\S]*?(?=^## )/m, "").replaceAll("](./", "](./cella/").replaceAll("](../", "](./").replaceAll("http://localhost:3000", `http://localhost:${frontendPort(appIndex)}`);
66
+ return source.replace(/^# .*$/m, `# ${displayName}`).replace(/^## Create\n[\s\S]*?(?=^## )/m, "").replaceAll("](./", "](./cella/").replaceAll("](../", "](./").replaceAll("http://localhost:3000", `http://localhost:${frontendPort(appIndex)}`);
143
67
  }
144
- var PLACEHOLDER_CONFIG = "shared/config/config.template.ts";
145
- var INITIAL_VERSION = "0.0.0";
68
+ /**
69
+ * Fork config template that replaces `shared/config/config.default.ts` in new forks.
70
+ */
71
+ const PLACEHOLDER_CONFIG = "shared/config/config.template.ts";
72
+ /**
73
+ * Starting version for a fresh fork. Resets the upstream cella version so
74
+ * release-please cuts the fork's first release from a clean slate.
75
+ */
76
+ const INITIAL_VERSION = "0.0.0";
77
+ /**
78
+ * Read a `.env.example` file and apply key=value replacements.
79
+ * Comments and unmatched keys are preserved as-is.
80
+ * Returns null if the file doesn't exist (caller should generate from scratch).
81
+ */
146
82
  async function generateEnvFromExample(examplePath, replacements) {
147
- const { readFile: readFile3 } = await import("fs/promises");
148
- let content;
149
- try {
150
- content = await readFile3(examplePath, "utf8");
151
- } catch {
152
- return null;
153
- }
154
- return content.replace(/^([A-Z_][A-Z0-9_]*)=(.*)$/gm, (match, key, _value) => {
155
- if (key in replacements) return `${key}=${replacements[key]}`;
156
- return match;
157
- });
83
+ const { readFile } = await import("node:fs/promises");
84
+ let content;
85
+ try {
86
+ content = await readFile(examplePath, "utf8");
87
+ } catch {
88
+ return null;
89
+ }
90
+ return content.replace(/^([A-Z_][A-Z0-9_]*)=(.*)$/gm, (match, key, _value) => {
91
+ if (key in replacements) return `${key}=${replacements[key]}`;
92
+ return match;
93
+ });
158
94
  }
95
+ /**
96
+ * Replacement map for the app's `.env`: the seed admin alone. The database ports and URLs follow `devAppIndex` in the
97
+ * shared config, and the service ports come from `services` there, so no port lives in the env file.
98
+ */
159
99
  function getBackendEnvReplacements(adminEmail) {
160
- return { ADMIN_EMAIL: adminEmail };
100
+ return { ADMIN_EMAIL: adminEmail };
161
101
  }
102
+ /** Set the app's number in the source of `config.default.ts`; a template without the key can only give index 0. */
162
103
  function setDevAppIndex(source, appIndex) {
163
- const pattern = /^(\s*devAppIndex:\s*)\d+/m;
164
- if (appIndex !== 0 && !pattern.test(source)) {
165
- throw new Error("This template has no devAppIndex in its config: use app index 0, or a newer template.");
166
- }
167
- return source.replace(pattern, (_, head) => `${head}${appIndex}`);
104
+ const pattern = /^(\s*devAppIndex:\s*)\d+/m;
105
+ if (appIndex !== 0 && !pattern.test(source)) throw new Error("This template has no devAppIndex in its config: use app index 0, or a newer template.");
106
+ return source.replace(pattern, (_, head) => `${head}${appIndex}`);
168
107
  }
169
-
170
- // src/create.ts
171
- import { existsSync } from "fs";
172
- import { cp, mkdir } from "fs/promises";
173
- import { dirname as dirname2, isAbsolute, join as join4, relative, resolve as resolve2 } from "path";
174
- import pc5 from "picocolors";
175
-
176
108
  // src/utils/git/command.ts
177
- import fs from "fs";
178
- import git from "isomorphic-git";
179
- var INITIAL_AUTHOR = { name: "cella", email: "info@cellajs.com" };
109
+ /**
110
+ * Git helpers backed by isomorphic-git (pure JS) instead of shelling out to the
111
+ * `git` binary. This keeps `create-cella` free of `child_process` (no shell access)
112
+ * and removes any dependency on the user's global git config — the initial commit
113
+ * uses an explicit author, so scaffolding never fails with "Author identity unknown".
114
+ */
115
+ /** Author used for the scaffold's initial commit (users re-author their own commits later). */
116
+ const INITIAL_AUTHOR = {
117
+ name: "cella",
118
+ email: "info@cellajs.com"
119
+ };
120
+ /**
121
+ * Initializes a new Git repository in the specified directory.
122
+ */
180
123
  async function gitInit(repoPath) {
181
- await git.init({ fs, dir: repoPath, defaultBranch: "main" });
124
+ await git.init({
125
+ fs,
126
+ dir: repoPath,
127
+ defaultBranch: "main"
128
+ });
182
129
  }
130
+ /**
131
+ * Stages all files in the repository (respects `.gitignore`).
132
+ */
183
133
  async function gitAddAll(repoPath) {
184
- await git.add({ fs, dir: repoPath, filepath: "." });
134
+ await git.add({
135
+ fs,
136
+ dir: repoPath,
137
+ filepath: "."
138
+ });
185
139
  }
140
+ /**
141
+ * Creates a commit with the specified message and returns the commit SHA.
142
+ */
186
143
  async function gitCommit(repoPath, message) {
187
- return git.commit({ fs, dir: repoPath, message, author: INITIAL_AUTHOR });
144
+ return git.commit({
145
+ fs,
146
+ dir: repoPath,
147
+ message,
148
+ author: INITIAL_AUTHOR
149
+ });
188
150
  }
151
+ /**
152
+ * Gets the URL of a remote. Throws when the remote does not exist (mirrors
153
+ * `git remote get-url` failing) so callers can detect a missing remote.
154
+ */
189
155
  async function gitRemoteGetUrl(repoPath, remoteName) {
190
- const remotes = await git.listRemotes({ fs, dir: repoPath });
191
- const match = remotes.find((r) => r.remote === remoteName);
192
- if (!match) throw new Error(`No such remote '${remoteName}'`);
193
- return match.url;
156
+ const match = (await git.listRemotes({
157
+ fs,
158
+ dir: repoPath
159
+ })).find((r) => r.remote === remoteName);
160
+ if (!match) throw new Error(`No such remote '${remoteName}'`);
161
+ return match.url;
194
162
  }
163
+ /**
164
+ * Adds a new remote.
165
+ */
195
166
  async function gitRemoteAdd(repoPath, remoteName, remoteUrl) {
196
- await git.addRemote({ fs, dir: repoPath, remote: remoteName, url: remoteUrl });
167
+ await git.addRemote({
168
+ fs,
169
+ dir: repoPath,
170
+ remote: remoteName,
171
+ url: remoteUrl
172
+ });
197
173
  }
174
+ /**
175
+ * Removes a remote.
176
+ */
198
177
  async function gitRemoteRemove(repoPath, remoteName) {
199
- await git.deleteRemote({ fs, dir: repoPath, remote: remoteName });
178
+ await git.deleteRemote({
179
+ fs,
180
+ dir: repoPath,
181
+ remote: remoteName
182
+ });
200
183
  }
201
-
202
184
  // src/add-remote.ts
203
- async function addRemote({
204
- targetFolder,
205
- remoteUrl = CELLA_REMOTE_URL,
206
- remoteName = CELLA_REMOTE_NAME,
207
- silent = false
208
- }) {
209
- try {
210
- let remote = null;
211
- try {
212
- remote = await gitRemoteGetUrl(targetFolder, remoteName);
213
- } catch {
214
- remote = null;
215
- }
216
- if (!remote) {
217
- await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
218
- } else if (remote !== remoteUrl) {
219
- await gitRemoteRemove(targetFolder, remoteName);
220
- await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
221
- }
222
- } catch (error) {
223
- if (!silent) {
224
- throw error;
225
- }
226
- }
185
+ /**
186
+ * Adds or updates the upstream remote for the Cella template.
187
+ * @param options - Configuration options
188
+ * @param options.silent - If true, don't throw on failure (used when called from progress tracker)
189
+ */
190
+ async function addRemote({ targetFolder, remoteUrl = CELLA_REMOTE_URL, remoteName = CELLA_REMOTE_NAME, silent = false }) {
191
+ try {
192
+ let remote = null;
193
+ try {
194
+ remote = await gitRemoteGetUrl(targetFolder, remoteName);
195
+ } catch {
196
+ remote = null;
197
+ }
198
+ if (!remote) await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
199
+ else if (remote !== remoteUrl) {
200
+ await gitRemoteRemove(targetFolder, remoteName);
201
+ await gitRemoteAdd(targetFolder, remoteName, remoteUrl);
202
+ }
203
+ } catch (error) {
204
+ if (!silent) throw error;
205
+ }
227
206
  }
228
-
229
- // src/modules/cli/commands.ts
230
- import { basename, resolve } from "path";
231
- import { Command, InvalidArgumentError } from "commander";
232
-
233
207
  // src/utils/detect-used-ports.ts
234
- import { readdir, readFile } from "fs/promises";
235
- import { dirname, join } from "path";
208
+ /**
209
+ * Scan sibling directories for existing cella apps and extract their dev ports.
210
+ * Looks for `shared/config/config.development.ts` to identify cella-based projects. The frontend port sits in that
211
+ * file's `origin`, or `frontendUrl` in older apps; the backend port in `services.backend.port` of `config.default.ts`,
212
+ * or `devPorts` in either file before that; `devAppIndex` in the default config moves whatever ports the files carry.
213
+ * Handles legacy configs with backendUrl on its own port.
214
+ */
236
215
  async function detectUsedPorts(targetFolder) {
237
- const parentDir = dirname(targetFolder);
238
- const used = [];
239
- let siblings;
240
- try {
241
- siblings = await readdir(parentDir);
242
- } catch {
243
- return used;
244
- }
245
- for (const name of siblings) {
246
- const configDir = join(parentDir, name, "shared/config");
247
- try {
248
- const development = await readFile(join(configDir, "config.development.ts"), "utf8");
249
- const defaults = await readFile(join(configDir, "config.default.ts"), "utf8").catch(() => "");
250
- const feMatch = development.match(/(?:origin|frontendUrl):\s*'http:\/\/localhost:(\d+)/);
251
- if (!feMatch) continue;
252
- const frontend = Number(feMatch[1]);
253
- const index = Number(defaults.match(/devAppIndex:\s*(\d+)/)?.[1] ?? 0);
254
- const servicePattern = /backend:\s*\{[^}]*?\bport:\s*(\d+)/;
255
- const apiPattern = /devPorts:\s*\{[^}]*?\bapi:\s*(\d+)/;
256
- const portMatch = defaults.match(servicePattern) ?? development.match(apiPattern) ?? defaults.match(apiPattern);
257
- const legacyBeMatch = development.match(/backendUrl:\s*'http:\/\/localhost:(\d+)'/);
258
- const backend = portMatch ? Number(portMatch[1]) : legacyBeMatch ? Number(legacyBeMatch[1]) : frontend + 1e3;
259
- used.push({ project: name, frontend: frontend + index, backend: backend + index * 10 });
260
- } catch {
261
- }
262
- }
263
- return used;
264
- }
265
- var isAppIndex = (index) => Number.isInteger(index) && index >= 0 && index <= 9 && index !== 4;
216
+ const parentDir = dirname(targetFolder);
217
+ const used = [];
218
+ let siblings;
219
+ try {
220
+ siblings = await readdir(parentDir);
221
+ } catch {
222
+ return used;
223
+ }
224
+ for (const name of siblings) {
225
+ const configDir = join(parentDir, name, "shared/config");
226
+ try {
227
+ const development = await readFile(join(configDir, "config.development.ts"), "utf8");
228
+ const defaults = await readFile(join(configDir, "config.default.ts"), "utf8").catch(() => "");
229
+ const feMatch = development.match(/(?:origin|frontendUrl):\s*'http:\/\/localhost:(\d+)/);
230
+ if (!feMatch) continue;
231
+ const frontend = Number(feMatch[1]);
232
+ const index = Number(defaults.match(/devAppIndex:\s*(\d+)/)?.[1] ?? 0);
233
+ const servicePattern = /backend:\s*\{[^}]*?\bport:\s*(\d+)/;
234
+ const apiPattern = /devPorts:\s*\{[^}]*?\bapi:\s*(\d+)/;
235
+ const portMatch = defaults.match(servicePattern) ?? development.match(apiPattern) ?? defaults.match(apiPattern);
236
+ const legacyBeMatch = development.match(/backendUrl:\s*'http:\/\/localhost:(\d+)'/);
237
+ const backend = portMatch ? Number(portMatch[1]) : legacyBeMatch ? Number(legacyBeMatch[1]) : frontend + 1e3;
238
+ used.push({
239
+ project: name,
240
+ frontend: frontend + index,
241
+ backend: backend + index * 10
242
+ });
243
+ } catch {}
244
+ }
245
+ return used;
246
+ }
247
+ /** Index 4 is never offered: its internal listener would sit on 4045, which fetch refuses. */
248
+ const isAppIndex = (index) => Number.isInteger(index) && index >= 0 && index <= 9 && index !== 4;
249
+ /** Find the first app index whose frontend port and service block no sibling uses and that `isBusy` leaves free. */
266
250
  function findNextAppIndex(usedPorts, isBusy = () => false) {
267
- for (let index = 0; index <= 9; index += 1) {
268
- if (!isAppIndex(index) || isBusy(index)) continue;
269
- const api = 4e3 + index * 10;
270
- const taken = usedPorts.some((p) => p.frontend === 3e3 + index || p.backend >= api && p.backend < api + 10);
271
- if (!taken) return index;
272
- }
273
- return 0;
251
+ for (let index = 0; index <= 9; index += 1) {
252
+ if (!isAppIndex(index) || isBusy(index)) continue;
253
+ const api = 4e3 + index * 10;
254
+ if (!usedPorts.some((p) => p.frontend === 3e3 + index || p.backend >= api && p.backend < api + 10)) return index;
255
+ }
256
+ return 0;
274
257
  }
275
-
276
258
  // src/utils/is-email.ts
277
- var isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
278
-
259
+ /** A plain shape check: the value lands on one line of the app's `.env` and is the seed user's sign-in address. */
260
+ const isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
279
261
  // src/utils/validate-project-name.ts
280
- import validate from "validate-npm-package-name";
281
262
  function validateProjectName(name) {
282
- const nameValidation = validate(name);
283
- if (nameValidation.validForNewPackages) {
284
- return { valid: true };
285
- }
286
- return {
287
- valid: false,
288
- problems: [...nameValidation.errors || [], ...nameValidation.warnings || []]
289
- };
263
+ const nameValidation = validate(name);
264
+ if (nameValidation.validForNewPackages) return { valid: true };
265
+ return {
266
+ valid: false,
267
+ problems: [...nameValidation.errors || [], ...nameValidation.warnings || []]
268
+ };
290
269
  }
291
-
292
270
  // src/modules/cli/commands.ts
293
271
  function parseAppIndex(value) {
294
- const parsed = Number(value);
295
- if (!isAppIndex(parsed)) {
296
- throw new InvalidArgumentError("App index must be a whole number from 0 to 9, not 4");
297
- }
298
- return parsed;
272
+ const parsed = Number(value);
273
+ if (!isAppIndex(parsed)) throw new InvalidArgumentError("App index must be a whole number from 0 to 9, not 4");
274
+ return parsed;
299
275
  }
300
276
  function parseAdminEmail(value) {
301
- if (!isEmail(value)) throw new InvalidArgumentError("Admin email must be an address such as admin@example.com");
302
- return value;
303
- }
304
- var directory = null;
305
- var packageManager = "pnpm";
306
- var command = new Command(NAME).version(VERSION, "-v, --version", `output the current version of ${NAME}`).argument("[directory]", "the directory name for the new project").usage("[directory] [options]").helpOption("-h, --help", "display this help message").option("--template <path>", "use a custom template (local path or github:user/repo)").option("--app-index <number>", "set this app's number for its dev ports (0-9, not 4)", parseAppIndex).option("--admin-email <email>", "set the admin email for the initial seed user", parseAdminEmail).action((name, _options, self) => {
307
- const trimmedName = typeof name === "string" ? name.trim() : name;
308
- if (trimmedName) {
309
- const validation = validateProjectName(basename(resolve(trimmedName)));
310
- if (!validation.valid) {
311
- self.error(
312
- `error: invalid project name "${trimmedName}": ${validation.problems?.[0] ?? "unknown error"}. Use lowercase letters, digits and dashes, such as my-app.`
313
- );
314
- }
315
- directory = trimmedName;
316
- }
277
+ if (!isEmail(value)) throw new InvalidArgumentError("Admin email must be an address such as admin@example.com");
278
+ return value;
279
+ }
280
+ let directory = null;
281
+ const packageManager = "pnpm";
282
+ /**
283
+ * Defines the root CLI command using Commander.
284
+ * This command accepts CLI options and validates user input.
285
+ */
286
+ const command = new Command(NAME).version(VERSION, "-v, --version", `output the current version of ${NAME}`).argument("[directory]", "the directory name for the new project").usage("[directory] [options]").helpOption("-h, --help", "display this help message").option("--template <path>", "use a custom template (local path or github:user/repo)").option("--app-index <number>", "set this app's number for its dev ports (0-9, not 4)", parseAppIndex).option("--admin-email <email>", "set the admin email for the initial seed user", parseAdminEmail).action((name, _options, self) => {
287
+ const trimmedName = typeof name === "string" ? name.trim() : name;
288
+ if (trimmedName) {
289
+ const validation = validateProjectName(basename(resolve(trimmedName)));
290
+ if (!validation.valid) self.error(`error: invalid project name "${trimmedName}": ${validation.problems?.[0] ?? "unknown error"}. Use lowercase letters, digits and dashes, such as my-app.`);
291
+ directory = trimmedName;
292
+ }
317
293
  }).parse();
318
- var options = command.opts();
294
+ const options = command.opts();
295
+ /**
296
+ * Runs the CLI and returns the parsed configuration.
297
+ * This function parses command line arguments and returns the CLI config.
298
+ */
319
299
  function runCli() {
320
- return {
321
- options,
322
- args: command.args,
323
- directory,
324
- packageManager
325
- };
326
- }
327
- var cli = runCli();
328
-
300
+ return {
301
+ options,
302
+ args: command.args,
303
+ directory,
304
+ packageManager
305
+ };
306
+ }
307
+ const cli = runCli();
329
308
  // src/modules/cli/display.ts
330
- import pc2 from "picocolors";
309
+ /** ASCII art logo for the CLI welcome screen. */
331
310
  function showAscii() {
332
- console.info(pc2.cyan(" _ _ "));
333
- console.info(pc2.cyan("\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2593\u2592 ___ ___| | | __ _ "));
334
- console.info(pc2.cyan("\u2592\u2593\u2588 \u2588\u2593\u2592 / __/ _ \\ | |/ _` | "));
335
- console.info(pc2.cyan("\u2592\u2593\u2588 \u2588\u2593\u2592 | (_| __/ | | (_| | "));
336
- console.info(pc2.cyan("\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2593\u2592 \\___\\___|_|_|\\__,_| "));
311
+ console.info(pc.cyan(" _ _ "));
312
+ console.info(pc.cyan("▒▓█████▓▒ ___ ___| | | __ _ "));
313
+ console.info(pc.cyan("▒▓█ █▓▒ / __/ _ \\ | |/ _` | "));
314
+ console.info(pc.cyan("▒▓█ █▓▒ | (_| __/ | | (_| | "));
315
+ console.info(pc.cyan("▒▓█████▓▒ \\___\\___|_|_|\\__,_| "));
337
316
  }
317
+ /**
318
+ * Displays the compact CLI welcome header.
319
+ */
338
320
  function showWelcome() {
339
- console.info();
340
- showAscii();
341
- console.info();
342
- console.info(pc2.dim(DESCRIPTION));
343
- console.info();
344
- console.info(getHeaderLine());
345
- console.info(DIVIDER);
321
+ console.info();
322
+ showAscii();
323
+ console.info();
324
+ console.info(pc.dim(DESCRIPTION));
325
+ console.info();
326
+ console.info(getHeaderLine());
327
+ console.info(DIVIDER);
346
328
  }
329
+ /**
330
+ * Print a cleared prompt's outcome as a persistent confirmation line:
331
+ * `✓ <label> · <value>`, followed by a blank separator line. Used after prompts
332
+ * that clear themselves on done so the chosen value stays visible.
333
+ */
347
334
  function confirmChoice(label, value) {
348
- console.info(`${pc2.green("\u2713")} ${label} \xB7 ${value}`);
349
- console.info();
350
- }
351
- function showSuccess(projectName, _targetFolder, relativePath, needsCd, packageManager2, appIndex, adminEmail) {
352
- console.info();
353
- console.info(pc2.bold("Next steps"));
354
- console.info(DIVIDER);
355
- console.info();
356
- if (needsCd) {
357
- console.info(`${pc2.dim("$")} cd ${pc2.cyan(relativePath)}`);
358
- }
359
- console.info(`${pc2.dim("$")} ${pc2.cyan(`${packageManager2} install`)}`);
360
- console.info(`${pc2.dim("$")} ${pc2.cyan(`${packageManager2} generate`)}`);
361
- console.info(
362
- `${pc2.dim("$")} ${pc2.cyan(`${packageManager2} docker`)} ${pc2.dim("&&")} ${pc2.cyan(`${packageManager2} seed`)} ${pc2.dim("&&")} ${pc2.cyan(`${packageManager2} dev`)}`
363
- );
364
- console.info();
365
- console.info(
366
- `${pc2.gray("Then open")} ${pc2.cyan(`http://localhost:${frontendPort(appIndex)}`)} ${pc2.gray("and sign in as")} ${pc2.cyan(adminEmail)}${pc2.gray(`: the magic link is printed in the ${packageManager2} dev output.`)}`
367
- );
368
- console.info();
369
- const readmePath = relativePath ? `${relativePath}/README.md` : "README.md";
370
- console.info(`${pc2.gray("To get started building, please read:")} ${pc2.cyan(readmePath)}`);
371
- console.info();
372
- console.info(`\u{1F973} enjoy building ${pc2.green(projectName)} with cella!`);
373
- console.info();
335
+ console.info(`${pc.green("✓")} ${label} · ${value}`);
336
+ console.info();
337
+ }
338
+ /**
339
+ * Displays the final success message after project creation.
340
+ */
341
+ function showSuccess(projectName, _targetFolder, relativePath, needsCd, packageManager, appIndex, adminEmail) {
342
+ console.info();
343
+ console.info(pc.bold("Next steps"));
344
+ console.info(DIVIDER);
345
+ console.info();
346
+ if (needsCd) console.info(`${pc.dim("$")} cd ${pc.cyan(relativePath)}`);
347
+ console.info(`${pc.dim("$")} ${pc.cyan(`${packageManager} install`)}`);
348
+ console.info(`${pc.dim("$")} ${pc.cyan(`${packageManager} generate`)}`);
349
+ console.info(`${pc.dim("$")} ${pc.cyan(`${packageManager} docker`)} ${pc.dim("&&")} ${pc.cyan(`${packageManager} seed`)} ${pc.dim("&&")} ${pc.cyan(`${packageManager} dev`)}`);
350
+ console.info();
351
+ console.info(`${pc.gray("Then open")} ${pc.cyan(`http://localhost:${frontendPort(appIndex)}`)} ${pc.gray("and sign in as")} ${pc.cyan(adminEmail)}${pc.gray(`: the magic link is printed in the ${packageManager} dev output.`)}`);
352
+ console.info();
353
+ const readmePath = relativePath ? `${relativePath}/README.md` : "README.md";
354
+ console.info(`${pc.gray("To get started building, please read:")} ${pc.cyan(readmePath)}`);
355
+ console.info();
356
+ console.info(`🥳 enjoy building ${pc.green(projectName)} with cella!`);
357
+ console.info();
374
358
  }
375
-
376
359
  // src/utils/clean-template.ts
377
- import fs2 from "fs/promises";
378
- import path from "path";
379
- import pc3 from "picocolors";
380
- var warningMark = pc3.yellow("\u26A0");
381
- async function cleanTemplate({
382
- targetFolder,
383
- projectName,
384
- displayName,
385
- appIndex = 0,
386
- adminEmail = `admin@${projectName}.example.com`
387
- }) {
388
- if (process.cwd() !== targetFolder) {
389
- process.chdir(targetFolder);
390
- }
391
- return new Promise((resolve4, reject) => {
392
- (async () => {
393
- try {
394
- for (const [src, dest] of Object.entries(TO_COPY)) {
395
- const srcAbsolutePath = path.resolve(targetFolder, src);
396
- const destAbsolutePath = path.resolve(targetFolder, dest);
397
- await copyFile(srcAbsolutePath, destAbsolutePath);
398
- }
399
- await writeReadme(targetFolder, displayName, appIndex);
400
- await writeAgentEntry(targetFolder);
401
- await applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex);
402
- await resetReleaseState(targetFolder, projectName);
403
- await removeTemplateForks(targetFolder);
404
- const replacements = getBackendEnvReplacements(adminEmail);
405
- const rootEnv = await generateEnvFromExample(path.resolve(targetFolder, ".env.example"), replacements);
406
- const appEnv = rootEnv ?? await generateEnvFromExample(path.resolve(targetFolder, "backend/.env.example"), replacements);
407
- if (appEnv) {
408
- await fs2.writeFile(path.resolve(targetFolder, rootEnv ? ".env" : "backend/.env"), appEnv, "utf8");
409
- }
410
- await Promise.all(
411
- TO_CLEAN.map((folderPath) => {
412
- const absolutePath = path.resolve(targetFolder, folderPath);
413
- return removeFolderContents(absolutePath);
414
- })
415
- );
416
- await Promise.all(
417
- TO_REMOVE.map((filePath) => {
418
- const absolutePath = path.resolve(targetFolder, filePath);
419
- return removeFileOrFolder(absolutePath);
420
- })
421
- );
422
- resolve4();
423
- } catch (err) {
424
- reject(`Error during the cleaning process: ${err}`);
425
- }
426
- })();
427
- });
360
+ const warningMark = pc.yellow("⚠");
361
+ /**
362
+ * Cleans the specified template by removing designated folders and files.
363
+ * @param params - Parameters containing the target folder, project name, and optional extra edits.
364
+ */
365
+ async function cleanTemplate({ targetFolder, projectName, displayName, appIndex = 0, adminEmail = `admin@${projectName}.example.com` }) {
366
+ if (process.cwd() !== targetFolder) process.chdir(targetFolder);
367
+ return new Promise((resolve, reject) => {
368
+ (async () => {
369
+ try {
370
+ for (const [src, dest] of Object.entries(TO_COPY)) await copyFile(path.resolve(targetFolder, src), path.resolve(targetFolder, dest));
371
+ await writeReadme(targetFolder, displayName, appIndex);
372
+ await writeAgentEntry(targetFolder);
373
+ await applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex);
374
+ await resetReleaseState(targetFolder, projectName);
375
+ await removeTemplateForks(targetFolder);
376
+ const replacements = getBackendEnvReplacements(adminEmail);
377
+ const rootEnv = await generateEnvFromExample(path.resolve(targetFolder, ".env.example"), replacements);
378
+ const appEnv = rootEnv ?? await generateEnvFromExample(path.resolve(targetFolder, "backend/.env.example"), replacements);
379
+ if (appEnv) await fs$1.writeFile(path.resolve(targetFolder, rootEnv ? ".env" : "backend/.env"), appEnv, "utf8");
380
+ await Promise.all(TO_CLEAN.map((folderPath) => {
381
+ return removeFolderContents(path.resolve(targetFolder, folderPath));
382
+ }));
383
+ await Promise.all(TO_REMOVE.map((filePath) => {
384
+ return removeFileOrFolder(path.resolve(targetFolder, filePath));
385
+ }));
386
+ resolve();
387
+ } catch (err) {
388
+ reject(`Error during the cleaning process: ${err}`);
389
+ }
390
+ })();
391
+ });
428
392
  }
393
+ /** Write the app's README from the template's quickstart. A template without one keeps its own README. */
429
394
  async function writeReadme(targetFolder, displayName, appIndex) {
430
- try {
431
- const quickstart = await fs2.readFile(path.resolve(targetFolder, QUICKSTART), "utf8");
432
- const readme = quickstartToReadme(quickstart, displayName, appIndex);
433
- await fs2.writeFile(path.resolve(targetFolder, "README.md"), readme, "utf8");
434
- } catch (err) {
435
- if (err.code !== "ENOENT") throw err;
436
- console.info(`
437
- ${warningMark} "${QUICKSTART}" not found > Skip README`);
438
- }
395
+ try {
396
+ const readme = quickstartToReadme(await fs$1.readFile(path.resolve(targetFolder, QUICKSTART), "utf8"), displayName, appIndex);
397
+ await fs$1.writeFile(path.resolve(targetFolder, "README.md"), readme, "utf8");
398
+ } catch (err) {
399
+ if (err.code !== "ENOENT") throw err;
400
+ console.info(`\n${warningMark} "${QUICKSTART}" not found > Skip README`);
401
+ }
439
402
  }
403
+ /** Point coding agents at the template's rules and skills, which sit in `cella/`, out of a root they would not search. */
440
404
  async function writeAgentEntry(targetFolder) {
441
- await Promise.all(
442
- Object.entries(AGENT_FILES).map(
443
- ([file, content]) => fs2.writeFile(path.resolve(targetFolder, file), content, "utf8")
444
- )
445
- );
446
- try {
447
- await fs2.mkdir(path.resolve(targetFolder, ".claude"), { recursive: true });
448
- await fs2.symlink("../cella/skills", path.resolve(targetFolder, ".claude/skills"));
449
- } catch (err) {
450
- console.info(`
451
- ${warningMark} skipped .claude/skills: ${err instanceof Error ? err.message : String(err)}`);
452
- }
405
+ await Promise.all(Object.entries(AGENT_FILES).map(([file, content]) => fs$1.writeFile(path.resolve(targetFolder, file), content, "utf8")));
406
+ try {
407
+ await fs$1.mkdir(path.resolve(targetFolder, ".claude"), { recursive: true });
408
+ await fs$1.symlink("../cella/skills", path.resolve(targetFolder, ".claude/skills"));
409
+ } catch (err) {
410
+ console.info(`\n${warningMark} skipped .claude/skills: ${err instanceof Error ? err.message : String(err)}`);
411
+ }
453
412
  }
413
+ /**
414
+ * Removes all contents within a specified folder.
415
+ * @param folderPath - The path of the folder to clean.
416
+ */
454
417
  async function removeFolderContents(folderPath) {
455
- let files;
456
- try {
457
- files = await fs2.readdir(folderPath);
458
- } catch (err) {
459
- if (err.code === "ENOENT") return;
460
- throw err;
461
- }
462
- await Promise.all(files.map((file) => fs2.rm(path.join(folderPath, file), { recursive: true, force: true })));
418
+ let files;
419
+ try {
420
+ files = await fs$1.readdir(folderPath);
421
+ } catch (err) {
422
+ if (err.code === "ENOENT") return;
423
+ throw err;
424
+ }
425
+ await Promise.all(files.map((file) => fs$1.rm(path.join(folderPath, file), {
426
+ recursive: true,
427
+ force: true
428
+ })));
463
429
  }
430
+ /**
431
+ * Removes a specified file or folder.
432
+ * @param pathToRemove - The path to the file or folder to remove.
433
+ */
464
434
  async function removeFileOrFolder(pathToRemove) {
465
- await fs2.rm(pathToRemove, { recursive: true, force: true });
435
+ await fs$1.rm(pathToRemove, {
436
+ recursive: true,
437
+ force: true
438
+ });
466
439
  }
440
+ /**
441
+ * Helper function to copy files if the source exists.
442
+ * @param src - The source file path.
443
+ * @param dest - The destination file path.
444
+ */
467
445
  async function copyFile(src, dest) {
468
- try {
469
- await fs2.access(src);
470
- await fs2.mkdir(path.dirname(dest), { recursive: true });
471
- await fs2.copyFile(src, dest);
472
- } catch (err) {
473
- if (err.code === "ENOENT") {
474
- console.info(`
475
- ${warningMark} Source file "${src}" does not exist > Skip copy`);
476
- } else {
477
- throw err;
478
- }
479
- }
446
+ try {
447
+ await fs$1.access(src);
448
+ await fs$1.mkdir(path.dirname(dest), { recursive: true });
449
+ await fs$1.copyFile(src, dest);
450
+ } catch (err) {
451
+ if (err.code === "ENOENT") console.info(`\n${warningMark} Source file "${src}" does not exist > Skip copy`);
452
+ else throw err;
453
+ }
480
454
  }
455
+ /**
456
+ * Read the fork config template shipped inside the cloned Cella template
457
+ * (`shared/config/config.template.ts`), interpolate project tokens, write the
458
+ * result as `shared/config/config.default.ts` — replacing the original — and
459
+ * delete the now-consumed template from the fork.
460
+ */
481
461
  async function applyPlaceholderConfig(targetFolder, projectName, displayName, appIndex) {
482
- const src = path.resolve(targetFolder, PLACEHOLDER_CONFIG);
483
- const dest = path.resolve(targetFolder, "./shared/config/config.default.ts");
484
- try {
485
- let content = await fs2.readFile(src, "utf8");
486
- content = content.replaceAll("__project_name__", displayName);
487
- content = content.replaceAll("__project_slug__", projectName);
488
- content = setDevAppIndex(content, appIndex);
489
- await fs2.writeFile(dest, content, "utf8");
490
- await fs2.rm(src, { force: true });
491
- } catch (err) {
492
- if (err.code === "ENOENT") {
493
- console.info(`
494
- ${warningMark} Fork config template "${src}" not found > Skip`);
495
- } else {
496
- throw err;
497
- }
498
- }
462
+ const src = path.resolve(targetFolder, PLACEHOLDER_CONFIG);
463
+ const dest = path.resolve(targetFolder, "./shared/config/config.default.ts");
464
+ try {
465
+ let content = await fs$1.readFile(src, "utf8");
466
+ content = content.replaceAll("__project_name__", displayName);
467
+ content = content.replaceAll("__project_slug__", projectName);
468
+ content = setDevAppIndex(content, appIndex);
469
+ await fs$1.writeFile(dest, content, "utf8");
470
+ await fs$1.rm(src, { force: true });
471
+ } catch (err) {
472
+ if (err.code === "ENOENT") console.info(`\n${warningMark} Fork config template "${src}" not found > Skip`);
473
+ else throw err;
474
+ }
499
475
  }
476
+ /**
477
+ * Remove the `forks` property, and a comment line directly above it, from the source of a sync
478
+ * config. Returns the source unchanged when it has no such property.
479
+ */
500
480
  function stripForks(source) {
501
- return source.replace(
502
- /^(?:[ \t]*\/\/[^\n]*\n)?([ \t]*)forks:\s*\[(?:[^\n]*|[\s\S]*?\n\1)\],?[ \t]*\n(?:[ \t]*\n)?/m,
503
- ""
504
- );
481
+ return source.replace(/^(?:[ \t]*\/\/[^\n]*\n)?([ \t]*)forks:\s*\[(?:[^\n]*|[\s\S]*?\n\1)\],?[ \t]*\n(?:[ \t]*\n)?/m, "");
505
482
  }
483
+ /**
484
+ * The template's sync config lists the repos the template itself syncs to. A new app has none,
485
+ * and the sync CLI never merges this file, so the list is removed once here.
486
+ */
506
487
  async function removeTemplateForks(targetFolder) {
507
- const configPath = path.resolve(targetFolder, SYNC_CONFIG);
508
- try {
509
- const source = await fs2.readFile(configPath, "utf8");
510
- const stripped = stripForks(source);
511
- if (stripped !== source) await fs2.writeFile(configPath, stripped, "utf8");
512
- } catch (err) {
513
- if (err.code === "ENOENT") {
514
- console.info(`
515
- ${warningMark} "${SYNC_CONFIG}" not found > Skip forks removal`);
516
- } else {
517
- throw err;
518
- }
519
- }
488
+ const configPath = path.resolve(targetFolder, SYNC_CONFIG);
489
+ try {
490
+ const source = await fs$1.readFile(configPath, "utf8");
491
+ const stripped = stripForks(source);
492
+ if (stripped !== source) await fs$1.writeFile(configPath, stripped, "utf8");
493
+ } catch (err) {
494
+ if (err.code === "ENOENT") console.info(`\n${warningMark} "${SYNC_CONFIG}" not found > Skip forks removal`);
495
+ else throw err;
496
+ }
520
497
  }
498
+ /**
499
+ * Reset the upstream cella release identity so the new fork starts clean:
500
+ * - root `package.json`: `name` → project slug, `version` → INITIAL_VERSION,
501
+ * and blank out `license`/`repository`/`description`/`keywords`/`author`/`homepage`
502
+ * (keys kept visible so the fork can fill in its own metadata)
503
+ * - `.github/release-please-manifest.json` → `{ ".": INITIAL_VERSION }`
504
+ * - `.github/release-please-config.json`: `changelog-path` → root `CHANGELOG.md`
505
+ * (cella tracks its own changelog in the template docs folder, which the fork
506
+ * keeps as upstream reference; the fork's own releases write to a fresh root changelog)
507
+ * - `CHANGELOG.md` → fresh stub
508
+ */
521
509
  async function resetReleaseState(targetFolder, projectName) {
522
- const pkgPath = path.resolve(targetFolder, "package.json");
523
- try {
524
- let pkg = await fs2.readFile(pkgPath, "utf8");
525
- pkg = pkg.replace(/^(\s*"name":\s*)"[^"]*"/m, `$1"${projectName}"`);
526
- pkg = pkg.replace(/^(\s*"version":\s*)"[^"]*"/m, `$1"${INITIAL_VERSION}"`);
527
- for (const field of ["license", "repository", "description", "author", "homepage"]) {
528
- pkg = pkg.replace(new RegExp(`^(\\s*"${field}":\\s*)"[^"]*"`, "m"), '$1""');
529
- }
530
- pkg = pkg.replace(/^(\s*"keywords":\s*)\[[^\]]*\]/m, "$1[]");
531
- await fs2.writeFile(pkgPath, pkg, "utf8");
532
- } catch (err) {
533
- if (err.code === "ENOENT") {
534
- console.info(`
535
- ${warningMark} "package.json" not found > Skip version reset`);
536
- } else {
537
- throw err;
538
- }
539
- }
540
- const configPath = path.resolve(targetFolder, ".github/release-please-config.json");
541
- try {
542
- const config = JSON.parse(await fs2.readFile(configPath, "utf8"));
543
- config.packages ??= {};
544
- config.packages["."] ??= {};
545
- config.packages["."]["changelog-path"] = "CHANGELOG.md";
546
- await fs2.writeFile(configPath, `${JSON.stringify(config, null, 2)}
547
- `, "utf8");
548
- } catch (err) {
549
- if (err.code === "ENOENT") {
550
- console.info(`
551
- ${warningMark} "release-please-config.json" not found > Skip changelog path reset`);
552
- } else {
553
- throw err;
554
- }
555
- }
556
- await fs2.writeFile(
557
- path.resolve(targetFolder, ".github/release-please-manifest.json"),
558
- `{
559
- ".": "${INITIAL_VERSION}"
560
- }
561
- `,
562
- "utf8"
563
- );
564
- await fs2.writeFile(path.resolve(targetFolder, "CHANGELOG.md"), "# Changelog\n", "utf8");
510
+ const pkgPath = path.resolve(targetFolder, "package.json");
511
+ try {
512
+ let pkg = await fs$1.readFile(pkgPath, "utf8");
513
+ pkg = pkg.replace(/^(\s*"name":\s*)"[^"]*"/m, `$1"${projectName}"`);
514
+ pkg = pkg.replace(/^(\s*"version":\s*)"[^"]*"/m, `$1"${INITIAL_VERSION}"`);
515
+ for (const field of [
516
+ "license",
517
+ "repository",
518
+ "description",
519
+ "author",
520
+ "homepage"
521
+ ]) pkg = pkg.replace(new RegExp(`^(\\s*"${field}":\\s*)"[^"]*"`, "m"), "$1\"\"");
522
+ pkg = pkg.replace(/^(\s*"keywords":\s*)\[[^\]]*\]/m, "$1[]");
523
+ await fs$1.writeFile(pkgPath, pkg, "utf8");
524
+ } catch (err) {
525
+ if (err.code === "ENOENT") console.info(`\n${warningMark} "package.json" not found > Skip version reset`);
526
+ else throw err;
527
+ }
528
+ const configPath = path.resolve(targetFolder, ".github/release-please-config.json");
529
+ try {
530
+ const config = JSON.parse(await fs$1.readFile(configPath, "utf8"));
531
+ config.packages ??= {};
532
+ config.packages["."] ??= {};
533
+ config.packages["."]["changelog-path"] = "CHANGELOG.md";
534
+ await fs$1.writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
535
+ } catch (err) {
536
+ if (err.code === "ENOENT") console.info(`\n${warningMark} "release-please-config.json" not found > Skip changelog path reset`);
537
+ else throw err;
538
+ }
539
+ await fs$1.writeFile(path.resolve(targetFolder, ".github/release-please-manifest.json"), `{\n ".": "${INITIAL_VERSION}"\n}\n`, "utf8");
540
+ await fs$1.writeFile(path.resolve(targetFolder, "CHANGELOG.md"), "# Changelog\n", "utf8");
565
541
  }
566
-
567
542
  // src/utils/download-template.ts
568
- import fs3 from "fs";
569
- import { rm } from "fs/promises";
570
- import { join as join2 } from "path";
571
- import git2 from "isomorphic-git";
572
- import http from "isomorphic-git/http/node";
543
+ /** Parse `github:owner/repo` or `owner/repo` into its owner and repo parts. */
573
544
  function parseGithubRepo(template) {
574
- const [owner, repo] = template.replace(/^github:/, "").split("/");
575
- if (!owner || !repo) {
576
- throw new Error(`Invalid template '${template}'. Expected 'github:owner/repo'.`);
577
- }
578
- return { owner, repo };
545
+ const [owner, repo] = template.replace(/^github:/, "").split("/");
546
+ if (!owner || !repo) throw new Error(`Invalid template '${template}'. Expected 'github:owner/repo'.`);
547
+ return {
548
+ owner,
549
+ repo
550
+ };
579
551
  }
552
+ /**
553
+ * Clones a GitHub template into `targetFolder` using isomorphic-git (pure JS).
554
+ *
555
+ * A shallow, single-branch clone over HTTPS — no `git` binary, no `child_process`,
556
+ * so `create-cella` keeps a clean supply-chain profile (no shell access). Unlike a
557
+ * raw tarball parse, isomorphic-git reconstructs the tree itself, so file modes and
558
+ * long paths are always correct. The cloned `.git` history is discarded afterwards;
559
+ * scaffolding re-initialises the repo with a fresh initial commit.
560
+ *
561
+ * @param template - `github:owner/repo` (or `owner/repo`).
562
+ * @param ref - Branch or tag to check out (e.g. `main` or a release tag).
563
+ * @param targetFolder - Directory to clone the template into.
564
+ * @returns The exact upstream commit SHA the template was scaffolded from.
565
+ */
580
566
  async function downloadGithubTemplate(template, ref, targetFolder) {
581
- const { owner, repo } = parseGithubRepo(template);
582
- const url = `https://github.com/${owner}/${repo}.git`;
583
- await git2.clone({ fs: fs3, http, dir: targetFolder, url, ref, singleBranch: true, depth: 1 });
584
- const baseSha = await git2.resolveRef({ fs: fs3, dir: targetFolder, ref: "HEAD" });
585
- await rm(join2(targetFolder, ".git"), { recursive: true, force: true });
586
- return baseSha;
567
+ const { owner, repo } = parseGithubRepo(template);
568
+ const url = `https://github.com/${owner}/${repo}.git`;
569
+ await git.clone({
570
+ fs,
571
+ http,
572
+ dir: targetFolder,
573
+ url,
574
+ ref,
575
+ singleBranch: true,
576
+ depth: 1
577
+ });
578
+ const baseSha = await git.resolveRef({
579
+ fs,
580
+ dir: targetFolder,
581
+ ref: "HEAD"
582
+ });
583
+ await rm(join(targetFolder, ".git"), {
584
+ recursive: true,
585
+ force: true
586
+ });
587
+ return baseSha;
587
588
  }
588
-
589
589
  // src/utils/list-template-files.ts
590
- import { readdir as readdir2, readFile as readFile2 } from "fs/promises";
591
- import { join as join3 } from "path";
592
- import ignore from "ignore";
590
+ /**
591
+ * Lists the files under `root` that git would track, without shelling out to git.
592
+ *
593
+ * Honors the root `.gitignore` (via the `ignore` package) and always skips `.git`
594
+ * and `node_modules`. Used for the local-template dev flow (`--template ./local`)
595
+ * so build output and local `.env` secrets aren't copied into the new project.
596
+ *
597
+ * Paths are returned relative to `root` using POSIX separators.
598
+ */
593
599
  async function listTemplateFiles(root) {
594
- const ig = ignore().add([".git", "node_modules"]);
595
- try {
596
- ig.add(await readFile2(join3(root, ".gitignore"), "utf8"));
597
- } catch {
598
- }
599
- const files = [];
600
- async function walk(relDir) {
601
- const entries = await readdir2(relDir ? join3(root, relDir) : root, { withFileTypes: true });
602
- for (const entry of entries) {
603
- const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
604
- if (ig.ignores(entry.isDirectory() ? `${rel}/` : rel)) continue;
605
- if (entry.isDirectory()) await walk(rel);
606
- else if (entry.isFile()) files.push(rel);
607
- }
608
- }
609
- await walk("");
610
- return files;
600
+ const ig = ignore().add([".git", "node_modules"]);
601
+ try {
602
+ ig.add(await readFile(join(root, ".gitignore"), "utf8"));
603
+ } catch {}
604
+ const files = [];
605
+ async function walk(relDir) {
606
+ const entries = await readdir(relDir ? join(root, relDir) : root, { withFileTypes: true });
607
+ for (const entry of entries) {
608
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
609
+ if (ig.ignores(entry.isDirectory() ? `${rel}/` : rel)) continue;
610
+ if (entry.isDirectory()) await walk(rel);
611
+ else if (entry.isFile()) files.push(rel);
612
+ }
613
+ }
614
+ await walk("");
615
+ return files;
611
616
  }
612
-
613
617
  // src/utils/progress.ts
614
- import ora from "ora";
615
- import pc4 from "picocolors";
616
- var activeSpinner = null;
618
+ /**
619
+ * Progress Tracker Utility
620
+ *
621
+ * Provides compact progress tracking for CLI operations.
622
+ * Uses a single spinner that updates in place.
623
+ */
624
+ /** Global reference to the currently active spinner */
625
+ let activeSpinner = null;
626
+ /** Pause the active spinner (for interactive prompts) */
617
627
  function pauseSpinner() {
618
- if (activeSpinner) {
619
- activeSpinner.stop();
620
- }
628
+ if (activeSpinner) activeSpinner.stop();
621
629
  }
630
+ /** Resume the active spinner after a prompt */
622
631
  function resumeSpinner() {
623
- if (activeSpinner) {
624
- activeSpinner.start();
625
- }
632
+ if (activeSpinner) activeSpinner.start();
626
633
  }
634
+ /**
635
+ * Creates a progress tracker for a multi-step operation.
636
+ * Shows a single spinner that updates in place.
637
+ *
638
+ * @param title - The initial title for the spinner
639
+ * @returns A ProgressTracker instance
640
+ *
641
+ * @example
642
+ * const progress = createProgress('creating project');
643
+ * progress.step('downloading template');
644
+ * progress.step('installing dependencies');
645
+ * progress.done('project created');
646
+ */
627
647
  function createProgress(title, silent = false) {
628
- const completedSteps = [];
629
- const spinner = ora({
630
- text: title,
631
- isSilent: silent
632
- });
633
- activeSpinner = spinner;
634
- spinner.start();
635
- const log = (msg) => {
636
- if (!silent) console.info(msg);
637
- };
638
- return {
639
- step: (message) => {
640
- if (completedSteps.length > 0) {
641
- spinner.stop();
642
- log(`${pc4.green("\u2713")} ${completedSteps[completedSteps.length - 1]}`);
643
- }
644
- completedSteps.push(message);
645
- spinner.text = message;
646
- spinner.start();
647
- },
648
- done: (message) => {
649
- if (completedSteps.length > 0) {
650
- spinner.stop();
651
- log(`${pc4.green("\u2713")} ${completedSteps[completedSteps.length - 1]}`);
652
- } else {
653
- spinner.stop();
654
- }
655
- activeSpinner = null;
656
- if (message) {
657
- log("");
658
- log(`${pc4.green("\u2713")} ${message}`);
659
- }
660
- },
661
- fail: (message) => {
662
- spinner.stop();
663
- activeSpinner = null;
664
- log(`${pc4.red("\u2717")} ${pc4.red(message)}`);
665
- }
666
- };
648
+ const completedSteps = [];
649
+ const spinner = ora({
650
+ text: title,
651
+ isSilent: silent
652
+ });
653
+ activeSpinner = spinner;
654
+ spinner.start();
655
+ const log = (msg) => {
656
+ if (!silent) console.info(msg);
657
+ };
658
+ return {
659
+ step: (message) => {
660
+ if (completedSteps.length > 0) {
661
+ spinner.stop();
662
+ log(`${pc.green("✓")} ${completedSteps[completedSteps.length - 1]}`);
663
+ }
664
+ completedSteps.push(message);
665
+ spinner.text = message;
666
+ spinner.start();
667
+ },
668
+ done: (message) => {
669
+ if (completedSteps.length > 0) {
670
+ spinner.stop();
671
+ log(`${pc.green("✓")} ${completedSteps[completedSteps.length - 1]}`);
672
+ } else spinner.stop();
673
+ activeSpinner = null;
674
+ if (message) {
675
+ log("");
676
+ log(`${pc.green("✓")} ${message}`);
677
+ }
678
+ },
679
+ fail: (message) => {
680
+ spinner.stop();
681
+ activeSpinner = null;
682
+ log(`${pc.red("✗")} ${pc.red(message)}`);
683
+ }
684
+ };
667
685
  }
668
-
669
686
  // src/create.ts
670
- function isLocalPath(path2) {
671
- return path2.startsWith("/") || path2.startsWith("./") || path2.startsWith("../");
672
- }
673
- async function create({
674
- projectName,
675
- targetFolder,
676
- packageManager: packageManager2,
677
- templateUrl,
678
- templateRef,
679
- appIndex,
680
- adminEmail,
681
- silent = false
682
- }) {
683
- const originalCwd = process.cwd();
684
- const template = templateUrl || TEMPLATE_URL;
685
- const isLocalTemplate = templateUrl && isLocalPath(templateUrl);
686
- const progress = createProgress("creating project", silent);
687
- try {
688
- progress.step("creating project folder");
689
- await mkdir(targetFolder, { recursive: true });
690
- process.chdir(targetFolder);
691
- let baseSha = null;
692
- if (isLocalTemplate) {
693
- progress.step("copying local template");
694
- const sourcePath = resolve2(originalCwd, templateUrl);
695
- const rel = relative(sourcePath, targetFolder);
696
- const targetInsideTemplate = rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
697
- if (targetInsideTemplate) {
698
- throw new Error(
699
- `Cannot create project inside the template directory.
700
- Run from outside: cd ~ && pnpm create @cellajs/cella ${projectName} --template ${templateUrl}`
701
- );
702
- }
703
- const tracked = await listTemplateFiles(sourcePath);
704
- for (const rel2 of tracked) {
705
- const src = join4(sourcePath, rel2);
706
- if (!existsSync(src)) continue;
707
- const dest = join4(targetFolder, rel2);
708
- await mkdir(dirname2(dest), { recursive: true });
709
- await cp(src, dest);
710
- }
711
- } else {
712
- const ref = templateRef ?? "main";
713
- progress.step(`downloading cella template${templateRef ? ` (${templateRef})` : ""}`);
714
- baseSha = await downloadGithubTemplate(template, ref, targetFolder);
715
- }
716
- progress.step("cleaning template");
717
- const displayName = projectName.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
718
- await cleanTemplate({ targetFolder, projectName, displayName, appIndex, adminEmail });
719
- const gitFolderPath = join4(targetFolder, ".git");
720
- if (!existsSync(gitFolderPath)) {
721
- try {
722
- progress.step("initializing git");
723
- await gitInit(targetFolder);
724
- await gitAddAll(targetFolder);
725
- const message = baseSha ? `Initial commit
726
-
727
- Cella-Base: ${baseSha}` : "Initial commit";
728
- await gitCommit(targetFolder, message);
729
- } catch (error) {
730
- if (!silent) {
731
- pauseSpinner();
732
- console.warn(`${pc5.yellow("\u26A0")} skipped git init: ${error instanceof Error ? error.message : String(error)}`);
733
- resumeSpinner();
734
- }
735
- }
736
- }
737
- progress.step("adding upstream remote");
738
- await addRemote({ targetFolder, silent: true });
739
- progress.done(pc5.bold(`created ${projectName}`));
740
- } catch (error) {
741
- progress.fail(error instanceof Error ? error.message : String(error));
742
- throw error;
743
- }
744
- const needsCd = originalCwd !== targetFolder;
745
- const relativePath = relative(originalCwd, targetFolder);
746
- showSuccess(
747
- projectName,
748
- targetFolder,
749
- relativePath,
750
- needsCd,
751
- packageManager2,
752
- appIndex,
753
- adminEmail ?? `admin@${projectName}.example.com`
754
- );
687
+ /** Check if a path is a local directory */
688
+ function isLocalPath(path) {
689
+ return path.startsWith("/") || path.startsWith("./") || path.startsWith("../");
690
+ }
691
+ async function create({ projectName, targetFolder, packageManager, templateUrl, templateRef, appIndex, adminEmail, silent = false }) {
692
+ const originalCwd = process.cwd();
693
+ const template = templateUrl || "github:cellajs/cella";
694
+ const isLocalTemplate = templateUrl && isLocalPath(templateUrl);
695
+ const progress = createProgress("creating project", silent);
696
+ try {
697
+ progress.step("creating project folder");
698
+ await mkdir(targetFolder, { recursive: true });
699
+ process.chdir(targetFolder);
700
+ let baseSha = null;
701
+ if (isLocalTemplate) {
702
+ progress.step("copying local template");
703
+ const sourcePath = resolve(originalCwd, templateUrl);
704
+ const rel = relative(sourcePath, targetFolder);
705
+ if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) throw new Error(`Cannot create project inside the template directory.
706
+ Run from outside: cd ~ && pnpm create @cellajs/cella ${projectName} --template ${templateUrl}`);
707
+ const tracked = await listTemplateFiles(sourcePath);
708
+ for (const rel of tracked) {
709
+ const src = join(sourcePath, rel);
710
+ if (!existsSync(src)) continue;
711
+ const dest = join(targetFolder, rel);
712
+ await mkdir(dirname(dest), { recursive: true });
713
+ await cp(src, dest);
714
+ }
715
+ } else {
716
+ const ref = templateRef ?? "main";
717
+ progress.step(`downloading cella template${templateRef ? ` (${templateRef})` : ""}`);
718
+ baseSha = await downloadGithubTemplate(template, ref, targetFolder);
719
+ }
720
+ progress.step("cleaning template");
721
+ await cleanTemplate({
722
+ targetFolder,
723
+ projectName,
724
+ displayName: projectName.replace(/[-_]/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
725
+ appIndex,
726
+ adminEmail
727
+ });
728
+ const gitFolderPath = join(targetFolder, ".git");
729
+ if (!existsSync(gitFolderPath)) try {
730
+ progress.step("initializing git");
731
+ await gitInit(targetFolder);
732
+ await gitAddAll(targetFolder);
733
+ await gitCommit(targetFolder, baseSha ? `Initial commit\n\nCella-Base: ${baseSha}` : "Initial commit");
734
+ } catch (error) {
735
+ if (!silent) {
736
+ pauseSpinner();
737
+ console.warn(`${pc.yellow("⚠")} skipped git init: ${error instanceof Error ? error.message : String(error)}`);
738
+ resumeSpinner();
739
+ }
740
+ }
741
+ progress.step("adding upstream remote");
742
+ await addRemote({
743
+ targetFolder,
744
+ silent: true
745
+ });
746
+ progress.done(pc.bold(`created ${projectName}`));
747
+ } catch (error) {
748
+ progress.fail(error instanceof Error ? error.message : String(error));
749
+ throw error;
750
+ }
751
+ const needsCd = originalCwd !== targetFolder;
752
+ showSuccess(projectName, targetFolder, relative(originalCwd, targetFolder), needsCd, packageManager, appIndex, adminEmail ?? `admin@${projectName}.example.com`);
755
753
  }
756
-
757
754
  // src/utils/busy-ports.ts
758
- import { connect } from "net";
759
- var SERVICE_PORTS = 7;
760
- var appPorts = (appIndex) => [
761
- 3e3 + appIndex,
762
- ...Array.from({ length: SERVICE_PORTS }, (_, i) => 4e3 + appIndex * 10 + i),
763
- 5432 + appIndex * 10,
764
- 5434 + appIndex * 10
755
+ const SERVICE_PORTS = 7;
756
+ /** Every local port an app number takes: the frontend, its service block, and the dev and test databases. */
757
+ const appPorts = (appIndex) => [
758
+ 3e3 + appIndex,
759
+ ...Array.from({ length: SERVICE_PORTS }, (_, i) => 4e3 + appIndex * 10 + i),
760
+ 5432 + appIndex * 10,
761
+ 5434 + appIndex * 10
765
762
  ];
766
- var isListening = (port) => new Promise((resolve4) => {
767
- const socket = connect({ port, host: "127.0.0.1", timeout: 300 });
768
- const finish = (listening) => {
769
- socket.destroy();
770
- resolve4(listening);
771
- };
772
- socket.once("connect", () => finish(true));
773
- socket.once("timeout", () => finish(false));
774
- socket.once("error", () => finish(false));
763
+ /** Whether something on this machine accepts a connection on the port. */
764
+ const isListening = (port) => new Promise((resolve) => {
765
+ const socket = connect({
766
+ port,
767
+ host: "127.0.0.1",
768
+ timeout: 300
769
+ });
770
+ const finish = (listening) => {
771
+ socket.destroy();
772
+ resolve(listening);
773
+ };
774
+ socket.once("connect", () => finish(true));
775
+ socket.once("timeout", () => finish(false));
776
+ socket.once("error", () => finish(false));
775
777
  });
778
+ /** The ports of an app number that are already taken, lowest first. */
776
779
  async function findBusyPorts(appIndex) {
777
- const ports = appPorts(appIndex);
778
- const listening = await Promise.all(ports.map(isListening));
779
- return ports.filter((_, i) => listening[i]);
780
+ const ports = appPorts(appIndex);
781
+ const listening = await Promise.all(ports.map(isListening));
782
+ return ports.filter((_, i) => listening[i]);
780
783
  }
781
-
782
784
  // src/utils/fetch-template-metadata.ts
783
- import git3 from "isomorphic-git";
784
- import http2 from "isomorphic-git/http/node";
785
- var TEMPLATE_METADATA_API_BASE = `https://api.github.com/repos/${TEMPLATE_REPOSITORY}`;
785
+ /**
786
+ * Fetch lightweight metadata about the cella template so the scaffolder can offer
787
+ * "latest release" vs "latest commit" as a starting point.
788
+ *
789
+ * The release tag is read from the template's git tags, over the transport the clone uses, so
790
+ * it does not depend on the GitHub API and its limit for callers without a token. Dates and the
791
+ * commit subject come from that API. Every helper fails soft; the caller falls back to the
792
+ * default branch when no release is known.
793
+ */
794
+ const TEMPLATE_METADATA_API_BASE = `https://api.github.com/repos/${TEMPLATE_REPOSITORY}`;
795
+ /** Format an ISO timestamp as a locale-independent YYYY-MM-DD date. */
786
796
  function toDate(iso) {
787
- return iso ? iso.slice(0, 10) : "unknown";
797
+ return iso ? iso.slice(0, 10) : "unknown";
788
798
  }
789
- var GITHUB_HEADERS = { Accept: "application/vnd.github+json" };
799
+ const GITHUB_HEADERS = { Accept: "application/vnd.github+json" };
800
+ /**
801
+ * Pick the latest template release from tag names: the highest plain version, with or without
802
+ * the `v` prefix. Tags of another series (`create-cella-0.2.3`, `archive/pre-release`) and
803
+ * pre-releases are no template release.
804
+ */
790
805
  function pickLatestReleaseTag(tags) {
791
- let latest = null;
792
- for (const tag of tags) {
793
- const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(tag);
794
- if (!match) continue;
795
- const version = match.slice(1).map(Number);
796
- if (!latest || isNewer(version, latest.version)) latest = { tag, version };
797
- }
798
- return latest?.tag ?? null;
806
+ let latest = null;
807
+ for (const tag of tags) {
808
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(tag);
809
+ if (!match) continue;
810
+ const version = match.slice(1).map(Number);
811
+ if (!latest || isNewer(version, latest.version)) latest = {
812
+ tag,
813
+ version
814
+ };
815
+ }
816
+ return latest?.tag ?? null;
799
817
  }
818
+ /** Whether version `a` is higher than `b`, both as [major, minor, patch]. */
800
819
  function isNewer(a, b) {
801
- for (let i = 0; i < a.length; i++) {
802
- if (a[i] !== b[i]) return a[i] > b[i];
803
- }
804
- return false;
820
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] > b[i];
821
+ return false;
805
822
  }
823
+ /** Fetch the latest template release: its tag from the git tags, its date from the GitHub API. */
806
824
  async function fetchLatestRelease() {
807
- let tag;
808
- try {
809
- const refs = await git3.listServerRefs({ http: http2, url: TEMPLATE_GIT_URL, prefix: "refs/tags/" });
810
- tag = pickLatestReleaseTag(refs.map(({ ref }) => ref.slice("refs/tags/".length)));
811
- } catch {
812
- return null;
813
- }
814
- if (!tag) return null;
815
- return { tag, date: await fetchReleaseDate(tag) };
825
+ let tag;
826
+ try {
827
+ tag = pickLatestReleaseTag((await git.listServerRefs({
828
+ http,
829
+ url: TEMPLATE_GIT_URL,
830
+ prefix: "refs/tags/"
831
+ })).map(({ ref }) => ref.slice(10)));
832
+ } catch {
833
+ return null;
834
+ }
835
+ if (!tag) return null;
836
+ return {
837
+ tag,
838
+ date: await fetchReleaseDate(tag)
839
+ };
816
840
  }
841
+ /** Publication date of a release, undefined when the GitHub API does not answer. */
817
842
  async function fetchReleaseDate(tag) {
818
- try {
819
- const response = await fetch(`${TEMPLATE_METADATA_API_BASE}/releases/tags/${tag}`, { headers: GITHUB_HEADERS });
820
- if (!response.ok) return void 0;
821
- const release = await response.json();
822
- return release.published_at ? toDate(release.published_at) : void 0;
823
- } catch {
824
- return void 0;
825
- }
843
+ try {
844
+ const response = await fetch(`${TEMPLATE_METADATA_API_BASE}/releases/tags/${tag}`, { headers: GITHUB_HEADERS });
845
+ if (!response.ok) return void 0;
846
+ const release = await response.json();
847
+ return release.published_at ? toDate(release.published_at) : void 0;
848
+ } catch {
849
+ return;
850
+ }
826
851
  }
852
+ /** Fetch the latest commit on a branch (defaults to 'main'). */
827
853
  async function fetchLatestCommit(branch = "main") {
828
- const apiUrl = `${TEMPLATE_METADATA_API_BASE}/commits/${branch}`;
829
- try {
830
- const response = await fetch(apiUrl, { headers: GITHUB_HEADERS });
831
- if (!response.ok) return null;
832
- const data = await response.json();
833
- if (!data.sha) return null;
834
- const message = (data.commit?.message ?? "").split("\n")[0];
835
- return { sha: data.sha, shortSha: data.sha.slice(0, 7), message, date: toDate(data.commit?.author?.date) };
836
- } catch {
837
- return null;
838
- }
854
+ const apiUrl = `${TEMPLATE_METADATA_API_BASE}/commits/${branch}`;
855
+ try {
856
+ const response = await fetch(apiUrl, { headers: GITHUB_HEADERS });
857
+ if (!response.ok) return null;
858
+ const data = await response.json();
859
+ if (!data.sha) return null;
860
+ const message = (data.commit?.message ?? "").split("\n")[0];
861
+ return {
862
+ sha: data.sha,
863
+ shortSha: data.sha.slice(0, 7),
864
+ message,
865
+ date: toDate(data.commit?.author?.date)
866
+ };
867
+ } catch {
868
+ return null;
869
+ }
839
870
  }
840
-
841
871
  // src/utils/is-empty-directory.ts
842
- import { readdir as readdir3 } from "fs/promises";
843
- async function isEmptyDirectory(path2) {
844
- const files = await readdir3(path2);
845
- return files.length === 0 || files.length === 1 && files[0] === ".git";
872
+ /**
873
+ * Checks if a directory is empty or only contains a .git directory.
874
+ *
875
+ * @param path - The path of the directory to check.
876
+ * @returns Resolves to true if the directory is empty or contains only a .git folder, false otherwise.
877
+ * @throws Throws an error if the path is not a directory or if there's an issue reading the directory.
878
+ */
879
+ async function isEmptyDirectory(path) {
880
+ const files = await readdir(path);
881
+ return files.length === 0 || files.length === 1 && files[0] === ".git";
846
882
  }
847
-
848
883
  // src/create-cella-cli.ts
849
884
  async function main() {
850
- showWelcome();
851
- const promptTheme = { prefix: "", style: { answer: (text) => text } };
852
- const promptContext = { clearPromptOnDone: true };
853
- const templateRef = cli.options.template ? void 0 : await promptTemplateRef(promptTheme, promptContext);
854
- if (!cli.directory) {
855
- cli.directory = await input(
856
- {
857
- message: "Enter your project name",
858
- default: "my-cella-app",
859
- theme: promptTheme,
860
- validate: (name) => {
861
- const validation = validateProjectName(basename2(resolve3(name)));
862
- return validation.valid ? true : `Invalid project name: ${validation.problems?.[0] ?? "unknown error"}`;
863
- }
864
- },
865
- promptContext
866
- );
867
- }
868
- const targetFolder = resolve3(cli.directory);
869
- const projectName = basename2(targetFolder)?.toLowerCase() || "project";
870
- if (existsSync2(targetFolder) && !await isEmptyDirectory(targetFolder)) {
871
- const dirName = cli.directory === "." ? "Current directory" : `Target directory "${targetFolder}"`;
872
- const message = `${dirName} is not empty. Please choose how you would like to proceed:`;
873
- const action = await select(
874
- {
875
- message,
876
- theme: promptTheme,
877
- choices: [
878
- { name: "Cancel and exit", value: "cancel" },
879
- { name: "Remove existing files and continue", value: "remove" }
880
- ]
881
- },
882
- promptContext
883
- );
884
- if (action === "cancel") {
885
- process.exit(1);
886
- }
887
- if (action === "remove") {
888
- await rm2(targetFolder, { recursive: true, force: true });
889
- }
890
- }
891
- const appIndex = cli.options.appIndex ?? await promptAppIndex(targetFolder, promptTheme, promptContext);
892
- confirmChoice("App index", formatAppIndex(appIndex));
893
- const busyPorts = await findBusyPorts(appIndex);
894
- if (busyPorts.length > 0) {
895
- console.info(
896
- `${pc6.yellow("\u26A0")} In use on this machine: ${busyPorts.join(", ")}. Stop what holds them before pnpm docker and pnpm dev.`
897
- );
898
- console.info();
899
- }
900
- const adminEmail = cli.options.adminEmail ?? await input(
901
- {
902
- message: "Admin email for initial seed user",
903
- default: "admin@example.com",
904
- theme: promptTheme,
905
- validate: (email) => isEmail(email) ? true : "Enter an address such as admin@example.com"
906
- },
907
- promptContext
908
- );
909
- confirmChoice("Admin email", adminEmail);
910
- const createOptions = {
911
- projectName,
912
- targetFolder,
913
- packageManager: cli.packageManager,
914
- templateUrl: cli.options.template,
915
- templateRef,
916
- appIndex,
917
- adminEmail
918
- };
919
- await create(createOptions);
885
+ showWelcome();
886
+ const promptTheme = {
887
+ prefix: "",
888
+ style: { answer: (text) => text }
889
+ };
890
+ const promptContext = { clearPromptOnDone: true };
891
+ const templateRef = cli.options.template ? void 0 : await promptTemplateRef(promptTheme, promptContext);
892
+ if (!cli.directory) cli.directory = await input({
893
+ message: "Enter your project name",
894
+ default: "my-cella-app",
895
+ theme: promptTheme,
896
+ validate: (name) => {
897
+ const validation = validateProjectName(basename(resolve(name)));
898
+ return validation.valid ? true : `Invalid project name: ${validation.problems?.[0] ?? "unknown error"}`;
899
+ }
900
+ }, promptContext);
901
+ const targetFolder = resolve(cli.directory);
902
+ const projectName = basename(targetFolder)?.toLowerCase() || "project";
903
+ if (existsSync(targetFolder) && !await isEmptyDirectory(targetFolder)) {
904
+ const message = `${cli.directory === "." ? "Current directory" : `Target directory "${targetFolder}"`} is not empty. Please choose how you would like to proceed:`;
905
+ const action = await select({
906
+ message,
907
+ theme: promptTheme,
908
+ choices: [{
909
+ name: "Cancel and exit",
910
+ value: "cancel"
911
+ }, {
912
+ name: "Remove existing files and continue",
913
+ value: "remove"
914
+ }]
915
+ }, promptContext);
916
+ if (action === "cancel") process.exit(1);
917
+ if (action === "remove") await rm(targetFolder, {
918
+ recursive: true,
919
+ force: true
920
+ });
921
+ }
922
+ const appIndex = cli.options.appIndex ?? await promptAppIndex(targetFolder, promptTheme, promptContext);
923
+ confirmChoice("App index", formatAppIndex(appIndex));
924
+ const busyPorts = await findBusyPorts(appIndex);
925
+ if (busyPorts.length > 0) {
926
+ console.info(`${pc.yellow("⚠")} In use on this machine: ${busyPorts.join(", ")}. Stop what holds them before pnpm docker and pnpm dev.`);
927
+ console.info();
928
+ }
929
+ const adminEmail = cli.options.adminEmail ?? await input({
930
+ message: "Admin email for initial seed user",
931
+ default: "admin@example.com",
932
+ theme: promptTheme,
933
+ validate: (email) => isEmail(email) ? true : "Enter an address such as admin@example.com"
934
+ }, promptContext);
935
+ confirmChoice("Admin email", adminEmail);
936
+ await create({
937
+ projectName,
938
+ targetFolder,
939
+ packageManager: cli.packageManager,
940
+ templateUrl: cli.options.template,
941
+ templateRef,
942
+ appIndex,
943
+ adminEmail
944
+ });
920
945
  }
921
946
  main().catch((error) => {
922
- console.error(error);
923
- process.exit(1);
947
+ console.error(error);
948
+ process.exit(1);
924
949
  });
950
+ /**
951
+ * Show a short intro with the two starting points (latest release and latest
952
+ * commit, each with its date) and let the user choose which template snapshot to
953
+ * scaffold from. Returns the template ref to check out (release tag or `main`), or
954
+ * undefined to use the default branch (when metadata is unavailable).
955
+ */
925
956
  async function promptTemplateRef(theme, context) {
926
- const [release, commit] = await Promise.all([fetchLatestRelease(), fetchLatestCommit()]);
927
- console.info(pc6.dim("This create CLI allows you to get started with cella quickly."));
928
- console.info();
929
- if (release)
930
- console.info(` Latest release: ${release.tag}${release.date ? ` ${pc6.dim(`\xB7 ${release.date}`)}` : ""}`);
931
- if (commit) {
932
- console.info(` Latest commit: ${commit.shortSha} ${pc6.dim(`\xB7 ${commit.message} \xB7 ${commit.date}`)}`);
933
- const repo = TEMPLATE_URL.replace("github:", "");
934
- console.info(` ${pc6.gray(`https://github.com/${repo}/commit/${commit.sha}`)}`);
935
- }
936
- if (release || commit) console.info();
937
- if (!release) {
938
- console.info(`${pc6.yellow("\u26A0")} Latest release not found \xB7 using the latest commit on main`);
939
- console.info();
940
- return commit ? "main" : void 0;
941
- }
942
- if (!commit || !process.stdin.isTTY) {
943
- confirmChoice("Latest release", release.tag);
944
- return release.tag;
945
- }
946
- const choice = await select(
947
- {
948
- message: "Choose which cella version to start from:",
949
- theme,
950
- choices: [
951
- { name: "Latest release", value: "release" },
952
- { name: "Latest commit", value: "commit" }
953
- ]
954
- },
955
- context
956
- );
957
- if (choice === "release") {
958
- confirmChoice("Latest release", release.tag);
959
- return release.tag;
960
- }
961
- confirmChoice("Latest commit", commit.shortSha);
962
- return "main";
957
+ const [release, commit] = await Promise.all([fetchLatestRelease(), fetchLatestCommit()]);
958
+ console.info(pc.dim("This create CLI allows you to get started with cella quickly."));
959
+ console.info();
960
+ if (release) console.info(` Latest release: ${release.tag}${release.date ? ` ${pc.dim(`· ${release.date}`)}` : ""}`);
961
+ if (commit) {
962
+ console.info(` Latest commit: ${commit.shortSha} ${pc.dim(`· ${commit.message} · ${commit.date}`)}`);
963
+ const repo = TEMPLATE_URL.replace("github:", "");
964
+ console.info(` ${pc.gray(`https://github.com/${repo}/commit/${commit.sha}`)}`);
965
+ }
966
+ if (release || commit) console.info();
967
+ if (!release) {
968
+ console.info(`${pc.yellow("⚠")} Latest release not found · using the latest commit on main`);
969
+ console.info();
970
+ return commit ? "main" : void 0;
971
+ }
972
+ if (!commit || !process.stdin.isTTY) {
973
+ confirmChoice("Latest release", release.tag);
974
+ return release.tag;
975
+ }
976
+ if (await select({
977
+ message: "Choose which cella version to start from:",
978
+ theme,
979
+ choices: [{
980
+ name: "Latest release",
981
+ value: "release"
982
+ }, {
983
+ name: "Latest commit",
984
+ value: "commit"
985
+ }]
986
+ }, context) === "release") {
987
+ confirmChoice("Latest release", release.tag);
988
+ return release.tag;
989
+ }
990
+ confirmChoice("Latest commit", commit.shortSha);
991
+ return "main";
963
992
  }
993
+ /** Format an app index as a port overview string, e.g. "1 → :3001 / :4010 / :5442" */
964
994
  function formatAppIndex(i, suffix = "") {
965
- return `${i} \u2192 :${3e3 + i} / :${4e3 + i * 10} / :${5432 + i * 10}${suffix}`;
995
+ return `${i} → :${3e3 + i} / :${4e3 + i * 10} / :${5432 + i * 10}${suffix}`;
966
996
  }
997
+ /** Scan sibling apps and prompt the user to pick an app index */
967
998
  async function promptAppIndex(targetFolder, theme, context) {
968
- const usedPorts = await detectUsedPorts(targetFolder);
969
- const presets = [1, 2, 3];
970
- const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)])));
971
- const isBusy = (i) => (busy.get(i)?.length ?? 0) > 0;
972
- const suggested = findNextAppIndex(usedPorts, isBusy);
973
- const label = (i, note = "") => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);
974
- let message = `${pc6.bold("App index")} ${pc6.dim("\xB7 to avoid port conflicts with other apps on this machine")}`;
975
- if (usedPorts.length > 0) {
976
- const count = usedPorts.length;
977
- message += pc6.dim(`
978
- Detected ${count} sibling app${count === 1 ? "" : "s"} \xB7 suggested index ${suggested}`);
979
- }
980
- const portTheme = {
981
- ...theme,
982
- style: { ...theme.style ?? {}, message: (text) => text }
983
- };
984
- const choice = await select(
985
- {
986
- message,
987
- theme: portTheme,
988
- choices: [
989
- ...suggested > 0 ? [{ name: formatAppIndex(suggested, " (suggested)"), value: suggested }] : [],
990
- { name: label(0, " (default)"), value: 0 },
991
- ...presets.filter((i) => i !== suggested).map((i) => ({ name: label(i), value: i })),
992
- { name: "Custom index", value: -1 }
993
- ]
994
- },
995
- context
996
- );
997
- if (choice !== -1) return choice;
998
- const custom = await input(
999
- {
1000
- message: "Enter custom index (0-9, not 4)",
1001
- default: String(suggested),
1002
- theme,
1003
- validate: (val) => isAppIndex(Number(val)) ? true : "Must be a whole number from 0 to 9, not 4"
1004
- },
1005
- context
1006
- );
1007
- return Number(custom);
999
+ const usedPorts = await detectUsedPorts(targetFolder);
1000
+ const presets = [
1001
+ 1,
1002
+ 2,
1003
+ 3
1004
+ ];
1005
+ const busy = new Map(await Promise.all([0, ...presets].map(async (i) => [i, await findBusyPorts(i)])));
1006
+ const isBusy = (i) => (busy.get(i)?.length ?? 0) > 0;
1007
+ const suggested = findNextAppIndex(usedPorts, isBusy);
1008
+ const label = (i, note = "") => formatAppIndex(i, isBusy(i) ? ` (port ${busy.get(i)?.[0]} in use)` : note);
1009
+ let message = `${pc.bold("App index")} ${pc.dim("· to avoid port conflicts with other apps on this machine")}`;
1010
+ if (usedPorts.length > 0) {
1011
+ const count = usedPorts.length;
1012
+ message += pc.dim(`\nDetected ${count} sibling app${count === 1 ? "" : "s"} · suggested index ${suggested}`);
1013
+ }
1014
+ const portTheme = {
1015
+ ...theme,
1016
+ style: {
1017
+ ...theme.style ?? {},
1018
+ message: (text) => text
1019
+ }
1020
+ };
1021
+ const choice = await select({
1022
+ message,
1023
+ theme: portTheme,
1024
+ choices: [
1025
+ ...suggested > 0 ? [{
1026
+ name: formatAppIndex(suggested, " (suggested)"),
1027
+ value: suggested
1028
+ }] : [],
1029
+ {
1030
+ name: label(0, " (default)"),
1031
+ value: 0
1032
+ },
1033
+ ...presets.filter((i) => i !== suggested).map((i) => ({
1034
+ name: label(i),
1035
+ value: i
1036
+ })),
1037
+ {
1038
+ name: "Custom index",
1039
+ value: -1
1040
+ }
1041
+ ]
1042
+ }, context);
1043
+ if (choice !== -1) return choice;
1044
+ const custom = await input({
1045
+ message: "Enter custom index (0-9, not 4)",
1046
+ default: String(suggested),
1047
+ theme,
1048
+ validate: (val) => isAppIndex(Number(val)) ? true : "Must be a whole number from 0 to 9, not 4"
1049
+ }, context);
1050
+ return Number(custom);
1008
1051
  }
1052
+ export {};
1053
+
1009
1054
  //# sourceMappingURL=index.js.map