firebase-tools 13.5.1 → 13.6.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 (83) hide show
  1. package/lib/accountExporter.js +1 -1
  2. package/lib/accountImporter.js +1 -1
  3. package/lib/api.js +112 -56
  4. package/lib/apiv2.js +3 -1
  5. package/lib/appdistribution/client.js +4 -4
  6. package/lib/auth.js +17 -17
  7. package/lib/commands/hosting-disable.js +1 -1
  8. package/lib/commands/open.js +1 -1
  9. package/lib/database/metadata.js +3 -3
  10. package/lib/defaultCredentials.js +2 -2
  11. package/lib/deploy/extensions/v2FunctionHelper.js +1 -1
  12. package/lib/deploy/functions/build.js +1 -1
  13. package/lib/deploy/functions/containerCleaner.js +4 -4
  14. package/lib/deploy/functions/deploy.js +8 -2
  15. package/lib/deploy/functions/ensure.js +1 -1
  16. package/lib/deploy/functions/prepare.js +5 -4
  17. package/lib/deploy/functions/release/fabricator.js +3 -3
  18. package/lib/deploy/functions/runtimes/discovery/index.js +2 -2
  19. package/lib/deploy/functions/runtimes/node/parseTriggers.js +2 -2
  20. package/lib/deploy/hosting/uploader.js +1 -1
  21. package/lib/deploy/index.js +1 -1
  22. package/lib/deploy/remoteconfig/functions.js +1 -1
  23. package/lib/emulator/adminSdkConfig.js +1 -1
  24. package/lib/emulator/downloadableEmulators.js +6 -6
  25. package/lib/ensureApiEnabled.js +1 -1
  26. package/lib/extensions/extensionsApi.js +5 -5
  27. package/lib/extensions/extensionsHelper.js +4 -4
  28. package/lib/extensions/provisioningHelper.js +2 -2
  29. package/lib/extensions/publishHelpers.js +1 -1
  30. package/lib/extensions/publisherApi.js +3 -3
  31. package/lib/extensions/resolveSource.js +1 -1
  32. package/lib/extensions/secretsUtils.js +1 -1
  33. package/lib/extensions/tos.js +1 -1
  34. package/lib/fetchMOTD.js +1 -1
  35. package/lib/fetchWebSetup.js +2 -2
  36. package/lib/firestore/api-sort.js +17 -0
  37. package/lib/firestore/api.js +9 -2
  38. package/lib/firestore/checkDatabaseType.js +1 -1
  39. package/lib/firestore/delete.js +1 -1
  40. package/lib/firestore/pretty-print.js +11 -2
  41. package/lib/functions/secrets.js +3 -3
  42. package/lib/functionsConfig.js +1 -1
  43. package/lib/gcp/apphosting.js +2 -2
  44. package/lib/gcp/artifactregistry.js +1 -1
  45. package/lib/gcp/auth.js +1 -1
  46. package/lib/gcp/cloudbilling.js +1 -1
  47. package/lib/gcp/cloudbuild.js +1 -1
  48. package/lib/gcp/cloudfunctions.js +1 -1
  49. package/lib/gcp/cloudfunctionsv2.js +1 -1
  50. package/lib/gcp/cloudlogging.js +1 -1
  51. package/lib/gcp/cloudmonitoring.js +1 -1
  52. package/lib/gcp/cloudscheduler.js +1 -1
  53. package/lib/gcp/cloudtasks.js +1 -1
  54. package/lib/gcp/devConnect.js +81 -0
  55. package/lib/gcp/eventarc.js +1 -1
  56. package/lib/gcp/firestore.js +2 -2
  57. package/lib/gcp/iam.js +2 -2
  58. package/lib/gcp/identityPlatform.js +1 -1
  59. package/lib/gcp/pubsub.js +1 -1
  60. package/lib/gcp/resourceManager.js +2 -1
  61. package/lib/gcp/rules.js +1 -1
  62. package/lib/gcp/run.js +1 -1
  63. package/lib/gcp/runtimeconfig.js +1 -1
  64. package/lib/gcp/secretManager.js +1 -1
  65. package/lib/gcp/serviceusage.js +1 -1
  66. package/lib/gcp/storage.js +12 -8
  67. package/lib/hosting/api.js +2 -2
  68. package/lib/hosting/cloudRunProxy.js +1 -1
  69. package/lib/init/features/apphosting/index.js +29 -7
  70. package/lib/init/features/apphosting/repo.js +88 -102
  71. package/lib/init/features/database.js +1 -1
  72. package/lib/init/features/extensions/index.js +1 -1
  73. package/lib/init/features/functions/index.js +2 -2
  74. package/lib/init/features/hosting/github.js +4 -3
  75. package/lib/management/apps.js +4 -4
  76. package/lib/management/database.js +1 -1
  77. package/lib/management/projects.js +4 -4
  78. package/lib/remoteconfig/get.js +1 -1
  79. package/lib/remoteconfig/rollback.js +1 -1
  80. package/lib/remoteconfig/versionslist.js +1 -1
  81. package/lib/shortenUrl.js +2 -2
  82. package/lib/utils.js +1 -1
  83. package/package.json +1 -1
@@ -9,12 +9,12 @@ const error_1 = require("../error");
9
9
  const prodOnlyClient = new apiv2_1.Client({
10
10
  auth: true,
11
11
  apiVersion: "v1",
12
- urlPrefix: api_1.firestoreOrigin,
12
+ urlPrefix: (0, api_1.firestoreOrigin)(),
13
13
  });
