firebase-tools 15.28.2 → 15.29.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 (76) hide show
  1. package/lib/api.js +4 -2
  2. package/lib/apphosting/config.js +10 -8
  3. package/lib/apphosting/localbuilds.js +8 -0
  4. package/lib/apphosting/yaml.js +27 -0
  5. package/lib/bin/cli.js +1 -1
  6. package/lib/bin/mcp.js +8 -3
  7. package/lib/commands/ext-export.js +34 -13
  8. package/lib/commands/ext-migrate.js +3 -0
  9. package/lib/commands/functions-delete.js +6 -67
  10. package/lib/commands/functions-kits-install.js +7 -0
  11. package/lib/commands/functions-kits-uninstall.js +7 -71
  12. package/lib/crashlytics/onboarding.js +23 -2
  13. package/lib/deploy/apphosting/deploy.js +2 -1
  14. package/lib/deploy/apphosting/prepare.js +12 -3
  15. package/lib/deploy/apphosting/release.js +3 -0
  16. package/lib/deploy/apphosting/util.js +3 -1
  17. package/lib/deploy/extensions/secrets.js +10 -0
  18. package/lib/deploy/functions/delete.js +80 -0
  19. package/lib/emulator/types.js +3 -1
  20. package/lib/extensions/askUserForParam.js +9 -8
  21. package/lib/extensions/export.js +46 -9
  22. package/lib/extensions/extensionsHelper.js +28 -0
  23. package/lib/extensions/migrate.js +121 -2
  24. package/lib/extensions/paramHelper.js +78 -25
  25. package/lib/extensions/secretsUtils.js +3 -0
  26. package/lib/extensions/updateHelper.js +3 -1
  27. package/lib/functions/kits/install.js +319 -69
  28. package/lib/gcp/apikeys.js +89 -0
  29. package/lib/gcp/storage.js +3 -2
  30. package/lib/logger.js +83 -9
  31. package/lib/mcp/tools/apphosting/fetch_logs.js +1 -0
  32. package/lib/mcp/tools/apphosting/list_backends.js +1 -0
  33. package/lib/mcp/tools/apptesting/tests.js +2 -0
  34. package/lib/mcp/tools/auth/get_users.js +1 -0
  35. package/lib/mcp/tools/auth/set_sms_region_policy.js +1 -0
  36. package/lib/mcp/tools/auth/update_user.js +1 -0
  37. package/lib/mcp/tools/core/create_android_sha.js +1 -0
  38. package/lib/mcp/tools/core/create_app.js +1 -0
  39. package/lib/mcp/tools/core/create_project.js +1 -0
  40. package/lib/mcp/tools/core/deploy.js +1 -0
  41. package/lib/mcp/tools/core/deploy_status.js +1 -0
  42. package/lib/mcp/tools/core/get_environment.js +1 -0
  43. package/lib/mcp/tools/core/get_project.js +1 -0
  44. package/lib/mcp/tools/core/get_sdk_config.js +1 -0
  45. package/lib/mcp/tools/core/get_security_rules.js +1 -0
  46. package/lib/mcp/tools/core/init.js +1 -0
  47. package/lib/mcp/tools/core/list_apps.js +1 -0
  48. package/lib/mcp/tools/core/list_projects.js +1 -0
  49. package/lib/mcp/tools/core/login.js +1 -0
  50. package/lib/mcp/tools/core/logout.js +1 -0
  51. package/lib/mcp/tools/core/read_resources.js +1 -0
  52. package/lib/mcp/tools/core/update_environment.js +1 -0
  53. package/lib/mcp/tools/core/validate_security_rules.js +1 -0
  54. package/lib/mcp/tools/crashlytics/events.js +2 -0
  55. package/lib/mcp/tools/crashlytics/issues.js +2 -0
  56. package/lib/mcp/tools/crashlytics/notes.js +3 -0
  57. package/lib/mcp/tools/crashlytics/reports.js +1 -0
  58. package/lib/mcp/tools/dataconnect/compile.js +1 -0
  59. package/lib/mcp/tools/dataconnect/execute.js +1 -0
  60. package/lib/mcp/tools/dataconnect/list_services.js +1 -0
  61. package/lib/mcp/tools/firestore/query_collection.js +1 -0
  62. package/lib/mcp/tools/functions/get_logs.js +1 -0
  63. package/lib/mcp/tools/functions/list_functions.js +1 -0
  64. package/lib/mcp/tools/index.js +3 -1
  65. package/lib/mcp/tools/messaging/send_message.js +1 -0
  66. package/lib/mcp/tools/realtime_database/get_data.js +1 -0
  67. package/lib/mcp/tools/realtime_database/set_data.js +1 -0
  68. package/lib/mcp/tools/remoteconfig/get_template.js +1 -0
  69. package/lib/mcp/tools/remoteconfig/update_template.js +1 -0
  70. package/lib/mcp/tools/storage/get_download_url.js +1 -0
  71. package/lib/prompt.js +10 -1
  72. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  73. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  74. package/package.json +1 -1
  75. package/templates/init/functions/typescript/index-kit-migration.ts +20 -2
  76. package/templates/init/functions/typescript/package-kit.json +21 -0
