@bitbybit-dev/create-app 1.1.0 → 1.2.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,922 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from "commander";
4
+ import inquirer from "inquirer";
5
+ import chalk from "chalk";
6
+ import gradient from "gradient-string";
7
+ import ora from "ora";
8
+ import fs from "fs-extra";
9
+ import path from "path";
10
+ import { fileURLToPath } from "url";
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
14
+
15
+ const BITBYBIT_LOGO = `
16
+ ╭──────────────────────────────────────────────────────────────────────╮
17
+ │ │
18
+ │ ░█▀▄░▀█▀░▀█▀░█▀▄░█░█░█▀▄░▀█▀░▀█▀░░░░░█▀▄░█▀▀░█░█ │
19
+ │ ░█▀▄░░█░░░█░░█▀▄░░█░░█▀▄░░█░░░█░░░░░░█░█░█▀▀░▀▄▀ │
20
+ │ ░▀▀░░▀▀▀░░▀░░▀▀░░░▀░░▀▀░░▀▀▀░░▀░░░▀░░▀▀░░▀▀▀░░▀░ │
21
+ │ │
22
+ │ 3D CAD Development on the Web │
23
+ ╰──────────────────────────────────────────────────────────────────────╯
24
+ `;
25
+
26
+ interface ProjectOptions {
27
+ projectName: string;
28
+ engine: "threejs" | "babylonjs" | "playcanvas";
29
+ bundler: "vite";
30
+ language: "typescript";
31
+ occtArchitecture: "32" | "64" | "64-mt";
32
+ }
33
+
34
+ interface CloudProjectOptions {
35
+ projectName: string;
36
+ backend: "hono-sdk" | "hono-rest" | "nodejs-sdk" | "nodejs-rest" | "dotnet-rest";
37
+ }
38
+
39
+ type AppType = "frontend" | "cloud";
40
+
41
+ type EngineType = "threejs" | "babylonjs" | "playcanvas";
42
+ type OcctArchitectureType = "32" | "64" | "64-mt";
43
+ type BackendType = "hono-sdk" | "hono-rest" | "nodejs-sdk" | "nodejs-rest" | "dotnet-rest";
44
+
45
+ const ENGINE_DISPLAY_NAMES: Record<EngineType, string> = {
46
+ "threejs": "Three.js",
47
+ "babylonjs": "Babylon.js",
48
+ "playcanvas": "PlayCanvas"
49
+ };
50
+
51
+ const ENGINE_DESCRIPTIONS: Record<EngineType, string> = {
52
+ "threejs": "Lightweight and flexible 3D library",
53
+ "babylonjs": "Powerful and feature-rich game engine",
54
+ "playcanvas": "Fast and lightweight WebGL game engine"
55
+ };
56
+
57
+ const ENGINE_COLORS: Record<EngineType, (text: string) => string> = {
58
+ "threejs": chalk.hex("#049EF4"),
59
+ "babylonjs": chalk.hex("#E0684B"),
60
+ "playcanvas": chalk.hex("#FF6600")
61
+ };
62
+
63
+ const OCCT_ARCHITECTURE_DISPLAY_NAMES: Record<OcctArchitectureType, string> = {
64
+ "32": "32-bit (Default)",
65
+ "64": "64-bit",
66
+ "64-mt": "64-bit Multi-threaded"
67
+ };
68
+
69
+ const OCCT_ARCHITECTURE_DESCRIPTIONS: Record<OcctArchitectureType, string> = {
70
+ "32": "Supported on all browsers (recommended)",
71
+ "64": "May not be supported on all browsers",
72
+ "64-mt": "Requires COOP/COEP server headers"
73
+ };
74
+
75
+ const BACKEND_DISPLAY_NAMES: Record<BackendType, string> = {
76
+ "hono-sdk": "Hono + SDK (Cloudflare Workers)",
77
+ "hono-rest": "Hono + REST (Cloudflare Workers)",
78
+ "nodejs-sdk": "Node.js Express + SDK",
79
+ "nodejs-rest": "Node.js Express + REST",
80
+ "dotnet-rest": "ASP.NET Core + REST (.NET 10)",
81
+ };
82
+
83
+ const BACKEND_DESCRIPTIONS: Record<BackendType, string> = {
84
+ "hono-sdk": "Type-safe SDK on Cloudflare Workers edge runtime",
85
+ "hono-rest": "Raw fetch calls on Cloudflare Workers edge runtime",
86
+ "nodejs-sdk": "Type-safe SDK on Node.js with Express 5",
87
+ "nodejs-rest": "Raw fetch calls on Node.js with Express 5",
88
+ "dotnet-rest": "HttpClient calls on ASP.NET Core minimal API (.NET 10)",
89
+ };
90
+
91
+ const BACKEND_COLORS: Record<BackendType, (text: string) => string> = {
92
+ "hono-sdk": chalk.hex("#FF6633"),
93
+ "hono-rest": chalk.hex("#FF6633"),
94
+ "nodejs-sdk": chalk.hex("#68A063"),
95
+ "nodejs-rest": chalk.hex("#68A063"),
96
+ "dotnet-rest": chalk.hex("#512BD4"),
97
+ };
98
+
99
+ async function displayWelcome(): Promise<void> {
100
+ console.clear();
101
+ const goldGradient = gradient(["#F0CEBB", "#fff6f3", "#d6b39f", "#F0CEBB"]);
102
+
103
+ console.log(goldGradient(BITBYBIT_LOGO));
104
+ console.log();
105
+ console.log(chalk.gray("─".repeat(72)));
106
+ console.log();
107
+ console.log(chalk.white.bold(" Welcome to the Bit By Bit Developers Project Scaffolder! 🚀"));
108
+ console.log();
109
+ console.log(chalk.gray(" Create stunning 3D/CAD applications using our powerful"));
110
+ console.log(chalk.gray(" geometry kernels: OCCT (OpenCascade), JSCAD, and Manifold."));
111
+ console.log();
112
+ console.log(chalk.gray("─".repeat(72)));
113
+ console.log();
114
+ console.log(chalk.cyan(" 🌐 Website: ") + chalk.underline.cyan("https://bitbybit.dev"));
115
+ console.log(chalk.yellow(" ⭐ Subscribe: ") + chalk.underline.yellow("https://bitbybit.dev/auth/pick-plan"));
116
+ console.log(chalk.gray(" Best way to support us is Silver or Gold plan subscription!"));
117
+ console.log();
118
+ console.log(chalk.gray("─".repeat(72)));
119
+ console.log();
120
+ }
121
+
122
+ async function promptAppType(): Promise<AppType> {
123
+ const { appType } = await inquirer.prompt<{ appType: AppType }>([
124
+ {
125
+ type: "list",
126
+ name: "appType",
127
+ message: chalk.cyan("🏗️ What type of application would you like to create?"),
128
+ choices: [
129
+ {
130
+ name: `${chalk.green("● Frontend App")} ${chalk.gray("- Browser-based 3D/CAD app with a game engine (Three.js, Babylon.js, PlayCanvas)")}`,
131
+ value: "frontend" as AppType,
132
+ short: "Frontend App"
133
+ },
134
+ {
135
+ name: `${chalk.hex("#FF6633")("● CAD Cloud App")} ${chalk.gray("- Backend + Frontend using managed Bitbybit CAD Cloud servers")}`,
136
+ value: "cloud" as AppType,
137
+ short: "CAD Cloud App"
138
+ },
139
+ ],
140
+ default: "frontend"
141
+ }
142
+ ]);
143
+ return appType;
144
+ }
145
+
146
+ async function promptCloudProjectOptions(projectNameArg?: string): Promise<CloudProjectOptions> {
147
+ interface CloudAnswers {
148
+ projectName?: string;
149
+ backend: BackendType;
150
+ }
151
+
152
+ const backendChoices = [
153
+ {
154
+ name: `${BACKEND_COLORS["hono-sdk"]("● Hono + SDK")} ${chalk.gray(`- ${BACKEND_DESCRIPTIONS["hono-sdk"]}`)}`,
155
+ value: "hono-sdk" as BackendType,
156
+ short: "Hono + SDK"
157
+ },
158
+ {
159
+ name: `${BACKEND_COLORS["hono-rest"]("● Hono + REST")} ${chalk.gray(`- ${BACKEND_DESCRIPTIONS["hono-rest"]}`)}`,
160
+ value: "hono-rest" as BackendType,
161
+ short: "Hono + REST"
162
+ },
163
+ {
164
+ name: `${BACKEND_COLORS["nodejs-sdk"]("● Node.js + SDK")} ${chalk.gray(`- ${BACKEND_DESCRIPTIONS["nodejs-sdk"]}`)}`,
165
+ value: "nodejs-sdk" as BackendType,
166
+ short: "Node.js + SDK"
167
+ },
168
+ {
169
+ name: `${BACKEND_COLORS["nodejs-rest"]("● Node.js + REST")} ${chalk.gray(`- ${BACKEND_DESCRIPTIONS["nodejs-rest"]}`)}`,
170
+ value: "nodejs-rest" as BackendType,
171
+ short: "Node.js + REST"
172
+ },
173
+ {
174
+ name: `${BACKEND_COLORS["dotnet-rest"]("● .NET + REST")} ${chalk.gray(`- ${BACKEND_DESCRIPTIONS["dotnet-rest"]}`)}`,
175
+ value: "dotnet-rest" as BackendType,
176
+ short: ".NET + REST"
177
+ },
178
+ ];
179
+
180
+ let answers: CloudAnswers;
181
+
182
+ if (!projectNameArg) {
183
+ answers = await inquirer.prompt<CloudAnswers>([
184
+ {
185
+ type: "input",
186
+ name: "projectName",
187
+ message: chalk.cyan("📁 What is your project name?"),
188
+ default: "my-bitbybit-cloud-app",
189
+ validate: (input: string) => {
190
+ if (!input.trim()) return "Project name is required";
191
+ if (!/^[a-z0-9-_]+$/i.test(input)) return "Project name can only contain letters, numbers, hyphens, and underscores";
192
+ return true;
193
+ }
194
+ },
195
+ {
196
+ type: "list",
197
+ name: "backend",
198
+ message: chalk.cyan("⚡ Which backend would you like to use?"),
199
+ choices: backendChoices,
200
+ default: "hono-sdk"
201
+ },
202
+ ]);
203
+ } else {
204
+ answers = await inquirer.prompt<CloudAnswers>([
205
+ {
206
+ type: "list",
207
+ name: "backend",
208
+ message: chalk.cyan("⚡ Which backend would you like to use?"),
209
+ choices: backendChoices,
210
+ default: "hono-sdk"
211
+ },
212
+ ]);
213
+ }
214
+
215
+ return {
216
+ projectName: projectNameArg || answers.projectName!,
217
+ backend: answers.backend,
218
+ };
219
+ }
220
+
221
+ async function promptProjectOptions(projectNameArg?: string): Promise<ProjectOptions> {
222
+ interface PromptAnswers {
223
+ projectName?: string;
224
+ engine: EngineType;
225
+ occtArchitecture: OcctArchitectureType;
226
+ }
227
+
228
+ const occtArchitectureChoices = [
229
+ {
230
+ name: `${chalk.green("● 32-bit")} ${chalk.gray(`- ${OCCT_ARCHITECTURE_DESCRIPTIONS["32"]}`)}`,
231
+ value: "32" as OcctArchitectureType,
232
+ short: "32-bit"
233
+ },
234
+ {
235
+ name: `${chalk.yellow("● 64-bit")} ${chalk.gray(`- ${OCCT_ARCHITECTURE_DESCRIPTIONS["64"]}`)}`,
236
+ value: "64" as OcctArchitectureType,
237
+ short: "64-bit"
238
+ },
239
+ {
240
+ name: `${chalk.magenta("● 64-bit MT")} ${chalk.gray(`- ${OCCT_ARCHITECTURE_DESCRIPTIONS["64-mt"]}`)}`,
241
+ value: "64-mt" as OcctArchitectureType,
242
+ short: "64-bit MT"
243
+ }
244
+ ];
245
+
246
+ let answers: PromptAnswers;
247
+
248
+ if (!projectNameArg) {
249
+ answers = await inquirer.prompt<PromptAnswers>([
250
+ {
251
+ type: "input",
252
+ name: "projectName",
253
+ message: chalk.cyan("📁 What is your project name?"),
254
+ default: "my-bitbybit-app",
255
+ validate: (input: string) => {
256
+ if (!input.trim()) {
257
+ return "Project name is required";
258
+ }
259
+ if (!/^[a-z0-9-_]+$/i.test(input)) {
260
+ return "Project name can only contain letters, numbers, hyphens, and underscores";
261
+ }
262
+ return true;
263
+ }
264
+ },
265
+ {
266
+ type: "list",
267
+ name: "engine",
268
+ message: chalk.cyan("🎮 Which 3D engine would you like to use?"),
269
+ choices: [
270
+ {
271
+ name: `${ENGINE_COLORS["threejs"]("● Three.js")} ${chalk.gray(`- ${ENGINE_DESCRIPTIONS["threejs"]}`)}`,
272
+ value: "threejs",
273
+ short: "Three.js"
274
+ },
275
+ {
276
+ name: `${ENGINE_COLORS["babylonjs"]("● Babylon.js")} ${chalk.gray(`- ${ENGINE_DESCRIPTIONS["babylonjs"]}`)}`,
277
+ value: "babylonjs",
278
+ short: "Babylon.js"
279
+ },
280
+ {
281
+ name: `${ENGINE_COLORS["playcanvas"]("● PlayCanvas")} ${chalk.gray(`- ${ENGINE_DESCRIPTIONS["playcanvas"]}`)}`,
282
+ value: "playcanvas",
283
+ short: "PlayCanvas"
284
+ }
285
+ ],
286
+ default: "threejs"
287
+ },
288
+ {
289
+ type: "list",
290
+ name: "occtArchitecture",
291
+ message: chalk.cyan("⚙️ Which OCCT worker architecture would you like to use?"),
292
+ choices: occtArchitectureChoices,
293
+ default: "32"
294
+ }
295
+ ]);
296
+ } else {
297
+ answers = await inquirer.prompt<PromptAnswers>([
298
+ {
299
+ type: "list",
300
+ name: "engine",
301
+ message: chalk.cyan("🎮 Which 3D engine would you like to use?"),
302
+ choices: [
303
+ {
304
+ name: `${ENGINE_COLORS["threejs"]("● Three.js")} ${chalk.gray(`- ${ENGINE_DESCRIPTIONS["threejs"]}`)}`,
305
+ value: "threejs",
306
+ short: "Three.js"
307
+ },
308
+ {
309
+ name: `${ENGINE_COLORS["babylonjs"]("● Babylon.js")} ${chalk.gray(`- ${ENGINE_DESCRIPTIONS["babylonjs"]}`)}`,
310
+ value: "babylonjs",
311
+ short: "Babylon.js"
312
+ },
313
+ {
314
+ name: `${ENGINE_COLORS["playcanvas"]("● PlayCanvas")} ${chalk.gray(`- ${ENGINE_DESCRIPTIONS["playcanvas"]}`)}`,
315
+ value: "playcanvas",
316
+ short: "PlayCanvas"
317
+ }
318
+ ],
319
+ default: "threejs"
320
+ },
321
+ {
322
+ type: "list",
323
+ name: "occtArchitecture",
324
+ message: chalk.cyan("⚙️ Which OCCT worker architecture would you like to use?"),
325
+ choices: occtArchitectureChoices,
326
+ default: "32"
327
+ }
328
+ ]);
329
+ }
330
+
331
+ return {
332
+ projectName: projectNameArg || answers.projectName!,
333
+ engine: answers.engine,
334
+ bundler: "vite",
335
+ language: "typescript",
336
+ occtArchitecture: answers.occtArchitecture
337
+ };
338
+ }
339
+
340
+ /**
341
+ * npm strips every file named .gitignore out of a package tarball, so the templates carry theirs as
342
+ * _gitignore and each copied template restores the name here. Without it a scaffolded backend
343
+ * arrives with the .env this CLI writes for it and nothing ignoring that file.
344
+ */
345
+ async function restoreTemplateDotfiles(dir: string): Promise<void> {
346
+ const staged = path.join(dir, "_gitignore");
347
+ if (await fs.pathExists(staged)) {
348
+ await fs.move(staged, path.join(dir, ".gitignore"), { overwrite: true });
349
+ }
350
+ }
351
+
352
+ async function createProject(options: ProjectOptions): Promise<void> {
353
+ const { projectName, engine, bundler, language, occtArchitecture } = options;
354
+ const targetDir = path.resolve(process.cwd(), projectName);
355
+
356
+ const occtArchColors: Record<OcctArchitectureType, (text: string) => string> = {
357
+ "32": chalk.green,
358
+ "64": chalk.yellow,
359
+ "64-mt": chalk.magenta
360
+ };
361
+
362
+ console.log();
363
+ console.log(chalk.gray("─".repeat(72)));
364
+ console.log();
365
+ console.log(chalk.white.bold(" 📋 Project Configuration:"));
366
+ console.log();
367
+ console.log(` ${chalk.gray("Project:")} ${chalk.white.bold(projectName)}`);
368
+ console.log(` ${chalk.gray("Engine:")} ${ENGINE_COLORS[engine](ENGINE_DISPLAY_NAMES[engine])}`);
369
+ console.log(` ${chalk.gray("Bundler:")} ${chalk.magenta("Vite")}`);
370
+ console.log(` ${chalk.gray("Language:")} ${chalk.blue("TypeScript")}`);
371
+ console.log(` ${chalk.gray("OCCT Arch:")} ${occtArchColors[occtArchitecture](OCCT_ARCHITECTURE_DISPLAY_NAMES[occtArchitecture])}`);
372
+ console.log();
373
+ console.log(chalk.gray("─".repeat(72)));
374
+ console.log();
375
+
376
+ if (fs.existsSync(targetDir)) {
377
+ const { overwrite } = await inquirer.prompt([
378
+ {
379
+ type: "confirm",
380
+ name: "overwrite",
381
+ message: chalk.yellow(`⚠️ Directory "${projectName}" already exists. Do you want to overwrite it?`),
382
+ default: false
383
+ }
384
+ ]);
385
+
386
+ if (!overwrite) {
387
+ console.log(chalk.red("\n ✖ Project creation cancelled.\n"));
388
+ process.exit(0);
389
+ }
390
+
391
+ const spinner = ora("Removing existing directory...").start();
392
+ await fs.remove(targetDir);
393
+ spinner.succeed("Existing directory removed");
394
+ }
395
+
396
+ const spinner = ora({
397
+ text: "Creating project structure...",
398
+ color: "cyan"
399
+ }).start();
400
+
401
+ try {
402
+ const templateDir = path.join(__dirname, "..", "templates", bundler, engine, language);
403
+
404
+ if (!fs.existsSync(templateDir)) {
405
+ spinner.fail("Template not found");
406
+ console.error(chalk.red(`\n ✖ Template for ${bundler}/${engine}/${language} not found.`));
407
+ console.error(chalk.gray(` Looking in: ${templateDir}`));
408
+ process.exit(1);
409
+ }
410
+
411
+ await fs.copy(templateDir, targetDir);
412
+ await restoreTemplateDotfiles(targetDir);
413
+ spinner.succeed("Project structure created");
414
+
415
+ const packageJsonPath = path.join(targetDir, "package.json");
416
+ if (fs.existsSync(packageJsonPath)) {
417
+ const packageJson = await fs.readJson(packageJsonPath);
418
+ packageJson.name = projectName;
419
+ await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
420
+ }
421
+
422
+ if (occtArchitecture !== "32") {
423
+ const mainTsPath = path.join(targetDir, "src", "main.ts");
424
+ if (!fs.existsSync(mainTsPath)) {
425
+ throw new Error(`Cannot select the ${occtArchitecture} OCCT kernel: ${path.relative(targetDir, mainTsPath)} is not in this template, and it is the file the architecture is written into.`);
426
+ }
427
+ const mainTsContent = await fs.readFile(mainTsPath, "utf-8");
428
+
429
+ const optionsPattern = /(const options:\s*InitBitByBitOptions\s*=\s*\{[\s\S]*?enableManifold:\s*true),(\s*\};)/;
430
+ const replacement = `$1,\n occtArchitecture: "${occtArchitecture}"$2`;
431
+
432
+ const patched = mainTsContent.replace(optionsPattern, replacement);
433
+ if (patched === mainTsContent) {
434
+ throw new Error(`Cannot select the ${occtArchitecture} OCCT kernel: the options object in src/main.ts is not in the shape this patch expects (enableManifold last). Writing the file unchanged would have produced a 32-bit project reported as ${occtArchitecture}.`);
435
+ }
436
+ await fs.writeFile(mainTsPath, patched, "utf-8");
437
+ }
438
+
439
+ if (occtArchitecture === "64-mt") {
440
+ const viteConfigPath = path.join(targetDir, "vite.config.ts");
441
+ const viteConfigContent = `import { defineConfig } from "vite";
442
+
443
+ // COOP/COEP headers required for SharedArrayBuffer support in multi-threaded OCCT
444
+ // Using 'credentialless' instead of 'require-corp' to allow cross-origin CDN resources
445
+ export default defineConfig({
446
+ server: {
447
+ headers: {
448
+ "Cross-Origin-Opener-Policy": "same-origin",
449
+ "Cross-Origin-Embedder-Policy": "credentialless",
450
+ },
451
+ },
452
+ preview: {
453
+ headers: {
454
+ "Cross-Origin-Opener-Policy": "same-origin",
455
+ "Cross-Origin-Embedder-Policy": "credentialless",
456
+ },
457
+ },
458
+ });
459
+ `;
460
+ await fs.writeFile(viteConfigPath, viteConfigContent, "utf-8");
461
+ }
462
+
463
+ console.log();
464
+ console.log(chalk.gray("─".repeat(72)));
465
+ console.log();
466
+ console.log(chalk.gray(" Home: ") + chalk.underline.cyan("https://bitbybit.dev"));
467
+ console.log(chalk.gray(" Learn: ") + chalk.underline.cyan("https://learn.bitbybit.dev"));
468
+ console.log(chalk.gray(" Blog: ") + chalk.underline.cyan("https://learn.bitbybit.dev/blog"));
469
+ console.log(chalk.gray(" Documentation: ") + chalk.underline.cyan("https://docs.bitbybit.dev"));
470
+ console.log(chalk.gray(" Community: ") + chalk.underline.cyan("https://discord.gg/GSe3VMe"));
471
+ console.log(chalk.gray(" GitHub: ") + chalk.underline.cyan("https://github.com/bitbybit-dev/bitbybit"));
472
+ console.log(chalk.gray(" LinkedIn: ") + chalk.underline.cyan("https://www.linkedin.com/company/bitbybit-dev/"));
473
+ console.log(chalk.gray(" X: ") + chalk.underline.cyan("https://x.com/bitbybit_dev"));
474
+ console.log(chalk.gray(" YouTube: ") + chalk.underline.cyan("https://www.youtube.com/@bitbybitdev"));
475
+ console.log(chalk.gray(" Facebook: ") + chalk.underline.cyan("https://www.facebook.com/bitbybitdev"));
476
+ console.log();
477
+ console.log(chalk.green.bold(" ✔ Project created successfully! 🎉"));
478
+ console.log();
479
+ console.log(chalk.white(" Next steps:"));
480
+ console.log();
481
+ console.log(chalk.gray(" 1. Navigate to your project:"));
482
+ console.log(chalk.cyan(` cd ${projectName}`));
483
+ console.log();
484
+ console.log(chalk.gray(" 2. Install dependencies:"));
485
+ console.log(chalk.cyan(" npm install"));
486
+ console.log();
487
+ console.log(chalk.gray(" 3. Start the development server:"));
488
+ console.log(chalk.cyan(" npm run dev"));
489
+ console.log();
490
+
491
+ if (occtArchitecture === "64") {
492
+ console.log(chalk.yellow(" ⚠️ Note: 64-bit OCCT may not be supported on all browsers."));
493
+ console.log(chalk.gray(" Some older browsers may lack WebAssembly Memory64 support."));
494
+ console.log();
495
+ } else if (occtArchitecture === "64-mt") {
496
+ console.log(chalk.yellow(" ⚠️ Note: 64-bit Multi-threaded OCCT requires special server configuration."));
497
+ console.log(chalk.gray(" Your server must send these headers for SharedArrayBuffer support:"));
498
+ console.log(chalk.gray(" • Cross-Origin-Opener-Policy: same-origin"));
499
+ console.log(chalk.gray(" • Cross-Origin-Embedder-Policy: require-corp"));
500
+ console.log(chalk.gray(" Vite dev server is pre-configured, but production servers need setup."));
501
+ console.log();
502
+ }
503
+
504
+ console.log(chalk.gray("─".repeat(72)));
505
+ console.log();
506
+ console.log(chalk.yellow.bold(" ⭐ Support Bit By Bit Developers with a Silver or Gold subscription:"));
507
+ console.log(chalk.yellow.italic(" https://bitbybit.dev/auth/pick-plan"));
508
+ console.log();
509
+ console.log(chalk.gray("─".repeat(72)));
510
+ console.log();
511
+ console.log(chalk.white(" Happy coding! 💻✨"));
512
+ console.log();
513
+
514
+ } catch (error) {
515
+ spinner.fail("Failed to create project");
516
+ console.error(chalk.red("\n ✖ Error creating project:"), error);
517
+ process.exit(1);
518
+ }
519
+ }
520
+
521
+ function generateCloudReadme(projectName: string, backend: BackendType): string {
522
+ const backendName = BACKEND_DISPLAY_NAMES[backend];
523
+
524
+ const keyConfigSection = backend === "dotnet-rest"
525
+ ? `Edit \`backend/appsettings.Development.json\`:
526
+
527
+ \`\`\`json
528
+ {
529
+ "Bitbybit": {
530
+ "ApiKey": "your-api-key-here",
531
+ "ApiUrl": "https://api.bitbybit.dev"
532
+ }
533
+ }
534
+ \`\`\``
535
+ : backend.startsWith("hono")
536
+ ? `Edit \`backend/.dev.vars\`:
537
+
538
+ \`\`\`
539
+ BITBYBIT_API_KEY=your-api-key-here
540
+ BITBYBIT_API_URL=https://api.bitbybit.dev
541
+ \`\`\``
542
+ : `Edit \`backend/.env\`:
543
+
544
+ \`\`\`
545
+ BITBYBIT_API_KEY=your-api-key-here
546
+ BITBYBIT_API_URL=https://api.bitbybit.dev
547
+ \`\`\``;
548
+
549
+ const backendStartCmd = backend === "dotnet-rest"
550
+ ? "cd backend\ndotnet run"
551
+ : "cd backend\nnpm install\nnpm run dev";
552
+
553
+ return `# ${projectName}
554
+
555
+ A CAD Cloud application powered by [Bitbybit](https://bitbybit.dev) managed CAD servers.
556
+
557
+ ## Architecture
558
+
559
+ \`\`\`
560
+ ┌─────────────────────────────┐ ┌─────────────────────────────┐
561
+ │ frontend/ │ │ Bitbybit CAD Cloud API │
562
+ │ React 19 + Vite + Three.js │──/api──▶ ${backendName.padEnd(27)} │──▶ api.bitbybit.dev
563
+ │ Port 5173 │ proxy │ Port 3000 │
564
+ └─────────────────────────────┘ └─────────────────────────────┘
565
+ \`\`\`
566
+
567
+ The frontend never calls the Bitbybit API directly — your **API key stays on the server**. Vite's dev proxy forwards \`/api/*\` requests to \`localhost:3000\`.
568
+
569
+ ## Prerequisites
570
+
571
+ - **Node.js** ≥ 20
572
+ ${backend === "dotnet-rest" ? "- **.NET** ≥ 10\n" : ""}- A **Bitbybit API key** — purchase one at [bitbybit.dev/auth/pick-plan?api-keys=true](https://bitbybit.dev/auth/pick-plan?api-keys=true)
573
+ ${backend.startsWith("hono") ? "- **Wrangler** CLI (installed as a dev dependency)\n" : ""}
574
+ ## Quick Start
575
+
576
+ ### 1. Configure your API key
577
+
578
+ ${keyConfigSection}
579
+
580
+ ### 2. Start the backend
581
+
582
+ \`\`\`bash
583
+ ${backendStartCmd}
584
+ \`\`\`
585
+
586
+ The backend starts on **port 3000**.
587
+
588
+ ### 3. Start the frontend (separate terminal)
589
+
590
+ \`\`\`bash
591
+ cd frontend
592
+ npm install
593
+ npm run dev
594
+ \`\`\`
595
+
596
+ ### 4. Open the app
597
+
598
+ Navigate to **http://localhost:5173** in your browser.
599
+
600
+ ## What This App Demonstrates
601
+
602
+ ### Single CAD Operation
603
+ Click **Generate** to create a parametric "dragon cup" model. The backend submits the request to Bitbybit CAD Cloud, polls until complete, and returns a glTF download URL. The frontend loads it into a Three.js scene.
604
+
605
+ ### Batch Generation
606
+ Click **Generate Batch** to create 3 model variations in parallel.
607
+
608
+ ### Pipelines
609
+ Several pipeline examples are available:
610
+
611
+ | Pipeline | What it does |
612
+ |----------|-------------|
613
+ | **Translate → Union → Fillet** | Creates two boxes, translates one, unions them, fillets edges — demonstrates \`$ref:N\` step references |
614
+ | **Map Cylinders** | Uses a \`map\` step to create cylinders at different positions — demonstrates iteration |
615
+ | **Map Spheres** | Maps over an array to create multiple spheres — demonstrates \`$item\` references |
616
+ | **Choice** | Uses a \`choice\` step to conditionally create a box or cylinder — demonstrates branching |
617
+ | **File Input** | Upload a STEP file, fillet its edges — demonstrates file upload flow |
618
+
619
+ ## Project Structure
620
+
621
+ \`\`\`
622
+ ${projectName}/
623
+ ├── README.md
624
+ ├── frontend/
625
+ │ ├── src/
626
+ │ │ ├── App.tsx
627
+ │ │ ├── components/ # Three.js viewer, header, API key warning
628
+ │ │ └── panels/ # Models and Pipelines UI panels
629
+ │ ├── vite.config.ts # Dev proxy: /api → localhost:3000
630
+ │ └── package.json
631
+ └── backend/
632
+ ${backend === "dotnet-rest" ? ` ├── Program.cs
633
+ ├── BitbybitClient.cs
634
+ ├── appsettings.json
635
+ └── dotnet-rest.csproj` : ` ├── src/
636
+ │ ├── index.ts # Routes
637
+ │ └── bitbybit-client.ts # API calls
638
+ └── package.json`}
639
+ \`\`\`
640
+
641
+ ## API Routes
642
+
643
+ | Method | Route | Description |
644
+ |--------|-------|-------------|
645
+ | \`POST\` | \`/api/generate\` | Single CAD operation (dragon cup) |
646
+ | \`POST\` | \`/api/generate-batch\` | Parallel batch generation |
647
+ | \`GET\` | \`/api/task/:id\` | Poll / fetch task result |
648
+ | \`POST\` | \`/api/pipeline/translate-union-fillet\` | Pipeline: translate → union → fillet |
649
+ | \`POST\` | \`/api/pipeline/map-cylinders\` | Pipeline: map cylinders |
650
+ | \`POST\` | \`/api/pipeline/map-spheres\` | Pipeline: map spheres |
651
+ | \`POST\` | \`/api/pipeline/choice\` | Pipeline: conditional logic |
652
+ | \`POST\` | \`/api/pipeline/file-input\` | Pipeline: file upload + fillet |
653
+ | \`GET\` | \`/api/proxy-download?url=...\` | Proxy glTF downloads (avoids CORS) |
654
+
655
+ ## Getting an API Key
656
+
657
+ 1. Create an account on [bitbybit.dev](https://bitbybit.dev)
658
+ 2. Go to [bitbybit.dev/auth/pick-plan?api-keys=true](https://bitbybit.dev/auth/pick-plan?api-keys=true)
659
+ 3. Purchase a Starter, Professional, or Business API key plan
660
+ 4. Manage your keys in [Bitbybit Studio](https://studio.bitbybit.dev/keys/billing)
661
+
662
+ ## Learn More
663
+
664
+ - [SDK Documentation](https://learn.bitbybit.dev/api/sdk/typescript/intro)
665
+ - [Pipeline Guide](https://learn.bitbybit.dev/api/sdk/typescript/pipelines)
666
+ - [Bitbybit GitHub](https://github.com/bitbybit-dev/bitbybit)
667
+ - [Discord Community](https://discord.gg/GSe3VMe)
668
+ `;
669
+ }
670
+
671
+ async function createCloudProject(options: CloudProjectOptions): Promise<void> {
672
+ const { projectName, backend } = options;
673
+ const targetDir = path.resolve(process.cwd(), projectName);
674
+
675
+ console.log();
676
+ console.log(chalk.gray("─".repeat(72)));
677
+ console.log();
678
+ console.log(chalk.white.bold(" 📋 Project Configuration:"));
679
+ console.log();
680
+ console.log(` ${chalk.gray("Project:")} ${chalk.white.bold(projectName)}`);
681
+ console.log(` ${chalk.gray("Type:")} ${chalk.hex("#FF6633")("CAD Cloud App")}`);
682
+ console.log(` ${chalk.gray("Backend:")} ${BACKEND_COLORS[backend](BACKEND_DISPLAY_NAMES[backend])}`);
683
+ console.log(` ${chalk.gray("Frontend:")} ${chalk.cyan("React 19 + Vite + Three.js")}`);
684
+ console.log();
685
+ console.log(chalk.gray("─".repeat(72)));
686
+ console.log();
687
+
688
+ if (fs.existsSync(targetDir)) {
689
+ const { overwrite } = await inquirer.prompt([
690
+ {
691
+ type: "confirm",
692
+ name: "overwrite",
693
+ message: chalk.yellow(`⚠️ Directory "${projectName}" already exists. Do you want to overwrite it?`),
694
+ default: false
695
+ }
696
+ ]);
697
+
698
+ if (!overwrite) {
699
+ console.log(chalk.red("\n ✖ Project creation cancelled.\n"));
700
+ process.exit(0);
701
+ }
702
+
703
+ const spinner = ora("Removing existing directory...").start();
704
+ await fs.remove(targetDir);
705
+ spinner.succeed("Existing directory removed");
706
+ }
707
+
708
+ const spinner = ora({
709
+ text: "Creating project structure...",
710
+ color: "cyan"
711
+ }).start();
712
+
713
+ try {
714
+ const cloudTemplatesDir = path.join(__dirname, "..", "templates", "cloud");
715
+
716
+ const frontendTemplateDir = path.join(cloudTemplatesDir, "frontend");
717
+ const frontendTargetDir = path.join(targetDir, "frontend");
718
+ await fs.copy(frontendTemplateDir, frontendTargetDir);
719
+ await restoreTemplateDotfiles(frontendTargetDir);
720
+
721
+ const frontendPackageJsonPath = path.join(frontendTargetDir, "package.json");
722
+ if (fs.existsSync(frontendPackageJsonPath)) {
723
+ const packageJson = await fs.readJson(frontendPackageJsonPath);
724
+ packageJson.name = `${projectName}-frontend`;
725
+ await fs.writeJson(frontendPackageJsonPath, packageJson, { spaces: 4 });
726
+ }
727
+
728
+ const backendTemplateDir = path.join(cloudTemplatesDir, "backends", backend);
729
+ const backendTargetDir = path.join(targetDir, "backend");
730
+ await fs.copy(backendTemplateDir, backendTargetDir);
731
+ await restoreTemplateDotfiles(backendTargetDir);
732
+
733
+ const backendPackageJsonPath = path.join(backendTargetDir, "package.json");
734
+ if (fs.existsSync(backendPackageJsonPath)) {
735
+ const packageJson = await fs.readJson(backendPackageJsonPath);
736
+ packageJson.name = `${projectName}-backend`;
737
+ await fs.writeJson(backendPackageJsonPath, packageJson, { spaces: 4 });
738
+ }
739
+
740
+ const wranglerPath = path.join(backendTargetDir, "wrangler.jsonc");
741
+ if (fs.existsSync(wranglerPath)) {
742
+ let wranglerContent = await fs.readFile(wranglerPath, "utf-8");
743
+ wranglerContent = wranglerContent.replace(/"name":\s*"[^"]*"/, `"name": "${projectName}-backend"`);
744
+ await fs.writeFile(wranglerPath, wranglerContent, "utf-8");
745
+ }
746
+
747
+ const envExamplePath = path.join(backendTargetDir, ".env.example");
748
+ if (fs.existsSync(envExamplePath)) {
749
+ await fs.copy(envExamplePath, path.join(backendTargetDir, ".env"));
750
+ }
751
+
752
+ if (backend.startsWith("hono")) {
753
+ const devVarsContent = "# Get your API key at https://bitbybit.dev/auth/pick-plan?api-keys=true\nBITBYBIT_API_KEY=\nBITBYBIT_API_URL=https://api.bitbybit.dev\n";
754
+ await fs.writeFile(path.join(backendTargetDir, ".dev.vars"), devVarsContent, "utf-8");
755
+ }
756
+
757
+ if (backend === "dotnet-rest") {
758
+ const devSettings = {
759
+ Bitbybit: {
760
+ ApiKey: "",
761
+ ApiUrl: "https://api.bitbybit.dev"
762
+ }
763
+ };
764
+ await fs.writeJson(path.join(backendTargetDir, "appsettings.Development.json"), devSettings, { spaces: 2 });
765
+ }
766
+
767
+ await fs.writeFile(path.join(targetDir, "README.md"), generateCloudReadme(projectName, backend), "utf-8");
768
+
769
+ spinner.succeed("Project structure created");
770
+
771
+ console.log();
772
+ console.log(chalk.gray("─".repeat(72)));
773
+ console.log();
774
+ console.log(chalk.gray(" Home: ") + chalk.underline.cyan("https://bitbybit.dev"));
775
+ console.log(chalk.gray(" Learn: ") + chalk.underline.cyan("https://learn.bitbybit.dev"));
776
+ console.log(chalk.gray(" SDK Docs: ") + chalk.underline.cyan("https://learn.bitbybit.dev/api/sdk/typescript/intro"));
777
+ console.log(chalk.gray(" Community: ") + chalk.underline.cyan("https://discord.gg/GSe3VMe"));
778
+ console.log(chalk.gray(" GitHub: ") + chalk.underline.cyan("https://github.com/bitbybit-dev/bitbybit"));
779
+ console.log();
780
+ console.log(chalk.green.bold(" ✔ CAD Cloud project created successfully! 🎉"));
781
+ console.log();
782
+ console.log(chalk.white(" Next steps:"));
783
+ console.log();
784
+ console.log(chalk.gray(" 1. Navigate to your project:"));
785
+ console.log(chalk.cyan(` cd ${projectName}`));
786
+ console.log();
787
+
788
+ if (backend === "dotnet-rest") {
789
+ console.log(chalk.gray(" 2. Add your API key to backend/appsettings.Development.json"));
790
+ console.log();
791
+ console.log(chalk.gray(" 3. Start the backend:"));
792
+ console.log(chalk.cyan(" cd backend && dotnet run"));
793
+ console.log();
794
+ } else if (backend.startsWith("hono")) {
795
+ console.log(chalk.gray(" 2. Add your API key to backend/.dev.vars"));
796
+ console.log();
797
+ console.log(chalk.gray(" 3. Start the backend:"));
798
+ console.log(chalk.cyan(" cd backend && npm install && npm run dev"));
799
+ console.log();
800
+ } else {
801
+ console.log(chalk.gray(" 2. Add your API key to backend/.env"));
802
+ console.log();
803
+ console.log(chalk.gray(" 3. Start the backend:"));
804
+ console.log(chalk.cyan(" cd backend && npm install && npm run dev"));
805
+ console.log();
806
+ }
807
+
808
+ console.log(chalk.gray(" 4. Start the frontend (in a separate terminal):"));
809
+ console.log(chalk.cyan(` cd ${projectName}/frontend && npm install && npm run dev`));
810
+ console.log();
811
+ console.log(chalk.gray(" 5. Open ") + chalk.cyan("http://localhost:5173") + chalk.gray(" in your browser"));
812
+ console.log();
813
+ console.log(chalk.gray("─".repeat(72)));
814
+ console.log();
815
+ console.log(chalk.yellow.bold(" 🔑 You need a Bitbybit API key to use CAD Cloud:"));
816
+ console.log(chalk.yellow(" 1. Create an account on https://bitbybit.dev"));
817
+ console.log(chalk.yellow(" 2. Purchase an API key plan at:"));
818
+ console.log(chalk.underline.yellow(" https://bitbybit.dev/auth/pick-plan?api-keys=true"));
819
+ console.log();
820
+ console.log(chalk.gray("─".repeat(72)));
821
+ console.log();
822
+ console.log(chalk.white(" Happy coding! 💻✨"));
823
+ console.log();
824
+
825
+ } catch (error) {
826
+ spinner.fail("Failed to create project");
827
+ console.error(chalk.red("\n ✖ Error creating project:"), error);
828
+ process.exit(1);
829
+ }
830
+ }
831
+
832
+ async function main(): Promise<void> {
833
+ const program = new Command();
834
+
835
+ program
836
+ .name("@bitbybit-dev/create-app")
837
+ .description("Scaffold a new Bit By Bit Developers 3D/CAD project")
838
+ .version("1.2.0-rc.0")
839
+ .argument("[project-name]", "Name of the project to create")
840
+ .option("-e, --engine <engine>", "Game engine to use (threejs, babylonjs, playcanvas)")
841
+ .option("-o, --occt-architecture <arch>", "OCCT worker architecture (32, 64, 64-mt). Default: 32")
842
+ .option("-t, --type <type>", "App type (frontend, cloud)")
843
+ .option("-b, --backend <backend>", "Backend for cloud app (hono-sdk, hono-rest, nodejs-sdk, nodejs-rest, dotnet-rest)")
844
+ .action(async (projectName: string | undefined, cmdOptions: { engine?: string; occtArchitecture?: string; type?: string; backend?: string }) => {
845
+ await displayWelcome();
846
+
847
+ let appType: AppType;
848
+ if (cmdOptions.type) {
849
+ if (cmdOptions.type !== "frontend" && cmdOptions.type !== "cloud") {
850
+ console.error(chalk.red(`\n ✖ Invalid app type: ${cmdOptions.type}`));
851
+ console.error(chalk.gray(` Valid options: frontend, cloud`));
852
+ process.exit(1);
853
+ }
854
+ appType = cmdOptions.type;
855
+ } else {
856
+ appType = await promptAppType();
857
+ }
858
+
859
+ if (appType === "cloud") {
860
+ if (cmdOptions.backend) {
861
+ const validBackends = ["hono-sdk", "hono-rest", "nodejs-sdk", "nodejs-rest", "dotnet-rest"];
862
+ if (!validBackends.includes(cmdOptions.backend)) {
863
+ console.error(chalk.red(`\n ✖ Invalid backend: ${cmdOptions.backend}`));
864
+ console.error(chalk.gray(` Valid options: ${validBackends.join(", ")}`));
865
+ process.exit(1);
866
+ }
867
+ }
868
+
869
+ let cloudOptions: CloudProjectOptions;
870
+ if (projectName && cmdOptions.backend) {
871
+ cloudOptions = { projectName, backend: cmdOptions.backend as BackendType };
872
+ } else {
873
+ cloudOptions = await promptCloudProjectOptions(projectName);
874
+ }
875
+ await createCloudProject(cloudOptions);
876
+ } else {
877
+ let options: ProjectOptions;
878
+
879
+ if (cmdOptions.engine) {
880
+ const validEngines = ["threejs", "babylonjs", "playcanvas"];
881
+ if (!validEngines.includes(cmdOptions.engine)) {
882
+ console.error(chalk.red(`\n ✖ Invalid engine: ${cmdOptions.engine}`));
883
+ console.error(chalk.gray(` Valid options: ${validEngines.join(", ")}`));
884
+ process.exit(1);
885
+ }
886
+ }
887
+
888
+ if (cmdOptions.occtArchitecture) {
889
+ const validArchitectures = ["32", "64", "64-mt"];
890
+ if (!validArchitectures.includes(cmdOptions.occtArchitecture)) {
891
+ console.error(chalk.red(`\n ✖ Invalid OCCT architecture: ${cmdOptions.occtArchitecture}`));
892
+ console.error(chalk.gray(` Valid options: ${validArchitectures.join(", ")}`));
893
+ process.exit(1);
894
+ }
895
+ }
896
+
897
+ if (projectName && cmdOptions.engine && cmdOptions.occtArchitecture) {
898
+ options = {
899
+ projectName,
900
+ engine: cmdOptions.engine as EngineType,
901
+ bundler: "vite",
902
+ language: "typescript",
903
+ occtArchitecture: cmdOptions.occtArchitecture as OcctArchitectureType
904
+ };
905
+ } else if (projectName && cmdOptions.engine) {
906
+ options = await promptProjectOptions(projectName);
907
+ options.engine = cmdOptions.engine as EngineType;
908
+ } else {
909
+ options = await promptProjectOptions(projectName);
910
+ }
911
+
912
+ await createProject(options);
913
+ }
914
+ });
915
+
916
+ await program.parseAsync(process.argv);
917
+ }
918
+
919
+ main().catch((error) => {
920
+ console.error(chalk.red("\n ✖ Unexpected error:"), error);
921
+ process.exit(1);
922
+ });