@donotdev/cli 0.0.34 → 0.0.35

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
@@ -8733,7 +8733,7 @@ var init_cli_input = __esm({
8733
8733
  });
8734
8734
 
8735
8735
  // packages/tooling/src/utils/cli-tools.ts
8736
- import { spawnSync as spawnSync5 } from "node:child_process";
8736
+ import { spawnSync } from "node:child_process";
8737
8737
  function checkCLI(command, args = ["--version"], useCache = true) {
8738
8738
  const cacheKey = `${command}:${args.join(",")}`;
8739
8739
  if (useCache && cliCache.has(cacheKey)) {
@@ -8757,7 +8757,7 @@ function checkCLI(command, args = ["--version"], useCache = true) {
8757
8757
  ].filter(Boolean);
8758
8758
  for (const fullPath of commonPaths) {
8759
8759
  try {
8760
- const testResult = spawnSync5(
8760
+ const testResult = spawnSync(
8761
8761
  "powershell.exe",
8762
8762
  [
8763
8763
  "-NoProfile",
@@ -8779,7 +8779,7 @@ function checkCLI(command, args = ["--version"], useCache = true) {
8779
8779
  continue;
8780
8780
  }
8781
8781
  }
8782
- result = spawnSync5(
8782
+ result = spawnSync(
8783
8783
  "powershell.exe",
8784
8784
  [
8785
8785
  "-NoProfile",
@@ -8794,7 +8794,7 @@ function checkCLI(command, args = ["--version"], useCache = true) {
8794
8794
  }
8795
8795
  );
8796
8796
  } else {
8797
- result = spawnSync5(`${command} ${args.join(" ")}`, {
8797
+ result = spawnSync(`${command} ${args.join(" ")}`, {
8798
8798
  stdio: "pipe",
8799
8799
  shell: true
8800
8800
  });
@@ -9022,6 +9022,29 @@ var init_cli_tools = __esm({
9022
9022
  }
9023
9023
  });
9024
9024
 
9025
+ // packages/tooling/src/utils/error-handling.ts
9026
+ function isError(error2) {
9027
+ return error2 instanceof Error;
9028
+ }
9029
+ function getErrorMessage(error2) {
9030
+ if (isError(error2)) {
9031
+ return error2.message;
9032
+ }
9033
+ if (typeof error2 === "string") {
9034
+ return error2;
9035
+ }
9036
+ if (error2 && typeof error2 === "object" && "message" in error2) {
9037
+ return String(error2.message);
9038
+ }
9039
+ return String(error2);
9040
+ }
9041
+ var init_error_handling = __esm({
9042
+ "packages/tooling/src/utils/error-handling.ts"() {
9043
+ "use strict";
9044
+ init_utils();
9045
+ }
9046
+ });
9047
+
9025
9048
  // node_modules/.bun/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js
9026
9049
  var require_identity = __commonJS({
9027
9050
  "node_modules/.bun/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports) {
@@ -16383,29 +16406,6 @@ var require_dist = __commonJS({
16383
16406
  }
16384
16407
  });
16385
16408
 
16386
- // packages/tooling/src/utils/error-handling.ts
16387
- function isError(error2) {
16388
- return error2 instanceof Error;
16389
- }
16390
- function getErrorMessage(error2) {
16391
- if (isError(error2)) {
16392
- return error2.message;
16393
- }
16394
- if (typeof error2 === "string") {
16395
- return error2;
16396
- }
16397
- if (error2 && typeof error2 === "object" && "message" in error2) {
16398
- return String(error2.message);
16399
- }
16400
- return String(error2);
16401
- }
16402
- var init_error_handling = __esm({
16403
- "packages/tooling/src/utils/error-handling.ts"() {
16404
- "use strict";
16405
- init_utils();
16406
- }
16407
- });
16408
-
16409
16409
  // packages/tooling/src/apps/vercel-api.ts
16410
16410
  function formatVercelError(status, body, context) {
16411
16411
  let vercelCode;
@@ -17317,237 +17317,553 @@ init_cli_output();
17317
17317
  init_errors();
17318
17318
  init_pathResolver();
17319
17319
  init_typed_file_operations();
17320
- import { spawnSync, execSync } from "node:child_process";
17321
- function validateFirebaseJson(appDir) {
17322
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
17323
- if (!pathExists(firebaseJsonPath)) {
17324
- return {
17325
- valid: false,
17326
- hasHosting: false,
17327
- hasFunctions: false
17328
- };
17320
+ import { spawnSync as spawnSync4, execSync as execSync2 } from "node:child_process";
17321
+
17322
+ // packages/tooling/src/apps/deploy-utils.ts
17323
+ init_utils();
17324
+ import { spawnSync as spawnSync3 } from "node:child_process";
17325
+
17326
+ // packages/tooling/src/utils/create-utils.ts
17327
+ init_utils();
17328
+ init_cli_output();
17329
+ init_pathResolver();
17330
+ init_typed_file_operations();
17331
+ async function copyTemplateFiles(sourceDir, destDir, replacements) {
17332
+ if (!pathExists(sourceDir)) {
17333
+ log.warn(`Warning: Template directory does not exist: ${sourceDir}`);
17334
+ return;
17335
+ }
17336
+ const files = await glob("**/*", {
17337
+ cwd: sourceDir,
17338
+ dot: true,
17339
+ onlyFiles: true
17340
+ });
17341
+ for (const file of files) {
17342
+ const sourcePath = joinPath(sourceDir, file);
17343
+ let destFileName = file;
17344
+ if (destFileName.endsWith(".example")) {
17345
+ destFileName = destFileName.slice(0, -8);
17346
+ }
17347
+ const destPath = joinPath(destDir, destFileName);
17348
+ await ensureDir(getDirname(destPath));
17349
+ await copy(sourcePath, destPath);
17350
+ if (await isTextFile(destPath)) {
17351
+ await replacePlaceholders(destPath, replacements);
17352
+ }
17329
17353
  }
17354
+ }
17355
+ async function isTextFile(filePath) {
17356
+ const binaryExtensions = [
17357
+ ".png",
17358
+ ".jpg",
17359
+ ".jpeg",
17360
+ ".gif",
17361
+ ".ico",
17362
+ ".woff",
17363
+ ".woff2",
17364
+ ".eot",
17365
+ ".ttf",
17366
+ ".otf",
17367
+ ".zip",
17368
+ ".pdf",
17369
+ ".exe",
17370
+ ".dll",
17371
+ ".so",
17372
+ ".bin",
17373
+ ".dat",
17374
+ ".class"
17375
+ ];
17376
+ if (binaryExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
17377
+ return false;
17378
+ const textExtensions = [
17379
+ ".json",
17380
+ ".js",
17381
+ ".ts",
17382
+ ".tsx",
17383
+ ".jsx",
17384
+ ".md",
17385
+ ".yml",
17386
+ ".yaml",
17387
+ ".html",
17388
+ ".css",
17389
+ ".scss",
17390
+ ".env",
17391
+ ".gitignore",
17392
+ ".npmrc",
17393
+ ".eslintrc",
17394
+ ".prettierrc",
17395
+ ".firebase",
17396
+ ".txt"
17397
+ ];
17398
+ if (textExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
17399
+ return true;
17330
17400
  try {
17331
- const config = readFirebaseJson(firebaseJsonPath);
17332
- if (!config.projectId) {
17333
- return {
17334
- valid: false,
17335
- hasHosting: false,
17336
- hasFunctions: false
17337
- };
17401
+ const buffer = await read(filePath, { format: "buffer" });
17402
+ if (buffer.length === 0) return true;
17403
+ for (let i = 0; i < Math.min(buffer.length, 1e3); i++) {
17404
+ if (buffer[i] === 0) return false;
17338
17405
  }
17339
- return {
17340
- valid: true,
17341
- hasHosting: !!config.hosting,
17342
- hasFunctions: !!config.functions && Array.isArray(config.functions)
17343
- };
17406
+ return true;
17344
17407
  } catch {
17345
- return {
17346
- valid: false,
17347
- hasHosting: false,
17348
- hasFunctions: false
17349
- };
17408
+ return false;
17350
17409
  }
17351
17410
  }
17352
- function parseBuildArgs(args) {
17353
- const result = {};
17354
- for (const arg of args) {
17355
- if (arg === ":front" || arg === ":frontend" || arg === "front" || arg === "frontend") {
17356
- result.buildType = "frontend";
17357
- } else if (arg === ":func" || arg === ":functions" || arg === "func" || arg === "functions") {
17358
- result.buildType = "functions";
17359
- } else if (arg === ":both" || arg === "both") {
17360
- result.buildType = "both";
17361
- } else if (arg.includes(":")) {
17362
- const parts = arg.split(":");
17363
- result.appName = parts[0];
17364
- const typePart = parts[1];
17365
- if (typePart === "front" || typePart === "frontend") {
17366
- result.buildType = "frontend";
17367
- } else if (typePart === "func" || typePart === "functions") {
17368
- result.buildType = "functions";
17369
- } else if (typePart === "both") {
17370
- result.buildType = "both";
17411
+ async function replacePlaceholders(filePath, replacements) {
17412
+ try {
17413
+ let content = await read(filePath, { format: "text" });
17414
+ if (typeof content !== "string") {
17415
+ content = typeof content === "object" ? JSON.stringify(content, null, 2) : String(content);
17416
+ }
17417
+ content = processConditionalSections(content, replacements);
17418
+ content = processArrayIterations(content, replacements);
17419
+ for (const [key, value] of Object.entries(replacements)) {
17420
+ if (value !== void 0) {
17421
+ const regex = new RegExp(`{{${key}}}`, "g");
17422
+ if (typeof value === "string") {
17423
+ content = content.replace(regex, value);
17424
+ }
17371
17425
  }
17372
- } else if (!arg.startsWith(":") && arg !== "build") {
17373
- result.appName = arg;
17374
17426
  }
17375
- }
17376
- return result;
17377
- }
17378
- async function main() {
17379
- const args = process.argv.slice(2);
17380
- const { appName: parsedAppName, buildType: parsedBuildType } = parseBuildArgs(args);
17381
- const debugMode = process.env.DEBUG === "true" || process.env.DEBUG === "1" || args.includes("--debug") || args.includes("-d");
17382
- if (debugMode) {
17383
- log.debug(` Args: ${args.join(" ")}`);
17384
- log.debug(
17385
- ` Parsed app: ${parsedAppName || "none"}, build type: ${parsedBuildType || "none"}
17386
- `
17427
+ await write(filePath, content, { overwrite: true });
17428
+ } catch (error2) {
17429
+ log.warn(
17430
+ `Warning: Could not process file ${filePath}: ${error2.message || "Unknown error"}`
17387
17431
  );
17388
17432
  }
17389
- const projectRoot = getRepoRoot();
17390
- if (!projectRoot) {
17391
- throw new DoNotDevError(
17392
- "Could not determine repository root",
17393
- "path-resolution-error"
17433
+ }
17434
+ function processConditionalSections(content, replacements) {
17435
+ Object.keys(replacements).forEach((key) => {
17436
+ const value = replacements[key];
17437
+ const isTruthy = value === true || value === "true";
17438
+ const positivePattern = new RegExp(
17439
+ `{{#${key}}}([\\s\\S]*?){{/${key}}}`,
17440
+ "g"
17394
17441
  );
17395
- }
17396
- const app = await selectApp(projectRoot, parsedAppName);
17397
- if (!app) {
17398
- return 1;
17399
- }
17400
- const appDir = app.path;
17401
- const firebaseConfig = validateFirebaseJson(appDir);
17402
- const hasFunctions = app.hasFunctions || firebaseConfig.hasFunctions;
17403
- const hasFrontend = app.framework !== "unknown";
17404
- let buildType = parsedBuildType;
17405
- if (!buildType) {
17406
- const choices = [];
17407
- if (hasFrontend) {
17408
- choices.push({
17409
- title: "Frontend only",
17410
- value: "frontend",
17411
- hint: "Build app bundle"
17412
- });
17442
+ if (isTruthy) {
17443
+ content = content.replace(positivePattern, (match, inner) => inner);
17444
+ } else {
17445
+ content = content.replace(positivePattern, "");
17413
17446
  }
17414
- if (hasFunctions) {
17415
- choices.push({
17416
- title: "Functions only",
17417
- value: "functions",
17418
- hint: "Build cloud functions"
17419
- });
17447
+ const negativePattern = new RegExp(
17448
+ `{{\\^${key}}}([\\s\\S]*?){{/${key}}}`,
17449
+ "g"
17450
+ );
17451
+ if (!isTruthy) {
17452
+ content = content.replace(negativePattern, (match, inner) => inner);
17453
+ } else {
17454
+ content = content.replace(negativePattern, "");
17420
17455
  }
17421
- if (hasFrontend && hasFunctions) {
17422
- choices.push({
17423
- title: "Both frontend and functions",
17424
- value: "both",
17425
- hint: "Build everything"
17426
- });
17456
+ });
17457
+ return content;
17458
+ }
17459
+ function processArrayIterations(content, replacements) {
17460
+ const appNamesPattern = /{{#appNames}}([\s\S]*?){{\/appNames}}/g;
17461
+ if (replacements.appNames && Array.isArray(replacements.appNames)) {
17462
+ const appNames = replacements.appNames;
17463
+ content = content.replace(appNamesPattern, (match, templateContent) => {
17464
+ return appNames.map((appName) => templateContent.replace(/{{\.}}/g, appName)).join("");
17465
+ });
17466
+ } else {
17467
+ content = content.replace(appNamesPattern, "");
17468
+ }
17469
+ return content;
17470
+ }
17471
+ function isValidFileName(name) {
17472
+ return typeof name === "string" && /^[a-zA-Z0-9_-]+$/.test(name);
17473
+ }
17474
+ var RESERVED_APP_NAMES = ["demo", "dndev"];
17475
+ function isReservedAppName(name) {
17476
+ return RESERVED_APP_NAMES.includes(
17477
+ name.toLowerCase()
17478
+ );
17479
+ }
17480
+ async function updateRootPackageJson(rootDir, appNames) {
17481
+ const packageJsonPath = joinPath(rootDir, "package.json");
17482
+ if (!pathExists(packageJsonPath)) {
17483
+ log.warn("Root package.json not found, skipping script updates");
17484
+ return;
17485
+ }
17486
+ try {
17487
+ const packageJson = await read(packageJsonPath, { format: "json" });
17488
+ packageJson.scripts = packageJson.scripts || {};
17489
+ } catch (error2) {
17490
+ log.warn(
17491
+ `Warning: Could not update root package.json: ${error2.message || "Unknown error"}`
17492
+ );
17493
+ }
17494
+ }
17495
+ async function mergeRootPackageJson(rootDir, allAppNames, options = {}) {
17496
+ const packageJsonPath = joinPath(rootDir, "package.json");
17497
+ if (!pathExists(packageJsonPath)) {
17498
+ log.warn("Root package.json not found, skipping merge");
17499
+ return;
17500
+ }
17501
+ try {
17502
+ const packageJson = await read(packageJsonPath, { format: "json" });
17503
+ packageJson.scripts = packageJson.scripts || {};
17504
+ } catch (error2) {
17505
+ log.warn(
17506
+ `Warning: Could not merge root package.json: ${error2.message || "Unknown error"}`
17507
+ );
17508
+ }
17509
+ }
17510
+ async function mergeRootTsConfig(rootDir, allAppNames, includeFunctions = false) {
17511
+ const tsconfigPath = joinPath(rootDir, "tsconfig.json");
17512
+ if (!pathExists(tsconfigPath)) {
17513
+ log.warn("Root tsconfig.json not found, skipping merge");
17514
+ return;
17515
+ }
17516
+ try {
17517
+ const tsconfig = readTsConfigJson(tsconfigPath);
17518
+ tsconfig.references = tsconfig.references || [];
17519
+ const existingPaths = new Set(
17520
+ tsconfig.references.map((ref) => ref.path)
17521
+ );
17522
+ let updated = false;
17523
+ for (const appName of allAppNames) {
17524
+ const appPath = `${appName}-app`;
17525
+ if (!existingPaths.has(appPath)) {
17526
+ tsconfig.references.push({ path: appPath });
17527
+ updated = true;
17528
+ }
17427
17529
  }
17428
- if (choices.length === 0) {
17429
- log.error("No build targets found. App must have frontend or functions.");
17430
- throw new DoNotDevError("No build targets found", "validation-error");
17530
+ if (includeFunctions && !existingPaths.has("functions")) {
17531
+ tsconfig.references.push({ path: "functions" });
17532
+ updated = true;
17431
17533
  }
17432
- if (choices.length === 1) {
17433
- buildType = choices[0].value;
17434
- Me(`Building: ${choices[0].title}`, "Auto-selected");
17435
- } else {
17436
- buildType = await askForSelection(
17437
- "What would you like to build?",
17438
- choices
17439
- );
17534
+ if (updated) {
17535
+ await write(tsconfigPath, tsconfig, { format: "json", overwrite: true });
17536
+ log.info("Merged root tsconfig.json");
17440
17537
  }
17538
+ } catch (error2) {
17539
+ log.warn(
17540
+ `Warning: Could not merge root tsconfig.json: ${error2.message || "Unknown error"}`
17541
+ );
17441
17542
  }
17442
- if (buildType === "frontend" || buildType === "both") {
17443
- if (!hasFrontend) {
17444
- log.error(
17445
- "Frontend build requested but app has no frontend configuration."
17446
- );
17447
- throw new DoNotDevError(
17448
- "Frontend build requested but app has no frontend configuration",
17449
- "validation-error"
17543
+ }
17544
+ async function mergeRootTurboJson(rootDir) {
17545
+ const turboJsonPath = joinPath(rootDir, "turbo.json");
17546
+ if (!pathExists(turboJsonPath)) {
17547
+ log.warn("Root turbo.json not found, skipping merge");
17548
+ return;
17549
+ }
17550
+ try {
17551
+ const turboJson = readTurboJson(turboJsonPath);
17552
+ if (!turboJson) {
17553
+ throw new Error(
17554
+ `turbo.json is empty or invalid JSON at ${turboJsonPath}`
17450
17555
  );
17451
17556
  }
17452
- log.info(`Building ${app.name} frontend...
17453
- `);
17454
- const turboArgs = ["build", "--filter", app.packageName];
17455
- const env = {
17456
- ...process.env,
17457
- DNDEV_APP_ROOT: app.path
17557
+ turboJson.tasks = turboJson.tasks || {};
17558
+ const defaultTasks = {
17559
+ build: {
17560
+ dependsOn: ["^build"],
17561
+ outputs: ["*/dist/**", "!**/node_modules/**"]
17562
+ },
17563
+ preview: {
17564
+ dependsOn: ["build"],
17565
+ cache: false,
17566
+ persistent: true
17567
+ },
17568
+ test: {
17569
+ dependsOn: ["^build"],
17570
+ outputs: ["coverage/**"]
17571
+ },
17572
+ lint: {
17573
+ outputs: []
17574
+ },
17575
+ dev: {
17576
+ cache: false,
17577
+ persistent: true
17578
+ },
17579
+ clean: {
17580
+ cache: false
17581
+ }
17458
17582
  };
17459
- const result = spawnSync("bunx", ["turbo", ...turboArgs], {
17460
- stdio: "inherit",
17461
- env,
17462
- cwd: projectRoot
17463
- });
17464
- if (result.status !== 0) {
17465
- return result.status || 1;
17466
- }
17467
- }
17468
- if (buildType === "functions" || buildType === "both") {
17469
- if (!hasFunctions) {
17470
- log.error(
17471
- "Functions build requested but app has no functions directory."
17472
- );
17473
- throw new DoNotDevError(
17474
- "Functions build requested but app has no functions directory",
17475
- "validation-error"
17476
- );
17583
+ let updated = false;
17584
+ for (const [taskName, taskConfig] of Object.entries(defaultTasks)) {
17585
+ if (!turboJson.tasks[taskName]) {
17586
+ turboJson.tasks[taskName] = taskConfig;
17587
+ updated = true;
17588
+ }
17477
17589
  }
17478
- const functionsDir = joinPath(appDir, "functions");
17479
- if (!pathExists(functionsDir)) {
17480
- log.error(`Functions directory not found: ${functionsDir}`);
17481
- throw new DoNotDevError(
17482
- `Functions directory not found: ${functionsDir}`,
17483
- "file-not-found"
17484
- );
17590
+ if (!turboJson.globalDependencies) {
17591
+ turboJson.globalDependencies = ["**/.env.*local"];
17592
+ updated = true;
17485
17593
  }
17486
- log.info(`Building ${app.name} functions...
17487
- `);
17488
- const s = Y2();
17489
- s.start("Building functions...");
17490
- try {
17491
- execSync("bun run build", {
17492
- cwd: functionsDir,
17493
- stdio: "inherit"
17594
+ if (updated) {
17595
+ await write(turboJsonPath, turboJson, {
17596
+ format: "json",
17597
+ overwrite: true
17494
17598
  });
17495
- s.stop("Functions built");
17496
- } catch (error2) {
17497
- s.stop("\u274C Functions build failed");
17498
- throw DoNotDevError.from(
17499
- error2,
17500
- "Functions build failed",
17501
- "cli-execution-error"
17502
- );
17599
+ log.info("Merged root turbo.json");
17503
17600
  }
17601
+ } catch (error2) {
17602
+ log.warn(
17603
+ `Warning: Could not merge root turbo.json: ${error2 instanceof Error ? error2.message : String(error2)}`
17604
+ );
17504
17605
  }
17505
- log.success(`Build complete for ${app.name}`);
17506
- return 0;
17507
17606
  }
17508
17607
 
17509
- // packages/tooling/src/apps/dev.ts
17510
- init_utils();
17511
- init_app_selector();
17512
- init_cli_output();
17513
- init_errors();
17514
- init_pathResolver();
17515
- import { execSync as execSync3 } from "node:child_process";
17516
- import { platform as platform2 } from "node:os";
17517
-
17518
- // packages/tooling/src/utils/spawn-utils.ts
17608
+ // packages/tooling/src/utils/matrix.ts
17519
17609
  init_utils();
17520
- init_cli_output();
17521
- init_errors();
17522
17610
  init_pathResolver();
17523
- import {
17524
- spawn,
17525
- spawnSync as spawnSync2,
17526
- execSync as execSync2
17527
- } from "node:child_process";
17528
- import { platform } from "node:os";
17529
- function createAppEnv(appPath) {
17530
- return {
17531
- ...process.env,
17532
- DNDEV_APP_ROOT: appPath
17533
- };
17534
- }
17535
- function spawnCrossPlatform(command, args, options) {
17536
- const isWindows = platform() === "win32";
17537
- const useShell = options.shell ?? isWindows;
17538
- if (useShell) {
17539
- const fullCommand = `${command} ${args.join(" ")}`;
17540
- const { shell: _4, ...rest2 } = options;
17541
- return spawn(fullCommand, [], { ...rest2, shell: true });
17611
+ import { createRequire as createRequire4 } from "node:module";
17612
+ var cachedMatrix = null;
17613
+ function getMatrixPath(mode) {
17614
+ try {
17615
+ const require3 = createRequire4(import.meta.url);
17616
+ const resolved = require3.resolve("@donotdev/cli/dependencies-matrix.json");
17617
+ if (pathExists(resolved)) {
17618
+ return resolved;
17619
+ }
17620
+ } catch {
17542
17621
  }
17543
- const { shell: _3, ...rest } = options;
17544
- return spawn(command, args, rest);
17545
- }
17546
- function createEmulatorEnv(appPath, framework = "vite", options) {
17547
- const baseEnv = createAppEnv(appPath);
17548
- const prefix = framework === "nextjs" ? "NEXT_PUBLIC_" : "VITE_";
17549
- const useEmulatorAuth = options?.useEmulatorAuth ?? false;
17550
- const useEmulatorFirestore = options?.useEmulatorFirestore ?? true;
17622
+ const executionMode = mode || detectExecutionMode();
17623
+ if (executionMode === "development") {
17624
+ const templatesRoot = getTemplatesRoot();
17625
+ const devPath = normalizePath(
17626
+ templatesRoot,
17627
+ "..",
17628
+ "dependencies-matrix.json"
17629
+ );
17630
+ if (pathExists(devPath)) {
17631
+ return devPath;
17632
+ }
17633
+ }
17634
+ return null;
17635
+ }
17636
+ function getCliVersion(mode) {
17637
+ try {
17638
+ const require3 = createRequire4(import.meta.url);
17639
+ const packageJsonPath = require3.resolve("@donotdev/cli/package.json");
17640
+ const pkg = readSync(packageJsonPath, { format: "json" });
17641
+ return String(pkg?.version || "0.0.0");
17642
+ } catch {
17643
+ }
17644
+ const executionMode = mode || detectExecutionMode();
17645
+ if (executionMode === "development") {
17646
+ const templatesRoot = getTemplatesRoot();
17647
+ const cliPackageJson = normalizePath(templatesRoot, "..", "package.json");
17648
+ if (pathExists(cliPackageJson)) {
17649
+ const pkg = readSync(cliPackageJson, { format: "json" });
17650
+ return String(pkg?.version || "0.0.0");
17651
+ }
17652
+ }
17653
+ return "0.0.0";
17654
+ }
17655
+ function loadMatrix(mode) {
17656
+ if (cachedMatrix) return cachedMatrix;
17657
+ const matrixPath = getMatrixPath(mode);
17658
+ if (!matrixPath) {
17659
+ return null;
17660
+ }
17661
+ const content = readSync(matrixPath, { format: "json" });
17662
+ if (!content) {
17663
+ return null;
17664
+ }
17665
+ cachedMatrix = {
17666
+ matrix: content,
17667
+ cliVersion: getCliVersion(mode)
17668
+ };
17669
+ return cachedMatrix;
17670
+ }
17671
+ function resolveGroup(groupName, matrix) {
17672
+ return matrix.groups[groupName]?.packages || {};
17673
+ }
17674
+ function resolveGroups(groupNames, matrix) {
17675
+ const result = {};
17676
+ for (const groupName of groupNames) {
17677
+ Object.assign(result, resolveGroup(groupName, matrix));
17678
+ }
17679
+ return result;
17680
+ }
17681
+
17682
+ // packages/tooling/src/utils/scaffolding-questionnaire.ts
17683
+ init_utils();
17684
+ var APP_QUESTIONNAIRE = [
17685
+ {
17686
+ id: "framework",
17687
+ question: "Which framework?",
17688
+ type: "select",
17689
+ defaultValue: "vite",
17690
+ choices: [
17691
+ {
17692
+ title: "Vite \u2014 SPA/SaaS (client-side rendering, fast dev)",
17693
+ value: "vite"
17694
+ },
17695
+ {
17696
+ title: "Next.js \u2014 Static content/SEO (SSR, SSG) \u2014 BETA",
17697
+ value: "nextjs"
17698
+ },
17699
+ {
17700
+ title: "Expo \u2014 Mobile app (iOS + Android)",
17701
+ value: "expo"
17702
+ }
17703
+ ]
17704
+ },
17705
+ {
17706
+ id: "host",
17707
+ question: "Where will you host?",
17708
+ type: "select",
17709
+ condition: (answers) => answers.framework !== "expo",
17710
+ defaultValue: (answers) => {
17711
+ return answers.framework === "nextjs" ? "vercel" : "none";
17712
+ },
17713
+ choices: [
17714
+ { title: "None \u2014 no hosting config", value: "none" },
17715
+ { title: "Vercel \u2014 edge CDN + serverless", value: "vercel" },
17716
+ { title: "Firebase Hosting \u2014 Google CDN", value: "firebase" }
17717
+ ]
17718
+ },
17719
+ {
17720
+ id: "functions",
17721
+ question: "Serverless functions?",
17722
+ type: "select",
17723
+ defaultValue: "none",
17724
+ // Choices filtered dynamically based on host
17725
+ choices: [
17726
+ { title: "None", value: "none" },
17727
+ { title: "Vercel Functions \u2014 edge + node.js", value: "vercel" },
17728
+ { title: "Firebase Functions \u2014 Google Cloud", value: "firebase" },
17729
+ { title: "Supabase Edge Functions \u2014 Deno", value: "supabase" }
17730
+ ],
17731
+ choicesFilter: (answers) => {
17732
+ const host = answers.host ?? "none";
17733
+ const framework = answers.framework;
17734
+ if (framework === "expo") return ["none", "firebase", "supabase"];
17735
+ if (host === "firebase") return ["none", "firebase"];
17736
+ if (host === "vercel") return ["none", "vercel", "supabase"];
17737
+ return ["none", "vercel", "firebase", "supabase"];
17738
+ }
17739
+ },
17740
+ {
17741
+ id: "backend",
17742
+ question: "Backend / BaaS provider?",
17743
+ type: "select",
17744
+ defaultValue: (answers) => {
17745
+ if (answers.functions === "firebase") return "firebase";
17746
+ if (answers.functions === "supabase") return "supabase";
17747
+ return "none";
17748
+ },
17749
+ choices: [
17750
+ { title: "None \u2014 frontend only", value: "none" },
17751
+ {
17752
+ title: "Firebase \u2014 Auth + Firestore + Storage",
17753
+ value: "firebase"
17754
+ },
17755
+ {
17756
+ title: "Supabase \u2014 Postgres + Auth + Storage",
17757
+ value: "supabase"
17758
+ }
17759
+ ],
17760
+ choicesFilter: (answers) => {
17761
+ const functions = answers.functions ?? "none";
17762
+ if (functions === "firebase") return ["none", "firebase"];
17763
+ if (functions === "supabase") return ["none", "supabase"];
17764
+ if (functions === "vercel") return ["none"];
17765
+ return ["none", "firebase", "supabase"];
17766
+ }
17767
+ }
17768
+ ];
17769
+ var PROJECT_QUESTIONNAIRE = [
17770
+ {
17771
+ id: "projectName",
17772
+ question: "Project name",
17773
+ type: "input",
17774
+ defaultValue: "my-project"
17775
+ },
17776
+ {
17777
+ id: "appNames",
17778
+ question: `App name(s) (comma-separated for multiple, e.g., web, admin) - '${RESERVED_APP_NAMES.join("', '")}' reserved`,
17779
+ type: "input",
17780
+ defaultValue: "web"
17781
+ }
17782
+ ];
17783
+ function aggregateRequirements(answers) {
17784
+ const hasBackend = answers.backend && answers.backend !== "none" || answers.functions && answers.functions !== "none";
17785
+ const requirements = {
17786
+ entities: [],
17787
+ // Entities created in apps/<app>/entities/ (v1), root entities/ for v2
17788
+ billing: true,
17789
+ // Always on (useStripeBillingSafe handles missing package)
17790
+ backend: hasBackend,
17791
+ features: [],
17792
+ template: "vite",
17793
+ // Only Vite for now
17794
+ userAuth: "social"
17795
+ // Always on (useAuthSafe handles missing package)
17796
+ };
17797
+ return requirements;
17798
+ }
17799
+ async function runQuestionnaire(questions, initialAnswers, showWIP, askFor) {
17800
+ const answers = { ...initialAnswers };
17801
+ for (const question of questions) {
17802
+ if (answers[question.id] !== void 0) continue;
17803
+ if (question.condition && !question.condition(answers)) continue;
17804
+ if (question.dependsOn && !answers[question.dependsOn]) continue;
17805
+ let answer;
17806
+ const resolvedDefault = typeof question.defaultValue === "function" ? question.defaultValue(answers) : question.defaultValue;
17807
+ switch (question.type) {
17808
+ case "select":
17809
+ case "multi-select": {
17810
+ let choices = question.choices || [];
17811
+ if (!showWIP) {
17812
+ choices = choices.filter((choice) => !choice.wip);
17813
+ }
17814
+ if (question.choicesFilter) {
17815
+ const allowed = question.choicesFilter(answers);
17816
+ choices = choices.filter((c) => allowed.includes(c.value));
17817
+ }
17818
+ if (choices.length === 0) continue;
17819
+ answer = await askFor.selection(question.question, choices);
17820
+ break;
17821
+ }
17822
+ case "confirm":
17823
+ answer = await askFor.confirmation(question.question, resolvedDefault);
17824
+ break;
17825
+ case "input":
17826
+ answer = await askFor.input(question.question, resolvedDefault);
17827
+ break;
17828
+ }
17829
+ answers[question.id] = answer;
17830
+ }
17831
+ return answers;
17832
+ }
17833
+
17834
+ // packages/tooling/src/utils/spawn-utils.ts
17835
+ init_utils();
17836
+ init_cli_output();
17837
+ init_errors();
17838
+ init_pathResolver();
17839
+ import {
17840
+ spawn,
17841
+ spawnSync as spawnSync2,
17842
+ execSync
17843
+ } from "node:child_process";
17844
+ import { platform } from "node:os";
17845
+ function createAppEnv(appPath) {
17846
+ return {
17847
+ ...process.env,
17848
+ DNDEV_APP_ROOT: appPath
17849
+ };
17850
+ }
17851
+ function spawnCrossPlatform(command, args, options) {
17852
+ const isWindows = platform() === "win32";
17853
+ const useShell = options.shell ?? isWindows;
17854
+ if (useShell) {
17855
+ const fullCommand = `${command} ${args.join(" ")}`;
17856
+ const { shell: _4, ...rest2 } = options;
17857
+ return spawn(fullCommand, [], { ...rest2, shell: true });
17858
+ }
17859
+ const { shell: _3, ...rest } = options;
17860
+ return spawn(command, args, rest);
17861
+ }
17862
+ function createEmulatorEnv(appPath, framework = "vite", options) {
17863
+ const baseEnv = createAppEnv(appPath);
17864
+ const prefix = framework === "nextjs" ? "NEXT_PUBLIC_" : "VITE_";
17865
+ const useEmulatorAuth = options?.useEmulatorAuth ?? false;
17866
+ const useEmulatorFirestore = options?.useEmulatorFirestore ?? true;
17551
17867
  const env = {
17552
17868
  ...baseEnv,
17553
17869
  [`${prefix}USE_FIREBASE_EMULATOR`]: "true",
@@ -17691,383 +18007,497 @@ function safeRemove(path, options = {}) {
17691
18007
  }
17692
18008
  }
17693
18009
 
17694
- // packages/tooling/src/apps/dev.ts
17695
- var SIGNAL_EXIT_CODES = {
17696
- SIGINT: 130,
17697
- // 128 + 2
17698
- SIGTERM: 143
17699
- // 128 + 15
17700
- };
17701
- async function main2() {
17702
- const args = process.argv.slice(2);
17703
- const appName = args[0] && args[0] !== "dev" ? args[0] : void 0;
17704
- const projectRoot = getRepoRoot();
17705
- if (!projectRoot) {
18010
+ // packages/tooling/src/apps/deploy-utils.ts
18011
+ init_error_handling();
18012
+ init_pathResolver();
18013
+ init_typed_file_operations();
18014
+ function detectAvailableApps() {
18015
+ const currentDir = process.cwd();
18016
+ const appsDir = joinPath(currentDir, "apps");
18017
+ if (!pathExists(appsDir)) {
18018
+ return [];
18019
+ }
18020
+ return readdirSync2(appsDir).filter((item) => {
18021
+ const itemPath = joinPath(appsDir, item);
18022
+ const stat2 = statSync2(itemPath);
18023
+ return stat2?.isDirectory() === true;
18024
+ }).filter((app) => {
18025
+ const appDir = joinPath(appsDir, app);
18026
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18027
+ const supabaseDir = joinPath(appDir, "supabase");
18028
+ const vercelJsonPath = joinPath(appDir, "vercel.json");
18029
+ return pathExists(firebaseJsonPath) || pathExists(supabaseDir) || pathExists(vercelJsonPath);
18030
+ }).sort();
18031
+ }
18032
+ function detectAppDir(appName) {
18033
+ const currentDir = process.cwd();
18034
+ const appDir = joinPath(currentDir, "apps", appName);
18035
+ if (!pathExists(appDir)) {
17706
18036
  throw new DoNotDevError(
17707
- "Could not determine repository root",
17708
- "path-resolution-error"
18037
+ `App directory not found: ${appDir}`,
18038
+ "file-not-found",
18039
+ { context: { appName, expectedPath: appDir } }
17709
18040
  );
17710
18041
  }
17711
- const app = await selectApp(projectRoot, appName);
17712
- if (!app) {
17713
- return 1;
18042
+ return appDir;
18043
+ }
18044
+ function validateServiceAccount(appDir, options) {
18045
+ const keyFileName = options?.staging ? "service-account-key.staging.json" : "service-account-key.json";
18046
+ const rootKeyPath = joinPath(appDir, keyFileName);
18047
+ const functionsDir = joinPath(appDir, "functions");
18048
+ const functionsKeyPath = joinPath(functionsDir, keyFileName);
18049
+ const keyPath = pathExists(rootKeyPath) ? rootKeyPath : functionsKeyPath;
18050
+ const errors = [];
18051
+ if (!pathExists(keyPath)) {
18052
+ return {
18053
+ valid: false,
18054
+ info: {
18055
+ path: keyPath,
18056
+ projectId: "",
18057
+ clientEmail: "",
18058
+ valid: false,
18059
+ errors: [
18060
+ `Service account key file not found. Checked:`,
18061
+ ` - ${rootKeyPath}`,
18062
+ ` - ${functionsKeyPath}`
18063
+ ]
18064
+ }
18065
+ };
17714
18066
  }
17715
- log.info(`Starting dev server for ${app.name}...
17716
- `);
17717
- const turboArgs = ["dev", "--filter", app.packageName];
17718
- const isWindows = platform2() === "win32";
17719
- const childProcess = spawnCrossPlatform(
17720
- "bunx",
17721
- ["turbo", ...turboArgs],
17722
- {
17723
- stdio: "inherit",
17724
- env: createAppEnv(app.path),
17725
- cwd: projectRoot
17726
- }
17727
- );
17728
- const cleanup = (signal) => {
17729
- if (!childProcess.pid) return;
17730
- log.debug(`Received ${signal}, cleaning up processes...`);
17731
- if (isWindows) {
17732
- try {
17733
- execSync3(`taskkill /F /T /PID ${childProcess.pid}`, {
17734
- stdio: "ignore",
17735
- timeout: 2e3
17736
- });
17737
- } catch {
18067
+ try {
18068
+ const keyData = readServiceAccountKey(keyPath);
18069
+ return {
18070
+ valid: true,
18071
+ info: {
18072
+ path: keyPath,
18073
+ projectId: keyData.project_id,
18074
+ clientEmail: keyData.client_email,
18075
+ valid: true,
18076
+ errors: []
17738
18077
  }
17739
- } else {
17740
- try {
17741
- process.kill(childProcess.pid, signal);
17742
- } catch {
18078
+ };
18079
+ } catch (error2) {
18080
+ return {
18081
+ valid: false,
18082
+ info: {
18083
+ path: keyPath,
18084
+ projectId: "",
18085
+ clientEmail: "",
18086
+ valid: false,
18087
+ errors: [`Invalid service account key: ${getErrorMessage(error2)}`]
17743
18088
  }
18089
+ };
18090
+ }
18091
+ }
18092
+ function validateFirebaseJson(appDir) {
18093
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18094
+ if (!pathExists(firebaseJsonPath)) {
18095
+ return {
18096
+ valid: false,
18097
+ hasHosting: false,
18098
+ hasFunctions: false,
18099
+ hasFirestoreRules: false,
18100
+ hasFirestoreIndexes: false,
18101
+ hasStorageRules: false,
18102
+ errors: [`firebase.json not found at: ${firebaseJsonPath}`]
18103
+ };
18104
+ }
18105
+ try {
18106
+ const config = readFirebaseJson(firebaseJsonPath);
18107
+ const hasHosting = !!config.hosting;
18108
+ const hasFunctions = !!config.functions && Array.isArray(config.functions);
18109
+ const hasFirestoreRules = !!config.firestore?.rules && pathExists(joinPath(appDir, config.firestore.rules));
18110
+ const hasFirestoreIndexes = !!config.firestore?.indexes && pathExists(joinPath(appDir, config.firestore.indexes));
18111
+ const hasStorageRules = !!config.storage?.rules && pathExists(joinPath(appDir, config.storage.rules));
18112
+ return {
18113
+ valid: true,
18114
+ projectId: config.projectId,
18115
+ hasHosting,
18116
+ hasFunctions,
18117
+ hasFirestoreRules,
18118
+ hasFirestoreIndexes,
18119
+ hasStorageRules,
18120
+ errors: []
18121
+ };
18122
+ } catch (error2) {
18123
+ return {
18124
+ valid: false,
18125
+ hasHosting: false,
18126
+ hasFunctions: false,
18127
+ hasFirestoreRules: false,
18128
+ hasFirestoreIndexes: false,
18129
+ hasStorageRules: false,
18130
+ errors: [`Invalid firebase.json: ${getErrorMessage(error2)}`]
18131
+ };
18132
+ }
18133
+ }
18134
+ function validateBuild(appDir) {
18135
+ const distPath = joinPath(appDir, "dist");
18136
+ if (!pathExists(distPath)) {
18137
+ return { exists: false, isEmpty: true, path: distPath };
18138
+ }
18139
+ try {
18140
+ const files = readdirSync2(distPath);
18141
+ return {
18142
+ exists: true,
18143
+ isEmpty: files.length === 0,
18144
+ path: distPath
18145
+ };
18146
+ } catch {
18147
+ return { exists: true, isEmpty: true, path: distPath };
18148
+ }
18149
+ }
18150
+ function readStagingProject(startDir) {
18151
+ let current = startDir;
18152
+ for (let i = 0; i < 10; i++) {
18153
+ const firebasercPath = joinPath(current, ".firebaserc");
18154
+ if (pathExists(firebasercPath)) {
17744
18155
  try {
17745
- execSync3(`pkill -P ${childProcess.pid}`, {
17746
- stdio: "ignore",
17747
- timeout: 1e3
17748
- });
17749
- } catch {
18156
+ const firebaserc = readFirebaserc(firebasercPath);
18157
+ if (firebaserc?.projects?.staging) {
18158
+ return firebaserc.projects.staging;
18159
+ }
18160
+ } catch (error2) {
17750
18161
  }
17751
18162
  }
17752
- };
17753
- const signals = ["SIGINT", "SIGTERM"];
17754
- const handlers = [];
17755
- for (const signal of signals) {
17756
- const handler = () => {
17757
- cleanup(signal);
17758
- handlers.forEach((h2) => h2());
17759
- process.exit(SIGNAL_EXIT_CODES[signal] ?? 130);
17760
- };
17761
- process.on(signal, handler);
17762
- handlers.push(() => process.removeListener(signal, handler));
18163
+ const parent = joinPath(current, "..");
18164
+ if (parent === current) break;
18165
+ current = parent;
17763
18166
  }
17764
- return new Promise((resolve4) => {
17765
- childProcess.on("exit", (code, signal) => {
17766
- handlers.forEach((h2) => h2());
17767
- if (signal) {
17768
- log.debug(`Process killed by signal: ${signal}`);
17769
- resolve4(SIGNAL_EXIT_CODES[signal] ?? 130);
17770
- } else {
17771
- resolve4(code ?? 0);
17772
- }
17773
- });
17774
- childProcess.on("error", (error2) => {
17775
- handlers.forEach((h2) => h2());
17776
- log.error(`Failed to start dev server: ${error2.message}`);
17777
- resolve4(1);
17778
- });
17779
- });
18167
+ return null;
17780
18168
  }
17781
-
17782
- // packages/tooling/src/apps/emu.ts
17783
- init_utils();
17784
-
17785
- // packages/tooling/src/apps/emu-firebase.ts
17786
- init_utils();
17787
- init_cli_input();
17788
- init_cli_output();
17789
- init_pathResolver();
17790
- import { spawnSync as spawnSync3, execSync as execSync4 } from "node:child_process";
17791
- import { platform as platform3 } from "node:os";
17792
- init_typed_file_operations();
17793
- function discoverFirebaseProjectId(appPath) {
17794
- const firebasercPath = joinPath(appPath, ".firebaserc");
17795
- if (pathExists(firebasercPath)) {
17796
- try {
17797
- const firebasercRaw = readSync(firebasercPath, { format: "json" });
17798
- const firebaserc = firebasercRaw && typeof firebasercRaw === "object" ? firebasercRaw : null;
17799
- if (firebaserc?.projects?.default) {
17800
- return firebaserc.projects.default;
17801
- }
17802
- } catch {
18169
+ function checkConfigPlaceholders(appDir) {
18170
+ const CONFIG_FILES = ["vercel.json", "firebase.json", ".firebaserc"];
18171
+ const bad = [];
18172
+ for (const file of CONFIG_FILES) {
18173
+ const filePath = joinPath(appDir, file);
18174
+ if (!pathExists(filePath)) continue;
18175
+ const content = readSync(filePath, { format: "text" });
18176
+ if (typeof content === "string" && (content.includes("{{") || content.includes("}}"))) {
18177
+ bad.push(file);
17803
18178
  }
17804
18179
  }
17805
- return process.env.FIREBASE_PROJECT_ID || null;
18180
+ if (bad.length > 0) {
18181
+ log.warn(`Unreplaced template placeholders found in: ${bad.join(", ")}`);
18182
+ log.warn(` Fix manually or re-run "dndev init" to regenerate.
18183
+ `);
18184
+ }
18185
+ return bad.length > 0;
17806
18186
  }
17807
- function killPorts(ports) {
17808
- if (ports.length === 0) return;
17809
- const isWindows = process.platform === "win32";
17810
- for (const port of ports) {
17811
- try {
17812
- if (isWindows) {
17813
- const findPort = execSync4(`netstat -ano | findstr :${port}`, {
17814
- encoding: "utf-8"
17815
- });
17816
- const lines = findPort.trim().split("\n");
17817
- const pids = /* @__PURE__ */ new Set();
17818
- for (const line of lines) {
17819
- const match = line.match(/\s+(\d+)\s*$/);
17820
- if (match && match[1]) {
17821
- pids.add(match[1]);
17822
- }
17823
- }
17824
- for (const pid of Array.from(pids)) {
17825
- try {
17826
- execSync4(`taskkill /F /PID ${pid}`, { stdio: "ignore" });
17827
- log.debug(`Killed process ${pid} on port ${port}`);
17828
- } catch {
17829
- }
17830
- }
17831
- } else {
17832
- try {
17833
- const output = execSync4(`lsof -ti:${port}`, {
17834
- encoding: "utf-8"
17835
- }).trim();
17836
- if (output) {
17837
- const pids = output.split("\n").filter(Boolean);
17838
- for (const pid of pids) {
17839
- try {
17840
- execSync4(`kill -9 ${pid}`, { stdio: "ignore" });
17841
- log.debug(`Killed process ${pid} on port ${port}`);
17842
- } catch {
17843
- }
17844
- }
17845
- }
17846
- } catch {
17847
- }
18187
+ async function showServiceAccountError(info2, projectId) {
18188
+ const consoleUrl = projectId ? `https://console.firebase.google.com/project/${projectId}/settings/serviceaccounts/adminsdk` : "https://console.firebase.google.com/project/YOUR_PROJECT/settings/serviceaccounts/adminsdk";
18189
+ const errorList = info2.errors.map((e2) => `\u2022 ${e2}`).join("\n");
18190
+ Me(
18191
+ `${errorList}
18192
+
18193
+ Why it matters:
18194
+ Firebase CLI needs service account credentials to deploy.
18195
+ Without valid credentials, deployment will fail.
18196
+
18197
+ How to fix:
18198
+ 1. Go to Firebase Console:
18199
+ ${consoleUrl}
18200
+ 2. Click "Generate New Private Key"
18201
+ 3. Save the JSON file as: ${info2.path}
18202
+ 4. Required IAM roles:
18203
+ \u2022 Firebase Hosting Admin (for frontend)
18204
+ \u2022 Cloud Functions Admin (for functions)
18205
+ \u2022 Or Firebase Admin (covers both)`,
18206
+ "Service Account Error"
18207
+ );
18208
+ if (projectId) {
18209
+ const shouldOpen = await askForConfirmation(
18210
+ "Open Firebase Console now?",
18211
+ true
18212
+ );
18213
+ if (shouldOpen) {
18214
+ try {
18215
+ const openCommand = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
18216
+ spawnSync3(`${openCommand} ${consoleUrl}`, { shell: true });
18217
+ log.success("Opening Firebase Console...");
18218
+ } catch {
18219
+ log.warn("Could not open browser. Please open the URL manually.");
17848
18220
  }
17849
- } catch {
17850
18221
  }
17851
18222
  }
17852
18223
  }
17853
- function getEmulatorPorts(emulatorConfig) {
17854
- const ports = [];
17855
- if (emulatorConfig?.auth?.port) ports.push(emulatorConfig.auth.port);
17856
- if (emulatorConfig?.functions?.port)
17857
- ports.push(emulatorConfig.functions.port);
17858
- if (emulatorConfig?.firestore?.port)
17859
- ports.push(emulatorConfig.firestore.port);
17860
- if (emulatorConfig?.hosting?.port) ports.push(emulatorConfig.hosting.port);
17861
- if (emulatorConfig?.ui?.port) ports.push(emulatorConfig.ui.port);
17862
- if (!emulatorConfig) {
17863
- ports.push(4e3, 5001, 8080, 9099, 5e3);
18224
+ function showFirebaseJsonError(errors, appDir, deploymentType) {
18225
+ const errorList = errors.map((e2) => `\u2022 ${e2}`).join("\n");
18226
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18227
+ let configExample = "";
18228
+ if (deploymentType === "frontend" || deploymentType === "both") {
18229
+ configExample += `
18230
+ Hosting config:
18231
+ { "hosting": { "public": "dist", ... } }`;
17864
18232
  }
17865
- return ports;
18233
+ if (deploymentType === "functions" || deploymentType === "both") {
18234
+ configExample += `
18235
+ Functions config:
18236
+ { "functions": [{ "source": "functions", ... }] }`;
18237
+ }
18238
+ Me(
18239
+ `${errorList}
18240
+
18241
+ Why it matters:
18242
+ firebase.json defines your deployment configuration.
18243
+ Without it, Firebase CLI doesn't know what to deploy.
18244
+
18245
+ How to fix:
18246
+ 1. Ensure firebase.json exists at: ${firebaseJsonPath}
18247
+ 2. Add required configuration:${configExample}`,
18248
+ "Firebase Configuration Error"
18249
+ );
17866
18250
  }
17867
- function loadEnvFile(filePath) {
17868
- if (!pathExists(filePath)) return;
18251
+ function clearFirebaseCache(appDir) {
18252
+ const firebaseCacheDir = joinPath(appDir, ".firebase");
18253
+ if (pathExists(firebaseCacheDir)) {
18254
+ log.info("Clearing Firebase cache...");
18255
+ const removed = safeRemove(firebaseCacheDir, { silent: true });
18256
+ if (removed) {
18257
+ log.success("Firebase cache cleared");
18258
+ } else {
18259
+ log.warn("Could not clear Firebase cache (non-critical)");
18260
+ }
18261
+ }
18262
+ }
18263
+
18264
+ // packages/tooling/src/apps/build.ts
18265
+ function validateFirebaseJson2(appDir) {
18266
+ const firebaseJsonPath = joinPath(appDir, "firebase.json");
18267
+ if (!pathExists(firebaseJsonPath)) {
18268
+ return {
18269
+ valid: false,
18270
+ hasHosting: false,
18271
+ hasFunctions: false
18272
+ };
18273
+ }
17869
18274
  try {
17870
- const content = readSync(filePath, { format: "text" });
17871
- if (!content) return;
17872
- content.split("\n").forEach((line) => {
17873
- const trimmed = line.trim();
17874
- if (!trimmed || trimmed.startsWith("#")) return;
17875
- const equalIndex = trimmed.indexOf("=");
17876
- if (equalIndex === -1) return;
17877
- const key = trimmed.substring(0, equalIndex).trim();
17878
- const value = trimmed.substring(equalIndex + 1).trim().replace(/^["']|["']$/g, "");
17879
- if (key && value) {
17880
- process.env[key] = value;
17881
- }
17882
- });
18275
+ const config = readFirebaseJson(firebaseJsonPath);
18276
+ if (!config.projectId) {
18277
+ return {
18278
+ valid: false,
18279
+ hasHosting: false,
18280
+ hasFunctions: false
18281
+ };
18282
+ }
18283
+ return {
18284
+ valid: true,
18285
+ hasHosting: !!config.hosting,
18286
+ hasFunctions: !!config.functions && Array.isArray(config.functions)
18287
+ };
17883
18288
  } catch {
18289
+ return {
18290
+ valid: false,
18291
+ hasHosting: false,
18292
+ hasFunctions: false
18293
+ };
17884
18294
  }
17885
18295
  }
17886
- async function startFirebase(app, projectRoot, options = {}) {
17887
- const debug = options.debug ?? false;
17888
- let selectedServices = options.selectedServices ?? [];
17889
- const serviceChoices = [
17890
- {
17891
- title: "Auth",
17892
- value: "auth",
17893
- hint: "Firebase Auth emulator (for user authentication)"
17894
- },
17895
- {
17896
- title: "Functions",
17897
- value: "functions",
17898
- hint: "Firebase Functions emulator (required for backend)"
17899
- },
17900
- {
17901
- title: "Firestore",
17902
- value: "firestore",
17903
- hint: "Firestore emulator (for database)"
17904
- },
17905
- {
17906
- title: "Stripe",
17907
- value: "stripe",
17908
- hint: "Stripe webhook forwarding (for payment testing)"
18296
+ function parseBuildArgs(args) {
18297
+ const result = {};
18298
+ for (const arg of args) {
18299
+ if (arg === ":front" || arg === ":frontend" || arg === "front" || arg === "frontend") {
18300
+ result.buildType = "frontend";
18301
+ } else if (arg === ":func" || arg === ":functions" || arg === "func" || arg === "functions") {
18302
+ result.buildType = "functions";
18303
+ } else if (arg === ":both" || arg === "both") {
18304
+ result.buildType = "both";
18305
+ } else if (arg.includes(":")) {
18306
+ const parts = arg.split(":");
18307
+ result.appName = parts[0];
18308
+ const typePart = parts[1];
18309
+ if (typePart === "front" || typePart === "frontend") {
18310
+ result.buildType = "frontend";
18311
+ } else if (typePart === "func" || typePart === "functions") {
18312
+ result.buildType = "functions";
18313
+ } else if (typePart === "both") {
18314
+ result.buildType = "both";
18315
+ }
18316
+ } else if (!arg.startsWith(":") && arg !== "build") {
18317
+ result.appName = arg;
17909
18318
  }
17910
- ];
17911
- log.info(`Starting Firebase emulators + dev server for ${app.name}...
17912
- `);
17913
- if (selectedServices.length === 0) {
17914
- selectedServices = await askForMultiSelection(
17915
- "Which services do you want to run?",
17916
- serviceChoices,
17917
- [1, 2]
17918
- // Default: Functions and Firestore
17919
- );
17920
- } else {
17921
- log.info(`Selected services: ${selectedServices.join(", ")}
17922
- `);
17923
- }
17924
- const useAuth = selectedServices.includes("auth");
17925
- const useFunctions = selectedServices.includes("functions");
17926
- const useFirestore = selectedServices.includes("firestore");
17927
- const useStripe = selectedServices.includes("stripe");
17928
- if (!useFunctions) {
17929
- log.error("Functions emulator is required for Firebase apps.");
17930
- return 1;
17931
18319
  }
17932
- const functionsDir = app.functionsPath;
17933
- const envLocalPath = joinPath(functionsDir, ".env.local");
17934
- if (pathExists(envLocalPath)) {
17935
- loadEnvFile(envLocalPath);
17936
- log.debug("Loaded functions/.env.local for emulator context");
17937
- } else {
17938
- log.warn(
17939
- "No .env.local found in functions directory. Emulator may lack required secrets."
18320
+ return result;
18321
+ }
18322
+ async function main() {
18323
+ const args = process.argv.slice(2);
18324
+ const { appName: parsedAppName, buildType: parsedBuildType } = parseBuildArgs(args);
18325
+ const debugMode = process.env.DEBUG === "true" || process.env.DEBUG === "1" || args.includes("--debug") || args.includes("-d");
18326
+ if (debugMode) {
18327
+ log.debug(` Args: ${args.join(" ")}`);
18328
+ log.debug(
18329
+ ` Parsed app: ${parsedAppName || "none"}, build type: ${parsedBuildType || "none"}
18330
+ `
17940
18331
  );
17941
18332
  }
17942
- if (useFunctions) {
17943
- const existingContent = pathExists(envLocalPath) ? readSync(envLocalPath, { format: "text" }) || "" : "";
17944
- const hasAuthEmulatorHost = existingContent.includes(
17945
- "FIREBASE_AUTH_EMULATOR_HOST"
18333
+ const projectRoot = getRepoRoot();
18334
+ if (!projectRoot) {
18335
+ throw new DoNotDevError(
18336
+ "Could not determine repository root",
18337
+ "path-resolution-error"
17946
18338
  );
17947
- if (useAuth && !hasAuthEmulatorHost) {
17948
- const authEmulatorHost = "localhost:9099";
17949
- const newContent = existingContent ? `${existingContent}
17950
- FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
17951
- ` : `FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
17952
- `;
17953
- writeSync(envLocalPath, newContent);
17954
- log.debug("Set FIREBASE_AUTH_EMULATOR_HOST in functions/.env.local");
17955
- } else if (!useAuth && hasAuthEmulatorHost) {
17956
- const lines = existingContent.split("\n");
17957
- const filteredLines = lines.filter(
17958
- (line) => !line.trim().startsWith("FIREBASE_AUTH_EMULATOR_HOST=")
17959
- );
17960
- const newContent = filteredLines.join("\n");
17961
- writeSync(envLocalPath, newContent);
17962
- log.debug(
17963
- "Removed FIREBASE_AUTH_EMULATOR_HOST from functions/.env.local"
18339
+ }
18340
+ const app = await selectApp(projectRoot, parsedAppName);
18341
+ if (!app) {
18342
+ return 1;
18343
+ }
18344
+ const appDir = app.path;
18345
+ checkConfigPlaceholders(appDir);
18346
+ const firebaseConfig = validateFirebaseJson2(appDir);
18347
+ const hasFunctions = app.hasFunctions || firebaseConfig.hasFunctions;
18348
+ const hasFrontend = app.framework !== "unknown";
18349
+ let buildType = parsedBuildType;
18350
+ if (!buildType) {
18351
+ const choices = [];
18352
+ if (hasFrontend) {
18353
+ choices.push({
18354
+ title: "Frontend only",
18355
+ value: "frontend",
18356
+ hint: "Build app bundle"
18357
+ });
18358
+ }
18359
+ if (hasFunctions) {
18360
+ choices.push({
18361
+ title: "Functions only",
18362
+ value: "functions",
18363
+ hint: "Build cloud functions"
18364
+ });
18365
+ }
18366
+ if (hasFrontend && hasFunctions) {
18367
+ choices.push({
18368
+ title: "Both frontend and functions",
18369
+ value: "both",
18370
+ hint: "Build everything"
18371
+ });
18372
+ }
18373
+ if (choices.length === 0) {
18374
+ log.error("No build targets found. App must have frontend or functions.");
18375
+ throw new DoNotDevError("No build targets found", "validation-error");
18376
+ }
18377
+ if (choices.length === 1) {
18378
+ buildType = choices[0].value;
18379
+ Me(`Building: ${choices[0].title}`, "Auto-selected");
18380
+ } else {
18381
+ buildType = await askForSelection(
18382
+ "What would you like to build?",
18383
+ choices
17964
18384
  );
17965
18385
  }
17966
18386
  }
17967
- log.info("Building functions...");
17968
- const buildResult = spawnSync3("bun", ["run", "build"], {
17969
- cwd: functionsDir,
17970
- stdio: "pipe",
17971
- env: createEmulatorEnv(app.path, app.framework, {
17972
- useEmulatorAuth: useAuth,
17973
- useEmulatorFirestore: useFirestore
17974
- })
17975
- });
17976
- if (buildResult.status !== 0) {
17977
- if (buildResult.stdout) {
17978
- process.stdout.write(buildResult.stdout);
18387
+ if (buildType === "frontend" || buildType === "both") {
18388
+ if (!hasFrontend) {
18389
+ log.error(
18390
+ "Frontend build requested but app has no frontend configuration."
18391
+ );
18392
+ throw new DoNotDevError(
18393
+ "Frontend build requested but app has no frontend configuration",
18394
+ "validation-error"
18395
+ );
17979
18396
  }
17980
- if (buildResult.stderr) {
17981
- process.stderr.write(buildResult.stderr);
18397
+ log.info(`Building ${app.name} frontend...
18398
+ `);
18399
+ const turboArgs = ["build", "--filter", app.packageName];
18400
+ const env = {
18401
+ ...process.env,
18402
+ DNDEV_APP_ROOT: app.path
18403
+ };
18404
+ const result = spawnSync4("bunx", ["turbo", ...turboArgs], {
18405
+ stdio: "inherit",
18406
+ env,
18407
+ cwd: projectRoot
18408
+ });
18409
+ if (result.status !== 0) {
18410
+ return result.status || 1;
17982
18411
  }
17983
- log.error("Functions build failed. Fix errors and try again.");
17984
- return 1;
17985
18412
  }
17986
- const appFirebaseJson = joinPath(app.path, "firebase.json");
17987
- let emulatorConfig = null;
17988
- if (pathExists(appFirebaseJson)) {
18413
+ if (buildType === "functions" || buildType === "both") {
18414
+ if (!hasFunctions) {
18415
+ log.error(
18416
+ "Functions build requested but app has no functions directory."
18417
+ );
18418
+ throw new DoNotDevError(
18419
+ "Functions build requested but app has no functions directory",
18420
+ "validation-error"
18421
+ );
18422
+ }
18423
+ const functionsDir = joinPath(appDir, "functions");
18424
+ if (!pathExists(functionsDir)) {
18425
+ log.error(`Functions directory not found: ${functionsDir}`);
18426
+ throw new DoNotDevError(
18427
+ `Functions directory not found: ${functionsDir}`,
18428
+ "file-not-found"
18429
+ );
18430
+ }
18431
+ log.info(`Building ${app.name} functions...
18432
+ `);
18433
+ const s = Y2();
18434
+ s.start("Building functions...");
17989
18435
  try {
17990
- const firebaseConfig = readFirebaseJson(appFirebaseJson);
17991
- if (firebaseConfig.emulators) {
17992
- emulatorConfig = firebaseConfig.emulators;
17993
- }
17994
- } catch {
18436
+ execSync2("bun run build", {
18437
+ cwd: functionsDir,
18438
+ stdio: "inherit"
18439
+ });
18440
+ s.stop("Functions built");
18441
+ } catch (error2) {
18442
+ s.stop("\u274C Functions build failed");
18443
+ throw DoNotDevError.from(
18444
+ error2,
18445
+ "Functions build failed",
18446
+ "cli-execution-error"
18447
+ );
17995
18448
  }
17996
18449
  }
17997
- const ports = getEmulatorPorts(emulatorConfig);
17998
- if (ports.length > 0) {
17999
- log.info("Clearing ports...");
18000
- killPorts(ports);
18001
- }
18002
- const emulatorsToStart = [];
18003
- if (useFunctions) emulatorsToStart.push("functions");
18004
- if (useAuth) emulatorsToStart.push("auth");
18005
- if (useFirestore) emulatorsToStart.push("firestore");
18006
- if (emulatorConfig?.hosting) {
18007
- emulatorsToStart.push("hosting");
18008
- }
18009
- const emulatorArgs = ["emulators:start"];
18010
- if (emulatorsToStart.length > 0) {
18011
- emulatorArgs.push("--only", emulatorsToStart.join(","));
18012
- }
18013
- if (debug) {
18014
- emulatorArgs.push("--debug");
18450
+ log.success(`Build complete for ${app.name}`);
18451
+ return 0;
18452
+ }
18453
+
18454
+ // packages/tooling/src/apps/dev.ts
18455
+ init_utils();
18456
+ init_app_selector();
18457
+ init_cli_output();
18458
+ init_errors();
18459
+ init_pathResolver();
18460
+ import { execSync as execSync3 } from "node:child_process";
18461
+ import { platform as platform2 } from "node:os";
18462
+ var SIGNAL_EXIT_CODES = {
18463
+ SIGINT: 130,
18464
+ // 128 + 2
18465
+ SIGTERM: 143
18466
+ // 128 + 15
18467
+ };
18468
+ async function main2() {
18469
+ const args = process.argv.slice(2);
18470
+ const appName = args[0] && args[0] !== "dev" ? args[0] : void 0;
18471
+ const projectRoot = getRepoRoot();
18472
+ if (!projectRoot) {
18473
+ throw new DoNotDevError(
18474
+ "Could not determine repository root",
18475
+ "path-resolution-error"
18476
+ );
18015
18477
  }
18016
- const firebaseToolsPath = joinPath(
18017
- projectRoot,
18018
- "node_modules",
18019
- "firebase-tools",
18020
- "lib",
18021
- "bin",
18022
- "firebase.js"
18023
- );
18024
- const emulatorCmd = `node "${firebaseToolsPath}" ${emulatorArgs.join(" ")}`;
18025
- const projectId = discoverFirebaseProjectId(app.path);
18026
- const region = process.env.FIREBASE_REGION || "europe-west1";
18027
- const concurrentlyArgs = [
18028
- "--kill-others-on-fail",
18029
- "--prefix-colors",
18030
- useStripe ? "cyan,green,yellow" : "cyan,green",
18031
- "--prefix",
18032
- "[{name}]",
18033
- "--names",
18034
- useStripe ? "emulators,dev,stripe" : "emulators,dev",
18035
- emulatorCmd,
18036
- `bunx turbo dev --filter=${app.packageName}`
18037
- ];
18038
- if (useStripe && projectId) {
18039
- const stripeWebhookUrl = `http://localhost:5001/${projectId}/${region}/stripeWebhook`;
18040
- concurrentlyArgs.push(`stripe listen --forward-to ${stripeWebhookUrl}`);
18041
- log.info("");
18042
- log.info("Stripe webhook forwarding will start automatically");
18043
- log.info(` Webhook URL: ${stripeWebhookUrl}`);
18044
- log.info(" To trigger test events, run in another terminal:");
18045
- log.info(" stripe trigger checkout.session.completed");
18046
- log.info("");
18478
+ const app = await selectApp(projectRoot, appName);
18479
+ if (!app) {
18480
+ return 1;
18047
18481
  }
18048
- const isWindows = platform3() === "win32";
18482
+ log.info(`Starting dev server for ${app.name}...
18483
+ `);
18484
+ const turboArgs = ["dev", "--filter", app.packageName];
18485
+ const isWindows = platform2() === "win32";
18049
18486
  const childProcess = spawnCrossPlatform(
18050
18487
  "bunx",
18051
- ["concurrently", ...concurrentlyArgs],
18488
+ ["turbo", ...turboArgs],
18052
18489
  {
18053
18490
  stdio: "inherit",
18054
- env: createEmulatorEnv(app.path, app.framework, {
18055
- useEmulatorAuth: useAuth,
18056
- useEmulatorFirestore: useFirestore
18057
- }),
18058
- cwd: app.path
18491
+ env: createAppEnv(app.path),
18492
+ cwd: projectRoot
18059
18493
  }
18060
18494
  );
18061
- const SIGNAL_EXIT_CODES3 = {
18062
- SIGINT: 130,
18063
- SIGTERM: 143
18064
- };
18065
18495
  const cleanup = (signal) => {
18066
18496
  if (!childProcess.pid) return;
18067
18497
  log.debug(`Received ${signal}, cleaning up processes...`);
18068
18498
  if (isWindows) {
18069
18499
  try {
18070
- execSync4(`taskkill /F /T /PID ${childProcess.pid}`, {
18500
+ execSync3(`taskkill /F /T /PID ${childProcess.pid}`, {
18071
18501
  stdio: "ignore",
18072
18502
  timeout: 2e3
18073
18503
  });
@@ -18079,7 +18509,7 @@ FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18079
18509
  } catch {
18080
18510
  }
18081
18511
  try {
18082
- execSync4(`pkill -P ${childProcess.pid}`, {
18512
+ execSync3(`pkill -P ${childProcess.pid}`, {
18083
18513
  stdio: "ignore",
18084
18514
  timeout: 1e3
18085
18515
  });
@@ -18093,7 +18523,7 @@ FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18093
18523
  const handler = () => {
18094
18524
  cleanup(signal);
18095
18525
  handlers.forEach((h2) => h2());
18096
- process.exit(SIGNAL_EXIT_CODES3[signal] ?? 130);
18526
+ process.exit(SIGNAL_EXIT_CODES[signal] ?? 130);
18097
18527
  };
18098
18528
  process.on(signal, handler);
18099
18529
  handlers.push(() => process.removeListener(signal, handler));
@@ -18103,66 +18533,403 @@ FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18103
18533
  handlers.forEach((h2) => h2());
18104
18534
  if (signal) {
18105
18535
  log.debug(`Process killed by signal: ${signal}`);
18106
- resolve4(SIGNAL_EXIT_CODES3[signal] ?? 130);
18536
+ resolve4(SIGNAL_EXIT_CODES[signal] ?? 130);
18107
18537
  } else {
18108
18538
  resolve4(code ?? 0);
18109
18539
  }
18110
18540
  });
18111
18541
  childProcess.on("error", (error2) => {
18112
18542
  handlers.forEach((h2) => h2());
18113
- log.error(`Failed to start Firebase emulators: ${error2.message}`);
18543
+ log.error(`Failed to start dev server: ${error2.message}`);
18114
18544
  resolve4(1);
18115
18545
  });
18116
18546
  });
18117
18547
  }
18118
18548
 
18119
- // packages/tooling/src/apps/emu-supabase.ts
18549
+ // packages/tooling/src/apps/emu.ts
18550
+ init_utils();
18551
+
18552
+ // packages/tooling/src/apps/emu-firebase.ts
18120
18553
  init_utils();
18554
+ init_cli_input();
18121
18555
  init_cli_output();
18122
- import { execSync as execSync5 } from "node:child_process";
18123
- import { platform as platform4 } from "node:os";
18124
- function isDockerRunning() {
18125
- try {
18126
- execSync5("docker info", { stdio: "pipe", timeout: 5e3 });
18127
- return true;
18128
- } catch {
18129
- return false;
18130
- }
18131
- }
18132
- async function startSupabase(app, _projectRoot) {
18133
- log.info(`Starting Supabase local stack + dev server for ${app.name}...
18134
- `);
18135
- if (!isDockerRunning()) {
18136
- log.error("Docker is not running. Supabase local dev requires Docker.");
18137
- log.error("Start Docker Desktop and try again.\n");
18138
- return 1;
18139
- }
18140
- try {
18141
- execSync5("supabase --version", { stdio: "pipe" });
18556
+ init_pathResolver();
18557
+ import { spawnSync as spawnSync5, execSync as execSync4 } from "node:child_process";
18558
+ import { platform as platform3 } from "node:os";
18559
+ init_typed_file_operations();
18560
+ function discoverFirebaseProjectId(appPath) {
18561
+ const firebasercPath = joinPath(appPath, ".firebaserc");
18562
+ if (pathExists(firebasercPath)) {
18563
+ try {
18564
+ const firebasercRaw = readSync(firebasercPath, { format: "json" });
18565
+ const firebaserc = firebasercRaw && typeof firebasercRaw === "object" ? firebasercRaw : null;
18566
+ if (firebaserc?.projects?.default) {
18567
+ return firebaserc.projects.default;
18568
+ }
18569
+ } catch {
18570
+ }
18571
+ }
18572
+ return process.env.FIREBASE_PROJECT_ID || null;
18573
+ }
18574
+ function killPorts(ports) {
18575
+ if (ports.length === 0) return;
18576
+ const isWindows = process.platform === "win32";
18577
+ for (const port of ports) {
18578
+ try {
18579
+ if (isWindows) {
18580
+ const findPort = execSync4(`netstat -ano | findstr :${port}`, {
18581
+ encoding: "utf-8"
18582
+ });
18583
+ const lines = findPort.trim().split("\n");
18584
+ const pids = /* @__PURE__ */ new Set();
18585
+ for (const line of lines) {
18586
+ const match = line.match(/\s+(\d+)\s*$/);
18587
+ if (match && match[1]) {
18588
+ pids.add(match[1]);
18589
+ }
18590
+ }
18591
+ for (const pid of Array.from(pids)) {
18592
+ try {
18593
+ execSync4(`taskkill /F /PID ${pid}`, { stdio: "ignore" });
18594
+ log.debug(`Killed process ${pid} on port ${port}`);
18595
+ } catch {
18596
+ }
18597
+ }
18598
+ } else {
18599
+ try {
18600
+ const output = execSync4(`lsof -ti:${port}`, {
18601
+ encoding: "utf-8"
18602
+ }).trim();
18603
+ if (output) {
18604
+ const pids = output.split("\n").filter(Boolean);
18605
+ for (const pid of pids) {
18606
+ try {
18607
+ execSync4(`kill -9 ${pid}`, { stdio: "ignore" });
18608
+ log.debug(`Killed process ${pid} on port ${port}`);
18609
+ } catch {
18610
+ }
18611
+ }
18612
+ }
18613
+ } catch {
18614
+ }
18615
+ }
18616
+ } catch {
18617
+ }
18618
+ }
18619
+ }
18620
+ function getEmulatorPorts(emulatorConfig) {
18621
+ const ports = [];
18622
+ if (emulatorConfig?.auth?.port) ports.push(emulatorConfig.auth.port);
18623
+ if (emulatorConfig?.functions?.port)
18624
+ ports.push(emulatorConfig.functions.port);
18625
+ if (emulatorConfig?.firestore?.port)
18626
+ ports.push(emulatorConfig.firestore.port);
18627
+ if (emulatorConfig?.hosting?.port) ports.push(emulatorConfig.hosting.port);
18628
+ if (emulatorConfig?.ui?.port) ports.push(emulatorConfig.ui.port);
18629
+ if (!emulatorConfig) {
18630
+ ports.push(4e3, 5001, 8080, 9099, 5e3);
18631
+ }
18632
+ return ports;
18633
+ }
18634
+ function loadEnvFile(filePath) {
18635
+ if (!pathExists(filePath)) return;
18636
+ try {
18637
+ const content = readSync(filePath, { format: "text" });
18638
+ if (!content) return;
18639
+ content.split("\n").forEach((line) => {
18640
+ const trimmed = line.trim();
18641
+ if (!trimmed || trimmed.startsWith("#")) return;
18642
+ const equalIndex = trimmed.indexOf("=");
18643
+ if (equalIndex === -1) return;
18644
+ const key = trimmed.substring(0, equalIndex).trim();
18645
+ const value = trimmed.substring(equalIndex + 1).trim().replace(/^["']|["']$/g, "");
18646
+ if (key && value) {
18647
+ process.env[key] = value;
18648
+ }
18649
+ });
18142
18650
  } catch {
18143
- log.error("Supabase CLI not found. Install it:");
18144
- log.error(" bun install -g supabase\n");
18651
+ }
18652
+ }
18653
+ async function startFirebase(app, projectRoot, options = {}) {
18654
+ const debug = options.debug ?? false;
18655
+ let selectedServices = options.selectedServices ?? [];
18656
+ const serviceChoices = [
18657
+ {
18658
+ title: "Auth",
18659
+ value: "auth",
18660
+ hint: "Firebase Auth emulator (for user authentication)"
18661
+ },
18662
+ {
18663
+ title: "Functions",
18664
+ value: "functions",
18665
+ hint: "Firebase Functions emulator (required for backend)"
18666
+ },
18667
+ {
18668
+ title: "Firestore",
18669
+ value: "firestore",
18670
+ hint: "Firestore emulator (for database)"
18671
+ },
18672
+ {
18673
+ title: "Stripe",
18674
+ value: "stripe",
18675
+ hint: "Stripe webhook forwarding (for payment testing)"
18676
+ }
18677
+ ];
18678
+ log.info(`Starting Firebase emulators + dev server for ${app.name}...
18679
+ `);
18680
+ if (selectedServices.length === 0) {
18681
+ selectedServices = await askForMultiSelection(
18682
+ "Which services do you want to run?",
18683
+ serviceChoices,
18684
+ [1, 2]
18685
+ // Default: Functions and Firestore
18686
+ );
18687
+ } else {
18688
+ log.info(`Selected services: ${selectedServices.join(", ")}
18689
+ `);
18690
+ }
18691
+ const useAuth = selectedServices.includes("auth");
18692
+ const useFunctions = selectedServices.includes("functions");
18693
+ const useFirestore = selectedServices.includes("firestore");
18694
+ const useStripe = selectedServices.includes("stripe");
18695
+ if (!useFunctions) {
18696
+ log.error("Functions emulator is required for Firebase apps.");
18145
18697
  return 1;
18146
18698
  }
18147
- const isWindows = platform4() === "win32";
18699
+ const functionsDir = app.functionsPath;
18700
+ const envLocalPath = joinPath(functionsDir, ".env.local");
18701
+ if (pathExists(envLocalPath)) {
18702
+ loadEnvFile(envLocalPath);
18703
+ log.debug("Loaded functions/.env.local for emulator context");
18704
+ } else {
18705
+ log.warn(
18706
+ "No .env.local found in functions directory. Emulator may lack required secrets."
18707
+ );
18708
+ }
18709
+ if (useFunctions) {
18710
+ const existingContent = pathExists(envLocalPath) ? readSync(envLocalPath, { format: "text" }) || "" : "";
18711
+ const hasAuthEmulatorHost = existingContent.includes(
18712
+ "FIREBASE_AUTH_EMULATOR_HOST"
18713
+ );
18714
+ if (useAuth && !hasAuthEmulatorHost) {
18715
+ const authEmulatorHost = "localhost:9099";
18716
+ const newContent = existingContent ? `${existingContent}
18717
+ FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18718
+ ` : `FIREBASE_AUTH_EMULATOR_HOST=${authEmulatorHost}
18719
+ `;
18720
+ writeSync(envLocalPath, newContent);
18721
+ log.debug("Set FIREBASE_AUTH_EMULATOR_HOST in functions/.env.local");
18722
+ } else if (!useAuth && hasAuthEmulatorHost) {
18723
+ const lines = existingContent.split("\n");
18724
+ const filteredLines = lines.filter(
18725
+ (line) => !line.trim().startsWith("FIREBASE_AUTH_EMULATOR_HOST=")
18726
+ );
18727
+ const newContent = filteredLines.join("\n");
18728
+ writeSync(envLocalPath, newContent);
18729
+ log.debug(
18730
+ "Removed FIREBASE_AUTH_EMULATOR_HOST from functions/.env.local"
18731
+ );
18732
+ }
18733
+ }
18734
+ log.info("Building functions...");
18735
+ const buildResult = spawnSync5("bun", ["run", "build"], {
18736
+ cwd: functionsDir,
18737
+ stdio: "pipe",
18738
+ env: createEmulatorEnv(app.path, app.framework, {
18739
+ useEmulatorAuth: useAuth,
18740
+ useEmulatorFirestore: useFirestore
18741
+ })
18742
+ });
18743
+ if (buildResult.status !== 0) {
18744
+ if (buildResult.stdout) {
18745
+ process.stdout.write(buildResult.stdout);
18746
+ }
18747
+ if (buildResult.stderr) {
18748
+ process.stderr.write(buildResult.stderr);
18749
+ }
18750
+ log.error("Functions build failed. Fix errors and try again.");
18751
+ return 1;
18752
+ }
18753
+ const appFirebaseJson = joinPath(app.path, "firebase.json");
18754
+ let emulatorConfig = null;
18755
+ if (pathExists(appFirebaseJson)) {
18756
+ try {
18757
+ const firebaseConfig = readFirebaseJson(appFirebaseJson);
18758
+ if (firebaseConfig.emulators) {
18759
+ emulatorConfig = firebaseConfig.emulators;
18760
+ }
18761
+ } catch {
18762
+ }
18763
+ }
18764
+ const ports = getEmulatorPorts(emulatorConfig);
18765
+ if (ports.length > 0) {
18766
+ log.info("Clearing ports...");
18767
+ killPorts(ports);
18768
+ }
18769
+ const emulatorsToStart = [];
18770
+ if (useFunctions) emulatorsToStart.push("functions");
18771
+ if (useAuth) emulatorsToStart.push("auth");
18772
+ if (useFirestore) emulatorsToStart.push("firestore");
18773
+ if (emulatorConfig?.hosting) {
18774
+ emulatorsToStart.push("hosting");
18775
+ }
18776
+ const emulatorArgs = ["emulators:start"];
18777
+ if (emulatorsToStart.length > 0) {
18778
+ emulatorArgs.push("--only", emulatorsToStart.join(","));
18779
+ }
18780
+ if (debug) {
18781
+ emulatorArgs.push("--debug");
18782
+ }
18783
+ const firebaseToolsPath = joinPath(
18784
+ projectRoot,
18785
+ "node_modules",
18786
+ "firebase-tools",
18787
+ "lib",
18788
+ "bin",
18789
+ "firebase.js"
18790
+ );
18791
+ const emulatorCmd = `node "${firebaseToolsPath}" ${emulatorArgs.join(" ")}`;
18792
+ const projectId = discoverFirebaseProjectId(app.path);
18793
+ const region = process.env.FIREBASE_REGION || "europe-west1";
18148
18794
  const concurrentlyArgs = [
18149
18795
  "--kill-others-on-fail",
18150
18796
  "--prefix-colors",
18151
- "cyan,green",
18797
+ useStripe ? "cyan,green,yellow" : "cyan,green",
18152
18798
  "--prefix",
18153
18799
  "[{name}]",
18154
18800
  "--names",
18155
- "supabase,dev",
18156
- "supabase start",
18801
+ useStripe ? "emulators,dev,stripe" : "emulators,dev",
18802
+ emulatorCmd,
18157
18803
  `bunx turbo dev --filter=${app.packageName}`
18158
18804
  ];
18805
+ if (useStripe && projectId) {
18806
+ const stripeWebhookUrl = `http://localhost:5001/${projectId}/${region}/stripeWebhook`;
18807
+ concurrentlyArgs.push(`stripe listen --forward-to ${stripeWebhookUrl}`);
18808
+ log.info("");
18809
+ log.info("Stripe webhook forwarding will start automatically");
18810
+ log.info(` Webhook URL: ${stripeWebhookUrl}`);
18811
+ log.info(" To trigger test events, run in another terminal:");
18812
+ log.info(" stripe trigger checkout.session.completed");
18813
+ log.info("");
18814
+ }
18815
+ const isWindows = platform3() === "win32";
18159
18816
  const childProcess = spawnCrossPlatform(
18160
18817
  "bunx",
18161
18818
  ["concurrently", ...concurrentlyArgs],
18162
18819
  {
18163
18820
  stdio: "inherit",
18164
- cwd: app.path
18165
- }
18821
+ env: createEmulatorEnv(app.path, app.framework, {
18822
+ useEmulatorAuth: useAuth,
18823
+ useEmulatorFirestore: useFirestore
18824
+ }),
18825
+ cwd: app.path
18826
+ }
18827
+ );
18828
+ const SIGNAL_EXIT_CODES3 = {
18829
+ SIGINT: 130,
18830
+ SIGTERM: 143
18831
+ };
18832
+ const cleanup = (signal) => {
18833
+ if (!childProcess.pid) return;
18834
+ log.debug(`Received ${signal}, cleaning up processes...`);
18835
+ if (isWindows) {
18836
+ try {
18837
+ execSync4(`taskkill /F /T /PID ${childProcess.pid}`, {
18838
+ stdio: "ignore",
18839
+ timeout: 2e3
18840
+ });
18841
+ } catch {
18842
+ }
18843
+ } else {
18844
+ try {
18845
+ process.kill(childProcess.pid, signal);
18846
+ } catch {
18847
+ }
18848
+ try {
18849
+ execSync4(`pkill -P ${childProcess.pid}`, {
18850
+ stdio: "ignore",
18851
+ timeout: 1e3
18852
+ });
18853
+ } catch {
18854
+ }
18855
+ }
18856
+ };
18857
+ const signals = ["SIGINT", "SIGTERM"];
18858
+ const handlers = [];
18859
+ for (const signal of signals) {
18860
+ const handler = () => {
18861
+ cleanup(signal);
18862
+ handlers.forEach((h2) => h2());
18863
+ process.exit(SIGNAL_EXIT_CODES3[signal] ?? 130);
18864
+ };
18865
+ process.on(signal, handler);
18866
+ handlers.push(() => process.removeListener(signal, handler));
18867
+ }
18868
+ return new Promise((resolve4) => {
18869
+ childProcess.on("exit", (code, signal) => {
18870
+ handlers.forEach((h2) => h2());
18871
+ if (signal) {
18872
+ log.debug(`Process killed by signal: ${signal}`);
18873
+ resolve4(SIGNAL_EXIT_CODES3[signal] ?? 130);
18874
+ } else {
18875
+ resolve4(code ?? 0);
18876
+ }
18877
+ });
18878
+ childProcess.on("error", (error2) => {
18879
+ handlers.forEach((h2) => h2());
18880
+ log.error(`Failed to start Firebase emulators: ${error2.message}`);
18881
+ resolve4(1);
18882
+ });
18883
+ });
18884
+ }
18885
+
18886
+ // packages/tooling/src/apps/emu-supabase.ts
18887
+ init_utils();
18888
+ init_cli_output();
18889
+ import { execSync as execSync5 } from "node:child_process";
18890
+ import { platform as platform4 } from "node:os";
18891
+ function isDockerRunning() {
18892
+ try {
18893
+ execSync5("docker info", { stdio: "pipe", timeout: 5e3 });
18894
+ return true;
18895
+ } catch {
18896
+ return false;
18897
+ }
18898
+ }
18899
+ async function startSupabase(app, _projectRoot) {
18900
+ log.info(`Starting Supabase local stack + dev server for ${app.name}...
18901
+ `);
18902
+ if (!isDockerRunning()) {
18903
+ log.error("Docker is not running. Supabase local dev requires Docker.");
18904
+ log.error("Start Docker Desktop and try again.\n");
18905
+ return 1;
18906
+ }
18907
+ try {
18908
+ execSync5("supabase --version", { stdio: "pipe" });
18909
+ } catch {
18910
+ log.error("Supabase CLI not found. Install it:");
18911
+ log.error(" bun install -g supabase\n");
18912
+ return 1;
18913
+ }
18914
+ const isWindows = platform4() === "win32";
18915
+ const concurrentlyArgs = [
18916
+ "--kill-others-on-fail",
18917
+ "--prefix-colors",
18918
+ "cyan,green",
18919
+ "--prefix",
18920
+ "[{name}]",
18921
+ "--names",
18922
+ "supabase,dev",
18923
+ "supabase start",
18924
+ `bunx turbo dev --filter=${app.packageName}`
18925
+ ];
18926
+ const childProcess = spawnCrossPlatform(
18927
+ "bunx",
18928
+ ["concurrently", ...concurrentlyArgs],
18929
+ {
18930
+ stdio: "inherit",
18931
+ cwd: app.path
18932
+ }
18166
18933
  );
18167
18934
  const cleanup = () => {
18168
18935
  if (!childProcess.pid) return;
@@ -18333,7 +19100,7 @@ init_cli_output();
18333
19100
  init_errors();
18334
19101
  init_pathResolver();
18335
19102
  import {
18336
- spawnSync as spawnSync4,
19103
+ spawnSync as spawnSync6,
18337
19104
  execSync as execSync7
18338
19105
  } from "node:child_process";
18339
19106
  import { platform as platform6 } from "node:os";
@@ -18363,7 +19130,7 @@ async function main4() {
18363
19130
  if (!hasBuild) {
18364
19131
  log.info(`Build not found. Building ${app.name} first...
18365
19132
  `);
18366
- const buildResult = spawnSync4(
19133
+ const buildResult = spawnSync6(
18367
19134
  "bunx",
18368
19135
  ["turbo", "build", "--filter", app.packageName],
18369
19136
  {
@@ -18448,517 +19215,7 @@ init_utils();
18448
19215
  import { execSync as execSync9 } from "node:child_process";
18449
19216
 
18450
19217
  // packages/tooling/src/apps/deploy-frontend.ts
18451
- init_utils();
18452
-
18453
- // packages/tooling/src/utils/create-utils.ts
18454
- init_utils();
18455
- init_cli_output();
18456
- init_pathResolver();
18457
- init_typed_file_operations();
18458
- async function copyTemplateFiles(sourceDir, destDir, replacements) {
18459
- if (!pathExists(sourceDir)) {
18460
- log.warn(`Warning: Template directory does not exist: ${sourceDir}`);
18461
- return;
18462
- }
18463
- const files = await glob("**/*", {
18464
- cwd: sourceDir,
18465
- dot: true,
18466
- onlyFiles: true
18467
- });
18468
- for (const file of files) {
18469
- const sourcePath = joinPath(sourceDir, file);
18470
- let destFileName = file;
18471
- if (destFileName.endsWith(".example")) {
18472
- destFileName = destFileName.slice(0, -8);
18473
- }
18474
- const destPath = joinPath(destDir, destFileName);
18475
- await ensureDir(getDirname(destPath));
18476
- await copy(sourcePath, destPath);
18477
- if (await isTextFile(destPath)) {
18478
- await replacePlaceholders(destPath, replacements);
18479
- }
18480
- }
18481
- }
18482
- async function isTextFile(filePath) {
18483
- const binaryExtensions = [
18484
- ".png",
18485
- ".jpg",
18486
- ".jpeg",
18487
- ".gif",
18488
- ".ico",
18489
- ".woff",
18490
- ".woff2",
18491
- ".eot",
18492
- ".ttf",
18493
- ".otf",
18494
- ".zip",
18495
- ".pdf",
18496
- ".exe",
18497
- ".dll",
18498
- ".so",
18499
- ".bin",
18500
- ".dat",
18501
- ".class"
18502
- ];
18503
- if (binaryExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
18504
- return false;
18505
- const textExtensions = [
18506
- ".json",
18507
- ".js",
18508
- ".ts",
18509
- ".tsx",
18510
- ".jsx",
18511
- ".md",
18512
- ".yml",
18513
- ".yaml",
18514
- ".html",
18515
- ".css",
18516
- ".scss",
18517
- ".env",
18518
- ".gitignore",
18519
- ".npmrc",
18520
- ".eslintrc",
18521
- ".prettierrc",
18522
- ".firebase",
18523
- ".txt"
18524
- ];
18525
- if (textExtensions.some((ext) => filePath.toLowerCase().endsWith(ext)))
18526
- return true;
18527
- try {
18528
- const buffer = await read(filePath, { format: "buffer" });
18529
- if (buffer.length === 0) return true;
18530
- for (let i = 0; i < Math.min(buffer.length, 1e3); i++) {
18531
- if (buffer[i] === 0) return false;
18532
- }
18533
- return true;
18534
- } catch {
18535
- return false;
18536
- }
18537
- }
18538
- async function replacePlaceholders(filePath, replacements) {
18539
- try {
18540
- let content = await read(filePath, { format: "text" });
18541
- if (typeof content !== "string") {
18542
- content = typeof content === "object" ? JSON.stringify(content, null, 2) : String(content);
18543
- }
18544
- content = processConditionalSections(content, replacements);
18545
- content = processArrayIterations(content, replacements);
18546
- for (const [key, value] of Object.entries(replacements)) {
18547
- if (value !== void 0) {
18548
- const regex = new RegExp(`{{${key}}}`, "g");
18549
- if (typeof value === "string") {
18550
- content = content.replace(regex, value);
18551
- }
18552
- }
18553
- }
18554
- await write(filePath, content, { overwrite: true });
18555
- } catch (error2) {
18556
- log.warn(
18557
- `Warning: Could not process file ${filePath}: ${error2.message || "Unknown error"}`
18558
- );
18559
- }
18560
- }
18561
- function processConditionalSections(content, replacements) {
18562
- Object.keys(replacements).forEach((key) => {
18563
- const value = replacements[key];
18564
- const isTruthy = value === true || value === "true";
18565
- const positivePattern = new RegExp(
18566
- `{{#${key}}}([\\s\\S]*?){{/${key}}}`,
18567
- "g"
18568
- );
18569
- if (isTruthy) {
18570
- content = content.replace(positivePattern, (match, inner) => inner);
18571
- } else {
18572
- content = content.replace(positivePattern, "");
18573
- }
18574
- const negativePattern = new RegExp(
18575
- `{{\\^${key}}}([\\s\\S]*?){{/${key}}}`,
18576
- "g"
18577
- );
18578
- if (!isTruthy) {
18579
- content = content.replace(negativePattern, (match, inner) => inner);
18580
- } else {
18581
- content = content.replace(negativePattern, "");
18582
- }
18583
- });
18584
- return content;
18585
- }
18586
- function processArrayIterations(content, replacements) {
18587
- const appNamesPattern = /{{#appNames}}([\s\S]*?){{\/appNames}}/g;
18588
- if (replacements.appNames && Array.isArray(replacements.appNames)) {
18589
- const appNames = replacements.appNames;
18590
- content = content.replace(appNamesPattern, (match, templateContent) => {
18591
- return appNames.map((appName) => templateContent.replace(/{{\.}}/g, appName)).join("");
18592
- });
18593
- } else {
18594
- content = content.replace(appNamesPattern, "");
18595
- }
18596
- return content;
18597
- }
18598
- function isValidFileName(name) {
18599
- return typeof name === "string" && /^[a-zA-Z0-9_-]+$/.test(name);
18600
- }
18601
- var RESERVED_APP_NAMES = ["demo", "dndev"];
18602
- function isReservedAppName(name) {
18603
- return RESERVED_APP_NAMES.includes(
18604
- name.toLowerCase()
18605
- );
18606
- }
18607
- async function updateRootPackageJson(rootDir, appNames) {
18608
- const packageJsonPath = joinPath(rootDir, "package.json");
18609
- if (!pathExists(packageJsonPath)) {
18610
- log.warn("Root package.json not found, skipping script updates");
18611
- return;
18612
- }
18613
- try {
18614
- const packageJson = await read(packageJsonPath, { format: "json" });
18615
- packageJson.scripts = packageJson.scripts || {};
18616
- } catch (error2) {
18617
- log.warn(
18618
- `Warning: Could not update root package.json: ${error2.message || "Unknown error"}`
18619
- );
18620
- }
18621
- }
18622
- async function mergeRootPackageJson(rootDir, allAppNames, options = {}) {
18623
- const packageJsonPath = joinPath(rootDir, "package.json");
18624
- if (!pathExists(packageJsonPath)) {
18625
- log.warn("Root package.json not found, skipping merge");
18626
- return;
18627
- }
18628
- try {
18629
- const packageJson = await read(packageJsonPath, { format: "json" });
18630
- packageJson.scripts = packageJson.scripts || {};
18631
- } catch (error2) {
18632
- log.warn(
18633
- `Warning: Could not merge root package.json: ${error2.message || "Unknown error"}`
18634
- );
18635
- }
18636
- }
18637
- async function mergeRootTsConfig(rootDir, allAppNames, includeFunctions = false) {
18638
- const tsconfigPath = joinPath(rootDir, "tsconfig.json");
18639
- if (!pathExists(tsconfigPath)) {
18640
- log.warn("Root tsconfig.json not found, skipping merge");
18641
- return;
18642
- }
18643
- try {
18644
- const tsconfig = readTsConfigJson(tsconfigPath);
18645
- tsconfig.references = tsconfig.references || [];
18646
- const existingPaths = new Set(
18647
- tsconfig.references.map((ref) => ref.path)
18648
- );
18649
- let updated = false;
18650
- for (const appName of allAppNames) {
18651
- const appPath = `${appName}-app`;
18652
- if (!existingPaths.has(appPath)) {
18653
- tsconfig.references.push({ path: appPath });
18654
- updated = true;
18655
- }
18656
- }
18657
- if (includeFunctions && !existingPaths.has("functions")) {
18658
- tsconfig.references.push({ path: "functions" });
18659
- updated = true;
18660
- }
18661
- if (updated) {
18662
- await write(tsconfigPath, tsconfig, { format: "json", overwrite: true });
18663
- log.info("Merged root tsconfig.json");
18664
- }
18665
- } catch (error2) {
18666
- log.warn(
18667
- `Warning: Could not merge root tsconfig.json: ${error2.message || "Unknown error"}`
18668
- );
18669
- }
18670
- }
18671
- async function mergeRootTurboJson(rootDir) {
18672
- const turboJsonPath = joinPath(rootDir, "turbo.json");
18673
- if (!pathExists(turboJsonPath)) {
18674
- log.warn("Root turbo.json not found, skipping merge");
18675
- return;
18676
- }
18677
- try {
18678
- const turboJson = readTurboJson(turboJsonPath);
18679
- if (!turboJson) {
18680
- throw new Error(
18681
- `turbo.json is empty or invalid JSON at ${turboJsonPath}`
18682
- );
18683
- }
18684
- turboJson.tasks = turboJson.tasks || {};
18685
- const defaultTasks = {
18686
- build: {
18687
- dependsOn: ["^build"],
18688
- outputs: ["*/dist/**", "!**/node_modules/**"]
18689
- },
18690
- preview: {
18691
- dependsOn: ["build"],
18692
- cache: false,
18693
- persistent: true
18694
- },
18695
- test: {
18696
- dependsOn: ["^build"],
18697
- outputs: ["coverage/**"]
18698
- },
18699
- lint: {
18700
- outputs: []
18701
- },
18702
- dev: {
18703
- cache: false,
18704
- persistent: true
18705
- },
18706
- clean: {
18707
- cache: false
18708
- }
18709
- };
18710
- let updated = false;
18711
- for (const [taskName, taskConfig] of Object.entries(defaultTasks)) {
18712
- if (!turboJson.tasks[taskName]) {
18713
- turboJson.tasks[taskName] = taskConfig;
18714
- updated = true;
18715
- }
18716
- }
18717
- if (!turboJson.globalDependencies) {
18718
- turboJson.globalDependencies = ["**/.env.*local"];
18719
- updated = true;
18720
- }
18721
- if (updated) {
18722
- await write(turboJsonPath, turboJson, {
18723
- format: "json",
18724
- overwrite: true
18725
- });
18726
- log.info("Merged root turbo.json");
18727
- }
18728
- } catch (error2) {
18729
- log.warn(
18730
- `Warning: Could not merge root turbo.json: ${error2 instanceof Error ? error2.message : String(error2)}`
18731
- );
18732
- }
18733
- }
18734
-
18735
- // packages/tooling/src/utils/matrix.ts
18736
- init_utils();
18737
- init_pathResolver();
18738
- import { createRequire as createRequire4 } from "node:module";
18739
- var cachedMatrix = null;
18740
- function getMatrixPath(mode) {
18741
- try {
18742
- const require3 = createRequire4(import.meta.url);
18743
- const resolved = require3.resolve("@donotdev/cli/dependencies-matrix.json");
18744
- if (pathExists(resolved)) {
18745
- return resolved;
18746
- }
18747
- } catch {
18748
- }
18749
- const executionMode = mode || detectExecutionMode();
18750
- if (executionMode === "development") {
18751
- const templatesRoot = getTemplatesRoot();
18752
- const devPath = normalizePath(
18753
- templatesRoot,
18754
- "..",
18755
- "dependencies-matrix.json"
18756
- );
18757
- if (pathExists(devPath)) {
18758
- return devPath;
18759
- }
18760
- }
18761
- return null;
18762
- }
18763
- function getCliVersion(mode) {
18764
- try {
18765
- const require3 = createRequire4(import.meta.url);
18766
- const packageJsonPath = require3.resolve("@donotdev/cli/package.json");
18767
- const pkg = readSync(packageJsonPath, { format: "json" });
18768
- return String(pkg?.version || "0.0.0");
18769
- } catch {
18770
- }
18771
- const executionMode = mode || detectExecutionMode();
18772
- if (executionMode === "development") {
18773
- const templatesRoot = getTemplatesRoot();
18774
- const cliPackageJson = normalizePath(templatesRoot, "..", "package.json");
18775
- if (pathExists(cliPackageJson)) {
18776
- const pkg = readSync(cliPackageJson, { format: "json" });
18777
- return String(pkg?.version || "0.0.0");
18778
- }
18779
- }
18780
- return "0.0.0";
18781
- }
18782
- function loadMatrix(mode) {
18783
- if (cachedMatrix) return cachedMatrix;
18784
- const matrixPath = getMatrixPath(mode);
18785
- if (!matrixPath) {
18786
- return null;
18787
- }
18788
- const content = readSync(matrixPath, { format: "json" });
18789
- if (!content) {
18790
- return null;
18791
- }
18792
- cachedMatrix = {
18793
- matrix: content,
18794
- cliVersion: getCliVersion(mode)
18795
- };
18796
- return cachedMatrix;
18797
- }
18798
- function resolveGroup(groupName, matrix) {
18799
- return matrix.groups[groupName]?.packages || {};
18800
- }
18801
- function resolveGroups(groupNames, matrix) {
18802
- const result = {};
18803
- for (const groupName of groupNames) {
18804
- Object.assign(result, resolveGroup(groupName, matrix));
18805
- }
18806
- return result;
18807
- }
18808
-
18809
- // packages/tooling/src/utils/scaffolding-questionnaire.ts
18810
- init_utils();
18811
- var APP_QUESTIONNAIRE = [
18812
- {
18813
- id: "framework",
18814
- question: "Which framework?",
18815
- type: "select",
18816
- defaultValue: "vite",
18817
- choices: [
18818
- {
18819
- title: "Vite \u2014 SPA/SaaS (client-side rendering, fast dev)",
18820
- value: "vite"
18821
- },
18822
- {
18823
- title: "Next.js \u2014 Static content/SEO (SSR, SSG) \u2014 BETA",
18824
- value: "nextjs"
18825
- },
18826
- {
18827
- title: "Expo \u2014 Mobile app (iOS + Android)",
18828
- value: "expo"
18829
- }
18830
- ]
18831
- },
18832
- {
18833
- id: "host",
18834
- question: "Where will you host?",
18835
- type: "select",
18836
- condition: (answers) => answers.framework !== "expo",
18837
- defaultValue: (answers) => {
18838
- return answers.framework === "nextjs" ? "vercel" : "none";
18839
- },
18840
- choices: [
18841
- { title: "None \u2014 no hosting config", value: "none" },
18842
- { title: "Vercel \u2014 edge CDN + serverless", value: "vercel" },
18843
- { title: "Firebase Hosting \u2014 Google CDN", value: "firebase" }
18844
- ]
18845
- },
18846
- {
18847
- id: "functions",
18848
- question: "Serverless functions?",
18849
- type: "select",
18850
- defaultValue: "none",
18851
- // Choices filtered dynamically based on host
18852
- choices: [
18853
- { title: "None", value: "none" },
18854
- { title: "Vercel Functions \u2014 edge + node.js", value: "vercel" },
18855
- { title: "Firebase Functions \u2014 Google Cloud", value: "firebase" },
18856
- { title: "Supabase Edge Functions \u2014 Deno", value: "supabase" }
18857
- ],
18858
- choicesFilter: (answers) => {
18859
- const host = answers.host ?? "none";
18860
- const framework = answers.framework;
18861
- if (framework === "expo") return ["none", "firebase", "supabase"];
18862
- if (host === "firebase") return ["none", "firebase"];
18863
- if (host === "vercel") return ["none", "vercel", "supabase"];
18864
- return ["none", "vercel", "firebase", "supabase"];
18865
- }
18866
- },
18867
- {
18868
- id: "backend",
18869
- question: "Backend / BaaS provider?",
18870
- type: "select",
18871
- defaultValue: (answers) => {
18872
- if (answers.functions === "firebase") return "firebase";
18873
- if (answers.functions === "supabase") return "supabase";
18874
- return "none";
18875
- },
18876
- choices: [
18877
- { title: "None \u2014 frontend only", value: "none" },
18878
- {
18879
- title: "Firebase \u2014 Auth + Firestore + Storage",
18880
- value: "firebase"
18881
- },
18882
- {
18883
- title: "Supabase \u2014 Postgres + Auth + Storage",
18884
- value: "supabase"
18885
- }
18886
- ],
18887
- choicesFilter: (answers) => {
18888
- const functions = answers.functions ?? "none";
18889
- if (functions === "firebase") return ["none", "firebase"];
18890
- if (functions === "supabase") return ["none", "supabase"];
18891
- if (functions === "vercel") return ["none"];
18892
- return ["none", "firebase", "supabase"];
18893
- }
18894
- }
18895
- ];
18896
- var PROJECT_QUESTIONNAIRE = [
18897
- {
18898
- id: "projectName",
18899
- question: "Project name",
18900
- type: "input",
18901
- defaultValue: "my-project"
18902
- },
18903
- {
18904
- id: "appNames",
18905
- question: `App name(s) (comma-separated for multiple, e.g., web, admin) - '${RESERVED_APP_NAMES.join("', '")}' reserved`,
18906
- type: "input",
18907
- defaultValue: "web"
18908
- }
18909
- ];
18910
- function aggregateRequirements(answers) {
18911
- const hasBackend = answers.backend && answers.backend !== "none" || answers.functions && answers.functions !== "none";
18912
- const requirements = {
18913
- entities: [],
18914
- // Entities created in apps/<app>/entities/ (v1), root entities/ for v2
18915
- billing: true,
18916
- // Always on (useStripeBillingSafe handles missing package)
18917
- backend: hasBackend,
18918
- features: [],
18919
- template: "vite",
18920
- // Only Vite for now
18921
- userAuth: "social"
18922
- // Always on (useAuthSafe handles missing package)
18923
- };
18924
- return requirements;
18925
- }
18926
- async function runQuestionnaire(questions, initialAnswers, showWIP, askFor) {
18927
- const answers = { ...initialAnswers };
18928
- for (const question of questions) {
18929
- if (answers[question.id] !== void 0) continue;
18930
- if (question.condition && !question.condition(answers)) continue;
18931
- if (question.dependsOn && !answers[question.dependsOn]) continue;
18932
- let answer;
18933
- const resolvedDefault = typeof question.defaultValue === "function" ? question.defaultValue(answers) : question.defaultValue;
18934
- switch (question.type) {
18935
- case "select":
18936
- case "multi-select": {
18937
- let choices = question.choices || [];
18938
- if (!showWIP) {
18939
- choices = choices.filter((choice) => !choice.wip);
18940
- }
18941
- if (question.choicesFilter) {
18942
- const allowed = question.choicesFilter(answers);
18943
- choices = choices.filter((c) => allowed.includes(c.value));
18944
- }
18945
- if (choices.length === 0) continue;
18946
- answer = await askFor.selection(question.question, choices);
18947
- break;
18948
- }
18949
- case "confirm":
18950
- answer = await askFor.confirmation(question.question, resolvedDefault);
18951
- break;
18952
- case "input":
18953
- answer = await askFor.input(question.question, resolvedDefault);
18954
- break;
18955
- }
18956
- answers[question.id] = answer;
18957
- }
18958
- return answers;
18959
- }
18960
-
18961
- // packages/tooling/src/apps/deploy-frontend.ts
19218
+ init_utils();
18962
19219
  async function deployFrontend(appDir, serviceAccountPath, projectId, config) {
18963
19220
  const s = Y2();
18964
19221
  s.start("Deploying frontend to Firebase Hosting...");
@@ -18992,7 +19249,7 @@ async function deployFrontend(appDir, serviceAccountPath, projectId, config) {
18992
19249
  // packages/tooling/src/apps/deploy-functions.ts
18993
19250
  init_utils();
18994
19251
  var import_yaml = __toESM(require_dist(), 1);
18995
- import { execSync as execSync8, spawnSync as spawnSync6 } from "node:child_process";
19252
+ import { execSync as execSync8, spawnSync as spawnSync7 } from "node:child_process";
18996
19253
  init_cli_tools();
18997
19254
  init_pathResolver();
18998
19255
  init_typed_file_operations();
@@ -19179,7 +19436,7 @@ function updateCloudRunIAM(functionNames, projectId, region, serviceAccountPath,
19179
19436
  let failCount = 0;
19180
19437
  for (const funcName of functionNames) {
19181
19438
  try {
19182
- const result = spawnSync6(
19439
+ const result = spawnSync7(
19183
19440
  "gcloud",
19184
19441
  [
19185
19442
  "run",
@@ -19297,7 +19554,7 @@ async function autoSyncSecrets(functionsDir, projectId, config) {
19297
19554
  let failCount = 0;
19298
19555
  for (const { key, value } of secrets) {
19299
19556
  try {
19300
- const result = spawnSync6(
19557
+ const result = spawnSync7(
19301
19558
  firebaseCmd,
19302
19559
  ["functions:secrets:set", key, "--project", projectId],
19303
19560
  {
@@ -19482,244 +19739,6 @@ async function deployRules(appDir, serviceAccountPath, projectId, config, option
19482
19739
  s.stop(`${targetNames} deployed successfully`);
19483
19740
  }
19484
19741
 
19485
- // packages/tooling/src/apps/deploy-utils.ts
19486
- init_utils();
19487
- import { spawnSync as spawnSync7 } from "node:child_process";
19488
- init_error_handling();
19489
- init_pathResolver();
19490
- init_typed_file_operations();
19491
- function detectAvailableApps() {
19492
- const currentDir = process.cwd();
19493
- const appsDir = joinPath(currentDir, "apps");
19494
- if (!pathExists(appsDir)) {
19495
- return [];
19496
- }
19497
- return readdirSync2(appsDir).filter((item) => {
19498
- const itemPath = joinPath(appsDir, item);
19499
- const stat2 = statSync2(itemPath);
19500
- return stat2?.isDirectory() === true;
19501
- }).filter((app) => {
19502
- const appDir = joinPath(appsDir, app);
19503
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
19504
- const supabaseDir = joinPath(appDir, "supabase");
19505
- const vercelJsonPath = joinPath(appDir, "vercel.json");
19506
- return pathExists(firebaseJsonPath) || pathExists(supabaseDir) || pathExists(vercelJsonPath);
19507
- }).sort();
19508
- }
19509
- function detectAppDir(appName) {
19510
- const currentDir = process.cwd();
19511
- const appDir = joinPath(currentDir, "apps", appName);
19512
- if (!pathExists(appDir)) {
19513
- throw new DoNotDevError(
19514
- `App directory not found: ${appDir}`,
19515
- "file-not-found",
19516
- { context: { appName, expectedPath: appDir } }
19517
- );
19518
- }
19519
- return appDir;
19520
- }
19521
- function validateServiceAccount(appDir, options) {
19522
- const keyFileName = options?.staging ? "service-account-key.staging.json" : "service-account-key.json";
19523
- const rootKeyPath = joinPath(appDir, keyFileName);
19524
- const functionsDir = joinPath(appDir, "functions");
19525
- const functionsKeyPath = joinPath(functionsDir, keyFileName);
19526
- const keyPath = pathExists(rootKeyPath) ? rootKeyPath : functionsKeyPath;
19527
- const errors = [];
19528
- if (!pathExists(keyPath)) {
19529
- return {
19530
- valid: false,
19531
- info: {
19532
- path: keyPath,
19533
- projectId: "",
19534
- clientEmail: "",
19535
- valid: false,
19536
- errors: [
19537
- `Service account key file not found. Checked:`,
19538
- ` - ${rootKeyPath}`,
19539
- ` - ${functionsKeyPath}`
19540
- ]
19541
- }
19542
- };
19543
- }
19544
- try {
19545
- const keyData = readServiceAccountKey(keyPath);
19546
- return {
19547
- valid: true,
19548
- info: {
19549
- path: keyPath,
19550
- projectId: keyData.project_id,
19551
- clientEmail: keyData.client_email,
19552
- valid: true,
19553
- errors: []
19554
- }
19555
- };
19556
- } catch (error2) {
19557
- return {
19558
- valid: false,
19559
- info: {
19560
- path: keyPath,
19561
- projectId: "",
19562
- clientEmail: "",
19563
- valid: false,
19564
- errors: [`Invalid service account key: ${getErrorMessage(error2)}`]
19565
- }
19566
- };
19567
- }
19568
- }
19569
- function validateFirebaseJson2(appDir) {
19570
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
19571
- if (!pathExists(firebaseJsonPath)) {
19572
- return {
19573
- valid: false,
19574
- hasHosting: false,
19575
- hasFunctions: false,
19576
- hasFirestoreRules: false,
19577
- hasFirestoreIndexes: false,
19578
- hasStorageRules: false,
19579
- errors: [`firebase.json not found at: ${firebaseJsonPath}`]
19580
- };
19581
- }
19582
- try {
19583
- const config = readFirebaseJson(firebaseJsonPath);
19584
- const hasHosting = !!config.hosting;
19585
- const hasFunctions = !!config.functions && Array.isArray(config.functions);
19586
- const hasFirestoreRules = !!config.firestore?.rules && pathExists(joinPath(appDir, config.firestore.rules));
19587
- const hasFirestoreIndexes = !!config.firestore?.indexes && pathExists(joinPath(appDir, config.firestore.indexes));
19588
- const hasStorageRules = !!config.storage?.rules && pathExists(joinPath(appDir, config.storage.rules));
19589
- return {
19590
- valid: true,
19591
- projectId: config.projectId,
19592
- hasHosting,
19593
- hasFunctions,
19594
- hasFirestoreRules,
19595
- hasFirestoreIndexes,
19596
- hasStorageRules,
19597
- errors: []
19598
- };
19599
- } catch (error2) {
19600
- return {
19601
- valid: false,
19602
- hasHosting: false,
19603
- hasFunctions: false,
19604
- hasFirestoreRules: false,
19605
- hasFirestoreIndexes: false,
19606
- hasStorageRules: false,
19607
- errors: [`Invalid firebase.json: ${getErrorMessage(error2)}`]
19608
- };
19609
- }
19610
- }
19611
- function validateBuild(appDir) {
19612
- const distPath = joinPath(appDir, "dist");
19613
- if (!pathExists(distPath)) {
19614
- return { exists: false, isEmpty: true, path: distPath };
19615
- }
19616
- try {
19617
- const files = readdirSync2(distPath);
19618
- return {
19619
- exists: true,
19620
- isEmpty: files.length === 0,
19621
- path: distPath
19622
- };
19623
- } catch {
19624
- return { exists: true, isEmpty: true, path: distPath };
19625
- }
19626
- }
19627
- function readStagingProject(startDir) {
19628
- let current = startDir;
19629
- for (let i = 0; i < 10; i++) {
19630
- const firebasercPath = joinPath(current, ".firebaserc");
19631
- if (pathExists(firebasercPath)) {
19632
- try {
19633
- const firebaserc = readFirebaserc(firebasercPath);
19634
- if (firebaserc?.projects?.staging) {
19635
- return firebaserc.projects.staging;
19636
- }
19637
- } catch (error2) {
19638
- }
19639
- }
19640
- const parent = joinPath(current, "..");
19641
- if (parent === current) break;
19642
- current = parent;
19643
- }
19644
- return null;
19645
- }
19646
- async function showServiceAccountError(info2, projectId) {
19647
- const consoleUrl = projectId ? `https://console.firebase.google.com/project/${projectId}/settings/serviceaccounts/adminsdk` : "https://console.firebase.google.com/project/YOUR_PROJECT/settings/serviceaccounts/adminsdk";
19648
- const errorList = info2.errors.map((e2) => `\u2022 ${e2}`).join("\n");
19649
- Me(
19650
- `${errorList}
19651
-
19652
- Why it matters:
19653
- Firebase CLI needs service account credentials to deploy.
19654
- Without valid credentials, deployment will fail.
19655
-
19656
- How to fix:
19657
- 1. Go to Firebase Console:
19658
- ${consoleUrl}
19659
- 2. Click "Generate New Private Key"
19660
- 3. Save the JSON file as: ${info2.path}
19661
- 4. Required IAM roles:
19662
- \u2022 Firebase Hosting Admin (for frontend)
19663
- \u2022 Cloud Functions Admin (for functions)
19664
- \u2022 Or Firebase Admin (covers both)`,
19665
- "Service Account Error"
19666
- );
19667
- if (projectId) {
19668
- const shouldOpen = await askForConfirmation(
19669
- "Open Firebase Console now?",
19670
- true
19671
- );
19672
- if (shouldOpen) {
19673
- try {
19674
- const openCommand = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
19675
- spawnSync7(`${openCommand} ${consoleUrl}`, { shell: true });
19676
- log.success("Opening Firebase Console...");
19677
- } catch {
19678
- log.warn("Could not open browser. Please open the URL manually.");
19679
- }
19680
- }
19681
- }
19682
- }
19683
- function showFirebaseJsonError(errors, appDir, deploymentType) {
19684
- const errorList = errors.map((e2) => `\u2022 ${e2}`).join("\n");
19685
- const firebaseJsonPath = joinPath(appDir, "firebase.json");
19686
- let configExample = "";
19687
- if (deploymentType === "frontend" || deploymentType === "both") {
19688
- configExample += `
19689
- Hosting config:
19690
- { "hosting": { "public": "dist", ... } }`;
19691
- }
19692
- if (deploymentType === "functions" || deploymentType === "both") {
19693
- configExample += `
19694
- Functions config:
19695
- { "functions": [{ "source": "functions", ... }] }`;
19696
- }
19697
- Me(
19698
- `${errorList}
19699
-
19700
- Why it matters:
19701
- firebase.json defines your deployment configuration.
19702
- Without it, Firebase CLI doesn't know what to deploy.
19703
-
19704
- How to fix:
19705
- 1. Ensure firebase.json exists at: ${firebaseJsonPath}
19706
- 2. Add required configuration:${configExample}`,
19707
- "Firebase Configuration Error"
19708
- );
19709
- }
19710
- function clearFirebaseCache(appDir) {
19711
- const firebaseCacheDir = joinPath(appDir, ".firebase");
19712
- if (pathExists(firebaseCacheDir)) {
19713
- log.info("Clearing Firebase cache...");
19714
- const removed = safeRemove(firebaseCacheDir, { silent: true });
19715
- if (removed) {
19716
- log.success("Firebase cache cleared");
19717
- } else {
19718
- log.warn("Could not clear Firebase cache (non-critical)");
19719
- }
19720
- }
19721
- }
19722
-
19723
19742
  // packages/tooling/src/apps/deploy-vercel-frontend.ts
19724
19743
  init_utils();
19725
19744
  init_vercel_api();
@@ -19791,8 +19810,26 @@ async function uploadFiles(files, token, orgId) {
19791
19810
  );
19792
19811
  }
19793
19812
  }
19794
- async function createDeployment(files, token, orgId, projectId, projectName) {
19813
+ function loadVercelConfig(appDir) {
19814
+ const configPath = joinPath(appDir, "vercel.json");
19815
+ if (!pathExists(configPath)) return {};
19816
+ try {
19817
+ const raw = readSync(configPath);
19818
+ const config = JSON.parse(raw);
19819
+ const result = {};
19820
+ if (config.rewrites) result.rewrites = config.rewrites;
19821
+ if (config.redirects) result.redirects = config.redirects;
19822
+ if (config.headers) result.headers = config.headers;
19823
+ if (config.cleanUrls != null) result.cleanUrls = config.cleanUrls;
19824
+ if (config.trailingSlash != null) result.trailingSlash = config.trailingSlash;
19825
+ return result;
19826
+ } catch {
19827
+ return {};
19828
+ }
19829
+ }
19830
+ async function createDeployment(files, token, orgId, projectId, projectName, appDir) {
19795
19831
  const q2 = teamQuery(orgId);
19832
+ const vercelConfig = loadVercelConfig(appDir);
19796
19833
  const body = {
19797
19834
  name: projectName,
19798
19835
  project: projectId,
@@ -19806,7 +19843,8 @@ async function createDeployment(files, token, orgId, projectId, projectName) {
19806
19843
  buildCommand: "",
19807
19844
  installCommand: "",
19808
19845
  outputDirectory: "."
19809
- }
19846
+ },
19847
+ ...vercelConfig
19810
19848
  };
19811
19849
  const res = await fetch(`${VERCEL_API2}/v13/deployments${q2}`, {
19812
19850
  method: "POST",
@@ -19890,7 +19928,8 @@ async function deployVercelFrontend(appDir, _config) {
19890
19928
  token,
19891
19929
  orgId,
19892
19930
  projectId,
19893
- project.projectName
19931
+ project.projectName,
19932
+ appDir
19894
19933
  );
19895
19934
  log.info(`Deployment ${deployment.id} created, waiting...`);
19896
19935
  const ready = await waitForReady(deployment.id, token, orgId);
@@ -20058,6 +20097,12 @@ async function main6(options = {}) {
20058
20097
  process.exit(1);
20059
20098
  }
20060
20099
  const appDir = appName ? detectAppDir(appName) : projectRoot;
20100
+ if (checkConfigPlaceholders(appDir)) {
20101
+ throw new DoNotDevError(
20102
+ "Config files contain unreplaced template placeholders. Fix before deploying.",
20103
+ "configuration-error"
20104
+ );
20105
+ }
20061
20106
  const appProviderInfo = detectProvider(appDir);
20062
20107
  const hasVercelConfig = pathExists(joinPath(appDir, "vercel.json"));
20063
20108
  let deploymentType = config.deploymentType;
@@ -20164,7 +20209,7 @@ async function main6(options = {}) {
20164
20209
  staging: isStaging
20165
20210
  });
20166
20211
  if (!serviceAccountResult.valid) {
20167
- const firebaseConfig2 = validateFirebaseJson2(appDir);
20212
+ const firebaseConfig2 = validateFirebaseJson(appDir);
20168
20213
  await showServiceAccountError(
20169
20214
  serviceAccountResult.info,
20170
20215
  firebaseConfig2.projectId
@@ -20183,7 +20228,7 @@ async function main6(options = {}) {
20183
20228
  }
20184
20229
  }
20185
20230
  if (!projectId) {
20186
- const fallbackConfig = validateFirebaseJson2(appDir);
20231
+ const fallbackConfig = validateFirebaseJson(appDir);
20187
20232
  projectId = serviceAccountResult.info.projectId || fallbackConfig.projectId;
20188
20233
  }
20189
20234
  if (!projectId) {
@@ -20198,7 +20243,7 @@ async function main6(options = {}) {
20198
20243
  } else {
20199
20244
  config.project = projectId;
20200
20245
  }
20201
- const firebaseConfig = await validateFirebaseJson2(appDir);
20246
+ const firebaseConfig = await validateFirebaseJson(appDir);
20202
20247
  if (!firebaseConfig.valid) {
20203
20248
  showFirebaseJsonError(firebaseConfig.errors, appDir, deploymentType);
20204
20249
  process.exit(1);
@@ -20679,7 +20724,10 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20679
20724
  backendPlatform,
20680
20725
  isFirebase: backendPlatform === "firebase",
20681
20726
  isSupabase: backendPlatform === "supabase",
20682
- isVercel: backendPlatform === "vercel"
20727
+ isVercel: backendPlatform === "vercel",
20728
+ needsAuth: appConfig.userAuth !== "none",
20729
+ needsBilling: appConfig.billing,
20730
+ needsOAuth: appConfig.userAuth === "social" || appConfig.userAuth === "full-social"
20683
20731
  };
20684
20732
  const templateSourceDir = joinPath(templatesRoot, templateDir);
20685
20733
  const templateFiles = await glob("**/*", {
@@ -20710,8 +20758,6 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20710
20758
  });
20711
20759
  for (const file of overlayFiles) {
20712
20760
  if (file.startsWith("env.fragment")) continue;
20713
- if (file === "vercel.headers.example") continue;
20714
- if (file === "vercel.json.example") continue;
20715
20761
  if (file === "src/config/providers.ts.example") {
20716
20762
  const variantFile = `src/config/providers.${appTemplate}.ts.example`;
20717
20763
  if (overlayFiles.includes(variantFile)) continue;
@@ -20748,32 +20794,6 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20748
20794
  const fragment = readSync(fragmentPath);
20749
20795
  await write(envPath, baseEnv + "\n" + fragment, { overwrite: true });
20750
20796
  }
20751
- if (deployConfig === "vercel-supabase") {
20752
- const vercelPath = joinPath(appDir, "vercel.json");
20753
- const headersFragmentPath = joinPath(
20754
- overlayDir,
20755
- "vercel.headers.example"
20756
- );
20757
- const fullVercelPath = joinPath(overlayDir, "vercel.json.example");
20758
- if (pathExists(vercelPath) && pathExists(headersFragmentPath)) {
20759
- const vercelJson = readSync(vercelPath, { format: "json" });
20760
- const headersFragment = readSync(headersFragmentPath, {
20761
- format: "json"
20762
- });
20763
- vercelJson.headers = [
20764
- ...vercelJson.headers ?? [],
20765
- ...headersFragment
20766
- ];
20767
- await write(vercelPath, vercelJson, {
20768
- format: "json",
20769
- overwrite: true
20770
- });
20771
- } else if (pathExists(fullVercelPath)) {
20772
- await copy(fullVercelPath, vercelPath);
20773
- if (await isTextFile(vercelPath))
20774
- await replacePlaceholders(vercelPath, replacements);
20775
- }
20776
- }
20777
20797
  }
20778
20798
  }
20779
20799
  const executionMode = detectExecutionMode();
@@ -20843,7 +20863,7 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20843
20863
  }
20844
20864
  }
20845
20865
  }
20846
- const deploymentTemplateDir = joinPath(templatesRoot, "root-consumer");
20866
+ const deploymentTemplateDir = joinPath(templatesRoot, "deploy-config");
20847
20867
  if (deployConfig === "firebase") {
20848
20868
  const firebaseJsonSource = joinPath(
20849
20869
  deploymentTemplateDir,
@@ -20955,7 +20975,7 @@ async function createApp(appName, appConfig, workspaceRoot, templatesRoot) {
20955
20975
  }
20956
20976
  }
20957
20977
  }
20958
- if (deployConfig === "vercel-vercel") {
20978
+ if (deployConfig === "vercel-supabase" || deployConfig === "vercel-vercel") {
20959
20979
  const vercelJsonSource = joinPath(
20960
20980
  deploymentTemplateDir,
20961
20981
  "vercel.json.example"
@@ -21097,7 +21117,7 @@ function detectExecutionMode2() {
21097
21117
  }
21098
21118
  return "published";
21099
21119
  }
21100
- async function main9(options) {
21120
+ async function main9(_options, name) {
21101
21121
  try {
21102
21122
  Ie("\u{1F680} DoNotDev Project Creator");
21103
21123
  try {
@@ -21117,7 +21137,7 @@ async function main9(options) {
21117
21137
  const executionMode = detectExecutionMode2();
21118
21138
  const monorepoRoot = process.cwd();
21119
21139
  const templatesRoot = getTemplatesRoot();
21120
- let projectName = options?.projectName || "";
21140
+ let projectName = name || "";
21121
21141
  while (!projectName) {
21122
21142
  const projectNameInput = await askForInput("Project name", "my-project");
21123
21143
  if (!isValidFileName(projectNameInput)) {
@@ -21381,13 +21401,6 @@ async function main9(options) {
21381
21401
  supabase: hasSupabase,
21382
21402
  stripe: hasBilling
21383
21403
  };
21384
- const firebaseRootFiles = /* @__PURE__ */ new Set([
21385
- "firebase.json.example",
21386
- ".firebaserc.example",
21387
- "firestore.rules.example",
21388
- "firestore.indexes.json.example",
21389
- "storage.rules.example"
21390
- ]);
21391
21404
  const files = await glob("**/*", {
21392
21405
  cwd: rootTemplateDir,
21393
21406
  dot: true,
@@ -21395,7 +21408,6 @@ async function main9(options) {
21395
21408
  });
21396
21409
  for (const file of files) {
21397
21410
  if (file === "package.json.example") continue;
21398
- if (firebaseRootFiles.has(file)) continue;
21399
21411
  const sourcePath = joinPath(rootTemplateDir, file);
21400
21412
  let destFileName = file;
21401
21413
  if (destFileName.endsWith(".example")) {