@@ -7,7 +7,7 @@ exports.validateNpmPackageName = validateNpmPackageName;
7
7
  exports.sanitizePackageNameToKitName = sanitizePackageNameToKitName;
8
8
  exports.isThirdPartyPackage = isThirdPartyPackage;
9
9
  exports.checkPackageHasShrinkwrap = checkPackageHasShrinkwrap;
10
- exports.isKitConfiguredForProject = isKitConfiguredForProject;
10
+ exports.getUnconfiguredInstancesForProject = getUnconfiguredInstancesForProject;
11
11
  exports.extractExistingFunctionsInfo = extractExistingFunctionsInfo;
12
12
  exports.promptKitInstanceId = promptKitInstanceId;
13
13
  exports.promptKitId = promptKitId;
@@ -16,6 +16,8 @@ exports.promptExistingInstanceForProject = promptExistingInstanceForProject;
16
16
  exports.writeKitPackageJson = writeKitPackageJson;
17
17
  exports.writeKitIndexTs = writeKitIndexTs;
18
18
  exports.scaffoldKitFiles = scaffoldKitFiles;
19
+ exports.resolveSdkSpecifierToSave = resolveSdkSpecifierToSave;
20
+ exports.getKitPackagesToSave = getKitPackagesToSave;
19
21
  exports.buildAndInstallKit = buildAndInstallKit;
20
22
  exports.addKitToConfig = addKitToConfig;
21
23
  exports.validateAndResolveDirectoryKit = validateAndResolveDirectoryKit;
@@ -25,6 +27,7 @@ exports.addInstanceToKitConfig = addInstanceToKitConfig;
25
27
  exports.scaffoldKit = scaffoldKit;
26
28
  exports.addInstanceToKit = addInstanceToKit;
27
29
  exports.discoverKitBuild = discoverKitBuild;
30
+ exports.promptAndWriteKitParams = promptAndWriteKitParams;
28
31
  exports.printKitFirstDeployReport = printKitFirstDeployReport;
29
32
  exports.addKitInstanceOrConfigureProject = addKitInstanceOrConfigureProject;
30
33
  exports.findExistingKit = findExistingKit;
@@ -35,6 +38,7 @@ const crypto = require("crypto");
35
38
  const path = require("path");
36
39
  const clc = require("colorette");
37
40
  const fs = require("fs-extra");
41
+ const semver = require("semver");
38
42
  const error_1 = require("../../error");
39
43
  const projectUtils_1 = require("../../projectUtils");
40
44
  const utils_1 = require("../../utils");
@@ -46,7 +50,13 @@ const templates_1 = require("../../templates");
46
50
  const supported = require("../../deploy/functions/runtimes/supported");
47
51
  const runtimes = require("../../deploy/functions/runtimes");
48
52
  const build = require("../../deploy/functions/build");
53
+ const params = require("../../deploy/functions/params");
54
+ const experiments = require("../../experiments");
49
55
  const iam = require("../../gcp/iam");
56
+ const functionsEnv = require("../env");
57
+ const functionsConfig = require("../../functionsConfig");
58
+ const prepare_1 = require("../../deploy/functions/prepare");
59
+ const utils_2 = require("../../utils");
50
60
  const env_1 = require("../env");
51
61
  const env_2 = require("./env");
