firebase-tools-with-isolate 15.32.0 → 15.34.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 (103) hide show
  1. package/lib/accountImporter.js +6 -3
  2. package/lib/api.js +3 -3
  3. package/lib/apphosting/backend.js +1 -1
  4. package/lib/apphosting/secrets/index.js +7 -2
  5. package/lib/checkValidTargetFilters.js +1 -0
  6. package/lib/command.js +31 -24
  7. package/lib/commands/apps-create.js +34 -3
  8. package/lib/commands/crashlytics-heapdumps-disable.js +26 -0
  9. package/lib/commands/crashlytics-heapdumps-enable.js +54 -0
  10. package/lib/commands/crashlytics-heapdumps-status.js +32 -0
  11. package/lib/commands/deploy.js +3 -0
  12. package/lib/commands/functions-kits-uninstall.js +43 -21
  13. package/lib/commands/functions-lifecycle-list.js +5 -6
  14. package/lib/commands/hosting-channel-deploy.js +3 -3
  15. package/lib/commands/hosting-clone.js +102 -31
  16. package/lib/commands/hosting-disable.js +5 -1
  17. package/lib/commands/index.js +9 -0
  18. package/lib/commands/init.js +7 -0
  19. package/lib/commands/run-services-update.js +16 -0
  20. package/lib/config.js +1 -0
  21. package/lib/crashlytics/alerts.js +122 -0
  22. package/lib/crashlytics/onboarding.js +71 -3
  23. package/lib/crashlytics/profilingManager.js +195 -0
  24. package/lib/crashlytics/sourcemap.js +46 -11
  25. package/lib/crashlytics/types.js +6 -1
  26. package/lib/deploy/apphosting/prepare.js +1 -0
  27. package/lib/deploy/auth/deploy.js +1 -1
  28. package/lib/deploy/auth/prepare.js +6 -7
  29. package/lib/deploy/firestore/prepare.js +5 -5
  30. package/lib/deploy/functions/build.js +3 -0
  31. package/lib/deploy/functions/cel.js +89 -58
  32. package/lib/deploy/functions/functionsDeployHelper.js +10 -0
  33. package/lib/deploy/functions/params.js +4 -2
  34. package/lib/deploy/functions/prepare.js +25 -8
  35. package/lib/deploy/functions/release/executor.js +7 -3
  36. package/lib/deploy/functions/release/fabricator.js +42 -14
  37. package/lib/deploy/functions/release/planner.js +3 -2
  38. package/lib/deploy/functions/release/sourceTokenScraper.js +1 -1
  39. package/lib/deploy/functions/validate.js +16 -0
  40. package/lib/deploy/hosting/prepare.js +1 -1
  41. package/lib/deploy/hosting/release.js +2 -2
  42. package/lib/deploy/index.js +5 -0
  43. package/lib/deploy/run/args.js +2 -0
  44. package/lib/deploy/run/buildEnv.js +72 -0
  45. package/lib/deploy/run/deploy.js +214 -0
  46. package/lib/deploy/run/index.js +23 -0
  47. package/lib/deploy/run/prepare.js +47 -0
  48. package/lib/deploy/run/prereqs.js +32 -0
  49. package/lib/deploy/run/release.js +9 -0
  50. package/lib/deploy/run/update.js +50 -0
  51. package/lib/deploy/run/util.js +73 -0
  52. package/lib/emulator/apphosting/serve.js +1 -1
  53. package/lib/emulator/auth/operations.js +8 -4
  54. package/lib/emulator/auth/utils.js +1 -1
  55. package/lib/emulator/commandUtils.js +7 -3
  56. package/lib/emulator/databaseEmulator.js +7 -3
  57. package/lib/emulator/dataconnect/pgliteServer.js +1 -1
  58. package/lib/emulator/dataconnectEmulator.js +1 -1
  59. package/lib/emulator/download.js +1 -1
  60. package/lib/emulator/downloadableEmulatorInfo.json +31 -31
  61. package/lib/emulator/downloadableEmulators.js +1 -3
  62. package/lib/emulator/emulatorLogger.js +2 -1
  63. package/lib/emulator/eventarcEmulator.js +1 -1
  64. package/lib/emulator/functionsEmulatorRuntime.js +2 -1
  65. package/lib/emulator/functionsEmulatorShared.js +1 -41
  66. package/lib/experiments.js +17 -11
  67. package/lib/extensions/warnings.js +48 -7
  68. package/lib/firestore/validator.js +1 -1
  69. package/lib/frameworks/next/constants.js +20 -12
  70. package/lib/frameworks/next/index.js +4 -23
  71. package/lib/frameworks/next/utils.js +28 -0
  72. package/lib/functions/env.js +4 -2
  73. package/lib/functions/projectConfig.js +10 -5
  74. package/lib/gcp/artifactregistry.js +20 -0
  75. package/lib/gcp/cloudmonitoring.js +80 -3
  76. package/lib/gcp/cloudsql/permissions.js +21 -32
  77. package/lib/gcp/cloudsql/permissionsSetup.js +6 -6
  78. package/lib/gcp/cloudtasks.js +15 -1
  79. package/lib/gcp/cloudtrace.js +38 -0
  80. package/lib/gcp/run.js +5 -0
  81. package/lib/gcp/runv2.js +32 -11
  82. package/lib/gcp/storage.js +9 -5
  83. package/lib/hosting/api.js +15 -15
  84. package/lib/hosting/runTags.js +1 -1
  85. package/lib/init/features/auth.js +46 -8
  86. package/lib/init/features/hosting/index.js +4 -2
  87. package/lib/init/features/index.js +4 -1
  88. package/lib/init/features/run.js +159 -0
  89. package/lib/init/index.js +6 -0
  90. package/lib/management/apps.js +4 -2
  91. package/lib/mcp/tools/firestore/converter.js +2 -2
  92. package/lib/mcp/util.js +11 -10
  93. package/lib/profileReport.js +12 -9
  94. package/lib/scopes.js +1 -3
  95. package/lib/streamJson.js +1 -0
  96. package/lib/throttler/throttler.js +1 -0
  97. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  98. package/lib/utils.js +0 -15
  99. package/package.json +11 -17
  100. package/schema/firebase-config.json +41 -0
  101. package/schema/firebaserc.json +133 -0
  102. package/lib/mcp/resources/guides/init_data_connect.js +0 -30
  103. package/lib/mcp/resources/guides/init_rtdb.js +0 -30