14
14
  const emuOrProdClient = new apiv2_1.Client({
15
15
  auth: true,
16
16
  apiVersion: "v1",
17
- urlPrefix: api_1.firestoreOriginOrEmulator,
17
+ urlPrefix: (0, api_1.firestoreOriginOrEmulator)(),
18
18
  });
19
19
  var DayOfWeek;
20
20
  (function (DayOfWeek) {
package/lib/gcp/iam.js CHANGED
@@ -4,7 +4,7 @@ exports.testIamPermissions = exports.testResourceIamPermissions = exports.getRol
4
4
  const api_1 = require("../api");
5
5
  const logger_1 = require("../logger");
6
6
  const apiv2_1 = require("../apiv2");
7
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.iamOrigin, apiVersion: "v1" });
7
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.iamOrigin)(), apiVersion: "v1" });
8
8
  async function createServiceAccount(projectId, accountId, description, displayName) {
9
9
  const response = await apiClient.post(`/projects/${projectId}/serviceAccounts`, {
10
10
  accountId,
@@ -71,6 +71,6 @@ async function testResourceIamPermissions(origin, apiVersion, resourceName, perm
71
71
  }
72
72
  exports.testResourceIamPermissions = testResourceIamPermissions;
73
73
  async function testIamPermissions(projectId, permissions) {
74
- return testResourceIamPermissions(api_1.resourceManagerOrigin, "v1", `projects/${projectId}`, permissions, `projects/${projectId}`);
74
+ return testResourceIamPermissions((0, api_1.resourceManagerOrigin)(), "v1", `projects/${projectId}`, permissions, `projects/${projectId}`);
75
75
  }
76
76
  exports.testIamPermissions = testIamPermissions;
@@ -6,7 +6,7 @@ const api_1 = require("../api");
6
6
  const apiv2_1 = require("../apiv2");
7
7
  const API_VERSION = "v2";
8
8
  const adminApiClient = new apiv2_1.Client({
9
- urlPrefix: api_1.identityOrigin + "/admin",
9
+ urlPrefix: (0, api_1.identityOrigin)() + "/admin",
10
10
  apiVersion: API_VERSION,
11
11
  });
12
12
  async function getBlockingFunctionsConfig(project) {
package/lib/gcp/pubsub.js CHANGED
@@ -6,7 +6,7 @@ const api_1 = require("../api");
6
6
  const proto = require("./proto");
7
7
  const API_VERSION = "v1";
8
8
  const client = new apiv2_1.Client({
9
- urlPrefix: api_1.pubsubOrigin,
9
+ urlPrefix: (0, api_1.pubsubOrigin)(),
10
10
  auth: true,
11
11
  apiVersion: API_VERSION,
12
12
  });
@@ -6,13 +6,14 @@ const api_1 = require("../api");
6
6
  const apiv2_1 = require("../apiv2");
7
7
  const iam_1 = require("./iam");
8
8
  const API_VERSION = "v1";
9
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.resourceManagerOrigin, apiVersion: API_VERSION });
9
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.resourceManagerOrigin)(), apiVersion: API_VERSION });
10
10
  exports.firebaseRoles = {
11
11
  apiKeysViewer: "roles/serviceusage.apiKeysViewer",
12
12
  authAdmin: "roles/firebaseauth.admin",
13
13
  functionsDeveloper: "roles/cloudfunctions.developer",
14
14
  hostingAdmin: "roles/firebasehosting.admin",
15
15
  runViewer: "roles/run.viewer",
16
+ serviceUsageConsumer: "roles/serviceusage.serviceUsageConsumer",
16
17
  };
