firebase-tools 15.34.2 → 15.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/lib/api.js +2 -4
  2. package/lib/appcheck/debugTokens.js +293 -0
  3. package/lib/appcheck/localConfig.js +191 -0
  4. package/lib/appdistribution/options-parser-util.js +1 -1
  5. package/lib/apphosting/constants.js +1 -4
  6. package/lib/apphosting/githubConnections.js +1 -1
  7. package/lib/apphosting/utils.js +0 -26
  8. package/lib/auth.js +8 -2
  9. package/lib/commands/appcheck-debugtokens-create.js +60 -35
  10. package/lib/commands/appcheck-debugtokens-delete.js +21 -7
  11. package/lib/commands/appcheck-debugtokens-list.js +37 -8
  12. package/lib/commands/appcheck-debugtokens-prune.js +59 -0
  13. package/lib/commands/crashlytics-heapdumps-status.js +1 -1
  14. package/lib/commands/{crashlytics-onboard-web.js → crashlytics-setup.js} +5 -5
  15. package/lib/commands/crashlytics-sourcemap-upload.js +4 -0
  16. package/lib/commands/deploy.js +1 -3
  17. package/lib/commands/emulators-start.js +2 -2
  18. package/lib/commands/hosting-channel-create.js +1 -3
  19. package/lib/commands/hosting-channel-delete.js +1 -3
  20. package/lib/commands/hosting-channel-deploy.js +1 -3
  21. package/lib/commands/hosting-channel-list.js +1 -3
  22. package/lib/commands/hosting-channel-open.js +1 -3
  23. package/lib/commands/hosting-clone.js +3 -5
  24. package/lib/commands/hosting-disable.js +2 -2
  25. package/lib/commands/hosting-sites-create.js +1 -3
  26. package/lib/commands/hosting-sites-delete.js +1 -3
  27. package/lib/commands/hosting-sites-get.js +1 -3
  28. package/lib/commands/hosting-sites-list.js +1 -3
  29. package/lib/commands/index.js +4 -2
  30. package/lib/commands/run-services-get.js +19 -0
  31. package/lib/commands/run-services-list.js +11 -0
  32. package/lib/crashlytics/alerts.js +1 -0
  33. package/lib/crashlytics/events.js +122 -1
  34. package/lib/crashlytics/filters.js +12 -6
  35. package/lib/crashlytics/firebasetelemetry.js +5 -3
  36. package/lib/crashlytics/onboarding.js +8 -7
  37. package/lib/crashlytics/profilingManager.js +14 -34
  38. package/lib/crashlytics/reports.js +46 -17
  39. package/lib/crashlytics/sourcemap.js +19 -5
  40. package/lib/crashlytics/utils.js +14 -0
  41. package/lib/database/import.js +5 -4
  42. package/lib/dataconnect/dataplaneClient.js +0 -10
  43. package/lib/dataconnect/names.js +3 -3
  44. package/lib/dataconnect/schemaMigration.js +1 -1
  45. package/lib/deploy/apphosting/deploy.js +20 -41
  46. package/lib/deploy/apphosting/localBuild.js +49 -0
  47. package/lib/deploy/apphosting/prepare.js +12 -25
  48. package/lib/deploy/apphosting/release.js +1 -1
  49. package/lib/deploy/apphosting/util.js +27 -4
  50. package/lib/deploy/functions/backend.js +0 -10
  51. package/lib/deploy/functions/cel.js +1 -1
  52. package/lib/deploy/functions/containerCleaner.js +1 -142
  53. package/lib/deploy/functions/functionsDeployHelper.js +0 -4
  54. package/lib/deploy/functions/release/reporter.js +0 -26
  55. package/lib/deploy/functions/runtimes/discovery/index.js +4 -1
  56. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +1 -1
  57. package/lib/deploy/functions/services/index.js +13 -11
  58. package/lib/deploy/functions/validate.js +1 -1
  59. package/lib/deploy/hosting/prepare.js +1 -3
  60. package/lib/deploy/lifecycleHooks.js +1 -1
  61. package/lib/deploy/run/deploy.js +26 -43
  62. package/lib/deploy/run/get.js +30 -0
  63. package/lib/deploy/run/list.js +38 -0
  64. package/lib/deploy/run/prereqs.js +0 -3
  65. package/lib/deploy/run/util.js +9 -0
  66. package/lib/emulator/auth/operations.js +2 -2
  67. package/lib/emulator/auth/server.js +4 -2
  68. package/lib/emulator/auth/widget_ui.js +1 -1
  69. package/lib/emulator/commandUtils.js +109 -24
  70. package/lib/emulator/databaseEmulator.js +16 -11
  71. package/lib/emulator/dataconnect/pgliteServer.js +31 -24
  72. package/lib/emulator/downloadableEmulatorInfo.json +24 -24
  73. package/lib/emulator/downloadableEmulators.js +45 -7
  74. package/lib/emulator/extensions/postinstall.js +6 -6
  75. package/lib/emulator/firestoreEmulator.js +21 -15
  76. package/lib/emulator/functionsEmulator.js +11 -7
  77. package/lib/emulator/functionsEmulatorRuntime.js +7 -2
  78. package/lib/emulator/hub.js +12 -8
  79. package/lib/emulator/shared/express.js +30 -0
  80. package/lib/emulator/storage/apis/firebase.js +11 -10
  81. package/lib/emulator/storage/apis/gcloud.js +21 -20
  82. package/lib/emulator/storage/files.js +1 -1
  83. package/lib/emulator/storage/rules/manager.js +15 -12
  84. package/lib/emulator/storage/rules/runtime.js +1 -0
  85. package/lib/emulator/storage/server.js +10 -5
  86. package/lib/extensions/extensionsApi.js +0 -8
  87. package/lib/extensions/extensionsHelper.js +3 -24
  88. package/lib/extensions/paramHelper.js +1 -1
  89. package/lib/extensions/provisioningHelper.js +1 -6
  90. package/lib/extensions/secretsUtils.js +0 -24
  91. package/lib/firestore/util.js +3 -3
  92. package/lib/frameworks/angular/utils.js +1 -1
  93. package/lib/frameworks/next/utils.js +1 -12
  94. package/lib/fsAsync.js +34 -20
  95. package/lib/functions/kits/install.js +233 -628
  96. package/lib/functions/kits/sources/directory.js +91 -0
  97. package/lib/functions/kits/sources/npm.js +324 -0
  98. package/lib/functions/kits/sources/types.js +12 -0
  99. package/lib/functionsConfig.js +0 -4
  100. package/lib/functionsShellCommandAction.js +1 -1
  101. package/lib/gcp/artifactregistry.js +0 -5
  102. package/lib/gcp/cloudfunctionsv2.js +0 -6
  103. package/lib/gcp/devConnect.js +2 -2
  104. package/lib/gcp/iam.js +0 -4
  105. package/lib/gcp/pubsub.js +0 -14
  106. package/lib/gcp/storage.js +2 -1
  107. package/lib/hosting/api.js +79 -0
  108. package/lib/hosting/proxy.js +4 -1
  109. package/lib/init/features/hosting/github.js +6 -4
  110. package/lib/init/features/hosting/index.js +4 -0
  111. package/lib/init/features/run.js +3 -7
  112. package/lib/mcp/apps/init/mcp-app.js +4 -1
  113. package/lib/mcp/index.js +8 -2
  114. package/lib/mcp/prompts/apptesting/run_test.js +3 -3
  115. package/lib/mcp/prompts/core/deploy.js +3 -3
  116. package/lib/mcp/resources/guides/crashlytics_reports.js +33 -71
  117. package/lib/mcp/resources/guides/init_ai.js +10 -10
  118. package/lib/mcp/tools/crashlytics/events.js +18 -93
  119. package/lib/mcp/tools/crashlytics/index.js +2 -0
  120. package/lib/mcp/tools/crashlytics/reports.js +26 -31
  121. package/lib/mcp/tools/crashlytics/setup.js +392 -0
  122. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  123. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  124. package/lib/utils.js +4 -10
  125. package/package.json +1 -2
  126. package/lib/deploy/hosting/args.js +0 -2