@@ -23,6 +23,7 @@ const experiments = require("../../experiments");
23
23
  const ensureApiEnabled = require("../../ensureApiEnabled");
24
24
  const functionsConfig = require("../../functionsConfig");
25
25
  const functionsEnv = require("../../functions/env");
26
+ const params = require("./params");
26
27
  const runtimes = require("./runtimes");
27
28
  const supported = require("./runtimes/supported");
28
29
  const validate = require("./validate");
@@ -206,12 +207,11 @@ async function prepare(context, options, payload) {
206
207
  const rawUserEnvs = functionsEnv.loadUserEnvs(userEnvOpt);
207
208
  const { userEnvs: userEnvs, secretRefs: secretRefs } = partitionUserEnvs(rawUserEnvs);
208
209
  const envs = { ...userEnvs, ...firebaseEnvs };
210
+ const parsedSecretRefs = (0, functional_1.mapObject)(secretRefs, (unparsed) => build.parseSecretRef(unparsed));
211
+ await build.applyEnvSecretBindingsToBuild(wantBuild, parsedSecretRefs);
209
212
  const relevantEndpoints = backend
210
213
  .allEndpoints(existingBackend)
211
214
  .filter((e) => e.codebase === codebase || e.codebase === undefined);
212
- await resolveDefaultRegionsForBuild(wantBuild, backend.of(...relevantEndpoints));
213
- const parsedSecretRefs = (0, functional_1.mapObject)(secretRefs, (unparsed) => build.parseSecretRef(unparsed));
214
- await build.applyEnvSecretBindingsToBuild(wantBuild, parsedSecretRefs);
215
215
  const { backend: wantBackend, envs: resolvedEnvs, secretRefs: resolvedSecretRefs, } = await build.resolveBackend({
216
216
  build: wantBuild,
217
217
  firebaseConfig,
@@ -219,6 +219,7 @@ async function prepare(context, options, payload) {
219
219
  codebase,
220
220
  nonInteractive: options.nonInteractive,
221
221
  isEmulator: false,
222
+ resolveRegions: (b, paramValues) => resolveDefaultRegionsForBuild(b, backend.of(...relevantEndpoints), paramValues),
222
223
  });
223
224
  functionsEnv.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);
224
225
  if (experiments.isEnabled("secretEnvParams") &&
@@ -276,6 +277,7 @@ async function prepare(context, options, payload) {
276
277
  context.codebaseDeployEvents[codebase].runtime = wantBuild.runtime;
277
278
  }
278
279
  validate.endpointsAreUnique(wantBackends);
280
+ validate.noGenerationDowngrades(wantBackends, existingBackend);
279
281
  context.sources = {};
280
282
  for (const [codebase, wantBackend] of Object.entries(wantBackends)) {
281
283
  const cfg = (0, projectConfig_1.configForCodebase)(context.config, codebase);
@@ -358,7 +360,7 @@ async function prepare(context, options, payload) {
358
360
  validate.checkFiltersIntegrity(wantBackends, context.filters);
359
361
  (0, applyHash_1.applyBackendHashToBackends)(wantBackends, context);
360
362
  }
361
- async function resolveDefaultRegionsForBuild(buildObj, have) {
363
+ async function resolveDefaultRegionsForBuild(buildObj, have, paramValues = {}) {
362
364
  for (const [id, endpoint] of Object.entries(buildObj.endpoints)) {
363
365
  if (!endpoint.region?.length || endpoint.region.includes(build.REGION_TBD)) {
364
366
  let resolvedRegion = services_1.FALLBACK_DEPLOYMENT_REGION;
@@ -376,7 +378,7 @@ async function resolveDefaultRegionsForBuild(buildObj, have) {
376
378
  }
377
379
  else {
378
380
  try {
379
- resolvedRegion = await resolveRegionForTrigger(endpoint);
381
+ resolvedRegion = await resolveRegionForTrigger(endpoint, paramValues);
380
382
  }
381
383
  catch (err) {
382
384
  logger_1.logger.debug(`Failed to resolve region for endpoint ${id}. Defaulting to ${services_1.FALLBACK_DEPLOYMENT_REGION}.`, (0, error_1.getErrStack)(err));
@@ -386,9 +388,24 @@ async function resolveDefaultRegionsForBuild(buildObj, have) {
386
388
  }
387
389
  }
388
390
  }
389
- async function resolveRegionForTrigger(endpoint) {
390
- const service = (0, services_1.serviceForEndpoint)(endpoint);
391
- return await service.getDefaultRegion(endpoint);
391
+ async function resolveRegionForTrigger(endpoint, paramValues = {}) {
392
+ let targetEndpoint = endpoint;
393
+ if (Object.keys(paramValues).length > 0 && build.isEventTriggered(endpoint)) {
394
+ targetEndpoint = {
395
+ ...endpoint,
396
+ eventTrigger: {
397
+ ...endpoint.eventTrigger,
398
+ ...(endpoint.eventTrigger.eventFilters && {
399
+ eventFilters: (0, functional_1.mapObject)(endpoint.eventTrigger.eventFilters, (v) => params.resolveString(v, paramValues)),
400
+ }),
401
+ ...(endpoint.eventTrigger.eventFilterPathPatterns && {
402
+ eventFilterPathPatterns: (0, functional_1.mapObject)(endpoint.eventTrigger.eventFilterPathPatterns, (v) => params.resolveString(v, paramValues)),
403
+ }),
404
+ },
405
+ };
406
+ }
407
+ const service = (0, services_1.serviceForEndpoint)(targetEndpoint);
408
+ return await service.getDefaultRegion(targetEndpoint);
392
409
  }
393
410
  function inferDetailsFromExisting(want, have, usedDotenv) {
394
411
  for (const wantE of backend.allEndpoints(want)) {
@@ -22,9 +22,10 @@ const isServiceUnavailable = (err) => parseErrorCode(err) === 503;
22
22
  exports.isServiceUnavailable = isServiceUnavailable;
23
23
  const isTransientError = (err) => (0, exports.isQuotaExhaustion)(err) || (0, exports.isConflict)(err) || (0, exports.isServiceUnavailable)(err);
24
24
  exports.isTransientError = isTransientError;
25
+ const MANAGED_SERVICE_ACCOUNT_REGEX = /\bfirebase-fn-[0-9]+@/i;
25
26
  const isServiceAccountPropagationError = (err) => {
26
27
  const code = parseErrorCode(err);
27
- if (code !== 404 && code !== 400) {
28
+ if (code !== 404 && code !== 400 && code !== 403) {
28
29
  return false;
29
30
  }
30
31
  let message = "";
@@ -44,13 +45,16 @@ const isServiceAccountPropagationError = (err) => {
44
45
  message = String(err).toLowerCase();
45
46
  }
46
47
  const hasSa = message.includes("serviceaccount") || message.includes("service account");
47
- if (!hasSa) {
48
+ if (!hasSa || !MANAGED_SERVICE_ACCOUNT_REGEX.test(message)) {
48
49
  return false;
49
50
  }
50
51
  if (code === 404) {
51
52
  return true;
52
53
  }
53
- return message.includes("invalid service account") && /\bfirebase-fn-[0-9]+@/i.test(message);
54
+ if (code === 400) {
55
+ return message.includes("invalid service account");
56
+ }
57
+ return message.includes("or it may not exist");
54
58
  };
55
59
  exports.isServiceAccountPropagationError = isServiceAccountPropagationError;
56
60
  const isCloudRunResourceExhausted = (err) => parseErrorCode(err) === 8;
@@ -173,14 +173,26 @@ class Fabricator {
173
173
  return this.applyUpserts(changes, scraperV1, scraperV2);
174
174
  });
175
175
  const createAndUpdateResultsArray = await Promise.allSettled(createAndUpdatePromises);
176
+ const upsertErrors = [];
176
177
  summary.results = createAndUpdateResultsArray.reduce((acc, r) => {
177
178
  if (r.status === "fulfilled") {
178
179
  return [...acc, ...r.value];
179
180
  }
180
- logger_1.logger.debug("Fabricator.applyUpserts returned an unhandled exception.", JSON.stringify(r.reason, null, 2));
181
+ upsertErrors.push((0, error_1.getError)(r.reason));
182
+ logger_1.logger.debug("Fabricator.applyUpserts returned an unhandled exception.", (0, error_1.getErrStack)(r.reason));
181
183
  return acc;
182
184
  }, []);
183
185
  await this.cleanupUnusedServiceAccounts(plan, summary.results);
186
+ if (upsertErrors.length) {
187
+ const opts = upsertErrors.length === 1 ? { original: upsertErrors[0] } : { children: upsertErrors };
188
+ const msg = upsertErrors.length === 1
189
+ ? `Fabricator.applyUpserts encountered an unhandled exception: ${upsertErrors[0].message}`
190
+ : "Fabricator.applyUpserts encountered unhandled exceptions";
191
+ throw new error_1.FirebaseError(msg, {
192
+ ...opts,
193
+ exit: 2,
194
+ });
195
+ }
184
196
  const hasFailures = summary.results.some((r) => r.error);
185
197
  if (hasFailures) {
186
198
  utils.logLabeledWarning("functions", "Deploys failed. Skipping deletes.");
@@ -196,14 +208,26 @@ class Fabricator {
196
208
  return summary;
197
209
  }
198
210
  const deleteResultsArray = await Promise.allSettled(allChangesets.map((changes) => this.applyDeletes(changes)));
211
+ const deleteErrors = [];
199
212
  const deleteResults = deleteResultsArray.reduce((acc, r) => {
200
213
  if (r.status === "fulfilled") {
201
214
  return [...acc, ...r.value];
202
215
  }
203
- logger_1.logger.debug("Fabricator.applyDeletes returned an unhandled exception. This should never happen", JSON.stringify(r.reason, null, 2));
216
+ deleteErrors.push((0, error_1.getError)(r.reason));
217
+ logger_1.logger.debug("Fabricator.applyDeletes returned an unhandled exception. This should never happen", (0, error_1.getErrStack)(r.reason));
204
218
  return acc;
205
219
  }, []);
206
220
  summary.results.push(...deleteResults);
221
+ if (deleteErrors.length) {
222
+ const opts = deleteErrors.length === 1 ? { original: deleteErrors[0] } : { children: deleteErrors };
223
+ const msg = deleteErrors.length === 1
224
+ ? `Fabricator.applyDeletes encountered an unhandled exception: ${deleteErrors[0].message}`
225
+ : "Fabricator.applyDeletes encountered unhandled exceptions";
226
+ throw new error_1.FirebaseError(msg, {
227
+ ...opts,
228
+ exit: 2,
229
+ });
230
+ }
207
231
  for (const [codebase, codebasePlan] of Object.entries(plan)) {
208
232
  await this.removeOldRoles(codebasePlan, codebase);
209
233
  }
@@ -231,23 +255,29 @@ class Fabricator {
231
255
  async applyUpserts(changes, scraperV1, scraperV2) {
232
256
  const ops = [];
233
257
  for (const endpoint of changes.endpointsToCreate) {
234
- this.logOpStart("creating", endpoint);
235
- ops.push(this.wrapOperation("create", endpoint, () => this.createEndpoint(endpoint, scraperV1, scraperV2)));
258
+ ops.push(this.wrapOperation("create", endpoint, () => {
259
+ this.logOpStart("creating", endpoint);
260
+ return this.createEndpoint(endpoint, scraperV1, scraperV2);
261
+ }));
236
262
  }
237
263
  for (const endpoint of changes.endpointsToSkip) {
238
264
  utils.logSuccess(this.getLogSuccessMessage("skip", endpoint));
239
265
  }
240
266
  for (const update of changes.endpointsToUpdate) {
241
- this.logOpStart("updating", update.endpoint);
242
- ops.push(this.wrapOperation("update", update.endpoint, () => this.updateEndpoint(update, scraperV1, scraperV2)));
267
+ ops.push(this.wrapOperation("update", update.endpoint, () => {
268
+ this.logOpStart("updating", update.endpoint);
269
+ return this.updateEndpoint(update, scraperV1, scraperV2);
270
+ }));
243
271
  }
244
272
  return Promise.all(ops);
245
273
  }
246
274
  async applyDeletes(changes) {
247
275
  const ops = [];
248
276
  for (const endpoint of changes.endpointsToDelete) {
249
- this.logOpStart("deleting", endpoint);
250
- ops.push(this.wrapOperation("delete", endpoint, () => this.deleteEndpoint(endpoint)));
277
+ ops.push(this.wrapOperation("delete", endpoint, () => {
278
+ this.logOpStart("deleting", endpoint);
279
+ return this.deleteEndpoint(endpoint);
280
+ }));
251
281
  }
252
282
  return Promise.all(ops);
253
283
  }
@@ -871,12 +901,8 @@ class Fabricator {
871
901
  .catch(rethrowAsUnlessNotFound(endpoint, "delete schedule"));
872
902
  }
873
903
  async disableTaskQueue(endpoint) {
874
- const update = {
875
- name: cloudtasks.queueNameForEndpoint(endpoint),
876
- state: "DISABLED",
877
- };
878
904
  await this.executor
879
- .run(() => cloudtasks.updateQueue(update))
905
+ .run(() => cloudtasks.disableQueue(cloudtasks.queueNameForEndpoint(endpoint)))
880
906
  .catch(rethrowAs(endpoint, "disable task queue"));
881
907
  }
882
908
  async unregisterBlockingTrigger(endpoint) {
@@ -885,7 +911,9 @@ class Fabricator {
885
911
  .catch(rethrowAs(endpoint, "unregister blocking trigger"));
886
912
  }
887
913
  logOpStart(op, endpoint) {
888
- const runtime = endpoint.runtime ? supported_1.RUNTIMES[endpoint.runtime].friendly : "unknown";
914
+ const runtime = endpoint.runtime
915
+ ? supported_1.RUNTIMES[endpoint.runtime]?.friendly ?? endpoint.runtime
916
+ : "unknown";
889
917
  const platform = (0, functionsDeployHelper_1.getHumanFriendlyPlatformName)(endpoint.platform);
890
918
  const label = helper.getFunctionLabel(endpoint);
891
919
  utils.logLabeledBullet("functions", `${op} ${runtime} (${platform}) function ${clc.bold(label)}...`);
@@ -250,8 +250,9 @@ function checkForIllegalUpdate(want, have) {
250
250
  if (wantType !== haveType && !upgradingHttpsFunction) {
251
251
  throw new error_1.FirebaseError(`[${(0, functionsDeployHelper_1.getFunctionLabel)(want)}] Changing from ${haveType} function to ${wantType} function is not allowed. Please delete your function and create a new one instead.`);
252
252
  }
253
- if (want.platform === "gcfv1" && have.platform === "gcfv2") {
254
- throw new error_1.FirebaseError(`[${(0, functionsDeployHelper_1.getFunctionLabel)(want)}] Functions cannot be downgraded from GCFv2 to GCFv1`);
253
+ const downgrade = (0, functionsDeployHelper_1.generationDowngradeMessage)(want, have);
254
+ if (downgrade) {
255
+ throw new error_1.FirebaseError(downgrade);
255
256
  }
256
257
  exports.checkForV2Upgrade(want, have);
257
258
  }
@@ -41,12 +41,12 @@ class SourceTokenScraper {
41
41
  return tokenResult.token;
42
42
  }
43
43
  else if (this.fetchState === "VALID") {
44
- const tokenResult = await this.promise;
45
44
  if (this.isTokenExpired()) {
46
45
  this.fetchState = "FETCHING";
47
46
  this.promise = new Promise((resolve) => (this.resolve = resolve));
48
47
  return undefined;
49
48
  }
49
+ const tokenResult = await this.promise;
50
50
  return tokenResult.token;
51
51
  }
52
52
  else {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MAX_V2_SCHEDULE_ATTEMPT_DEADLINE_SECONDS = exports.DEFAULT_V2_SCHEDULE_ATTEMPT_DEADLINE_SECONDS = void 0;
4
4
  exports.endpointsAreValid = endpointsAreValid;
5
+ exports.noGenerationDowngrades = noGenerationDowngrades;
5
6
  exports.cpuConfigIsValid = cpuConfigIsValid;
6
7
  exports.validateTimeoutConfig = validateTimeoutConfig;
7
8
  exports.endpointsAreUnique = endpointsAreUnique;
@@ -85,6 +86,21 @@ function endpointsAreValid(wantBackend, existingBackend) {
85
86
  }
86
87
  cpuConfigIsValid(endpoints);
87
88
  }
89
+ function noGenerationDowngrades(wantBackends, existingBackend) {
90
+ const msgs = [];
91
+ for (const wantBackend of Object.values(wantBackends)) {
92
+ for (const want of backend.allEndpoints(wantBackend).sort(backend.compareFunctions)) {
93
+ const have = existingBackend.endpoints[want.region]?.[want.id];
94
+ const msg = have && (0, functionsDeployHelper_1.generationDowngradeMessage)(want, have);
95
+ if (msg) {
96
+ msgs.push(msg);
97
+ }
98
+ }
99
+ }
100
+ if (msgs.length) {
101
+ throw new error_1.FirebaseError(msgs.join("\n"));
102
+ }
103
+ }
88
104
  function cpuConfigIsValid(endpoints) {
89
105
  const gcfV1WithCPU = matchingIds(endpoints, (endpoint) => endpoint.platform === "gcfv1" && typeof endpoint["cpu"] !== "undefined");
90
106
  if (gcfV1WithCPU.length) {
@@ -105,7 +105,7 @@ async function prepare(context, options) {
105
105
  (0, track_1.trackGA4)("hosting_version", {
106
106
  framework: config.webFramework || "classic",
107
107
  }),
108
- api.createVersion(config.site, version),
108
+ api.createVersion(context.projectId, config.site, version),
109
109
  ]);
110
110
  return versionName;
111
111
  }));
@@ -21,7 +21,7 @@ async function release(context, options, functionsPayload) {
21
21
  config: await (0, convertConfig_1.convertConfig)(context, functionsPayload, deploy),
22
22
  };
23
23
  const versionId = utils.last(deploy.version.split("/"));
24
- const finalizedVersion = await api.updateVersion(deploy.config.site, versionId, update);
24
+ const finalizedVersion = await api.updateVersion(context.projectId, deploy.config.site, versionId, update);
25
25
  logger_1.logger.debug(`[hosting] finalized version for ${deploy.config.site}:${finalizedVersion}`);
26
26
  utils.logLabeledSuccess(`hosting[${deploy.config.site}]`, "version finalized");
27
27
  utils.logLabeledBullet(`hosting[${deploy.config.site}]`, "releasing new version...");
@@ -32,7 +32,7 @@ async function release(context, options, functionsPayload) {
32
32
  if (options.message) {
33
33
  otherReleaseOpts.message = options.message;
34
34
  }
35
- const release = await api.createRelease(deploy.config.site, context.hostingChannel || "live", deploy.version, otherReleaseOpts);
35
+ const release = await api.createRelease(context.projectId, deploy.config.site, context.hostingChannel || "live", deploy.version, otherReleaseOpts);
36
36
  logger_1.logger.debug("[hosting] release:", release);
37
37
  utils.logLabeledSuccess(`hosting[${deploy.config.site}]`, "release complete");
38
38
  }));
@@ -23,6 +23,8 @@ const DataConnectTarget = require("./dataconnect");
23
23
  const AppHostingTarget = require("./apphosting");
24
24
  const AuthTarget = require("./auth");
25
25
  const AiLogicTarget = require("./ailogic");
26
+ const RunTarget = require("./run");
27
+ const prereqs_1 = require("./run/prereqs");
26
28
  const frameworks_1 = require("../frameworks");
27
29
  const prepare_1 = require("./hosting/prepare");
28
30
  const requirePermissions_1 = require("../requirePermissions");
@@ -39,6 +41,7 @@ exports.VALID_DEPLOY_TARGETS = [
39
41
  "apphosting",
40
42
  "auth",
41
43
  "ailogic",
44
+ "run",
42
45
  ];
43
46
  exports.TARGET_PERMISSIONS = {
44
47
  database: ["firebasedatabase.instances.update"],
@@ -95,6 +98,7 @@ exports.TARGET_PERMISSIONS = {
95
98
  "firebasevertexai.templates.delete",
96
99
  "serviceusage.services.get",
97
100
  ],
101
+ run: prereqs_1.RUN_PERMISSIONS,
98
102
  };
99
103
  exports.TARGETS = {
100
104
  hosting: HostingTarget,
@@ -108,6 +112,7 @@ exports.TARGETS = {
108
112
  apphosting: AppHostingTarget,
109
113
  auth: AuthTarget,
110
114
  ailogic: AiLogicTarget,
115
+ run: RunTarget,
111
116
  };
112
117
  const chain = async function (fns, context, options, payload) {
113
118
  for (const latest of fns) {
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BUILD_ENV_ANNOTATION = void 0;
4
+ exports.getBuildEnv = getBuildEnv;
5
+ exports.secretNames = secretNames;
6
+ exports.nonSecretValues = nonSecretValues;
7
+ exports.toLocalBuildEnv = toLocalBuildEnv;
8
+ const error_1 = require("../../error");
9
+ exports.BUILD_ENV_ANNOTATION = "firebase.google.com/buildConfig.environmentVariablesAndSecrets";
10
+ function getBuildEnv(service) {
11
+ const raw = service?.annotations?.[exports.BUILD_ENV_ANNOTATION];
12
+ if (!service || !raw) {
13
+ return {};
14
+ }
15
+ const invalid = (reason) => new error_1.FirebaseError(`Invalid ${exports.BUILD_ENV_ANNOTATION} annotation on ${service.name}: ${reason}`);
16
+ let parsed;
17
+ try {
18
+ parsed = JSON.parse(raw);
19
+ }
20
+ catch {
21
+ throw invalid("it isn't valid JSON.");
22
+ }
23
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
24
+ throw invalid("it must be a JSON object.");
25
+ }
26
+ const env = {};
27
+ for (const [name, value] of Object.entries(parsed)) {
28
+ if (typeof value === "string" || isSecretRef(value)) {
29
+ env[name] = value;
30
+ }
31
+ else if (typeof value === "number" || typeof value === "boolean") {
32
+ env[name] = String(value);
33
+ }
34
+ else {
35
+ throw invalid(`${name} must be a string, number, boolean, or {"secret": "<secret name>"}.`);
36
+ }
37
+ }
38
+ return env;
39
+ }
40
+ function isSecretRef(value) {
41
+ const ref = value;
42
+ return (typeof ref === "object" &&
43
+ ref !== null &&
44
+ Object.keys(ref).length === 1 &&
45
+ typeof ref.secret === "string");
46
+ }
47
+ function secretNames(env) {
48
+ return Object.entries(env)
49
+ .filter(([, value]) => isSecretRef(value))
50
+ .map(([name]) => name);
51
+ }
52
+ function nonSecretValues(env) {
53
+ const values = {};
54
+ for (const [name, value] of Object.entries(env)) {
55
+ if (!isSecretRef(value)) {
56
+ values[name] = value;
57
+ }
58
+ }
59
+ return values;
60
+ }
61
+ function toLocalBuildEnv(env) {
62
+ const result = {};
63
+ for (const [name, value] of Object.entries(env)) {
64
+ if (isSecretRef(value)) {
65
+ result[name] = { secret: value.secret, availability: ["BUILD"] };
66
+ }
67
+ else {
68
+ result[name] = { value, availability: ["BUILD"] };
69
+ }
70
+ }
71
+ return result;
72
+ }
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deploy = deploy;
4
+ exports.revisionTemplate = revisionTemplate;
5
+ exports.localBuildTemplate = localBuildTemplate;
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+ const constants_1 = require("../../apphosting/constants");
10
+ const localbuilds_1 = require("../../apphosting/localbuilds");
11
+ const error_1 = require("../../error");
12
+ const artifactregistry = require("../../gcp/artifactregistry");
13
+ const runv2 = require("../../gcp/runv2");
14
+ const gcs = require("../../gcp/storage");
15
+ const getProjectNumber_1 = require("../../getProjectNumber");
16
+ const logger_1 = require("../../logger");
17
+ const utils_1 = require("../../utils");
18
+ const prepare_1 = require("../apphosting/prepare");
19
+ const util_1 = require("../apphosting/util");
20
+ const buildEnv_1 = require("./buildEnv");
21
+ const util_2 = require("./util");
22
+ const DEPLOY_MESSAGE_ANNOTATION = "firebase.google.com/deploy-message";
23
+ const ROLLOUT_TIMEOUT_MS = 10 * 60 * 1000;
24
+ const NO_IMAGE = "scratch";
25
+ async function deploy(context, options, payload) {
26
+ for (const svc of payload.run?.services || []) {
27
+ if (svc.config.localBuild) {
28
+ await deployLocalBuild(context, options, svc);
29
+ }
30
+ else {
31
+ await deployRemoteBuild(context, options, svc);
32
+ }
33
+ }
34
+ }
35
+ async function deployRemoteBuild(context, options, svc) {
36
+ const { projectId } = context;
37
+ const source = await uploadSource(projectId, options, svc.config);
38
+ const image = await buildImage(projectId, svc, source);
39
+ const template = revisionTemplate(svc, image, options.message);
40
+ svc.deployed = await rollOut(projectId, svc, template);
41
+ }
42
+ async function deployLocalBuild(context, options, svc) {
43
+ const { projectId } = context;
44
+ const scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), `run-local-build-${svc.config.serviceId}-`));
45
+ try {
46
+ const build = await buildLocally(context, options, svc, scratchDir);
47
+ const builtApp = await uploadBuiltApp(projectId, options, svc.config, scratchDir, build);
48
+ const message = options.message;
49
+ const template = localBuildTemplate(svc, build, builtApp, message);
50
+ svc.deployed = await rollOut(projectId, svc, template);
51
+ }
52
+ finally {
53
+ removeTempPath(scratchDir);
54
+ }
55
+ }
56
+ async function buildLocally(context, options, svc, scratchDir) {
57
+ const { config } = svc;
58
+ const { serviceId, region } = config;
59
+ const cfg = toAppHostingConfig(config);
60
+ (0, localbuilds_1.validateLocalBuildNodeVersion)({ runtime: { value: svc.baseImage?.split("/").pop() } }, path.join(options.config.projectDir, cfg.rootDir));
61
+ (0, utils_1.logLabeledBullet)("run", `Starting local build for service ${serviceId} in ${region}`);
62
+ const secrets = (0, buildEnv_1.secretNames)(svc.buildEnv || {});
63
+ if (secrets.length) {
64
+ (0, utils_1.logLabeledBullet)("run", `Reading build secrets ${secrets.join(", ")} with your credentials. Their values may be ` +
65
+ `included in the build output.`);
66
+ }
67
+ await (0, prepare_1.prepareLocalBuildScratchDirectory)(options.config.projectDir, scratchDir, cfg);
68
+ const { outputFiles, buildConfig } = await (0, localbuilds_1.localBuild)(context.projectId, scratchDir, (0, buildEnv_1.toLocalBuildEnv)(svc.buildEnv || {}), { rootDir: config.rootDir, allowLocalBuildSecrets: true });
69
+ const env = (buildConfig.env || [])
70
+ .filter((e) => e.variable &&
71
+ e.value !== undefined &&
72
+ (!e.availability || e.availability.includes("RUNTIME")))
73
+ .map((e) => ({ name: e.variable, value: e.value }));
74
+ return { outputFiles, runCommand: buildConfig.runCommand, env };
75
+ }
76
+ async function uploadSource(projectId, options, config) {
77
+ const { serviceId, region } = config;
78
+ const bucketName = await sourceBucket(projectId, options, region);
79
+ const cfg = toAppHostingConfig(config);
80
+ const archive = await (0, util_1.createSourceDeployArchive)(cfg, path.join(options.config.projectDir, cfg.rootDir));
81
+ (0, utils_1.logLabeledBullet)("run", `Uploading source for service ${serviceId} in ${region}...`);
82
+ const { bucket, object } = await gcs.uploadObject({ file: archive, stream: fs.createReadStream(archive) }, bucketName, gcs.ContentType.ZIP);
83
+ return { bucket, object };
84
+ }
85
+ async function uploadBuiltApp(projectId, options, config, scratchDir, build) {
86
+ const { serviceId, region } = config;
87
+ const bucketName = await sourceBucket(projectId, options, region);
88
+ const archive = await (0, util_1.createLocalBuildTarArchive)(toAppHostingConfig(config), scratchDir, build.outputFiles);
89
+ (0, utils_1.logLabeledBullet)("run", `Uploading built app for service ${serviceId} in ${region}...`);
90
+ const { bucket, object } = await gcs.uploadObject({ file: archive, stream: fs.createReadStream(archive) }, bucketName, gcs.ContentType.TAR, constants_1.CLOUD_RUN_SIZE_LIMIT_BYTES);
91
+ return { bucket, object };
92
+ }
93
+ async function sourceBucket(projectId, options, region) {
94
+ const baseName = `firebase-run-src-${await (0, getProjectNumber_1.getProjectNumber)(options)}-${region.toLowerCase()}`;
95
+ return gcs.upsertBucket({
96
+ product: "run",
97
+ createMessage: `Creating Cloud Storage bucket in ${region} to store Cloud Run source code uploads at ${baseName}...`,
98
+ projectId,
99
+ req: {
100
+ baseName,
101
+ purposeLabel: `run-source-${region.toLowerCase()}`,
102
+ location: region,
103
+ lifecycle: { rule: [{ action: { type: "Delete" }, condition: { age: 30 } }] },
104
+ },
105
+ });
106
+ }
107
+ async function buildImage(projectId, svc, source) {
108
+ const { serviceId, region } = svc.config;
109
+ await artifactregistry.ensureDockerRepository(projectId, region, "cloud-run-source-deploy");
110
+ const imageUri = `${region}-docker.pkg.dev/${projectId}/cloud-run-source-deploy/${serviceId}:${Date.now()}`;
111
+ (0, utils_1.logLabeledBullet)("run", `Building service ${serviceId} in ${region}...`);
112
+ const buildpackBuild = {
113
+ environmentVariables: {
114
+ ...(0, buildEnv_1.nonSecretValues)(svc.buildEnv || {}),
115
+ X_GOOGLE_TARGET_PLATFORM: "fah",
116
+ FIREBASE_OUTPUT_BUNDLE_DIR: "/workspace/.apphosting",
117
+ },
118
+ };
119
+ if (svc.baseImage) {
120
+ buildpackBuild.baseImage = svc.baseImage;
121
+ buildpackBuild.enableAutomaticUpdates = true;
122
+ }
123
+ await runv2.submitBuild(projectId, region, { storageSource: source, imageUri, buildpackBuild });
124
+ return imageUri;
125
+ }
126
+ function revisionTemplate(svc, image, message) {
127
+ const { serviceId, region } = svc.config;
128
+ const template = svc.existing
129
+ ? (0, utils_1.cloneDeep)(svc.existing.template)
130
+ : { containers: [{ name: serviceId, image }] };
131
+ delete template.revision;
132
+ const container = (0, util_2.mainContainer)(template);
133
+ if (!container) {
134
+ throw new error_1.FirebaseError(`Service ${serviceId} in ${region} has no containers.`);
135
+ }
136
+ container.image = image;
137
+ if (container.sourceCode) {
138
+ delete container.sourceCode;
139
+ delete container.command;
140
+ }
141
+ if (svc.baseImage) {
142
+ container.baseImageUri = svc.baseImage;
143
+ }
144
+ else {
145
+ delete container.baseImageUri;
146
+ }
147
+ if (message) {
148
+ template.annotations = { ...template.annotations, [DEPLOY_MESSAGE_ANNOTATION]: message };
149
+ }
150
+ else if (template.annotations) {
151
+ delete template.annotations[DEPLOY_MESSAGE_ANNOTATION];
152
+ }
153
+ return template;
154
+ }
155
+ function localBuildTemplate(svc, build, builtApp, message) {
156
+ const template = revisionTemplate(svc, NO_IMAGE, message);
157
+ const container = (0, util_2.mainContainer)(template);
158
+ container.sourceCode = { cloudStorageSource: builtApp };
159
+ const command = build.runCommand?.trim();
160
+ if (command) {
161
+ container.command = command.split(/\s+/);
162
+ }
163
+ else {
164
+ delete container.command;
165
+ }
166
+ if (build.env.length) {
167
+ const buildNames = new Set(build.env.map((e) => e.name));
168
+ const otherEnv = (container.env || []).filter((e) => !buildNames.has(e.name));
169
+ container.env = [...otherEnv, ...build.env];
170
+ }
171
+ return template;
172
+ }
173
+ function rollOut(projectId, svc, template) {
174
+ if (svc.existing) {
175
+ return deployRevision(svc.existing, template);
176
+ }
177
+ return createNewService(projectId, svc.config, template);
178
+ }
179
+ function createNewService(projectId, config, template) {
180
+ const { serviceId, region } = config;
181
+ return runv2.createService(projectId, region, serviceId, {
182
+ name: `projects/${projectId}/locations/${region}/services/${serviceId}`,
183
+ template,
184
+ client: "cli-firebase",
185
+ invokerIamDisabled: true,
186
+ ingress: "INGRESS_TRAFFIC_ALL",
187
+ }, { pollTimeoutMs: ROLLOUT_TIMEOUT_MS });
188
+ }
189
+ function deployRevision(service, template) {
190
+ const tags = (service.traffic || [])
191
+ .filter((t) => t.tag)
192
+ .map((t) => ({ type: t.type, revision: t.revision, tag: t.tag }));
193
+ return runv2.updateService({
194
+ name: service.name,
195
+ template,
196
+ traffic: [{ type: "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST", percent: 100 }, ...tags],
197
+ }, { updateMask: ["template", "traffic"], pollTimeoutMs: ROLLOUT_TIMEOUT_MS });
198
+ }
199
+ function toAppHostingConfig(config) {
200
+ return {
201
+ backendId: config.serviceId,
202
+ rootDir: config.rootDir || "",
203
+ ignore: config.ignore,
204
+ localBuild: config.localBuild,
205
+ };
206
+ }
207
+ function removeTempPath(tempPath) {
208
+ try {
209
+ fs.rmSync(tempPath, { recursive: true, force: true });
210
+ }
211
+ catch (err) {
212
+ logger_1.logger.debug(`Failed to clean up ${tempPath}: ${(0, error_1.getErrMsg)(err)}`);
213
+ }
214
+ }