17
18
  async function getIamPolicy(projectIdOrNumber) {
18
19
  const response = await apiClient.post(`/projects/${projectIdOrNumber}:getIamPolicy`);
package/lib/gcp/rules.js CHANGED
@@ -6,7 +6,7 @@ const apiv2_1 = require("../apiv2");
6
6
  const logger_1 = require("../logger");
7
7
  const utils = require("../utils");
8
8
  const API_VERSION = "v1";
9
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.rulesOrigin, apiVersion: API_VERSION });
9
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.rulesOrigin)(), apiVersion: API_VERSION });
10
10
  function _handleErrorResponse(response) {
11
11
  if (response.body && response.body.error) {
12
12
  return utils.reject(response.body.error, { code: 2 });
package/lib/gcp/run.js CHANGED
@@ -9,7 +9,7 @@ const throttler_1 = require("../throttler/throttler");
9
9
  const logger_1 = require("../logger");
10
10
  const API_VERSION = "v1";
11
11
  const client = new apiv2_1.Client({
12
- urlPrefix: api_1.runOrigin,
12
+ urlPrefix: (0, api_1.runOrigin)(),
13
13
  auth: true,
14
14
  apiVersion: API_VERSION,
15
15
  });
@@ -6,7 +6,7 @@ const api_1 = require("../api");
6
6
  const apiv2_1 = require("../apiv2");
7
7
  const logger_1 = require("../logger");
8
8
  const API_VERSION = "v1beta1";
9
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.runtimeconfigOrigin, apiVersion: API_VERSION });
9
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.runtimeconfigOrigin)(), apiVersion: API_VERSION });
10
10
  function listConfigs(projectId) {
11
11
  return apiClient
12
12
  .get(`/projects/${projectId}/configs`, {
@@ -13,7 +13,7 @@ const SECRET_VERSION_NAME_REGEX = new RegExp(SECRET_NAME_REGEX.source + "\\/vers
13
13
  const secretManagerConsoleUri = (projectId) => `https://console.cloud.google.com/security/secret-manager?project=${projectId}`;
14
14
  exports.secretManagerConsoleUri = secretManagerConsoleUri;
15
15
  const API_VERSION = "v1";
16
- const client = new apiv2_1.Client({ urlPrefix: api_1.secretManagerOrigin, apiVersion: API_VERSION });
16
+ const client = new apiv2_1.Client({ urlPrefix: (0, api_1.secretManagerOrigin)(), apiVersion: API_VERSION });
17
17
  async function getSecret(projectId, name) {
18
18
  var _a;
19
19
  const getRes = await client.get(`projects/${projectId}/secrets/${name}`);
@@ -7,7 +7,7 @@ const apiv2_1 = require("../apiv2");
7
7
  const error_1 = require("../error");
8
8
  const utils = require("../utils");
9
9
  const apiClient = new apiv2_1.Client({
10
- urlPrefix: api_1.serviceUsageOrigin,
10
+ urlPrefix: (0, api_1.serviceUsageOrigin)(),
11
11
  apiVersion: "v1beta1",
12
12
  });
13
13
  async function generateServiceIdentity(projectNumber, service, prefix) {
@@ -10,9 +10,12 @@ const logger_1 = require("../logger");
10
10
  const ensureApiEnabled_1 = require("../ensureApiEnabled");
11
11
  async function getDefaultBucket(projectId) {
12
12
  var _a;
13
- await (0, ensureApiEnabled_1.ensure)(projectId, api_1.firebaseStorageOrigin, "storage", false);
13
+ await (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.firebaseStorageOrigin)(), "storage", false);
14
14
  try {
15
- const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.firebaseStorageOrigin, apiVersion: "v1alpha" });
15
+ const localAPIClient = new apiv2_1.Client({
16
+ urlPrefix: (0, api_1.firebaseStorageOrigin)(),
17
+ apiVersion: "v1alpha",
18
+ });
16
19
  const response = await localAPIClient.get(`/projects/${projectId}/defaultBucket`);
17
20
  if (!((_a = response.body) === null || _a === void 0 ? void 0 : _a.bucket.name)) {
18
21
  logger_1.logger.debug("Default storage bucket is undefined.");
@@ -29,7 +32,7 @@ async function getDefaultBucket(projectId) {
29
32
  }
30
33
  }
31
34
  exports.getDefaultBucket = getDefaultBucket;
32
- async function upload(source, uploadUrl, extraHeaders) {
35
+ async function upload(source, uploadUrl, extraHeaders, ignoreQuotaProject) {
33
36
  const url = new URL(uploadUrl);
34
37
  const localAPIClient = new apiv2_1.Client({ urlPrefix: url.origin, auth: false });
35
38
  const res = await localAPIClient.request({
@@ -40,6 +43,7 @@ async function upload(source, uploadUrl, extraHeaders) {
40
43
  headers: Object.assign({ "content-type": "application/zip" }, extraHeaders),
41
44
  body: source.stream,
42
45
  skipLog: { resBody: true },
46
+ ignoreQuotaProject,
43
47
  });
44
48
  return {
45
49
  generation: res.response.headers.get("x-goog-generation"),
@@ -50,7 +54,7 @@ async function uploadObject(source, bucketName) {
50
54
  if (path.extname(source.file) !== ".zip") {
51
55
  throw new error_1.FirebaseError(`Expected a file name ending in .zip, got ${source.file}`);
52
56
  }
53
- const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.storageOrigin });
57
+ const localAPIClient = new apiv2_1.Client({ urlPrefix: (0, api_1.storageOrigin)() });
54
58
  const location = `/${bucketName}/${path.basename(source.file)}`;
55
59
  const res = await localAPIClient.request({
56
60
  method: "PUT",
@@ -69,13 +73,13 @@ async function uploadObject(source, bucketName) {
69
73
  }
70
74
  exports.uploadObject = uploadObject;
71
75
  function deleteObject(location) {
72
- const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.storageOrigin });
76
+ const localAPIClient = new apiv2_1.Client({ urlPrefix: (0, api_1.storageOrigin)() });
73
77
  return localAPIClient.delete(location);
74
78
  }
75
79
  exports.deleteObject = deleteObject;
76
80
  async function getBucket(bucketName) {
77
81
  try {
78
- const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.storageOrigin });
82
+ const localAPIClient = new apiv2_1.Client({ urlPrefix: (0, api_1.storageOrigin)() });
79
83
  const result = await localAPIClient.get(`/storage/v1/b/${bucketName}`);
80
84
  return result.body;
81
85
  }
@@ -89,7 +93,7 @@ async function getBucket(bucketName) {
89
93
  exports.getBucket = getBucket;
90
94
  async function listBuckets(projectId) {
91
95
  try {
92
- const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.storageOrigin });
96
+ const localAPIClient = new apiv2_1.Client({ urlPrefix: (0, api_1.storageOrigin)() });
93
97
  const result = await localAPIClient.get(`/storage/v1/b?project=${projectId}`);
94
98
  return result.body.items.map((bucket) => bucket.name);
95
99
  }
@@ -103,7 +107,7 @@ async function listBuckets(projectId) {
103
107
  exports.listBuckets = listBuckets;
104
108
  async function getServiceAccount(projectId) {
105
109
  try {
106
- const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.storageOrigin });
110
+ const localAPIClient = new apiv2_1.Client({ urlPrefix: (0, api_1.storageOrigin)() });
107
111
  const response = await localAPIClient.get(`/storage/v1/projects/${projectId}/serviceAccount`);
108
112
  return response.body;
109
113
  }
@@ -28,7 +28,7 @@ function normalizeName(s) {
28
28
  }
29
29
  exports.normalizeName = normalizeName;
30
30
  const apiClient = new apiv2_1.Client({
31
- urlPrefix: api_1.hostingApiOrigin,
31
+ urlPrefix: (0, api_1.hostingApiOrigin)(),
32
32
  apiVersion: "v1beta1",
33
33
  auth: true,
34
34
  });
@@ -122,7 +122,7 @@ async function cloneVersion(site, versionName, finalize = false) {
122
122
  });
123
123
  const { name: operationName } = res.body;
124
124
  const pollRes = await operationPoller.pollOperation({
125
- apiOrigin: api_1.hostingApiOrigin,
125
+ apiOrigin: (0, api_1.hostingApiOrigin)(),
126
126
  apiVersion: "v1beta1",
127
127
  operationResourceName: operationName,
128
128
  masterTimeout: 600000,
@@ -7,7 +7,7 @@ const error_1 = require("../error");
7
7
  const logger_1 = require("../logger");
8
8
  const projectUtils_1 = require("../projectUtils");
9
9
  const cloudRunCache = {};
10
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.cloudRunApiOrigin, apiVersion: "v1" });
10
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.cloudRunApiOrigin)(), apiVersion: "v1" });
11
11
  async function getCloudRunUrl(rewrite, projectId) {
12
12
  var _a;
13
13
  const alreadyFetched = cloudRunCache[`${rewrite.run.region}/${rewrite.run.serviceId}`];
@@ -17,17 +17,17 @@ const ensureApiEnabled_1 = require("../../../ensureApiEnabled");
17
17
  const deploymentTool = require("../../../deploymentTool");
18
18
  const DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME = "firebase-app-hosting-compute";
19
19
  const apphostingPollerOptions = {
20
- apiOrigin: api_1.apphostingOrigin,
20
+ apiOrigin: (0, api_1.apphostingOrigin)(),
21
21
  apiVersion: apphosting_1.API_VERSION,
22
22
  masterTimeout: 25 * 60 * 1000,
23
23
  maxBackoff: 10000,
24
24
  };
25
25
  async function doSetup(projectId, location, serviceAccount) {
26
26
  await Promise.all([
27
- (0, ensureApiEnabled_1.ensure)(projectId, api_1.cloudbuildOrigin, "apphosting", true),
28
- (0, ensureApiEnabled_1.ensure)(projectId, api_1.secretManagerOrigin, "apphosting", true),
29
- (0, ensureApiEnabled_1.ensure)(projectId, api_1.cloudRunApiOrigin, "apphosting", true),
30
- (0, ensureApiEnabled_1.ensure)(projectId, api_1.artifactRegistryDomain, "apphosting", true),
27
+ (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudbuildOrigin)(), "apphosting", true),
28
+ (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.secretManagerOrigin)(), "apphosting", true),
29
+ (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudRunApiOrigin)(), "apphosting", true),
30
+ (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.artifactRegistryDomain)(), "apphosting", true),
31
31
  ]);
32
32
  const allowedLocations = (await apphosting.listLocations(projectId)).map((loc) => loc.locationId);
33
33
  if (location) {
@@ -172,9 +172,31 @@ async function orchestrateRollout(projectId, location, backendId, buildInput) {
172
172
  (0, utils_1.logBullet)("Starting a new rollout... this may take a few minutes.");
173
173
  const buildId = await apphosting.getNextRolloutId(projectId, location, backendId, 1);
174
174
  const buildOp = await apphosting.createBuild(projectId, location, backendId, buildId, buildInput);
175
- const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, {
175
+ const rolloutBody = {
176
176
  build: `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`,
177
- });
177
+ };
178
+ let tries = 0;
179
+ let done = false;
180
+ while (!done) {
181
+ tries++;
182
+ try {
183
+ const validateOnly = true;
184
+ await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody, validateOnly);
185
+ done = true;
186
+ }
187
+ catch (err) {
188
+ if (err instanceof error_1.FirebaseError && err.status === 400) {
189
+ if (tries >= 5) {
190
+ throw err;
191
+ }
192
+ await new Promise((resolve) => setTimeout(resolve, 1000));
193
+ }
194
+ else {
195
+ throw err;
196
+ }
197
+ }
198
+ }
199
+ const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody);
178
200
  const rolloutPoll = poller.pollOperation(Object.assign(Object.assign({}, apphostingPollerOptions), { pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${buildId}`, operationResourceName: rolloutOp.name }));
179
201
  const buildPoll = poller.pollOperation(Object.assign(Object.assign({}, apphostingPollerOptions), { pollerName: `create-${projectId}-${location}-backend-${backendId}-build-${buildId}`, operationResourceName: buildOp.name }));
180
202
  const [rollout, build] = await Promise.all([rolloutPoll, buildPoll]);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchAllRepositories = exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.linkGitHubRepository = exports.parseConnectionName = void 0;
3
+ exports.fetchAllRepositories = exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.getOrCreateOauthConnection = exports.linkGitHubRepository = exports.parseConnectionName = void 0;
4
4
  const clc = require("colorette");
5
5
  const gcb = require("../../../gcp/cloudbuild");
6
6
  const rm = require("../../../gcp/resourceManager");
@@ -29,7 +29,7 @@ function parseConnectionName(name) {
29
29
  }
30
30
  exports.parseConnectionName = parseConnectionName;
31
31
  const gcbPollerOptions = {
32
- apiOrigin: api_1.cloudbuildOrigin,
32
+ apiOrigin: (0, api_1.cloudbuildOrigin)(),
33
33
  apiVersion: "v2",
34
34
  masterTimeout: 25 * 60 * 1000,
35
35
  maxBackoff: 10000,
@@ -49,107 +49,119 @@ function generateConnectionId() {
49
49
  const randomHash = Math.random().toString(36).slice(6);
50
50
  return `apphosting-github-conn-${randomHash}`;
51
51
  }
52
- const ADD_REPO_CHOICE = "@ADD_REPO";
53
52
  const ADD_CONN_CHOICE = "@ADD_CONN";
54
- const CONFIGURE_REMOTE_URI_CHOICES = [ADD_REPO_CHOICE, ADD_CONN_CHOICE];
55
53
  async function linkGitHubRepository(projectId, location) {
56
- var _a, _b, _c, _d;
54
+ var _a, _b;
57
55
  utils.logBullet(clc.bold(`${clc.yellow("===")} Set up a GitHub connection`));
58
- let oauthConn = await getOrCreateConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
59
- while (oauthConn.installationState.stage === "PENDING_USER_OAUTH") {
60
- oauthConn = await promptConnectionAuth(oauthConn);
61
- }
56
+ const oauthConn = await getOrCreateOauthConnection(projectId, location);
62
57
  const existingConns = await listAppHostingConnections(projectId);
63
- if (existingConns.length < 1) {
64
- const grantSuccess = await promptSecretManagerAdminGrant(projectId);
65
- if (!grantSuccess) {
66
- throw new error_1.FirebaseError("Insufficient IAM permissions to create a new connection to GitHub");
67
- }
68
- const connectionId = generateConnectionId();
69
- const conn = await createConnection(projectId, location, connectionId, {
70
- authorizerCredential: (_a = oauthConn.githubConfig) === null || _a === void 0 ? void 0 : _a.authorizerCredential,
71
- });
72
- let refreshedConn = conn;
73
- while (refreshedConn.installationState.stage !== "COMPLETE") {
74
- refreshedConn = await promptAppInstall(conn);
75
- }
76
- existingConns.push(refreshedConn);
58
+ if (existingConns.length === 0) {
59
+ existingConns.push(await createFullyInstalledConnection(projectId, location, generateConnectionId(), oauthConn));
77
60
  }
78
- let { remoteUri, connection } = await promptRepositoryUri(projectId, existingConns);
79
- while (CONFIGURE_REMOTE_URI_CHOICES.includes(remoteUri)) {
80
- if (remoteUri === ADD_REPO_CHOICE) {
81
- await utils.openInBrowser("https://github.com/apps/google-cloud-build/installations/new");
82
- await (0, prompt_1.promptOnce)({
83
- type: "input",
84
- message: "Press ENTER once you have provided the GitHub app installation with access to your desired repository.",
85
- });
86
- }
87
- else if (remoteUri === ADD_CONN_CHOICE) {
88
- const connectionId = generateConnectionId();
89
- const conn = await createConnection(projectId, location, connectionId, {
90
- authorizerCredential: (_b = oauthConn.githubConfig) === null || _b === void 0 ? void 0 : _b.authorizerCredential,
91
- });
92
- let refreshedConn = conn;
93
- while (refreshedConn.installationState.stage !== "COMPLETE") {
94
- refreshedConn = await promptAppInstall(conn);
95
- }
96
- existingConns.push(refreshedConn);
61
+ let repoRemoteUri;
62
+ let connection;
63
+ do {
64
+ if (repoRemoteUri === ADD_CONN_CHOICE) {
65
+ existingConns.push(await createFullyInstalledConnection(projectId, location, generateConnectionId(), oauthConn));
97
66
  }
98
67
  const selection = await promptRepositoryUri(projectId, existingConns);
99
- remoteUri = selection.remoteUri;
68
+ repoRemoteUri = selection.remoteUri;
100
69
  connection = selection.connection;
101
- }
70
+ } while (repoRemoteUri === ADD_CONN_CHOICE);
102
71
  const { id: connectionId } = parseConnectionName(connection.name);
103
72
  await getOrCreateConnection(projectId, location, connectionId, {
104
- authorizerCredential: (_c = connection.githubConfig) === null || _c === void 0 ? void 0 : _c.authorizerCredential,
105
- appInstallationId: (_d = connection.githubConfig) === null || _d === void 0 ? void 0 : _d.appInstallationId,
73
+ authorizerCredential: (_a = connection.githubConfig) === null || _a === void 0 ? void 0 : _a.authorizerCredential,
74
+ appInstallationId: (_b = connection.githubConfig) === null || _b === void 0 ? void 0 : _b.appInstallationId,
106
75
  });
107
- const repo = await getOrCreateRepository(projectId, location, connectionId, remoteUri);
76
+ const repo = await getOrCreateRepository(projectId, location, connectionId, repoRemoteUri);
108
77
  utils.logSuccess(`Successfully linked GitHub repository at remote URI`);
109
- utils.logSuccess(`\t${remoteUri}`);
78
+ utils.logSuccess(`\t${repoRemoteUri}`);
110
79
  return repo;
111
80
  }
112
81
  exports.linkGitHubRepository = linkGitHubRepository;
82
+ async function createFullyInstalledConnection(projectId, location, connectionId, oauthConn) {
83
+ var _a;
84
+ let conn = await createConnection(projectId, location, connectionId, {
85
+ authorizerCredential: (_a = oauthConn.githubConfig) === null || _a === void 0 ? void 0 : _a.authorizerCredential,
86
+ });
87
+ while (conn.installationState.stage !== "COMPLETE") {
88
+ utils.logBullet("Install the Cloud Build GitHub app to enable access to GitHub repositories");
89
+ const targetUri = conn.installationState.actionUri.replace("install_v2", "direct_install_v2");
90
+ utils.logBullet(targetUri);
91
+ await utils.openInBrowser(targetUri);
92
+ await (0, prompt_1.promptOnce)({
93
+ type: "input",
94
+ message: "Press Enter once you have installed or configured the Cloud Build GitHub app to access your GitHub repo.",
95
+ });
96
+ conn = await gcb.getConnection(projectId, location, connectionId);
97
+ }
98
+ return conn;
99
+ }
100
+ async function getOrCreateOauthConnection(projectId, location) {
101
+ let conn;
102
+ try {
103
+ conn = await gcb.getConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
104
+ }
105
+ catch (err) {
106
+ if (err.status === 404) {
107
+ await ensureSecretManagerAdminGrant(projectId);
108
+ conn = await createConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
109
+ }
110
+ else {
111
+ throw err;
112
+ }
113
+ }
114
+ while (conn.installationState.stage === "PENDING_USER_OAUTH") {
115
+ utils.logBullet("You must authorize the Cloud Build GitHub app.");
116
+ utils.logBullet("Sign in to GitHub and authorize Cloud Build GitHub app:");
117
+ const { url, cleanup } = await utils.openInBrowserPopup(conn.installationState.actionUri, "Authorize the GitHub app");
118
+ utils.logBullet(`\t${url}`);
119
+ await (0, prompt_1.promptOnce)({
120
+ type: "input",
121
+ message: "Press Enter once you have authorized the app",
122
+ });
123
+ cleanup();
124
+ const { projectId, location, id } = parseConnectionName(conn.name);
125
+ conn = await gcb.getConnection(projectId, location, id);
126
+ }
127
+ return conn;
128
+ }
129
+ exports.getOrCreateOauthConnection = getOrCreateOauthConnection;
113
130
  async function promptRepositoryUri(projectId, connections) {
114
131
  const { repos, remoteUriToConnection } = await fetchAllRepositories(projectId, connections);
115
- const searchRepos = (repos) => async (_, input = "") => {
116
- return [
117
- new inquirer.Separator(),
118
- {
119
- name: "Missing a repo? Select this option to configure your installation's access settings",
120
- value: ADD_REPO_CHOICE,
121
- },
122
- {
123
- name: "Missing an account or org? Select this option to create a new connection",
124
- value: ADD_CONN_CHOICE,
125
- },
126
- new inquirer.Separator(),
127
- ...fuzzy
128
- .filter(input, repos, {
129
- extract: (repo) => extractRepoSlugFromUri(repo.remoteUri) || "",
130
- })
131
- .map((result) => {
132
- return {
133
- name: extractRepoSlugFromUri(result.original.remoteUri) || "",
134
- value: result.original.remoteUri,
135
- };
136
- }),
137
- ];
138
- };
139
132
  const remoteUri = await (0, prompt_1.promptOnce)({
140
133
  type: "autocomplete",
141
134
  name: "remoteUri",
142
135
  message: "Which of the following repositories would you like to deploy?",
143
- source: searchRepos(repos),
136
+ source: (_, input = "") => {
137
+ return new Promise((resolve) => resolve([
138
+ new inquirer.Separator(),
139
+ {
140
+ name: "Missing a repo? Select this option to configure your GitHub connection settings",
141
+ value: ADD_CONN_CHOICE,
142
+ },
143
+ new inquirer.Separator(),
144
+ ...fuzzy
145
+ .filter(input, repos, {
146
+ extract: (repo) => extractRepoSlugFromUri(repo.remoteUri) || "",
147
+ })
148
+ .map((result) => {
149
+ return {
150
+ name: extractRepoSlugFromUri(result.original.remoteUri) || "",
151
+ value: result.original.remoteUri,
152
+ };
153
+ }),
154
+ ]));
155
+ },
144
156
  });
145
157
  return { remoteUri, connection: remoteUriToConnection[remoteUri] };
146
158
  }
147
- async function promptSecretManagerAdminGrant(projectId) {
159
+ async function ensureSecretManagerAdminGrant(projectId) {
148
160
  const projectNumber = await (0, getProjectNumber_1.getProjectNumber)({ projectId });
149
161
  const cbsaEmail = gcb.serviceAgentEmail(projectNumber);
150
162
  const alreadyGranted = await rm.serviceAccountHasRoles(projectId, cbsaEmail, ["roles/secretmanager.admin"], true);
151
163
  if (alreadyGranted) {
152
- return true;
164
+ return;
153
165
  }
154
166
  utils.logBullet("To create a new GitHub connection, Secret Manager Admin role (roles/secretmanager.admin) is required on the Cloud Build Service Agent.");
155
167
  const grant = await (0, prompt_1.promptOnce)({
@@ -162,36 +174,10 @@ async function promptSecretManagerAdminGrant(projectId) {
162
174
  `\tgcloud projects add-iam-policy-binding ${projectId} \\\n` +
163
175
  `\t --member="serviceAccount:${cbsaEmail} \\\n` +
164
176
  `\t --role="roles/secretmanager.admin\n`);
165
- return false;
177
+ throw new error_1.FirebaseError("Insufficient IAM permissions to create a new connection to GitHub");
166
178
  }
167
179
  await rm.addServiceAccountToRoles(projectId, cbsaEmail, ["roles/secretmanager.admin"], true);
168
180
  utils.logSuccess("Successfully granted the required role to the Cloud Build Service Agent!");
169
- return true;
170
- }
171
- async function promptConnectionAuth(conn) {
172
- utils.logBullet("You must authorize the Cloud Build GitHub app.");
173
- utils.logBullet("Sign in to GitHub and authorize Cloud Build GitHub app:");
174
- const { url, cleanup } = await utils.openInBrowserPopup(conn.installationState.actionUri, "Authorize the GitHub app");
175
- utils.logBullet(`\t${url}`);
176
- await (0, prompt_1.promptOnce)({
177
- type: "input",
178
- message: "Press Enter once you have authorized the app",
179
- });
180
- cleanup();
181
- const { projectId, location, id } = parseConnectionName(conn.name);
182
- return await gcb.getConnection(projectId, location, id);
183
- }
184
- async function promptAppInstall(conn) {
185
- utils.logBullet("Install the Cloud Build GitHub app to enable access to GitHub repositories");
186
- const targetUri = conn.installationState.actionUri.replace("install_v2", "direct_install_v2");
187
- utils.logBullet(targetUri);
188
- await utils.openInBrowser(targetUri);
189
- await (0, prompt_1.promptOnce)({
190
- type: "input",
191
- message: "Press Enter once you have installed or configured the Cloud Build GitHub app to access your GitHub repo.",
192
- });
193
- const { projectId, location, id } = parseConnectionName(conn.name);
194
- return await gcb.getConnection(projectId, location, id);
195
181
  }
