create-vanilla-vite 0.0.0-stage → 1.0.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/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # Vanilla Vite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Create a Vite app with the official interactive setup. Choose React or any other offered template, and optionally add a Node.js or Express backend in the same npm or pnpm workspace.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/create-vanilla-vite)](https://www.npmjs.com/package/create-vanilla-vite)
6
+ [![npm downloads](https://img.shields.io/npm/dm/create-vanilla-vite)](https://www.npmjs.com/package/create-vanilla-vite)
7
+ [![GitHub repository](https://img.shields.io/badge/GitHub-Wasib--2005%2Fvanilla--vite-181717?logo=github)](https://github.com/Wasib-2005/vanilla-vite)
8
+
9
+ **Links:** [npm package](https://www.npmjs.com/package/create-vanilla-vite) · [GitHub repository](https://github.com/Wasib-2005/vanilla-vite) · [Report an issue](https://github.com/Wasib-2005/vanilla-vite/issues)
10
+
11
+ ## Requirements
12
+
13
+ - Node.js 20 or newer
14
+ - npm or pnpm
15
+
16
+ The commands below work in Windows PowerShell or Command Prompt as well as macOS and Linux terminals. pnpm commands require pnpm to be installed; npm is sufficient.
17
+
18
+ ## Create a project
19
+
20
+ With pnpm:
21
+
22
+ ```bash
23
+ pnpm create vanilla-vite@latest my-app
24
+ ```
25
+
26
+ With npm:
27
+
28
+ ```bash
29
+ npm create vanilla-vite@latest my-app
30
+ ```
31
+
32
+ Omit the project name to enter it when prompted:
33
+
34
+ ```bash
35
+ pnpm create vanilla-vite@latest
36
+ # or
37
+ npm create vanilla-vite@latest
38
+ ```
39
+
40
+ The generator starts the official `create-vite@latest` wizard in `my-app-client`. Choose **React** for a React application, then select JavaScript or TypeScript. You can instead choose any other template offered by Vite. Afterward, choose whether to add a backend (frontend-only is the default). The frontend wizard may install dependencies temporarily; the generator removes nested install files and Git metadata, configures one shared workspace, and installs all dependencies from the project root.
41
+
42
+ The optional backend supports JavaScript or TypeScript, either basic Node.js or Express, and a simple or module-based folder layout. Both layouts create the `src/app` and `src/server` entry points. The simple layout has `routes`, `controllers`, `middleware`, and `config` folders; the module-based layout has `module`, `config`, `middleware`, and `utils` folders plus `mainRouter`. Express adds Express and dotenv, enables JSON parsing, and provides `GET /api/health`, returning `{ "status": "ok" }`.
43
+
44
+ Pass `--default` after the project name to use the simple backend folder layout without prompting:
45
+
46
+ ```bash
47
+ pnpm create vanilla-vite@latest my-app --default
48
+ npm create vanilla-vite@latest my-app --default
49
+ ```
50
+
51
+ The generated project structure is:
52
+
53
+ ```text
54
+ my-app/
55
+ ├── my-app-client/ # Vite app; choose React or another Vite template
56
+ ├── my-app-server/ # optional backend
57
+ ├── scripts/
58
+ ├── package.json
59
+ └── pnpm-workspace.yaml # used by pnpm; npm uses package.json workspaces
60
+ ```
61
+
62
+ The frontend gets a `.env.local` file with `VITE_API_URL=http://localhost:4000`. If you choose a backend, it gets a `.env` file with `PORT=4000`. Both are ignored by Git.
63
+
64
+ ## Run the project
65
+
66
+ From the project root:
67
+
68
+ ```bash
69
+ pnpm dev
70
+ # or
71
+ npm run dev
72
+ ```
73
+
74
+ This starts the frontend and, if selected, the backend together. In an interactive terminal, press `r` to restart both apps, `c` to clear the terminal, or Ctrl+C to stop.
75
+
76
+ Run one workspace individually:
77
+
78
+ ```bash
79
+ pnpm client
80
+ pnpm server
81
+ ```
82
+
83
+ Or with npm:
84
+
85
+ ```bash
86
+ npm run client
87
+ npm run server
88
+ ```
89
+
90
+ The server commands are only available if you chose a backend. Add `-dev` to run a workspace in development mode, for example `pnpm client -dev` or `pnpm server -dev`.
91
+
92
+ ## Add dependencies
93
+
94
+ With pnpm:
95
+
96
+ ```bash
97
+ pnpm client add <package>
98
+ pnpm server add <package>
99
+ ```
100
+
101
+ With npm:
102
+
103
+ ```bash
104
+ npm install <package> --workspace=my-app-client
105
+ npm install <package> --workspace=my-app-server
106
+ ```
107
+
108
+ ## Development
109
+
110
+ To test the source before publishing:
111
+
112
+ ```bash
113
+ pnpm exec node ./bin/create-template.mjs my-app
114
+ # or
115
+ npm exec -- node ./bin/create-template.mjs my-app
116
+ ```
117
+
118
+ ## License
119
+
120
+ ISC
@@ -0,0 +1,452 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import spawn from "cross-spawn";
5
+ import { emitKeypressEvents } from "node:readline";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { stdin, stdout } from "node:process";
8
+ import { join, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const args = process.argv.slice(2);
12
+ const useDefaultStructure = args.includes("--default");
13
+ let projectName = args.find((arg) => !arg.startsWith("--"));
14
+ const validProjectName = (name) => /^[a-z0-9][a-z0-9_-]*$/.test(name);
15
+
16
+ if (!projectName && stdin.isTTY) {
17
+ const prompt = createInterface({ input: stdin, output: stdout });
18
+ try {
19
+ do {
20
+ projectName = (await prompt.question("Project name: ")).trim();
21
+ if (!validProjectName(projectName)) {
22
+ console.error("Use lowercase letters, numbers, hyphens, or underscores.");
23
+ }
24
+ } while (!validProjectName(projectName));
25
+ } finally {
26
+ prompt.close();
27
+ }
28
+ }
29
+
30
+ if (!projectName || !validProjectName(projectName)) {
31
+ console.error("Usage: create-vanilla-vite <lowercase-project-name>");
32
+ if (!projectName && !stdin.isTTY) {
33
+ console.error("Run this command in an interactive terminal to be prompted for a name.");
34
+ }
35
+ process.exit(1);
36
+ }
37
+
38
+ const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
39
+ ? "pnpm"
40
+ : "npm";
41
+ const root = resolve(process.cwd(), projectName);
42
+ const clientFolder = `${projectName}-client`;
43
+ const serverFolder = `${projectName}-server`;
44
+ const packageRoot = fileURLToPath(new URL("../", import.meta.url));
45
+ const scriptRoot = fileURLToPath(new URL("../scripts/", import.meta.url));
46
+ const cliPackage = JSON.parse(
47
+ await readFile(join(packageRoot, "package.json"), "utf8"),
48
+ );
49
+
50
+ async function updateIfOutdated() {
51
+ const { version: installedVersion } = cliPackage;
52
+ const registry = (process.env.npm_config_registry || "https://registry.npmjs.org")
53
+ .replace(/\/$/, "");
54
+
55
+ let latestVersion;
56
+ try {
57
+ const response = await fetch(`${registry}/create-vanilla-vite/latest`, {
58
+ signal: AbortSignal.timeout(3000),
59
+ });
60
+ if (!response.ok) throw new Error(`registry returned HTTP ${response.status}`);
61
+ latestVersion = (await response.json()).version;
62
+ if (typeof latestVersion !== "string") {
63
+ throw new Error("registry response did not include a version");
64
+ }
65
+ } catch (error) {
66
+ console.warn(`\nCould not check for CLI updates: ${error.message}`);
67
+ return;
68
+ }
69
+
70
+ if (installedVersion === latestVersion) return;
71
+ if (!stdin.isTTY) {
72
+ console.warn(
73
+ `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}). Run ${packageManager} create vanilla-vite@latest to use it.`,
74
+ );
75
+ return;
76
+ }
77
+
78
+ console.warn(
79
+ `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}).`,
80
+ );
81
+ const useLatest = await selectOption("Which version would you like to use?", [
82
+ { label: `Use the latest version (${latestVersion})`, value: true },
83
+ { label: `Continue with the current version (${installedVersion})`, value: false },
84
+ ]);
85
+ if (!useLatest) return;
86
+
87
+ const updateArgs =
88
+ packageManager === "pnpm"
89
+ ? ["dlx", "create-vanilla-vite@latest", ...args]
90
+ : [
91
+ "exec",
92
+ "--yes",
93
+ "--package=create-vanilla-vite@latest",
94
+ "--",
95
+ "create-vanilla-vite",
96
+ ...args,
97
+ ];
98
+ try {
99
+ await run(packageManager, updateArgs, process.cwd());
100
+ } catch (error) {
101
+ console.error(`Unable to start the latest CLI version: ${error.message}`);
102
+ process.exit(1);
103
+ }
104
+ process.exit(0);
105
+ }
106
+
107
+ function run(command, commandArgs, cwd) {
108
+ return new Promise((resolveRun, rejectRun) => {
109
+ const child = spawn(command, commandArgs, { cwd, stdio: "inherit" });
110
+ child.once("error", rejectRun);
111
+ child.once("close", (code, signal) => {
112
+ if (code === 0) resolveRun();
113
+ else {
114
+ rejectRun(
115
+ new Error(`${command} exited ${signal ? `from ${signal}` : `with code ${code}`}`),
116
+ );
117
+ }
118
+ });
119
+ });
120
+ }
121
+
122
+ async function selectOption(question, options, defaultIndex = 0) {
123
+ if (!stdin.isTTY) return options[defaultIndex].value;
124
+ let selected = defaultIndex;
125
+ emitKeypressEvents(stdin);
126
+
127
+ return new Promise((resolveSelection) => {
128
+ function render() {
129
+ stdout.write(`\r\x1b[2K${question}\n`);
130
+ for (const [index, option] of options.entries()) {
131
+ stdout.write(` ${index === selected ? "❯" : " "} ${option.label}\n`);
132
+ }
133
+ stdout.write(" Use ↑/↓ to select, Enter to confirm, or Esc to keep the default.\n");
134
+ stdout.write(`\x1b[${options.length + 2}A`);
135
+ }
136
+
137
+ function finish(value) {
138
+ stdin.off("keypress", onKeypress);
139
+ stdin.setRawMode(false);
140
+ stdin.pause();
141
+ stdout.write(`\x1b[${options.length + 2}B\n`);
142
+ resolveSelection(value);
143
+ }
144
+
145
+ function onKeypress(_input, key) {
146
+ if (key?.name === "up" || key?.name === "down") {
147
+ selected =
148
+ (selected + (key.name === "down" ? 1 : options.length - 1)) %
149
+ options.length;
150
+ render();
151
+ } else if (key?.name === "return") finish(options[selected].value);
152
+ else if (key?.name === "escape" || (key?.ctrl && key.name === "c")) {
153
+ finish(options[defaultIndex].value);
154
+ }
155
+ }
156
+
157
+ stdin.setRawMode(true);
158
+ stdin.resume();
159
+ stdin.on("keypress", onKeypress);
160
+ render();
161
+ });
162
+ }
163
+
164
+ async function copyScript(name) {
165
+ const source = await readFile(join(scriptRoot, name), "utf8");
166
+ await writeFile(join(root, "scripts", name), source);
167
+ }
168
+
169
+ function backendFiles(language, framework) {
170
+ const extension = language;
171
+ const typeAnnotation = language === "ts" ? ": number" : "";
172
+ const request = language === "ts"
173
+ ? framework === "express"
174
+ ? "request: import('express').Request"
175
+ : "request: import('node:http').IncomingMessage"
176
+ : "request";
177
+ const response = language === "ts"
178
+ ? framework === "express"
179
+ ? "response: import('express').Response"
180
+ : "response: import('node:http').ServerResponse"
181
+ : "response";
182
+ const app =
183
+ framework === "express"
184
+ ? `import express from "express";
185
+
186
+ export function createApp() {
187
+ const app = express();
188
+ app.use(express.json());
189
+ app.get("/", (_request, response) => response.json({ message: "Backend is running" }));
190
+ app.get("/api/health", (_request, response) => response.json({ status: "ok" }));
191
+ return app;
192
+ }
193
+ `
194
+ : `import { createServer } from "node:http";
195
+
196
+ export function createApp() {
197
+ return createServer((${request}, ${response}) => {
198
+ response.writeHead(200, { "content-type": "application/json" });
199
+ response.end(JSON.stringify({ message: "Backend is running" }));
200
+ });
201
+ }
202
+ `;
203
+ const server = `${framework === "express" ? 'import "dotenv/config";\n' : ""}import { createApp } from "./app.${extension}";
204
+
205
+ const port${typeAnnotation} = Number(process.env.PORT ?? 4000);
206
+ const app = createApp();
207
+ app.listen(port, () => {
208
+ console.log(\`Backend listening at http://localhost:\${port}\`);
209
+ });
210
+ `;
211
+ return { app, server };
212
+ }
213
+
214
+ async function createBackend(serverRoot) {
215
+ const language = await selectOption("Select a language for the backend:", [
216
+ { label: "JavaScript", value: "js" },
217
+ { label: "TypeScript", value: "ts" },
218
+ ]);
219
+ const framework = await selectOption("Select a backend framework:", [
220
+ { label: "Basic Node.js — no additional framework", value: "basic" },
221
+ { label: "Express — install Express and dotenv", value: "express" },
222
+ ]);
223
+ const structure = useDefaultStructure
224
+ ? "simple"
225
+ : await selectOption("Select a backend folder structure:", [
226
+ { label: "Simple — standard folders (default)", value: "simple" },
227
+ { label: "Module-based — organized by feature", value: "module" },
228
+ ]);
229
+ const typed = language === "ts";
230
+ let { app, server } = backendFiles(language, framework);
231
+ const sourceRoot = join(serverRoot, "src");
232
+ const folders =
233
+ structure === "simple"
234
+ ? ["routes", "controllers", "middleware", "config"]
235
+ : ["module", "config", "middleware", "utils"];
236
+ for (const folder of folders) {
237
+ await mkdir(join(sourceRoot, folder), { recursive: true });
238
+ }
239
+ if (structure === "module") {
240
+ const request = typed
241
+ ? framework === "express"
242
+ ? "request: import('express').Request"
243
+ : "request: import('node:http').IncomingMessage"
244
+ : "request";
245
+ const response = typed
246
+ ? framework === "express"
247
+ ? "response: import('express').Response"
248
+ : "response: import('node:http').ServerResponse"
249
+ : "response";
250
+ const router =
251
+ framework === "express"
252
+ ? `import { Router } from "express";
253
+
254
+ export const mainRouter = Router();
255
+ mainRouter.get("/api/health", (_request, response) => {
256
+ response.json({ status: "ok" });
257
+ });
258
+ `
259
+ : `export function handleRequest(${request}, ${response}) {
260
+ response.writeHead(200, { "content-type": "application/json" });
261
+ response.end(JSON.stringify({ message: "Backend is running" }));
262
+ }
263
+ `;
264
+ await writeFile(join(sourceRoot, `mainRouter.${language}`), router);
265
+ app =
266
+ framework === "express"
267
+ ? `import express from "express";
268
+ import { mainRouter } from "./mainRouter.${language}";
269
+
270
+ export function createApp() {
271
+ const app = express();
272
+ app.use(express.json());
273
+ app.use(mainRouter);
274
+ return app;
275
+ }
276
+ `
277
+ : `import { createServer } from "node:http";
278
+ import { handleRequest } from "./mainRouter.${language}";
279
+
280
+ export function createApp() {
281
+ return createServer(handleRequest);
282
+ }
283
+ `;
284
+ }
285
+ await writeFile(join(sourceRoot, `app.${language}`), app);
286
+ await writeFile(join(sourceRoot, `server.${language}`), server);
287
+
288
+ const scripts = typed
289
+ ? { dev: `tsx watch src/server.${language}`, start: `tsx src/server.${language}` }
290
+ : { dev: `node --watch src/server.${language}`, start: `node src/server.${language}` };
291
+ const dependencies = framework === "express" ? { express: "^5", dotenv: "^16" } : {};
292
+ const packageJson = {
293
+ name: serverFolder,
294
+ version: "1.0.0",
295
+ private: true,
296
+ type: "module",
297
+ scripts,
298
+ ...(typed
299
+ ? {
300
+ dependencies: { ...dependencies, tsx: "^4" },
301
+ devDependencies: {
302
+ ...(framework === "express" ? { "@types/express": "^5" } : {}),
303
+ "@types/node": "^22",
304
+ typescript: "^5",
305
+ },
306
+ }
307
+ : Object.keys(dependencies).length
308
+ ? { dependencies }
309
+ : {}),
310
+ };
311
+ await writeFile(join(serverRoot, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`);
312
+ if (typed) {
313
+ await writeFile(
314
+ join(serverRoot, "tsconfig.json"),
315
+ `${JSON.stringify(
316
+ {
317
+ compilerOptions: {
318
+ target: "ES2022",
319
+ module: "NodeNext",
320
+ moduleResolution: "NodeNext",
321
+ strict: true,
322
+ esModuleInterop: true,
323
+ skipLibCheck: true,
324
+ noEmit: true,
325
+ allowImportingTsExtensions: true,
326
+ },
327
+ include: ["**/*.ts"],
328
+ },
329
+ null,
330
+ 2,
331
+ )}\n`,
332
+ );
333
+ }
334
+ await writeFile(
335
+ join(serverRoot, ".env"),
336
+ "# Local backend environment variables\nPORT=4000\n",
337
+ { flag: "wx" },
338
+ );
339
+ }
340
+
341
+ await updateIfOutdated();
342
+
343
+ try {
344
+ await mkdir(root);
345
+ } catch (error) {
346
+ if (error.code === "EEXIST") console.error(`The destination already exists: ${root}`);
347
+ else console.error(`Unable to create project directory: ${error.message}`);
348
+ process.exit(1);
349
+ }
350
+
351
+ try {
352
+ console.log(`\nCreating the frontend in ${clientFolder} with create-vite...\n`);
353
+ const viteArgs =
354
+ packageManager === "pnpm"
355
+ ? ["create", "vite@latest", clientFolder, "--no-immediate"]
356
+ : ["create", "vite@latest", "--", clientFolder, "--no-immediate"];
357
+ await run(packageManager, viteArgs, root);
358
+
359
+ const clientRoot = join(root, clientFolder);
360
+ await Promise.all(
361
+ [".git", "node_modules", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"].map(
362
+ (entry) => rm(join(clientRoot, entry), { recursive: true, force: true }),
363
+ ),
364
+ );
365
+ const clientPackagePath = join(clientRoot, "package.json");
366
+ const clientPackage = JSON.parse(await readFile(clientPackagePath, "utf8"));
367
+ clientPackage.scripts ??= {};
368
+ clientPackage.scripts.start ??= clientPackage.scripts.dev;
369
+ await writeFile(clientPackagePath, `${JSON.stringify(clientPackage, null, 2)}\n`);
370
+ await writeFile(
371
+ join(clientRoot, ".env.local"),
372
+ "# Local frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
373
+ { flag: "wx" },
374
+ );
375
+
376
+ const includeServer = await selectOption(
377
+ "Would you like to add a separate backend server?",
378
+ [
379
+ { label: "Yes — include a backend workspace", value: true },
380
+ { label: "No — create a frontend-only project (default)", value: false },
381
+ ],
382
+ 1,
383
+ );
384
+ const workspaces = [clientFolder];
385
+ if (includeServer) {
386
+ await createBackend(join(root, serverFolder));
387
+ workspaces.push(serverFolder);
388
+ }
389
+
390
+ await mkdir(join(root, "scripts"), { recursive: true });
391
+ await Promise.all(["dev.mjs", "run-app.mjs", "install-info.mjs"].map(copyScript));
392
+ const rootPackage = {
393
+ name: projectName,
394
+ version: "1.0.0",
395
+ private: true,
396
+ workspaces,
397
+ scripts: {
398
+ preinstall: "node scripts/install-info.mjs",
399
+ dev: "node scripts/dev.mjs",
400
+ client: "node scripts/run-app.mjs client",
401
+ ...(includeServer ? { server: "node scripts/run-app.mjs server" } : {}),
402
+ },
403
+ type: "module",
404
+ dependencies: {
405
+ "cross-spawn": cliPackage.dependencies["cross-spawn"],
406
+ },
407
+ };
408
+ await writeFile(join(root, "package.json"), `${JSON.stringify(rootPackage, null, 2)}\n`);
409
+ await writeFile(
410
+ join(root, "pnpm-workspace.yaml"),
411
+ [
412
+ "packages:",
413
+ ...workspaces.map((workspace) => ` - ${workspace}`),
414
+ "",
415
+ "allowBuilds:",
416
+ " esbuild: true",
417
+ " sharp: false",
418
+ " unrs-resolver: false",
419
+ "",
420
+ ].join("\n"),
421
+ );
422
+ await writeFile(
423
+ join(root, ".gitignore"),
424
+ [
425
+ "# Dependencies",
426
+ "node_modules/",
427
+ "",
428
+ "# Build output",
429
+ "**/dist/",
430
+ "**/coverage/",
431
+ "",
432
+ "# Local environment files",
433
+ "**/.env*",
434
+ "!**/.env.example",
435
+ "",
436
+ "# Logs",
437
+ "npm-debug.log*",
438
+ "pnpm-debug.log*",
439
+ "yarn-debug.log*",
440
+ "",
441
+ ].join("\n"),
442
+ );
443
+
444
+ console.log(`\nInstalling dependencies for ${workspaces.join(" and ")}...`);
445
+ await run(packageManager, ["install"], root);
446
+ console.log(
447
+ `\nProject created successfully: ${projectName}/\n\nTo get started:\n cd ${projectName}\n ${packageManager} dev`,
448
+ );
449
+ } catch (error) {
450
+ console.error(`\nProject creation failed: ${error.message}`);
451
+ process.exit(1);
452
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "create-vanilla-vite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Scaffold a React or Vite app with an optional Node.js or Express backend",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Wasib-2005/vanilla-vite.git"
9
+ },
10
+ "homepage": "https://github.com/Wasib-2005/vanilla-vite#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/Wasib-2005/vanilla-vite/issues"
13
+ },
14
+ "bin": {
15
+ "create-vanilla-vite": "./bin/create-template.mjs"
16
+ },
17
+ "files": [
18
+ "bin/",
19
+ "scripts/",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "keywords": [
26
+ "create",
27
+ "create-vite",
28
+ "react",
29
+ "vite",
30
+ "scaffold",
31
+ "generator",
32
+ "starter",
33
+ "fullstack",
34
+ "full-stack",
35
+ "monorepo",
36
+ "pnpm",
37
+ "npm",
38
+ "node",
39
+ "nodejs",
40
+ "express",
41
+ "typescript",
42
+ "javascript",
43
+ "cli"
44
+ ],
45
+ "license": "ISC",
46
+ "dependencies": {
47
+ "cross-spawn": "^7.0.6"
48
+ }
49
+ }
@@ -0,0 +1,132 @@
1
+ import spawn from "cross-spawn";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = fileURLToPath(new URL("../", import.meta.url));
7
+ const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
8
+ const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
9
+ ? "pnpm"
10
+ : "npm";
11
+ const apps = project.workspaces.map((workspace) => ({
12
+ name: workspace.endsWith("-client") ? "client" : "server",
13
+ workspace,
14
+ }));
15
+ const colors = { client: 36, server: 35, dev: 90 };
16
+ const children = [];
17
+ let stopping = false;
18
+ let restarting = false;
19
+
20
+ function log(name, message, write = console.log) {
21
+ const prefix = `[${name}]`;
22
+ write(
23
+ `${process.env.NO_COLOR === undefined && process.stdout.isTTY ? `\x1b[${colors[name]}m${prefix}\x1b[0m` : prefix} ${message}`,
24
+ );
25
+ }
26
+
27
+ function start({ name, workspace }) {
28
+ const args =
29
+ packageManager === "pnpm"
30
+ ? ["--filter", workspace, "run", "dev"]
31
+ : ["run", "dev", "--workspace", workspace];
32
+ const child = spawn(packageManager, args, {
33
+ cwd: root,
34
+ detached: process.platform !== "win32",
35
+ stdio: ["ignore", "pipe", "pipe"],
36
+ });
37
+ children.push(child);
38
+ for (const stream of [child.stdout, child.stderr]) {
39
+ stream.setEncoding("utf8");
40
+ stream.on("data", (chunk) => {
41
+ for (const line of chunk.split(/\r?\n/).filter(Boolean)) log(name, line);
42
+ });
43
+ }
44
+ child.once("error", (error) => {
45
+ log(name, `Unable to start: ${error.message}`, console.error);
46
+ process.exitCode = 1;
47
+ void stop();
48
+ });
49
+ child.once("close", (code) => {
50
+ if (!stopping && !restarting) {
51
+ process.exitCode = code ?? 1;
52
+ void stop();
53
+ }
54
+ });
55
+ }
56
+
57
+ function signalChild(child, signal) {
58
+ try {
59
+ if (process.platform !== "win32" && child.pid) {
60
+ process.kill(-child.pid, signal);
61
+ } else if (child.exitCode === null && child.signalCode === null) {
62
+ child.kill(signal);
63
+ }
64
+ } catch (error) {
65
+ if (error.code !== "ESRCH") throw error;
66
+ }
67
+ }
68
+
69
+ function waitForClose(child, timeout) {
70
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
71
+ return new Promise((resolve) => {
72
+ const timer = setTimeout(() => {
73
+ child.off("close", onClose);
74
+ resolve();
75
+ }, timeout);
76
+ const onClose = () => {
77
+ clearTimeout(timer);
78
+ resolve();
79
+ };
80
+ child.once("close", onClose);
81
+ });
82
+ }
83
+
84
+ async function stopChildren() {
85
+ const running = [...children];
86
+ for (const child of running) signalChild(child, "SIGINT");
87
+ await Promise.all(running.map((child) => waitForClose(child, 3000)));
88
+ for (const child of running) signalChild(child, "SIGTERM");
89
+ await Promise.all(running.map((child) => waitForClose(child, 1000)));
90
+ for (const child of running) signalChild(child, "SIGKILL");
91
+ await Promise.all(running.map((child) => waitForClose(child, 1000)));
92
+ children.length = 0;
93
+ }
94
+
95
+ async function stop() {
96
+ if (stopping) return;
97
+ stopping = true;
98
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
99
+ process.stdin.pause();
100
+ await stopChildren();
101
+ }
102
+
103
+ async function restart() {
104
+ if (restarting || stopping) return;
105
+ restarting = true;
106
+ log("dev", "Restarting application processes...");
107
+ await stopChildren();
108
+ if (stopping) return;
109
+ restarting = false;
110
+ for (const app of apps) start(app);
111
+ log("dev", "Application processes restarted.");
112
+ }
113
+
114
+ for (const app of apps) start(app);
115
+
116
+ for (const signal of ["SIGINT", "SIGTERM"]) {
117
+ process.once(signal, () => void stop());
118
+ }
119
+
120
+ if (process.stdin.isTTY) {
121
+ console.log("Shortcuts: r = restart, c = clear terminal, Ctrl+C = stop.");
122
+ process.stdin.setRawMode(true);
123
+ process.stdin.resume();
124
+ process.stdin.on("data", (key) => {
125
+ if (key.includes("\u0003")) void stop();
126
+ else if (key.toString().toLowerCase() === "r") void restart();
127
+ else if (key.toString().toLowerCase() === "c") {
128
+ process.stdout.write("\x1b[2J\x1b[H");
129
+ console.log("Shortcuts: r = restart, c = clear terminal, Ctrl+C = stop.");
130
+ }
131
+ });
132
+ }
@@ -0,0 +1,25 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const root = fileURLToPath(new URL("../", import.meta.url));
6
+ const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
7
+
8
+ console.log("Installing workspace dependencies:");
9
+ for (const workspace of project.workspaces) {
10
+ const manifest = JSON.parse(
11
+ await readFile(join(root, workspace, "package.json"), "utf8"),
12
+ );
13
+ const dependencies = {
14
+ ...manifest.dependencies,
15
+ ...manifest.devDependencies,
16
+ };
17
+ console.log(`\n${manifest.name} (${workspace}):`);
18
+ if (!Object.keys(dependencies).length) {
19
+ console.log(" No dependencies declared.");
20
+ continue;
21
+ }
22
+ for (const [name, version] of Object.entries(dependencies)) {
23
+ console.log(` - ${name}@${version}`);
24
+ }
25
+ }
@@ -0,0 +1,45 @@
1
+ import spawn from "cross-spawn";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const [app, ...args] = process.argv.slice(2);
7
+ const root = fileURLToPath(new URL("../", import.meta.url));
8
+ const { workspaces } = JSON.parse(
9
+ await readFile(join(root, "package.json"), "utf8"),
10
+ );
11
+ const workspace = workspaces.find((name) => name.endsWith(`-${app}`));
12
+
13
+ if (!workspace || !["client", "server"].includes(app)) {
14
+ console.error("Usage: npm|pnpm client|server [ -dev | add <package...> ]");
15
+ process.exit(1);
16
+ }
17
+
18
+ const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
19
+ ? "pnpm"
20
+ : "npm";
21
+ let commandArgs;
22
+ if (args[0] === "add" && args.length > 1) {
23
+ commandArgs =
24
+ packageManager === "pnpm"
25
+ ? ["--filter", workspace, "add", ...args.slice(1)]
26
+ : ["install", ...args.slice(1), "--workspace", workspace];
27
+ } else if (args.length === 0 || (args.length === 1 && args[0] === "-dev")) {
28
+ const script = args[0] === "-dev" ? "dev" : "start";
29
+ commandArgs =
30
+ packageManager === "pnpm"
31
+ ? ["--filter", workspace, "run", script]
32
+ : ["run", script, "--workspace", workspace];
33
+ } else {
34
+ console.error(`Usage: ${packageManager} ${app} [ -dev | add <package...> ]`);
35
+ process.exit(1);
36
+ }
37
+
38
+ const child = spawn(packageManager, commandArgs, { cwd: root, stdio: "inherit" });
39
+ child.once("error", (error) => {
40
+ console.error(`Unable to run ${packageManager}: ${error.message}`);
41
+ process.exitCode = 1;
42
+ });
43
+ child.once("exit", (code, signal) => {
44
+ process.exitCode = code ?? (signal ? 1 : 0);
45
+ });