@@ -1,55 +1,47 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FUNCTION_KITS_DIR = exports.DEFAULT_TEMPLATE = exports.TEMPLATES = void 0;
4
17
  exports.generateUniqueId = generateUniqueId;
5
- exports.parseNpmPackageSpecifier = parseNpmPackageSpecifier;
6
- exports.validateNpmPackageName = validateNpmPackageName;
7
- exports.validateNpmPackageExists = validateNpmPackageExists;
8
- exports.sanitizePackageNameToKitName = sanitizePackageNameToKitName;
9
- exports.isThirdPartyPackage = isThirdPartyPackage;
10
- exports.checkPackageHasShrinkwrap = checkPackageHasShrinkwrap;
11
18
  exports.getUnconfiguredInstancesForProject = getUnconfiguredInstancesForProject;
12
19
  exports.extractExistingFunctionsInfo = extractExistingFunctionsInfo;
13
20
  exports.promptKitInstanceId = promptKitInstanceId;
14
21
  exports.promptKitId = promptKitId;
15
- exports.promptSecurityConfirmation = promptSecurityConfirmation;
16
22
  exports.promptExistingInstanceForProject = promptExistingInstanceForProject;
17
- exports.writeKitPackageJson = writeKitPackageJson;
18
- exports.writeKitIndexTs = writeKitIndexTs;
19
- exports.scaffoldKitFiles = scaffoldKitFiles;
20
- exports.resolveSdkSpecifierToSave = resolveSdkSpecifierToSave;
21
- exports.getKitPackagesToSave = getKitPackagesToSave;
22
- exports.buildAndInstallKit = buildAndInstallKit;
23
23
  exports.addKitToConfig = addKitToConfig;
24
- exports.validateAndResolveDirectoryKit = validateAndResolveDirectoryKit;
25
- exports.buildAndInstallDirectoryKit = buildAndInstallDirectoryKit;
26
24
  exports.findKitConfig = findKitConfig;
27
25
  exports.addInstanceToKitConfig = addInstanceToKitConfig;
28
26
  exports.revertFunctionsConfig = revertFunctionsConfig;
29
- exports.scaffoldKit = scaffoldKit;
30
27
  exports.addInstanceToKit = addInstanceToKit;
31
28
  exports.discoverKitBuild = discoverKitBuild;
32
29
  exports.promptAndWriteKitParams = promptAndWriteKitParams;
33
30
  exports.printKitFirstDeployReport = printKitFirstDeployReport;
34
- exports.addKitInstanceOrConfigureProject = addKitInstanceOrConfigureProject;
35
- exports.findExistingKit = findExistingKit;
36
- exports.resolvePackageSource = resolvePackageSource;
37
- exports.resolveDirectorySource = resolveDirectorySource;
31
+ exports.ensureKit = ensureKit;
32
+ exports.resolveOrCreateInstance = resolveOrCreateInstance;
33
+ exports.configureInstanceForProject = configureInstanceForProject;
38
34
  exports.installKitOrInstance = installKitOrInstance;
39
35
  const crypto = require("crypto");
40
36
  const path = require("path");
41
37
  const clc = require("colorette");
42
38
  const fs = require("fs-extra");
43
- const semver = require("semver");
44
39
  const error_1 = require("../../error");
45
40
  const projectUtils_1 = require("../../projectUtils");
46
41
  const utils_1 = require("../../utils");
47
42
  const projectConfig_1 = require("../projectConfig");
48
43
  const logger_1 = require("../../logger");
49
44
  const prompt_1 = require("../../prompt");
50
- const spawn_1 = require("../../init/spawn");
51
- const templates_1 = require("../../templates");
52
- const supported = require("../../deploy/functions/runtimes/supported");
53
45
  const runtimes = require("../../deploy/functions/runtimes");
54
46
  const build = require("../../deploy/functions/build");
55
47
  const params = require("../../deploy/functions/params");
@@ -59,15 +51,14 @@ const functionsEnv = require("../env");
59
51
  const functionsConfig = require("../../functionsConfig");
60
52
  const prepare_1 = require("../../deploy/functions/prepare");
61
53
  const functional_1 = require("../../functional");
62
- const env_1 = require("../env");
63
- const env_2 = require("./env");
54
+ const env_1 = require("./env");
64
55
  const fsutils_1 = require("../../fsutils");