196
182
  async function createConnection(projectId, location, connectionId, githubConfig) {
197
183
  const op = await gcb.createConnection(projectId, location, connectionId, githubConfig);
@@ -71,7 +71,7 @@ async function doSetup(setup, config) {
71
71
  setup.config = setup.config || {};
72
72
  let instanceDetails;
73
73
  if (setup.projectId) {
74
- await (0, ensureApiEnabled_1.ensure)(setup.projectId, api_1.rtdbManagementOrigin, "database", false);
74
+ await (0, ensureApiEnabled_1.ensure)(setup.projectId, (0, api_1.rtdbManagementOrigin)(), "database", false);
75
75
  logger_1.logger.info();
76
76
  setup.instance =
77
77
  setup.instance || (await (0, getDefaultDatabaseInstance_1.getDefaultDatabaseInstance)({ project: setup.projectId }));
@@ -10,7 +10,7 @@ async function doSetup(setup, config, options) {
10
10
  const projectId = (_b = (_a = setup === null || setup === void 0 ? void 0 : setup.rcfile) === null || _a === void 0 ? void 0 : _a.projects) === null || _b === void 0 ? void 0 : _b.default;
11
11
  if (projectId) {
12
12
  await (0, requirePermissions_1.requirePermissions)(Object.assign(Object.assign({}, options), { project: projectId }));
13
- await Promise.all([(0, ensureApiEnabled_1.ensure)(projectId, api_1.extensionsOrigin, "unused", true)]);
13
+ await Promise.all([(0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.extensionsOrigin)(), "unused", true)]);
14
14
  }
15
15
  return manifest.writeEmptyManifest(config, options);
16
16
  }
@@ -16,8 +16,8 @@ async function doSetup(setup, config, options) {
16
16
  if (projectId) {
17
17
  await (0, requirePermissions_1.requirePermissions)(Object.assign(Object.assign({}, options), { project: projectId }));
18
18
  await Promise.all([
19
- (0, ensureApiEnabled_1.ensure)(projectId, api_1.functionsOrigin, "unused", true),
20
- (0, ensureApiEnabled_1.ensure)(projectId, api_1.runtimeconfigOrigin, "unused", true),
19
+ (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.functionsOrigin)(), "unused", true),
20
+ (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.runtimeconfigOrigin)(), "unused", true),
21
21
  ]);
22
22
  }
23
23
  setup.functions = {};
@@ -28,7 +28,7 @@ const YML_MERGE_FILENAME = "firebase-hosting-merge.yml";
28
28
  const CHECKOUT_GITHUB_ACTION_NAME = "actions/checkout@v4";
29
29
  const HOSTING_GITHUB_ACTION_NAME = "FirebaseExtended/action-hosting-deploy@v0";
30
30
  const SERVICE_ACCOUNT_MAX_KEY_NUMBER = 10;
31
- const githubApiClient = new apiv2_1.Client({ urlPrefix: api_1.githubApiOrigin, auth: false });
31
+ const githubApiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.githubApiOrigin)(), auth: false });
32
32
  async function initGitHub(setup) {
33
33
  if (!setup.projectId) {
34
34
  return (0, utils_1.reject)("Could not determine Project ID, can't set up GitHub workflow.", { exit: 1 });
@@ -109,7 +109,7 @@ async function initGitHub(setup) {
109
109
  }
110
110
  logger_1.logger.info();
111
111
  (0, utils_1.logLabeledBullet)("Action required", `Visit this URL to revoke authorization for the Firebase CLI GitHub OAuth App:`);
112
- logger_1.logger.info((0, colorette_1.bold)((0, colorette_1.underline)(`https://github.com/settings/connections/applications/${api_1.githubClientId}`)));
112
+ logger_1.logger.info((0, colorette_1.bold)((0, colorette_1.underline)(`https://github.com/settings/connections/applications/${(0, api_1.githubClientId)()}`)));
113
113
  (0, utils_1.logLabeledBullet)("Action required", `Push any new workflow file(s) to your repo`);
114
114
  }
115
115
  exports.initGitHub = initGitHub;
@@ -260,7 +260,7 @@ async function promptForRepo(options, ghAccessToken) {
260
260
  (0, utils_1.logWarning)("The provided authorization cannot be used with this repository. If this repository is in an organization, did you remember to grant access?", "error");
261
261
  logger_1.logger.info();
262
262
  (0, utils_1.logLabeledBullet)("Action required", `Visit this URL to ensure access has been granted to the appropriate organization(s) for the Firebase CLI GitHub OAuth App:`);
263
- logger_1.logger.info((0, colorette_1.bold)((0, colorette_1.underline)(`https://github.com/settings/connections/applications/${api_1.githubClientId}`)));
263
+ logger_1.logger.info((0, colorette_1.bold)((0, colorette_1.underline)(`https://github.com/settings/connections/applications/${(0, api_1.githubClientId)()}`)));
264
264
  logger_1.logger.info();
265
265
  }
266
266
  return false;
@@ -378,6 +378,7 @@ async function createServiceAccountAndKey(options, repo, accountId) {
378
378
  }
379
379
  const requiredRoles = [
380
380
  resourceManager_1.firebaseRoles.authAdmin,
381
+ resourceManager_1.firebaseRoles.serviceUsageConsumer,
381
382
  resourceManager_1.firebaseRoles.apiKeysViewer,
382
383
  resourceManager_1.firebaseRoles.hostingAdmin,
383
384
  resourceManager_1.firebaseRoles.runViewer,
@@ -40,7 +40,7 @@ function getAppPlatform(platform) {
40
40
  }
41
41
  }
42
42
  exports.getAppPlatform = getAppPlatform;
43
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.firebaseApiOrigin, apiVersion: "v1beta1" });
43
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.firebaseApiOrigin)(), apiVersion: "v1beta1" });
44
44
  async function createIosApp(projectId, options) {
45
45
  try {
46
46
  const response = await apiClient.request({
@@ -51,7 +51,7 @@ async function createIosApp(projectId, options) {
51
51
  });
52
52
  const appData = await (0, operation_poller_1.pollOperation)({
53
53
  pollerName: "Create iOS app Poller",
54
- apiOrigin: api_1.firebaseApiOrigin,
54
+ apiOrigin: (0, api_1.firebaseApiOrigin)(),
55
55
  apiVersion: "v1beta1",
56
56
  operationResourceName: response.body.name,
57
57
  });
@@ -73,7 +73,7 @@ async function createAndroidApp(projectId, options) {
73
73
  });
74
74
  const appData = await (0, operation_poller_1.pollOperation)({
75
75
  pollerName: "Create Android app Poller",
76
- apiOrigin: api_1.firebaseApiOrigin,
76
+ apiOrigin: (0, api_1.firebaseApiOrigin)(),
77
77
  apiVersion: "v1beta1",
78
78
  operationResourceName: response.body.name,
79
79
  });
@@ -98,7 +98,7 @@ async function createWebApp(projectId, options) {
98
98
  });
99
99
  const appData = await (0, operation_poller_1.pollOperation)({
100
100
  pollerName: "Create Web app Poller",
101
- apiOrigin: api_1.firebaseApiOrigin,
101
+ apiOrigin: (0, api_1.firebaseApiOrigin)(),
102
102
  apiVersion: "v1beta1",
103
103
  operationResourceName: response.body.name,
104
104
  });
@@ -31,7 +31,7 @@ var DatabaseLocation;
31
31
  DatabaseLocation["ASIA_SOUTHEAST1"] = "asia-southeast1";
32
32
  DatabaseLocation["ANY"] = "-";
33
33
  })(DatabaseLocation = exports.DatabaseLocation || (exports.DatabaseLocation = {}));
34
- const apiClient = new apiv2_1.Client({ urlPrefix: api_1.rtdbManagementOrigin, apiVersion: exports.MGMT_API_VERSION });
34
+ const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.rtdbManagementOrigin)(), apiVersion: exports.MGMT_API_VERSION });
35
35
  async function populateInstanceDetails(options) {
36
36
  options.instanceDetails = await getDatabaseInstanceDetails(options.project, options.instance);
37
37
  return Promise.resolve();