52
62
  exports.TEMPLATES = {
@@ -56,7 +66,7 @@ exports.TEMPLATES = {
56
66
  exports.DEFAULT_TEMPLATE = "installation";
57
67
  exports.FUNCTION_KITS_DIR = "function-kits";
58
68
  function generateUniqueId(baseId, existingIds) {
59
- if (!existingIds.has(baseId)) {
69
+ if (!existingIds.includes(baseId)) {
60
70
  return baseId;
61
71
  }
62
72
  const prefix = baseId.slice(0, 35);
@@ -64,32 +74,39 @@ function generateUniqueId(baseId, existingIds) {
64
74
  do {
65
75
  const randomSuffix = crypto.randomBytes(2).toString("hex");
66
76
  candidate = `${prefix}-${randomSuffix}`;
67
- } while (existingIds.has(candidate));
77
+ } while (existingIds.includes(candidate));
68
78
  return candidate;
69
79
  }
70
80
  function parseNpmPackageSpecifier(rawPkg) {
71
81
  const lastAt = rawPkg.lastIndexOf("@");
72
82
  if (lastAt > 0) {
83
+ const version = rawPkg.substring(lastAt + 1);
73
84
  return {
74
85
  packageName: rawPkg.substring(0, lastAt),
75
- version: rawPkg.substring(lastAt + 1),
86
+ ...(version ? { version } : {}),
76
87
  };
77
88
  }
78
89
  return { packageName: rawPkg };
79
90
  }
80
- function validateNpmPackageName(packageName) {
91
+ function validateNpmPackageName(packageNameOrSpecifier) {
92
+ const { packageName, version } = parseNpmPackageSpecifier(packageNameOrSpecifier);
81
93
  const npmPackageRegex = /^(?:@[a-z0-9_.-]+\/[a-z0-9_.-]+|[a-z0-9_.-]+)$/i;
82
- if (!packageName || packageName.length > 214 || !npmPackageRegex.test(packageName)) {
83
- throw new error_1.FirebaseError(`Invalid NPM package name '${packageName}'. Package names must be valid npm package specifiers (e.g. 'my-kit' or '@scope/my-kit').`);
94
+ if (!packageName ||
95
+ packageName.length > 214 ||
96
+ !npmPackageRegex.test(packageName) ||
97
+ (packageNameOrSpecifier.lastIndexOf("@") > 0 && !version)) {
98
+ 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').`);
84
99
  }
85
100
  }
86
- function sanitizePackageNameToKitName(packageName) {
101
+ function sanitizePackageNameToKitName(packageNameOrSpecifier) {
102
+ const { packageName } = parseNpmPackageSpecifier(packageNameOrSpecifier);
87
103
  const parts = packageName.split("/");
88
104
  const nameWithoutScope = parts[parts.length - 1] || packageName;
89
105
  const sanitized = nameWithoutScope.toLowerCase().replace(/[^a-z0-9_-]/g, "");
90
106
  return sanitized.slice(0, 40);
91
107
  }
92
- function isThirdPartyPackage(packageName) {
108
+ function isThirdPartyPackage(packageNameOrSpecifier) {
109
+ const { packageName } = parseNpmPackageSpecifier(packageNameOrSpecifier);
93
110
  return !packageName.startsWith("@firebase-function-kits/");
94
111
  }
95
112
  async function checkPackageHasShrinkwrap(rawPkgName) {
@@ -111,29 +128,29 @@ async function checkPackageHasShrinkwrap(rawPkgName) {
111
128
  }
112
129
  return false;
113
130
  }
114
- function isKitConfiguredForProject(config, kit, projectId, projectAlias) {
115
- return Object.values(kit.instances || {}).some((configDir) => (0, env_1.hasProjectEnv)(config.path(configDir), projectId, projectAlias));
131
+ function getUnconfiguredInstancesForProject(config, kit, projectId, projectAlias) {
132
+ return Object.entries(kit.instances || {})
133
+ .filter(([, configDir]) => !(0, env_1.hasProjectEnv)(config.path(configDir), projectId, projectAlias))
134
+ .map(([instanceId]) => instanceId);
116
135
  }
117
136
  function extractExistingFunctionsInfo(configFunctions) {
118
137
  const existingFunctions = configFunctions && (!Array.isArray(configFunctions) || configFunctions.length > 0)
119
138
  ? (0, projectConfig_1.normalizeAndValidate)(configFunctions)
120
139
  : [];
121
- const existingKitIds = new Set();
122
- const existingCodebases = new Set();
123
- const existingInstanceIds = new Set();
140
+ const existingKitIds = [];
141
+ const existingCodebases = [];
142
+ const existingInstanceIds = [];
124
143
  for (const c of existingFunctions) {
125
144
  if ((0, projectConfig_1.isKitConfig)(c)) {
126
145
  if (c.kit) {
127
- existingKitIds.add(c.kit);
146
+ existingKitIds.push(c.kit);
128
147
  }
129
148
  if (c.instances) {
130
- for (const instId of Object.keys(c.instances)) {
131
- existingInstanceIds.add(instId);
132
- }
149
+ existingInstanceIds.push(...Object.keys(c.instances));
133
150
  }
134
151
  }
135
152
  else if (c.codebase) {
136
- existingCodebases.add(c.codebase);
153
+ existingCodebases.push(c.codebase);
137
154
  }
138
155
  }
139
156
  return {
@@ -144,14 +161,14 @@ function extractExistingFunctionsInfo(configFunctions) {
144
161
  };
145
162
  }
146
163
  async function promptKitInstanceId(baseKitId, existingInstanceIds, existingCodebases, nonInteractive, customInstanceId) {
147
- const instanceCollisions = new Set([...existingInstanceIds, ...existingCodebases]);
164
+ const instanceCollisions = [...existingInstanceIds, ...existingCodebases];
148
165
  const defaultInstanceId = generateUniqueId(baseKitId, instanceCollisions);
149
166
  if (customInstanceId) {
150
167
  (0, projectConfig_1.validateKitInstanceId)(customInstanceId);
151
- if (existingInstanceIds.has(customInstanceId)) {
168
+ if (existingInstanceIds.includes(customInstanceId)) {
152
169
  throw new error_1.FirebaseError(`functions kit instance ID must be unique across all kits, but '${customInstanceId}' was used more than once.`);
153
170
  }
154
- if (existingCodebases.has(customInstanceId)) {
171
+ if (existingCodebases.includes(customInstanceId)) {
155
172
  throw new error_1.FirebaseError(`functions codebase name and kit instance ID must be mutually exclusive, but '${customInstanceId}' was used as both a codebase name and a kit instance ID.`);
156
173
  }
157
174
  return customInstanceId;
@@ -167,20 +184,20 @@ async function promptKitInstanceId(baseKitId, existingInstanceIds, existingCodeb
167
184
  catch (err) {
168
185
  return (0, error_1.getErrMsg)(err);
169
186
  }
170
- if (existingInstanceIds.has(val)) {
187
+ if (existingInstanceIds.includes(val)) {
171
188
  return `functions kit instance ID must be unique across all kits, but '${val}' was used more than once.`;
172
189
  }
173
- if (existingCodebases.has(val)) {
190
+ if (existingCodebases.includes(val)) {
174
191
  return `functions codebase name and kit instance ID must be mutually exclusive, but '${val}' was used as both a codebase name and a kit instance ID.`;
175
192
  }
176
193
  return true;
177
194
  },
178
195
  });
179
196
  (0, projectConfig_1.validateKitInstanceId)(instanceId);
180
- if (existingInstanceIds.has(instanceId)) {
197
+ if (existingInstanceIds.includes(instanceId)) {
181
198
  throw new error_1.FirebaseError(`functions kit instance ID must be unique across all kits, but '${instanceId}' was used more than once.`);
182
199
  }
183
- if (existingCodebases.has(instanceId)) {
200
+ if (existingCodebases.includes(instanceId)) {
184
201
  throw new error_1.FirebaseError(`functions codebase name and kit instance ID must be mutually exclusive, but '${instanceId}' was used as both a codebase name and a kit instance ID.`);
185
202
  }
186
203
  return instanceId;
@@ -190,7 +207,7 @@ async function promptKitId(packageName, existingKitIds, nonInteractive, customKi
190
207
  const defaultKitId = generateUniqueId(baseKitId, existingKitIds);
191
208
  if (customKitId) {
192
209
  (0, projectConfig_1.validateKit)(customKitId);
193
- if (existingKitIds.has(customKitId)) {
210
+ if (existingKitIds.includes(customKitId)) {
194
211
  throw new error_1.FirebaseError(`functions.kit must be unique but '${customKitId}' was used more than once.`);
195
212
  }
196
213
  return customKitId;
@@ -206,14 +223,14 @@ async function promptKitId(packageName, existingKitIds, nonInteractive, customKi
206
223
  catch (err) {
207
224
  return (0, error_1.getErrMsg)(err);
208
225
  }
209
- if (existingKitIds.has(val)) {
226
+ if (existingKitIds.includes(val)) {
210
227
  return `functions.kit must be unique but '${val}' was used more than once.`;
211
228
  }
212
229
  return true;
213
230
  },
214
231
  });
215
232
  (0, projectConfig_1.validateKit)(kitId);
216
- if (existingKitIds.has(kitId)) {
233
+ if (existingKitIds.includes(kitId)) {
217
234
  throw new error_1.FirebaseError(`functions.kit must be unique but '${kitId}' was used more than once.`);
218
235
  }
219
236
  return kitId;
@@ -249,25 +266,33 @@ async function promptSecurityConfirmation(rawPkgName, packageName, nonInteractiv
249
266
  }
250
267
  return isThirdParty;
251
268
  }
252
- async function promptExistingInstanceForProject(options, existingKit) {
253
- const instanceIds = Object.keys(existingKit.instances || {});
254
- if (instanceIds.length === 0) {
255
- throw new error_1.FirebaseError(`Kit '${existingKit.kit}' has no instances configured.`);
269
+ async function promptExistingInstanceForProject(options) {
270
+ const allInstanceIds = Object.keys(options.existingKit.instances || {});
271
+ if (allInstanceIds.length === 0) {
272
+ throw new error_1.FirebaseError(`Kit '${options.existingKit.kit}' has no instances configured.`);
273
+ }
274
+ if (options.instanceId) {
275
+ if (!allInstanceIds.includes(options.instanceId)) {
276
+ throw new error_1.FirebaseError(`Instance '${options.instanceId}' does not exist in kit '${options.existingKit.kit}'. Available instances: ${allInstanceIds.join(", ")}`);
277
+ }
278
+ if (!options.unconfiguredInstanceIds.includes(options.instanceId)) {
279
+ throw new error_1.FirebaseError(`Instance '${options.instanceId}' is already configured for this project.`);
280
+ }
281
+ return options.instanceId;
256
282
  }
257
- let selectedInstanceId = "<instance-name>";
258
- if (instanceIds.length === 1) {
259
- selectedInstanceId = instanceIds[0];
283
+ if (options.unconfiguredInstanceIds.length === 0) {
284
+ throw new error_1.FirebaseError(`Kit '${options.existingKit.kit}' has no unconfigured instances for this project.`);
260
285
  }
261
- else if (!options.nonInteractive) {
262
- selectedInstanceId = await (0, prompt_1.select)({
263
- message: "Which instance would you like to configure for this project?",
264
- choices: instanceIds.map((id) => ({ name: id, value: id })),
265
- });
286
+ if (options.unconfiguredInstanceIds.length === 1) {
287
+ const instanceId = options.unconfiguredInstanceIds[0];
288
+ (0, utils_1.logLabeledBullet)("functions", `${clc.bold(instanceId)} is the only instance without a configuration. Configuring...`);
289
+ return instanceId;
266
290
  }
267
- const targetProject = (0, projectUtils_1.getProjectId)(options) || options.project || "<project-name>";
268
- (0, utils_1.logLabeledBullet)("functions", `To create a new instance in this project, deploy the instance dedicated to this project using\n` +
269
- clc.bold(`firebase deploy --only functions:${selectedInstanceId} --project ${targetProject}`));
270
- return selectedInstanceId;
291
+ return (0, prompt_1.select)({
292
+ message: "Which instance would you like to configure for this project?",
293
+ choices: options.unconfiguredInstanceIds,
294
+ nonInteractive: options.nonInteractive,
295
+ });
271
296
  }
272
297
  async function writeKitPackageJson(config, sourcePath, kitId) {
273
298
  const relPackageJsonPath = path.join(sourcePath, "package.json");
@@ -283,13 +308,15 @@ async function writeKitPackageJson(config, sourcePath, kitId) {
283
308
  }
284
309
  else {
285
310
  const latestNodeVersion = supported.latest("nodejs").replace("nodejs", "");
286
- const packageNoLintingTemplate = (0, templates_1.readTemplateSync)("init/functions/typescript/package.nolint.json");
287
- const subbedTemplate = packageNoLintingTemplate.replace(/{{RUNTIME}}/g, latestNodeVersion);
311
+ const packageKitTemplate = (0, templates_1.readTemplateSync)("init/functions/typescript/package-kit.json");
312
+ const subbedTemplate = packageKitTemplate.replace(/{{RUNTIME}}/g, latestNodeVersion);
288
313
  try {
289
314
  pkgJson = JSON.parse(subbedTemplate);
290
315
  }
291
316
  catch (err) {
292
- throw new error_1.FirebaseError("Failed to parse package.nolint.json template: " + (0, error_1.getErrMsg)(err));
317
+ throw new error_1.FirebaseError("Failed to parse package-kit.json template: " + (0, error_1.getErrMsg)(err), {
318
+ original: err instanceof Error ? err : undefined,
319
+ });
293
320
  }
294
321
  }
295
322
  pkgJson.name = `${kitId}-wrapper`;
@@ -317,7 +344,67 @@ async function scaffoldKitFiles(config, kitId, instanceId, packageName, template
317
344
  await writeKitIndexTs(config, sourcePath, packageName, templateType);
318
345
  return { sourcePath, configDirPath, absSourcePath, absConfigDirPath };
319
346
  }
347
+ function resolveSdkSpecifierToSave(packageName, declaredVer, installedVer) {
348
+ const cleanVer = semver.clean(declaredVer);
349
+ if (cleanVer) {
350
+ return `${packageName}@=${installedVer || cleanVer}`;
351
+ }
352
+ if (declaredVer.trim().startsWith("~")) {
353
+ return installedVer ? `${packageName}@~${installedVer}` : `${packageName}@${declaredVer}`;
354
+ }
355
+ if (installedVer) {
356
+ return `${packageName}@^${installedVer}`;
357
+ }
358
+ return `${packageName}@${declaredVer}`;
359
+ }
360
+ async function getKitPackagesToSave(absSourcePath, packageName) {
361
+ const lockfilePath = path.join(absSourcePath, "package-lock.json");
362
+ let peerDeps = {};
363
+ let directDeps = {};
364
+ let installedFunctionsVer;
365
+ let installedAdminVer;
366
+ if (await fs.pathExists(lockfilePath)) {
367
+ try {
368
+ const lockfile = (await fs.readJson(lockfilePath));
369
+ const packages = lockfile.packages || {};
370
+ const kitEntry = packages[`node_modules/${packageName}`] || {};
371
+ peerDeps = kitEntry.peerDependencies || {};
372
+ directDeps = kitEntry.dependencies || {};
373
+ installedFunctionsVer = packages["node_modules/firebase-functions"]?.version;
374
+ installedAdminVer = packages["node_modules/firebase-admin"]?.version;
375
+ }
376
+ catch (err) {
377
+ logger_1.logger.debug(`Failed to read package-lock.json: ${(0, error_1.getErrMsg)(err)}`);
378
+ }
379
+ }
380
+ if (Object.keys(peerDeps).length === 0 && Object.keys(directDeps).length === 0) {
381
+ const kitPkgJsonPath = path.join(absSourcePath, "node_modules", packageName, "package.json");
382
+ if (await fs.pathExists(kitPkgJsonPath)) {
383
+ try {
384
+ const kitPkgJson = (await fs.readJson(kitPkgJsonPath));
385
+ peerDeps = kitPkgJson.peerDependencies || {};
386
+ directDeps = kitPkgJson.dependencies || {};
387
+ }
388
+ catch (err) {
389
+ logger_1.logger.debug(`Failed to read kit package.json: ${(0, error_1.getErrMsg)(err)}`);
390
+ }
391
+ }
392
+ }
393
+ const declaredFunctionsVer = peerDeps["firebase-functions"] || directDeps["firebase-functions"];
394
+ if (!declaredFunctionsVer) {
395
+ throw new error_1.FirebaseError(`Package '${packageName}' is not a valid Function Kit: it must declare 'firebase-functions' as a dependency or peer dependency.`);
396
+ }
397
+ const packagesToSave = [
398
+ resolveSdkSpecifierToSave("firebase-functions", declaredFunctionsVer, installedFunctionsVer),
399
+ ];
400
+ const declaredAdminVer = peerDeps["firebase-admin"] || directDeps["firebase-admin"];
401
+ if (declaredAdminVer) {
402
+ packagesToSave.push(resolveSdkSpecifierToSave("firebase-admin", declaredAdminVer, installedAdminVer));
403
+ }
404
+ return packagesToSave;
405
+ }
320
406
  async function buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty) {
407
+ const { packageName } = parseNpmPackageSpecifier(rawPkgName);
321
408
  const installArgs = ["install", rawPkgName, "--save-prefix=^"];
322
409
  if (isThirdParty) {
323
410
  installArgs.push("--ignore-scripts");
@@ -329,6 +416,21 @@ async function buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty) {
329
416
  catch (err) {
330
417
  throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
331
418
  }
419
+ const packagesToSave = await getKitPackagesToSave(absSourcePath, packageName);
420
+ if (packagesToSave.length > 0) {
421
+ (0, utils_1.logLabeledBullet)("functions", `Saving resolved SDK dependencies: ${clc.bold(packagesToSave.join(", "))}...`);
422
+ const saveArgs = ["install", ...packagesToSave, "--save-prefix=^"];
423
+ if (isThirdParty) {
424
+ saveArgs.push("--ignore-scripts");
425
+ }
426
+ try {
427
+ await (0, spawn_1.wrapSpawn)("npm", saveArgs, absSourcePath);
428
+ }
429
+ catch (err) {
430
+ throw new error_1.FirebaseError(`Failed to install required SDK dependencies (${packagesToSave.join(", ")}): ${(0, error_1.getErrMsg)(err)}. ` +
431
+ "Verify that the kit's dependencies are compatible with the resolved Firebase SDK versions.", { original: err instanceof Error ? err : undefined });
432
+ }
433
+ }
332
434
  (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
333
435
  try {
334
436
  await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
@@ -489,11 +591,44 @@ async function discoverKitBuild(options, absSourcePath) {
489
591
  const runtimeDelegate = await runtimes.getRuntimeDelegate(delegateContext);
490
592
  return runtimeDelegate.discoverBuild({}, {});
491
593
  }
492
- async function printKitFirstDeployReport(options, instanceId, absSourcePath) {
594
+ async function promptAndWriteKitParams(options) {
595
+ if (!options.params || options.params.length === 0) {
596
+ return;
597
+ }
598
+ if (!options.projectId) {
599
+ logger_1.logger.debug("Skipping functions kit parameter prompt: no active project ID.");
600
+ return;
601
+ }
602
+ const userEnvOpt = {
603
+ configDir: options.absConfigDirPath,
604
+ functionsSource: options.absSourcePath,
605
+ projectDir: options.config.projectDir,
606
+ projectId: options.projectId,
607
+ projectAlias: options.projectAlias,
608
+ };
609
+ const rawUserEnvs = functionsEnv.loadUserEnvs(userEnvOpt);
610
+ const { userEnvs, secretRefs } = (0, prepare_1.partitionUserEnvs)(rawUserEnvs);
611
+ let firebaseConfig = { projectId: options.projectId };
612
+ try {
613
+ firebaseConfig = await functionsConfig.getFirebaseConfig({ projectId: options.projectId });
614
+ }
615
+ catch (err) {
616
+ logger_1.logger.debug(`Could not fetch Firebase config for project ${options.projectId}: ${(0, error_1.getErrMsg)(err)}`);
617
+ }
618
+ const typedUserEnvs = build.envWithTypes(options.params, userEnvs);
619
+ const { paramValues: resolvedEnvs, secretRefs: resolvedSecretRefs } = await params.resolveParams(options.params, firebaseConfig, typedUserEnvs, options.instanceId, options.nonInteractive, options.force);
620
+ functionsEnv.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);
621
+ if (experiments.isEnabled("secretEnvParams")) {
622
+ functionsEnv.writeResolvedSecretRefs(resolvedSecretRefs, secretRefs, userEnvOpt);
623
+ }
624
+ }
625
+ async function printKitFirstDeployReport(options) {
493
626
  let discoveredBuild;
494
- const prefix = (0, projectConfig_1.addKitPrefix)(instanceId);
627
+ const prefix = (0, projectConfig_1.addKitPrefix)(options.instanceId);
495
628
  try {
496
- discoveredBuild = await discoverKitBuild(options, absSourcePath);
629
+ discoveredBuild = options.preDiscoveredBuild
630
+ ? (0, utils_2.cloneDeep)(options.preDiscoveredBuild)
631
+ : await discoverKitBuild(options, options.absSourcePath);
497
632
  build.applyPrefix(discoveredBuild, prefix);
498
633
  }
499
634
  catch (err) {
@@ -547,12 +682,22 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
547
682
  const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
548
683
  ? options.project
549
684
  : undefined;
550
- const isConfiguredForProject = isKitConfiguredForProject(options.config, existingKit, projectId, projectAlias);
685
+ const unconfiguredInstances = getUnconfiguredInstancesForProject(options.config, existingKit, projectId, projectAlias);
686
+ const isConfiguredForProject = Object.keys(existingKit.instances || {}).length > 0 && unconfiguredInstances.length === 0;
551
687
  let action;
552
- if (!isConfiguredForProject && !options.nonInteractive) {
553
- const existingInstances = Object.keys(existingKit.instances || {}).join(", ");
688
+ if (options.instanceId && existingKit.instances && options.instanceId in existingKit.instances) {
689
+ if (!unconfiguredInstances.includes(options.instanceId)) {
690
+ throw new error_1.FirebaseError(`Instance '${options.instanceId}' is already configured for this project.`);
691
+ }
692
+ action = "addEnv";
693
+ }
694
+ else if (options.instanceId) {
695
+ action = "addInstance";
696
+ }
697
+ else if (unconfiguredInstances.length > 0 && !options.nonInteractive) {
698
+ const unconfiguredInstancesList = unconfiguredInstances.join(", ");
554
699
  action = await (0, prompt_1.select)({
555
- message: `The following instances already exist, but are not configured for this project: ${existingInstances}. What would you like to do?`,
700
+ message: `The following instances already exist, but are not configured for this project: ${unconfiguredInstancesList}. What would you like to do?`,
556
701
  choices: [
557
702
  {
558
703
  name: "Add an instance to the existing kit",
@@ -571,29 +716,97 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
571
716
  }
572
717
  action = "addInstance";
573
718
  }
719
+ let resultAction;
720
+ let instanceId;
721
+ let configDirPath;
722
+ let absConfigDirPath;
574
723
  if (action === "addInstance") {
575
- const instanceId = await promptKitInstanceId(existingKit.kit, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
724
+ resultAction = "addedInstance";
725
+ instanceId = await promptKitInstanceId(existingKit.kit, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
576
726
  const result = await addInstanceToKit({
577
727
  config: options.config,
578
728
  kitId: existingKit.kit,
579
729
  instanceId,
580
730
  seedEnv: options.seedEnv,
581
731
  });
732
+ configDirPath = result.configDirPath;
733
+ absConfigDirPath = result.absConfigDirPath;
734
+ }
735
+ else if (action === "addEnv") {
736
+ resultAction = "configuredEnv";
737
+ instanceId = await promptExistingInstanceForProject({
738
+ ...options,
739
+ existingKit,
740
+ unconfiguredInstanceIds: unconfiguredInstances,
741
+ });
742
+ configDirPath = existingKit.instances[instanceId];
743
+ if (!configDirPath) {
744
+ throw new error_1.FirebaseError(`Configuration directory for instance '${instanceId}' not found in kit '${existingKit.kit}'.`);
745
+ }
746
+ absConfigDirPath = options.config.path(configDirPath);
747
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
748
+ await fs.ensureDir(absConfigDirPath);
749
+ (0, env_2.seedKitInstanceEnv)({
750
+ configDir: absConfigDirPath,
751
+ functionsSource: options.config.path(existingKit.source),
752
+ projectDir: options.config.projectDir,
753
+ projectId: options.seedEnv.projectId,
754
+ projectAlias: options.seedEnv.projectAlias,
755
+ envs: options.seedEnv.envs,
756
+ });
757
+ }
758
+ }
759
+ else {
760
+ throw new error_1.FirebaseError(`Unexpected action '${String(action)}' for kit installation.`);
761
+ }
762
+ if (projectId) {
763
+ fs.ensureFileSync(path.join(absConfigDirPath, `.env.${projectId}`));
764
+ }
765
+ const absSourcePath = options.config.path(existingKit.source);
766
+ let discoveredBuild;
767
+ const shouldConfigure = options.configure !== false;
768
+ if (shouldConfigure) {
769
+ try {
770
+ discoveredBuild = await discoverKitBuild(options, absSourcePath);
771
+ }
772
+ catch (err) {
773
+ logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
774
+ }
775
+ if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
776
+ await promptAndWriteKitParams({
777
+ config: options.config,
778
+ projectId,
779
+ projectAlias,
780
+ absConfigDirPath,
781
+ absSourcePath,
782
+ instanceId,
783
+ nonInteractive: options.nonInteractive,
784
+ force: options.force,
785
+ params: discoveredBuild.params,
786
+ });
787
+ }
788
+ }
789
+ if (action === "addInstance") {
582
790
  (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully added to kit ${clc.bold(existingKit.kit)}.`);
583
- await printKitFirstDeployReport(options, instanceId, options.config.path(existingKit.source));
584
- return {
585
- action: "addedInstance",
586
- kitId: existingKit.kit,
587
- instanceId,
588
- sourcePath: existingKit.source,
589
- configDirPath: result.configDirPath,
590
- };
591
791
  }
592
- const selectedInstanceId = await promptExistingInstanceForProject(options, existingKit);
792
+ else if (action === "addEnv") {
793
+ const projectDisplay = projectId || options.project || "project";
794
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully configured for ${clc.bold(projectDisplay)}.`);
795
+ }
796
+ await printKitFirstDeployReport({
797
+ config: options.config,
798
+ project: options.project,
799
+ projectId: options.projectId,
800
+ instanceId,
801
+ absSourcePath,
802
+ preDiscoveredBuild: discoveredBuild,
803
+ });
593
804
  return {
594
- action: "configuredEnv",
805
+ action: resultAction,
595
806
  kitId: existingKit.kit,
596
- instanceId: selectedInstanceId,
807
+ instanceId,
808
+ sourcePath: existingKit.source,
809
+ configDirPath,
597
810
  };
598
811
  }
599
812
  function findExistingKit(existingFunctions, options) {
@@ -623,8 +836,8 @@ async function resolvePackageSource(options) {
623
836
  if (!rawPkgName) {
624
837
  throw new error_1.FirebaseError("Set the --package option to a valid NPM package and try again.");
625
838
  }
839
+ validateNpmPackageName(rawPkgName);
626
840
  const { packageName } = parseNpmPackageSpecifier(rawPkgName);
627
- validateNpmPackageName(packageName);
628
841
  const isThirdParty = await promptSecurityConfirmation(rawPkgName, packageName, options.nonInteractive);
629
842
  return {
630
843
  defaultKitName: packageName,
@@ -689,6 +902,36 @@ async function installKitOrInstance(options) {
689
902
  });
690
903
  }
691
904
  await source.buildAndInstall(absSourcePath);
905
+ const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
906
+ const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
907
+ ? options.project
908
+ : undefined;
909
+ if (projectId) {
910
+ fs.ensureFileSync(path.join(absConfigDirPath, `.env.${projectId}`));
911
+ }
912
+ let discoveredBuild;
913
+ const shouldConfigure = options.configure !== false;
914
+ if (shouldConfigure) {
915
+ try {
916
+ discoveredBuild = await discoverKitBuild(options, absSourcePath);
917
+ }
918
+ catch (err) {
919
+ logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
920
+ }
921
+ if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
922
+ await promptAndWriteKitParams({
923
+ config: options.config,
924
+ projectId,
925
+ projectAlias,
926
+ absConfigDirPath,
927
+ absSourcePath,
928
+ instanceId,
929
+ nonInteractive: options.nonInteractive,
930
+ force: options.force,
931
+ params: discoveredBuild.params,
932
+ });
933
+ }
934
+ }
692
935
  addKitToConfig(options.config, {
693
936
  kitId,
694
937
  instanceId,
@@ -698,7 +941,14 @@ async function installKitOrInstance(options) {
698
941
  hasBuildScript: source.hasBuildScript,
699
942
  });
700
943
  (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
701
- await printKitFirstDeployReport(options, instanceId, absSourcePath);
944
+ await printKitFirstDeployReport({
945
+ config: options.config,
946
+ project: options.project,
947
+ projectId: options.projectId,
948
+ instanceId,
949
+ absSourcePath,
950
+ preDiscoveredBuild: discoveredBuild,
951
+ });
702
952
  return {
703
953
  action: "installedKit",
704
954
  kitId,