65
- exports.TEMPLATES = {
66
- installation: "init/functions/typescript/index-kit.ts",
67
- migration: "init/functions/typescript/index-kit-migration.ts",
68
- };
69
- exports.DEFAULT_TEMPLATE = "installation";
70
- exports.FUNCTION_KITS_DIR = "function-kits";
56
+ const types_1 = require("./sources/types");
57
+ const directory_1 = require("./sources/directory");
58
+ const npm_1 = require("./sources/npm");
59
+ __exportStar(require("./sources/types"), exports);
60
+ __exportStar(require("./sources/npm"), exports);
61
+ __exportStar(require("./sources/directory"), exports);
71
62
  function generateUniqueId(baseId, existingIds) {
72
63
  if (!existingIds.includes(baseId)) {
73
64
  return baseId;
@@ -80,72 +71,10 @@ function generateUniqueId(baseId, existingIds) {
80
71
  } while (existingIds.includes(candidate));
81
72
  return candidate;
82
73
  }
83
- function parseNpmPackageSpecifier(rawPkg) {
84
- const lastAt = rawPkg.lastIndexOf("@");
85
- if (lastAt > 0) {
86
- const version = rawPkg.substring(lastAt + 1);
87
- return {
88
- packageName: rawPkg.substring(0, lastAt),
89
- ...(version ? { version } : {}),
90
- };
91
- }
92
- return { packageName: rawPkg };
93
- }
94
- function validateNpmPackageName(packageNameOrSpecifier) {
95
- const { packageName, version } = parseNpmPackageSpecifier(packageNameOrSpecifier);
96
- const npmPackageRegex = /^(?:@[a-z0-9_.-]+\/[a-z0-9_.-]+|[a-z0-9_.-]+)$/i;
97
- if (!packageName ||
98
- packageName.length > 214 ||
99
- !npmPackageRegex.test(packageName) ||
100
- (packageNameOrSpecifier.lastIndexOf("@") > 0 && !version)) {
101
- throw new error_1.FirebaseError(`Invalid NPM package name '${packageNameOrSpecifier}'. Package names must be valid npm package specifiers (e.g. 'my-kit' or '@scope/my-kit').`);
102
- }
103
- }
104
- async function validateNpmPackageExists(rawPkgName) {
105
- validateNpmPackageName(rawPkgName);
106
- try {
107
- const output = await (0, spawn_1.spawnWithOutput)("npm", ["view", rawPkgName, "version"]);
108
- if (!output.trim()) {
109
- throw new Error(`No version found for '${rawPkgName}'`);
110
- }
111
- }
112
- catch (err) {
113
- throw new error_1.FirebaseError(`NPM package '${rawPkgName}' could not be found in the npm registry. Please verify the package name and version.`, { original: err instanceof Error ? err : undefined });
114
- }
115
- }
116
- function sanitizePackageNameToKitName(packageNameOrSpecifier) {
117
- const { packageName } = parseNpmPackageSpecifier(packageNameOrSpecifier);
118
- const parts = packageName.split("/");
119
- const nameWithoutScope = parts[parts.length - 1] || packageName;
120
- const sanitized = nameWithoutScope.toLowerCase().replace(/[^a-z0-9_-]/g, "");
121
- return sanitized.slice(0, 40);
122
- }
123
- function isThirdPartyPackage(packageNameOrSpecifier) {
124
- const { packageName } = parseNpmPackageSpecifier(packageNameOrSpecifier);
125
- return !packageName.startsWith("@firebase-function-kits/");
126
- }
127
- async function checkPackageHasShrinkwrap(rawPkgName) {
128
- try {
129
- const output = await (0, spawn_1.spawnWithOutput)("npm", ["pack", rawPkgName, "--dry-run", "--json"]);
130
- const parsed = JSON.parse(output);
131
- if (Array.isArray(parsed) && parsed.length > 0) {
132
- const pkgInfo = parsed[0];
133
- if (pkgInfo.hasShrinkwrap) {
134
- return true;
135
- }
136
- if (Array.isArray(pkgInfo.files)) {
137
- return pkgInfo.files.some((f) => f.path === "npm-shrinkwrap.json" || f.path === "npm-shrinkwrap.js");
138
- }
139
- }
140
- }
141
- catch (err) {
142
- logger_1.logger.debug(`Failed to inspect package shrinkwrap for ${rawPkgName}: ${(0, error_1.getErrMsg)(err)}`);
143
- }
144
- return false;
145
- }
146
- function getUnconfiguredInstancesForProject(config, kit, projectId, projectAlias) {
74
+ function getUnconfiguredInstancesForProject(options) {
75
+ const { config, kit, projectId, projectAlias } = options;
147
76
  return Object.entries(kit.instances || {})
148
- .filter(([, configDir]) => !(0, env_1.hasProjectEnv)(config.path(configDir), projectId, projectAlias))
77
+ .filter(([, configDir]) => !functionsEnv.hasProjectEnv(config.path(configDir), projectId, projectAlias))
149
78
  .map(([instanceId]) => instanceId);
150
79
  }
151
80
  function extractExistingFunctionsInfo(configFunctions) {
@@ -175,7 +104,8 @@ function extractExistingFunctionsInfo(configFunctions) {
175
104
  existingInstanceIds,
176
105
  };
177
106
  }
178
- async function promptKitInstanceId(baseKitId, existingInstanceIds, existingCodebases, nonInteractive, customInstanceId) {
107
+ async function promptKitInstanceId(options) {
108
+ const { baseKitId, existingInstanceIds, existingCodebases, nonInteractive, customInstanceId } = options;
179
109
  const instanceCollisions = [...existingInstanceIds, ...existingCodebases];
180
110
  const defaultInstanceId = generateUniqueId(baseKitId, instanceCollisions);
181
111
  if (customInstanceId) {
@@ -217,9 +147,9 @@ async function promptKitInstanceId(baseKitId, existingInstanceIds, existingCodeb
217
147
  }
218
148
  return instanceId;
219
149
  }
220
- async function promptKitId(packageName, existingKitIds, nonInteractive, customKitId) {
221
- const baseKitId = sanitizePackageNameToKitName(packageName) || "kit";
222
- const defaultKitId = generateUniqueId(baseKitId, existingKitIds);
150
+ async function promptKitId(options) {
151
+ const { baseKitId, existingKitIds, nonInteractive, customKitId } = options;
152
+ const defaultKitId = generateUniqueId(baseKitId || "kit", existingKitIds);
223
153
  if (customKitId) {
224
154
  (0, projectConfig_1.validateKit)(customKitId);
225
155
  if (existingKitIds.includes(customKitId)) {
@@ -250,39 +180,6 @@ async function promptKitId(packageName, existingKitIds, nonInteractive, customKi
250
180
  }
251
181
  return kitId;
252
182
  }
253
- async function promptSecurityConfirmation(options) {
254
- const { rawPkgName, packageName, nonInteractive, force } = options;
255
- const isThirdParty = isThirdPartyPackage(packageName);
256
- if (isThirdParty) {
257
- (0, utils_1.logLabeledWarning)("functions", `Package ${clc.bold(packageName)} is a third-party kit (outside the @firebase-function-kits scope).`);
258
- }
259
- const hasShrinkwrap = await checkPackageHasShrinkwrap(rawPkgName);
260
- if (!hasShrinkwrap) {
261
- (0, utils_1.logLabeledWarning)("functions", `Package ${clc.bold(packageName)} does not have an npm-shrinkwrap.json file. npm-shrinkwrap guarantees that you deploy the same version of dependencies that the publisher tested against. Since this kit does not have an npm-shrinkwrap, it is possible that deploys or updates may introduce bugs or vulnerabilities in newer dependency versions that the publisher did not test against.`);
262
- }
263
- if (isThirdParty || !hasShrinkwrap) {
264
- let confirmMessage;
265
- if (isThirdParty && !hasShrinkwrap) {
266
- confirmMessage = `Are you sure you want to install the third-party kit ${packageName} without locked dependencies?`;
267
- }
268
- else if (isThirdParty) {
269
- confirmMessage = `Are you sure you want to install the third-party kit ${packageName}?`;
270
- }
271
- else {
272
- confirmMessage = `Are you sure you want to install ${packageName} without locked dependencies?`;
273
- }
274
- const confirmInstallation = await (0, prompt_1.confirm)({
275
- message: confirmMessage,
276
- default: false,
277
- nonInteractive,
278
- force,
279
- });
280
- if (!confirmInstallation) {
281
- throw new error_1.FirebaseError("Installation cancelled.");
282
- }
283
- }
284
- return isThirdParty;
285
- }
286
183
  async function promptExistingInstanceForProject(options) {
287
184
  const allInstanceIds = Object.keys(options.existingKit.instances || {});
288
185
  if (allInstanceIds.length === 0) {
@@ -311,163 +208,15 @@ async function promptExistingInstanceForProject(options) {
311
208
  nonInteractive: options.nonInteractive,
312
209
  });
313
210
  }
314
- async function writeKitPackageJson(config, sourcePath, kitId) {
315
- const relPackageJsonPath = path.join(sourcePath, "package.json");
316
- const absPackageJsonPath = config.path(relPackageJsonPath);
317
- let pkgJson = {};
318
- if (await fs.pathExists(absPackageJsonPath)) {
319
- try {
320
- pkgJson = (await fs.readJson(absPackageJsonPath));
321
- }
322
- catch (err) {
323
- logger_1.logger.debug(`Failed to read existing package.json: ${(0, error_1.getErrMsg)(err)}`);
324
- }
325
- }
326
- else {
327
- const latestNodeVersion = supported.latest("nodejs").replace("nodejs", "");
328
- const packageKitTemplate = (0, templates_1.readTemplateSync)("init/functions/typescript/package-kit.json");
329
- const subbedTemplate = packageKitTemplate.replace(/{{RUNTIME}}/g, latestNodeVersion);
330
- try {
331
- pkgJson = JSON.parse(subbedTemplate);
332
- }
333
- catch (err) {
334
- throw new error_1.FirebaseError("Failed to parse package-kit.json template: " + (0, error_1.getErrMsg)(err), {
335
- original: err instanceof Error ? err : undefined,
336
- });
337
- }
338
- }
339
- pkgJson.name = `${kitId}-wrapper`;
340
- await config.askWriteProjectFile(relPackageJsonPath, pkgJson);
341
- }
342
- async function writeKitIndexTs(config, sourcePath, packageName, templateType) {
343
- const relIndexTsPath = path.join(sourcePath, "src", "index.ts");
344
- const absIndexTsPath = config.path(relIndexTsPath);
345
- if (!(await fs.pathExists(absIndexTsPath))) {
346
- const template = (0, templates_1.readTemplateSync)(exports.TEMPLATES[templateType]);
347
- const indexContent = template.replace(/{{PACKAGE_NAME}}/g, packageName);
348
- await config.askWriteProjectFile(relIndexTsPath, indexContent);
349
- }
350
- }
351
- async function scaffoldKitFiles(config, kitId, instanceId, packageName, templateType = exports.DEFAULT_TEMPLATE) {
352
- const sourcePath = path.join(exports.FUNCTION_KITS_DIR, kitId, "source");
353
- const configDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
354
- const absSourcePath = config.path(sourcePath);
355
- const absConfigDirPath = config.path(configDirPath);
356
- await fs.ensureDir(absSourcePath);
357
- await fs.ensureDir(absConfigDirPath);
358
- await writeKitPackageJson(config, sourcePath, kitId);
359
- await config.askWriteProjectFile(path.join(sourcePath, "tsconfig.json"), (0, templates_1.readTemplateSync)("init/functions/typescript/tsconfig.json"));
360
- await config.askWriteProjectFile(path.join(sourcePath, ".gitignore"), (0, templates_1.readTemplateSync)("init/functions/typescript/_gitignore"));
361
- await writeKitIndexTs(config, sourcePath, packageName, templateType);
362
- return { sourcePath, configDirPath, absSourcePath, absConfigDirPath };
363
- }
364
- function resolveSdkSpecifierToSave(packageName, declaredVer, installedVer) {
365
- const cleanVer = semver.clean(declaredVer);
366
- if (cleanVer) {
367
- return `${packageName}@=${installedVer || cleanVer}`;
368
- }
369
- if (declaredVer.trim().startsWith("~")) {
370
- return installedVer ? `${packageName}@~${installedVer}` : `${packageName}@${declaredVer}`;
371
- }
372
- if (installedVer) {
373
- return `${packageName}@^${installedVer}`;
374
- }
375
- return `${packageName}@${declaredVer}`;
376
- }
377
- async function getKitPackagesToSave(absSourcePath, packageName) {
378
- const lockfilePath = path.join(absSourcePath, "package-lock.json");
379
- let peerDeps = {};
380
- let directDeps = {};
381
- let installedFunctionsVer;
382
- let installedAdminVer;
383
- if (await fs.pathExists(lockfilePath)) {
384
- try {
385
- const lockfile = (await fs.readJson(lockfilePath));
386
- const packages = lockfile.packages || {};
387
- const kitEntry = packages[`node_modules/${packageName}`] || {};
388
- peerDeps = kitEntry.peerDependencies || {};
389
- directDeps = kitEntry.dependencies || {};
390
- installedFunctionsVer = packages["node_modules/firebase-functions"]?.version;
391
- installedAdminVer = packages["node_modules/firebase-admin"]?.version;
392
- }
393
- catch (err) {
394
- logger_1.logger.debug(`Failed to read package-lock.json: ${(0, error_1.getErrMsg)(err)}`);
395
- }
396
- }
397
- if (Object.keys(peerDeps).length === 0 && Object.keys(directDeps).length === 0) {
398
- const kitPkgJsonPath = path.join(absSourcePath, "node_modules", packageName, "package.json");
399
- if (await fs.pathExists(kitPkgJsonPath)) {
400
- try {
401
- const kitPkgJson = (await fs.readJson(kitPkgJsonPath));
402
- peerDeps = kitPkgJson.peerDependencies || {};
403
- directDeps = kitPkgJson.dependencies || {};
404
- }
405
- catch (err) {
406
- logger_1.logger.debug(`Failed to read kit package.json: ${(0, error_1.getErrMsg)(err)}`);
407
- }
408
- }
409
- }
410
- const declaredFunctionsVer = peerDeps["firebase-functions"] || directDeps["firebase-functions"];
411
- if (!declaredFunctionsVer) {
412
- throw new error_1.FirebaseError(`Package '${packageName}' is not a valid Function Kit: it must declare 'firebase-functions' as a dependency or peer dependency.`);
413
- }
414
- const packagesToSave = [
415
- resolveSdkSpecifierToSave("firebase-functions", declaredFunctionsVer, installedFunctionsVer),
416
- ];
417
- const declaredAdminVer = peerDeps["firebase-admin"] || directDeps["firebase-admin"];
418
- if (declaredAdminVer) {
419
- packagesToSave.push(resolveSdkSpecifierToSave("firebase-admin", declaredAdminVer, installedAdminVer));
420
- }
421
- return packagesToSave;
422
- }
423
- async function buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty) {
424
- const { packageName } = parseNpmPackageSpecifier(rawPkgName);
425
- const installArgs = ["install", rawPkgName, "--save-prefix=^"];
426
- if (isThirdParty) {
427
- installArgs.push("--ignore-scripts");
428
- }
429
- (0, utils_1.logLabeledBullet)("functions", `Running npm ${installArgs.join(" ")}...`);
430
- try {
431
- await (0, spawn_1.wrapSpawn)("npm", installArgs, absSourcePath);
432
- }
433
- catch (err) {
434
- throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
435
- }
436
- const packagesToSave = await getKitPackagesToSave(absSourcePath, packageName);
437
- if (packagesToSave.length > 0) {
438
- (0, utils_1.logLabeledBullet)("functions", `Saving resolved SDK dependencies: ${clc.bold(packagesToSave.join(", "))}...`);
439
- const saveArgs = ["install", ...packagesToSave, "--save-prefix=^"];
440
- if (isThirdParty) {
441
- saveArgs.push("--ignore-scripts");
442
- }
443
- try {
444
- await (0, spawn_1.wrapSpawn)("npm", saveArgs, absSourcePath);
445
- }
446
- catch (err) {
447
- throw new error_1.FirebaseError(`Failed to install required SDK dependencies (${packagesToSave.join(", ")}): ${(0, error_1.getErrMsg)(err)}. ` +
448
- "Verify that the kit's dependencies are compatible with the resolved Firebase SDK versions.", { original: err instanceof Error ? err : undefined });
449
- }
450
- }
451
- (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
452
- try {
453
- await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
454
- }
455
- catch (err) {
456
- throw new error_1.FirebaseError(`TypeScript build failed: ${(0, error_1.getErrMsg)(err)}`);
457
- }
458
- }
459
- function addKitToConfig(config, options) {
460
- const configSrc = config.src;
211
+ function addKitToConfig(options) {
212
+ const configSrc = options.config.src;
461
213
  const newKitConfig = {
462
214
  kit: options.kitId,
463
- ...(options.packageName ? { sourcePackage: { name: options.packageName } } : {}),
215
+ ...(options.sourcePackage ? { sourcePackage: options.sourcePackage } : {}),
464
216
  source: options.sourcePath,
465
- instances: {
466
- [options.instanceId]: options.configDirPath,
467
- },
468
- ...(options.hasBuildScript ?? true
469
- ? { predeploy: ['npm --prefix "$RESOURCE_DIR" run build'] }
470
- : {}),
217
+ instances: {},
218
+ ...(options.runtime ? { runtime: options.runtime } : {}),
219
+ ...(options.predeploy ? { predeploy: options.predeploy } : {}),
471
220
  };
472
221
  const functionsRaw = configSrc.functions;
473
222
  if (!functionsRaw) {
@@ -479,57 +228,10 @@ function addKitToConfig(config, options) {
479
228
  else {
480
229
  configSrc.functions = [functionsRaw, newKitConfig];
481
230
  }
482
- config.writeProjectFile("firebase.json", configSrc);
483
- }
484
- async function validateAndResolveDirectoryKit(projectDir, rawDir) {
485
- const absDirectoryPath = (0, utils_1.resolveWithin)(projectDir, rawDir, `Directory '${rawDir}' is outside of project directory. Function kit directory must be inside the project directory.`);
486
- if (!(await fs.pathExists(absDirectoryPath))) {
487
- throw new error_1.FirebaseError(`Directory '${rawDir}' does not exist.`);
488
- }
489
- const stat = await fs.stat(absDirectoryPath);
490
- if (!stat.isDirectory()) {
491
- throw new error_1.FirebaseError(`Directory '${rawDir}' is not a directory.`);
492
- }
493
- const packageJsonPath = path.join(absDirectoryPath, "package.json");
494
- if (!(await fs.pathExists(packageJsonPath))) {
495
- throw new error_1.FirebaseError(`Directory '${rawDir}' must contain a package.json file to be installed as a function kit.`);
496
- }
497
- let packageJson = {};
498
- try {
499
- packageJson = (await fs.readJson(packageJsonPath));
500
- }
501
- catch (err) {
502
- throw new error_1.FirebaseError(`Failed to parse package.json in '${rawDir}': ${(0, error_1.getErrMsg)(err)}`);
503
- }
504
- const hasBuildScript = Boolean(packageJson.scripts && packageJson.scripts.build);
505
- let relSourcePath = path.relative(projectDir, absDirectoryPath);
506
- if (!relSourcePath) {
507
- relSourcePath = ".";
508
- }
509
- relSourcePath = relSourcePath.split(path.sep).join("/");
510
- return {
511
- absDirectoryPath,
512
- relSourcePath,
513
- hasBuildScript,
514
- };
515
- }
516
- async function buildAndInstallDirectoryKit(absSourcePath, hasBuildScript) {
517
- (0, utils_1.logLabeledBullet)("functions", "Running npm install...");
518
- try {
519
- await (0, spawn_1.wrapSpawn)("npm", ["install"], absSourcePath);
520
- }
521
- catch (err) {
522
- throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
523
- }
524
- if (hasBuildScript) {
525
- (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
526
- try {
527
- await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
528
- }
529
- catch (err) {
530
- throw new error_1.FirebaseError(`TypeScript build failed: ${(0, error_1.getErrMsg)(err)}`);
531
- }
231
+ if (options.write) {
232
+ options.config.writeProjectFile("firebase.json", configSrc);
532
233
  }
234
+ return newKitConfig;
533
235
  }
534
236
  function findKitConfig(config, kitId) {
535
237
  const functions = config.src.functions;
@@ -546,7 +248,8 @@ function findKitConfig(config, kitId) {
546
248
  }
547
249
  return undefined;
548
250
  }
549
- function addInstanceToKitConfig(config, kitId, instanceId, configDirPath) {
251
+ function addInstanceToKitConfig(options) {
252
+ const { config, kitId, instanceId, configDirPath } = options;
550
253
  const target = findKitConfig(config, kitId);
551
254
  if (!target) {
552
255
  throw new error_1.FirebaseError(`Kit '${kitId}' not found in firebase.json.`);
@@ -571,55 +274,29 @@ function revertFunctionsConfig(options) {
571
274
  logger_1.logger.debug(`Failed to revert firebase.json: ${(0, error_1.getErrMsg)(err)}`);
572
275
  }
573
276
  }
574
- async function scaffoldKit(options) {
575
- const paths = await scaffoldKitFiles(options.config, options.kitId, options.instanceId, options.packageName, options.templateType);
576
- if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
577
- (0, env_2.seedKitInstanceEnv)({
578
- configDir: paths.absConfigDirPath,
579
- functionsSource: paths.absSourcePath,
580
- projectDir: options.config.projectDir,
581
- projectId: options.seedEnv.projectId,
582
- projectAlias: options.seedEnv.projectAlias,
583
- envs: options.seedEnv.envs,
584
- });
585
- }
586
- addKitToConfig(options.config, {
587
- kitId: options.kitId,
588
- instanceId: options.instanceId,
589
- packageName: options.packageName,
590
- sourcePath: paths.sourcePath,
591
- configDirPath: paths.configDirPath,
592
- });
593
- return paths;
594
- }
595
277
  async function addInstanceToKit(options) {
596
278
  const target = findKitConfig(options.config, options.kitId);
597
279
  if (!target) {
598
280
  throw new error_1.FirebaseError(`Kit '${options.kitId}' not found in firebase.json.`);
599
281
  }
600
- const configDirPath = path.join(exports.FUNCTION_KITS_DIR, options.kitId, `config-${options.instanceId}`);
282
+ const configDirPath = path.join(types_1.FUNCTION_KITS_DIR, options.kitId, `config-${options.instanceId}`);
601
283
  const absConfigDirPath = options.config.path(configDirPath);
602
284
  await fs.ensureDir(absConfigDirPath);
603
- if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
604
- (0, env_2.seedKitInstanceEnv)({
605
- configDir: absConfigDirPath,
606
- functionsSource: options.config.path(target.source),
607
- projectDir: options.config.projectDir,
608
- projectId: options.seedEnv.projectId,
609
- projectAlias: options.seedEnv.projectAlias,
610
- envs: options.seedEnv.envs,
611
- });
612
- }
613
- addInstanceToKitConfig(options.config, options.kitId, options.instanceId, configDirPath);
285
+ addInstanceToKitConfig({
286
+ config: options.config,
287
+ kitId: options.kitId,
288
+ instanceId: options.instanceId,
289
+ configDirPath,
290
+ });
614
291
  return { configDirPath, absConfigDirPath };
615
292
  }
616
- async function discoverKitBuild(options, absSourcePath) {
293
+ async function discoverKitBuild(options) {
617
294
  const projectId = (0, projectUtils_1.getProjectId)(options) || "";
618
295
  const delegateContext = {
619
296
  projectId,
620
- sourceDir: absSourcePath,
297
+ sourceDir: options.absSourcePath,
621
298
  projectDir: options.config?.projectDir || "",
622
- runtime: supported.latest("nodejs"),
299
+ ...(options.runtime ? { runtime: options.runtime } : {}),
623
300
  };
624
301
  const runtimeDelegate = await runtimes.getRuntimeDelegate(delegateContext);
625
302
  const firebaseEnvs = functionsEnv.loadFirebaseEnvs({ projectId }, projectId, options.instanceId);
@@ -675,7 +352,7 @@ async function printKitFirstDeployReport(options) {
675
352
  try {
676
353
  discoveredBuild = options.preDiscoveredBuild
677
354
  ? (0, utils_1.cloneDeep)(options.preDiscoveredBuild)
678
- : await discoverKitBuild(options, options.absSourcePath);
355
+ : await discoverKitBuild(options);
679
356
  build.applyEndpointPrefix(discoveredBuild, prefix);
680
357
  }
681
358
  catch (err) {
@@ -724,109 +401,162 @@ async function printKitFirstDeployReport(options) {
724
401
  (0, utils_1.logLabeledWarning)("functions", `${clc.bold("Please review the changes above. If you do not want them applied to your project, uninstall this kit before running firebase deploy.")}`);
725
402
  }
726
403
  }
727
- async function addKitInstanceOrConfigureProject(options) {
728
- const { existingKit, existingFunctionsInfo, createdPaths = [] } = options;
404
+ async function ensureKit(options) {
405
+ const { config, adapter, existingFunctionsInfo, createdPaths = [] } = options;
406
+ const existingKit = adapter.findExistingKit(existingFunctionsInfo.existingFunctions);
407
+ if (existingKit) {
408
+ return { kit: existingKit, isNewKit: false };
409
+ }
410
+ await adapter.validateAndConfirm();
411
+ const kitId = await promptKitId({
412
+ baseKitId: adapter.defaultKitId,
413
+ existingKitIds: existingFunctionsInfo.existingKitIds,
414
+ nonInteractive: options.nonInteractive,
415
+ customKitId: options.kitId,
416
+ });
417
+ const prepared = await adapter.prepareSource(kitId);
418
+ if (prepared.createdPaths) {
419
+ createdPaths.push(...prepared.createdPaths);
420
+ }
421
+ const kit = addKitToConfig({
422
+ config,
423
+ kitId,
424
+ sourcePath: prepared.sourcePath,
425
+ sourcePackage: prepared.sourcePackage,
426
+ predeploy: prepared.predeploy,
427
+ });
428
+ return { kit, isNewKit: true };
429
+ }
430
+ async function resolveOrCreateInstance(options) {
431
+ const { kit, existingFunctionsInfo, createdPaths = [] } = options;
729
432
  const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
730
433
  const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
731
434
  ? options.project
732
435
  : undefined;
733
- const unconfiguredInstances = getUnconfiguredInstancesForProject(options.config, existingKit, projectId, projectAlias);
734
- const isConfiguredForProject = Object.keys(existingKit.instances || {}).length > 0 && unconfiguredInstances.length === 0;
735
- let action;
736
- if (options.instanceId &&
737
- existingKit.instances &&
738
- Object.prototype.hasOwnProperty.call(existingKit.instances, options.instanceId)) {
739
- if (!unconfiguredInstances.includes(options.instanceId)) {
740
- throw new error_1.FirebaseError(`Instance '${options.instanceId}' is already configured for this project.`);
741
- }
742
- action = "addEnv";
743
- }
744
- else if (options.instanceId) {
745
- action = "addInstance";
746
- }
747
- else if (unconfiguredInstances.length > 0 && !options.nonInteractive) {
748
- const unconfiguredInstancesList = unconfiguredInstances.join(", ");
749
- action = await (0, prompt_1.select)({
750
- message: `The following instances already exist, but are not configured for this project: ${unconfiguredInstancesList}. What would you like to do?`,
751
- choices: [
752
- {
753
- name: "Add an instance to the existing kit",
754
- value: "addInstance",
755
- },
756
- {
757
- name: "Configure an existing instance for this project",
758
- value: "addEnv",
759
- },
760
- ],
761
- });
436
+ let mode;
437
+ let unconfiguredInstances = [];
438
+ const existingInstancesCount = Object.keys(kit.instances || {}).length;
439
+ if (existingInstancesCount === 0) {
440
+ mode = "addInstance";
762
441
  }
763
442
  else {
764
- if (isConfiguredForProject) {
765
- (0, utils_1.logLabeledBullet)("functions", `This package is already installed as kit ${existingKit.kit}, creating a new instance.`);
443
+ unconfiguredInstances = getUnconfiguredInstancesForProject({
444
+ config: options.config,
445
+ kit,
446
+ projectId,
447
+ projectAlias,
448
+ });
449
+ const isConfiguredForProject = existingInstancesCount > 0 && unconfiguredInstances.length === 0;
450
+ if (options.instanceId &&
451
+ kit.instances &&
452
+ Object.prototype.hasOwnProperty.call(kit.instances, options.instanceId)) {
453
+ if (!unconfiguredInstances.includes(options.instanceId)) {
454
+ throw new error_1.FirebaseError(`Instance '${options.instanceId}' is already configured for this project.`);
455
+ }
456
+ mode = "addEnv";
457
+ }
458
+ else if (options.instanceId) {
459
+ mode = "addInstance";
460
+ }
461
+ else if (unconfiguredInstances.length > 0 && !options.nonInteractive) {
462
+ const unconfiguredInstancesList = unconfiguredInstances.join(", ");
463
+ mode = await (0, prompt_1.select)({
464
+ message: `The following instances already exist, but are not configured for this project: ${unconfiguredInstancesList}. What would you like to do?`,
465
+ choices: [
466
+ {
467
+ name: "Add an instance to the existing kit",
468
+ value: "addInstance",
469
+ },
470
+ {
471
+ name: "Configure an existing instance for this project",
472
+ value: "addEnv",
473
+ },
474
+ ],
475
+ });
476
+ }
477
+ else {
478
+ if (isConfiguredForProject) {
479
+ const sourceLabel = kit.sourcePackage ? "package" : "directory";
480
+ (0, utils_1.logLabeledBullet)("functions", `This ${sourceLabel} is already installed as kit ${kit.kit}, creating a new instance.`);
481
+ }
482
+ mode = "addInstance";
766
483
  }
767
- action = "addInstance";
768
484
  }
769
- let resultAction;
770
- let instanceId;
771
- let configDirPath;
772
- let absConfigDirPath;
773
- if (action === "addInstance") {
774
- resultAction = "addedInstance";
775
- instanceId = await promptKitInstanceId(options.defaultInstanceId ?? existingKit.kit, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
776
- const expectedConfigDirPath = path.join(exports.FUNCTION_KITS_DIR, existingKit.kit, `config-${instanceId}`);
777
- absConfigDirPath = options.config.path(expectedConfigDirPath);
778
- createdPaths.push(absConfigDirPath);
485
+ if (mode === "addInstance") {
486
+ const instanceId = await promptKitInstanceId({
487
+ baseKitId: options.defaultInstanceId ?? kit.kit,
488
+ existingInstanceIds: existingFunctionsInfo.existingInstanceIds,
489
+ existingCodebases: existingFunctionsInfo.existingCodebases,
490
+ nonInteractive: options.nonInteractive,
491
+ customInstanceId: options.instanceId,
492
+ });
779
493
  const result = await addInstanceToKit({
780
494
  config: options.config,
781
- kitId: existingKit.kit,
495
+ kitId: kit.kit,
782
496
  instanceId,
783
- seedEnv: options.seedEnv,
784
497
  });
785
- configDirPath = result.configDirPath;
786
- absConfigDirPath = result.absConfigDirPath;
498
+ createdPaths.push(result.absConfigDirPath);
499
+ return {
500
+ instanceId,
501
+ configDirPath: result.configDirPath,
502
+ absConfigDirPath: result.absConfigDirPath,
503
+ isNewInstance: true,
504
+ };
787
505
  }
788
- else if (action === "addEnv") {
789
- resultAction = "configuredEnv";
790
- instanceId = await promptExistingInstanceForProject({
791
- ...options,
792
- existingKit,
793
- unconfiguredInstanceIds: unconfiguredInstances,
794
- });
795
- configDirPath = existingKit.instances?.[instanceId];
796
- if (!configDirPath) {
797
- throw new error_1.FirebaseError(`Configuration directory for instance '${instanceId}' not found in kit '${existingKit.kit}'.`);
798
- }
799
- absConfigDirPath = options.config.path(configDirPath);
800
- if (projectId) {
801
- const envPath = path.join(absConfigDirPath, `.env.${projectId}`);
802
- if (!(await fs.pathExists(envPath))) {
803
- createdPaths.push(envPath);
804
- }
805
- }
806
- if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
807
- await fs.ensureDir(absConfigDirPath);
808
- (0, env_2.seedKitInstanceEnv)({
809
- configDir: absConfigDirPath,
810
- functionsSource: options.config.path(existingKit.source),
811
- projectDir: options.config.projectDir,
812
- projectId: options.seedEnv.projectId,
813
- projectAlias: options.seedEnv.projectAlias,
814
- envs: options.seedEnv.envs,
815
- });
506
+ const instanceId = await promptExistingInstanceForProject({
507
+ ...options,
508
+ existingKit: kit,
509
+ unconfiguredInstanceIds: unconfiguredInstances,
510
+ });
511
+ const configDirPath = kit.instances?.[instanceId];
512
+ if (!configDirPath) {
513
+ throw new error_1.FirebaseError(`Configuration directory for instance '${instanceId}' not found in kit '${kit.kit}'.`);
514
+ }
515
+ const absConfigDirPath = options.config.path(configDirPath);
516
+ return {
517
+ instanceId,
518
+ configDirPath,
519
+ absConfigDirPath,
520
+ isNewInstance: false,
521
+ };
522
+ }
523
+ async function configureInstanceForProject(options) {
524
+ const { kit, instanceId, absConfigDirPath, createdPaths = [] } = options;
525
+ const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
526
+ const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
527
+ ? options.project
528
+ : undefined;
529
+ const absSourcePath = options.config.path(kit.source);
530
+ if (projectId) {
531
+ const envPath = path.join(absConfigDirPath, `.env.${projectId}`);
532
+ if (!(await fs.pathExists(envPath))) {
533
+ createdPaths.push(envPath);
816
534
  }
817
535
  }
818
- else {
819
- throw new error_1.FirebaseError(`Unexpected action '${String(action)}' for kit installation.`);
536
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
537
+ await fs.ensureDir(absConfigDirPath);
538
+ (0, env_1.seedKitInstanceEnv)({
539
+ configDir: absConfigDirPath,
540
+ functionsSource: absSourcePath,
541
+ projectDir: options.config.projectDir,
542
+ projectId: options.seedEnv.projectId,
543
+ projectAlias: options.seedEnv.projectAlias,
544
+ envs: options.seedEnv.envs,
545
+ });
820
546
  }
821
547
  if (projectId) {
822
548
  fs.ensureFileSync(path.join(absConfigDirPath, `.env.${projectId}`));
823
549
  }
824
- const absSourcePath = options.config.path(existingKit.source);
825
550
  let discoveredBuild;
826
551
  const shouldConfigure = options.configure !== false;
827
552
  if (shouldConfigure) {
828
553
  try {
829
- discoveredBuild = await discoverKitBuild({ ...options, instanceId }, absSourcePath);
554
+ discoveredBuild = await discoverKitBuild({
555
+ ...options,
556
+ absSourcePath,
557
+ instanceId,
558
+ runtime: kit.runtime,
559
+ });
830
560
  }
831
561
  catch (err) {
832
562
  logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
@@ -844,202 +574,77 @@ async function addKitInstanceOrConfigureProject(options) {
844
574
  });
845
575
  }
846
576
  }
847
- if (action === "addInstance") {
848
- (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully added to kit ${clc.bold(existingKit.kit)}.`);
849
- }
850
- else if (action === "addEnv") {
851
- const projectDisplay = projectId || options.project || "project";
852
- (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully configured for ${clc.bold(projectDisplay)}.`);
853
- }
854
- await printKitFirstDeployReport({
855
- config: options.config,
856
- project: options.project,
857
- projectId: options.projectId,
858
- instanceId,
859
- absSourcePath,
860
- preDiscoveredBuild: discoveredBuild,
861
- });
862
- return {
863
- action: resultAction,
864
- kitId: existingKit.kit,
865
- instanceId,
866
- sourcePath: existingKit.source,
867
- configDirPath,
868
- };
869
- }
870
- function findExistingKit(existingFunctions, options) {
871
- if (options.package) {
872
- const { packageName } = parseNpmPackageSpecifier(options.package);
873
- return existingFunctions.find((c) => (0, projectConfig_1.isKitConfig)(c) && c.sourcePackage?.name === packageName);
874
- }
875
- if (options.directory) {
876
- const absDir = path.isAbsolute(options.directory)
877
- ? options.directory
878
- : path.resolve(options.config.projectDir, options.directory);
879
- return existingFunctions.find((c) => (0, projectConfig_1.isKitConfig)(c) &&
880
- !c.sourcePackage &&
881
- path.resolve(options.config.projectDir, c.source) === absDir);
882
- }
883
- return undefined;
884
- }
885
- async function resolvePackageSource(options) {
886
- const templateType = options.template || exports.DEFAULT_TEMPLATE;
887
- if (!(templateType in exports.TEMPLATES)) {
888
- const validTemplates = Object.keys(exports.TEMPLATES)
889
- .map((t) => `'${t}'`)
890
- .join(" or ");
891
- throw new error_1.FirebaseError(`Invalid template '${templateType}'. Template must be ${validTemplates}.`);
892
- }
893
- const rawPkgName = options.package;
894
- if (!rawPkgName) {
895
- throw new error_1.FirebaseError("Set the --package option to a valid NPM package and try again.");
896
- }
897
- await validateNpmPackageExists(rawPkgName);
898
- const { packageName } = parseNpmPackageSpecifier(rawPkgName);
899
- const isThirdParty = await promptSecurityConfirmation({
900
- rawPkgName,
901
- packageName,
902
- nonInteractive: options.nonInteractive,
903
- force: options.force,
904
- });
905
- return {
906
- defaultKitName: packageName,
907
- sourcePackageName: packageName,
908
- hasBuildScript: true,
909
- setup: (kitId, instanceId) => scaffoldKitFiles(options.config, kitId, instanceId, packageName, templateType),
910
- buildAndInstall: (absSourcePath) => buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty),
911
- };
912
- }
913
- async function resolveDirectorySource(options) {
914
- if (!options.directory) {
915
- throw new error_1.FirebaseError("Must specify --directory.");
916
- }
917
- const { absDirectoryPath, relSourcePath, hasBuildScript } = await validateAndResolveDirectoryKit(options.config.projectDir, options.directory);
918
- return {
919
- defaultKitName: path.basename(absDirectoryPath),
920
- sourcePackageName: undefined,
921
- hasBuildScript,
922
- setup: async (kitId, instanceId) => {
923
- const configDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
924
- const absConfigDirPath = options.config.path(configDirPath);
925
- await fs.ensureDir(absConfigDirPath);
926
- return {
927
- sourcePath: relSourcePath,
928
- configDirPath,
929
- absSourcePath: absDirectoryPath,
930
- absConfigDirPath,
931
- };
932
- },
933
- buildAndInstall: (absSourcePath) => buildAndInstallDirectoryKit(absSourcePath, hasBuildScript),
934
- };
577
+ return discoveredBuild;
935
578
  }
936
579
  async function installKitOrInstance(options) {
937
580
  if (options.package && options.directory) {
938
581
  throw new error_1.FirebaseError("Cannot specify both --package and --directory. Please choose one.");
939
582
  }
940
- if (!options.package && !options.directory) {
941
- throw new error_1.FirebaseError("Must specify either --package or --directory.");
942
- }
943
583
  if (options.directory && options.template) {
944
584
  throw new error_1.FirebaseError("Cannot specify --template with --directory.");
945
585
  }
946
- if (options.package) {
947
- validateNpmPackageName(options.package);
586
+ if (!options.package && !options.directory) {
587
+ throw new error_1.FirebaseError("Must specify either --package or --directory.");
948
588
  }
589
+ const adapter = options.directory
590
+ ? (0, directory_1.createDirectoryAdapter)(options.config, options.directory)
591
+ : (0, npm_1.createNpmPackageAdapter)({
592
+ config: options.config,
593
+ package: options.package || "",
594
+ template: options.template,
595
+ nonInteractive: options.nonInteractive,
596
+ force: options.force,
597
+ });
949
598
  const originalFunctions = (0, utils_1.cloneDeep)(options.config.src.functions);
950
599
  const createdPaths = [];
951
600
  let kitId;
952
601
  try {
953
602
  const existingFunctionsInfo = extractExistingFunctionsInfo(options.config.src.functions);
954
- const existingKit = findExistingKit(existingFunctionsInfo.existingFunctions, options);
955
- if (existingKit) {
956
- kitId = existingKit.kit;
957
- return await addKitInstanceOrConfigureProject({
958
- ...options,
959
- existingKit,
960
- existingFunctionsInfo,
961
- createdPaths,
962
- });
963
- }
964
- const source = options.directory
965
- ? await resolveDirectorySource(options)
966
- : await resolvePackageSource(options);
967
- kitId = await promptKitId(source.defaultKitName, existingFunctionsInfo.existingKitIds, options.nonInteractive, options.kitId);
968
- const instanceId = await promptKitInstanceId(options.defaultInstanceId ?? kitId, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
969
- const isPackageKit = !options.directory;
970
- const absKitDir = options.config.path(path.join(exports.FUNCTION_KITS_DIR, kitId));
971
- const expectedConfigDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
972
- const absConfigDirPath = options.config.path(expectedConfigDirPath);
973
- if (isPackageKit) {
974
- createdPaths.push(absKitDir);
975
- }
976
- else {
977
- createdPaths.push(absConfigDirPath);
978
- }
979
- const setupResult = await source.setup(kitId, instanceId);
980
- const { sourcePath, configDirPath, absSourcePath } = setupResult;
981
- if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
982
- (0, env_2.seedKitInstanceEnv)({
983
- configDir: setupResult.absConfigDirPath,
984
- functionsSource: absSourcePath,
985
- projectDir: options.config.projectDir,
986
- projectId: options.seedEnv.projectId,
987
- projectAlias: options.seedEnv.projectAlias,
988
- envs: options.seedEnv.envs,
989
- });
990
- }
991
- await source.buildAndInstall(absSourcePath);
992
603
  const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
993
- const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
994
- ? options.project
995
- : undefined;
996
- if (projectId) {
997
- fs.ensureFileSync(path.join(setupResult.absConfigDirPath, `.env.${projectId}`));
998
- }
999
- let discoveredBuild;
1000
- const shouldConfigure = options.configure !== false;
1001
- if (shouldConfigure) {
1002
- try {
1003
- discoveredBuild = await discoverKitBuild({ ...options, instanceId }, absSourcePath);
1004
- }
1005
- catch (err) {
1006
- logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
1007
- }
1008
- if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
1009
- await promptAndWriteKitParams({
1010
- config: options.config,
1011
- projectId,
1012
- projectAlias,
1013
- absConfigDirPath: setupResult.absConfigDirPath,
1014
- absSourcePath,
1015
- instanceId,
1016
- nonInteractive: options.nonInteractive,
1017
- params: discoveredBuild.params,
1018
- });
1019
- }
1020
- }
1021
- addKitToConfig(options.config, {
1022
- kitId,
604
+ const { kit, isNewKit } = await ensureKit({
605
+ ...options,
606
+ adapter,
607
+ existingFunctionsInfo,
608
+ createdPaths,
609
+ });
610
+ kitId = kit.kit;
611
+ const { instanceId, configDirPath, absConfigDirPath, isNewInstance } = await resolveOrCreateInstance({
612
+ ...options,
613
+ kit,
614
+ existingFunctionsInfo,
615
+ createdPaths,
616
+ });
617
+ const discoveredBuild = await configureInstanceForProject({
618
+ ...options,
619
+ kit,
1023
620
  instanceId,
1024
- packageName: source.sourcePackageName,
1025
- sourcePath,
1026
621
  configDirPath,
1027
- hasBuildScript: source.hasBuildScript,
622
+ absConfigDirPath,
623
+ createdPaths,
1028
624
  });
1029
- (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
625
+ if (isNewKit) {
626
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kit.kit)} successfully installed.`);
627
+ }
628
+ else if (isNewInstance) {
629
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully added to kit ${clc.bold(kit.kit)}.`);
630
+ }
631
+ else {
632
+ const projectDisplay = projectId || options.project || "project";
633
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully configured for ${clc.bold(projectDisplay)}.`);
634
+ }
1030
635
  await printKitFirstDeployReport({
1031
636
  config: options.config,
1032
637
  project: options.project,
1033
638
  projectId: options.projectId,
1034
639
  instanceId,
1035
- absSourcePath,
640
+ absSourcePath: options.config.path(kit.source),
641
+ runtime: kit.runtime,
1036
642
  preDiscoveredBuild: discoveredBuild,
1037
643
  });
1038
644
  return {
1039
- action: "installedKit",
1040
- kitId,
645
+ kitId: kit.kit,
1041
646
  instanceId,
1042
- sourcePath,
647
+ sourcePath: kit.source,
1043
648
  configDirPath,
1044
649
  };
1045
650
  }
@@ -1048,9 +653,9 @@ async function installKitOrInstance(options) {
1048
653
  logger_1.logger.debug(`Failed to clean up path '${targetPath}': ${(0, error_1.getErrMsg)(cleanupErr)}`);
1049
654
  })));
1050
655
  if (kitId) {
1051
- await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(path.join(exports.FUNCTION_KITS_DIR, kitId)));
656
+ await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(path.join(types_1.FUNCTION_KITS_DIR, kitId)));
1052
657
  }
1053
- await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(exports.FUNCTION_KITS_DIR));
658
+ await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(types_1.FUNCTION_KITS_DIR));
1054
659
  revertFunctionsConfig({ config: options.config, originalFunctions });
1055
660
  throw err;
1056
661
  }