firebase-tools-with-isolate 13.2.1-0 → 13.3.1

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 (46) hide show
  1. package/lib/auth.js +11 -2
  2. package/lib/commands/apphosting-backends-create.js +6 -3
  3. package/lib/commands/apphosting-backends-delete.js +3 -5
  4. package/lib/commands/apphosting-backends-get.js +2 -2
  5. package/lib/commands/apphosting-backends-list.js +3 -3
  6. package/lib/commands/apphosting-builds-create.js +4 -4
  7. package/lib/commands/apphosting-builds-get.js +2 -2
  8. package/lib/commands/apphosting-rollouts-create.js +3 -3
  9. package/lib/commands/apphosting-rollouts-list.js +2 -2
  10. package/lib/commands/firestore-backups-delete.js +44 -0
  11. package/lib/commands/firestore-backups-get.js +25 -0
  12. package/lib/commands/firestore-backups-list.js +33 -0
  13. package/lib/commands/firestore-backups-schedules-create.js +67 -0
  14. package/lib/commands/firestore-backups-schedules-delete.js +46 -0
  15. package/lib/commands/firestore-backups-schedules-list.js +27 -0
  16. package/lib/commands/firestore-backups-schedules-update.js +33 -0
  17. package/lib/commands/firestore-databases-create.js +4 -2
  18. package/lib/commands/firestore-databases-delete.js +4 -2
  19. package/lib/commands/firestore-databases-get.js +3 -1
  20. package/lib/commands/firestore-databases-list.js +3 -1
  21. package/lib/commands/firestore-databases-restore.js +42 -0
  22. package/lib/commands/firestore-databases-update.js +4 -2
  23. package/lib/commands/firestore-indexes-list.js +5 -3
  24. package/lib/commands/firestore-locations.js +3 -1
  25. package/lib/commands/index.js +11 -1
  26. package/lib/commands/init.js +3 -3
  27. package/lib/deploy/functions/runtimes/index.js +2 -0
  28. package/lib/deploy/functions/runtimes/python/index.js +4 -1
  29. package/lib/deploy/functions/services/firestore.js +1 -1
  30. package/lib/emulator/downloadableEmulators.js +3 -3
  31. package/lib/emulator/storage/rules/runtime.js +1 -1
  32. package/lib/experiments.js +2 -2
  33. package/lib/firestore/api-sort.js +23 -1
  34. package/lib/firestore/api-types.js +6 -1
  35. package/lib/firestore/api.js +18 -115
  36. package/lib/firestore/backupUtils.js +30 -0
  37. package/lib/firestore/delete.js +3 -3
  38. package/lib/firestore/pretty-print.js +184 -0
  39. package/lib/gcp/apphosting.js +2 -2
  40. package/lib/gcp/cloudbuild.js +7 -2
  41. package/lib/gcp/firestore.js +89 -6
  42. package/lib/init/features/apphosting/index.js +140 -79
  43. package/lib/init/features/apphosting/repo.js +80 -32
  44. package/lib/init/features/hosting/github.js +5 -0
  45. package/lib/prompt.js +1 -0
  46. package/package.json +10 -5
@@ -84,14 +84,14 @@ async function createBuild(projectId, location, backendId, buildId, buildInput)
84
84
  return res.body;
85
85
  }
86
86
  exports.createBuild = createBuild;
87
- async function createRollout(projectId, location, backendId, rolloutId, rollout) {
87
+ async function createRollout(projectId, location, backendId, rolloutId, rollout, validateOnly = false) {
88
88
  const res = await exports.client.post(`projects/${projectId}/locations/${location}/backends/${backendId}/rollouts`, {
89
89
  ...rollout,
90
90
  labels: {
91
91
  ...rollout.labels,
92
92
  ...deploymentTool.labels(),
93
93
  },
94
- }, { queryParams: { rolloutId } });
94
+ }, { queryParams: { rolloutId, validateOnly: validateOnly ? "true" : "false" } });
95
95
  return res.body;
96
96
  }
97
97
  exports.createRollout = createRollout;
@@ -46,9 +46,14 @@ async function deleteConnection(projectId, location, connectionId) {
46
46
  return res.body;
47
47
  }
48
48
  exports.deleteConnection = deleteConnection;
49
- async function fetchLinkableRepositories(projectId, location, connectionId) {
49
+ async function fetchLinkableRepositories(projectId, location, connectionId, pageToken = "", pageSize = 1000) {
50
50
  const name = `projects/${projectId}/locations/${location}/connections/${connectionId}:fetchLinkableRepositories`;
51
- const res = await client.get(name);
51
+ const res = await client.get(name, {
52
+ queryParams: {
53
+ pageSize,
54
+ pageToken,
55
+ },
56
+ });
52
57
  return res.body;
53
58
  }
54
59
  exports.fetchLinkableRepositories = fetchLinkableRepositories;
@@ -1,15 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteDocuments = exports.deleteDocument = exports.listCollectionIds = exports.getDatabase = void 0;
3
+ exports.getBackupSchedule = exports.listBackupSchedules = exports.getBackup = exports.listBackups = exports.deleteBackupSchedule = exports.deleteBackup = exports.updateBackupSchedule = exports.createBackupSchedule = exports.deleteDocuments = exports.deleteDocument = exports.listCollectionIds = exports.getDatabase = exports.DayOfWeek = void 0;
4
4
  const api_1 = require("../api");
5
5
  const apiv2_1 = require("../apiv2");
6
6
  const logger_1 = require("../logger");
7
- const apiClient = new apiv2_1.Client({
7
+ const proto_1 = require("./proto");
8
+ const error_1 = require("../error");
9
+ const prodOnlyClient = new apiv2_1.Client({
8
10
  auth: true,
9
11
  apiVersion: "v1",
10
12
  urlPrefix: api_1.firestoreOrigin,
11
13
  });
12
- async function getDatabase(project, database) {
14
+ const emuOrProdClient = new apiv2_1.Client({
15
+ auth: true,
16
+ apiVersion: "v1",
17
+ urlPrefix: api_1.firestoreOriginOrEmulator,
18
+ });
19
+ var DayOfWeek;
20
+ (function (DayOfWeek) {
21
+ DayOfWeek["MONDAY"] = "MONDAY";
22
+ DayOfWeek["TUEDAY"] = "TUESDAY";
23
+ DayOfWeek["WEDNESDAY"] = "WEDNESDAY";
24
+ DayOfWeek["THURSDAY"] = "THURSDAY";
25
+ DayOfWeek["FRIDAY"] = "FRIDAY";
26
+ DayOfWeek["SATURDAY"] = "SATURDAY";
27
+ DayOfWeek["SUNDAY"] = "SUNDAY";
28
+ })(DayOfWeek = exports.DayOfWeek || (exports.DayOfWeek = {}));
29
+ async function getDatabase(project, database, allowEmulator = false) {
30
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
13
31
  const url = `projects/${project}/databases/${database}`;
14
32
  try {
15
33
  const resp = await apiClient.get(url);
@@ -21,7 +39,8 @@ async function getDatabase(project, database) {
21
39
  }
22
40
  }
23
41
  exports.getDatabase = getDatabase;
24
- function listCollectionIds(project) {
42
+ function listCollectionIds(project, allowEmulator = false) {
43
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
25
44
  const url = "projects/" + project + "/databases/(default)/documents:listCollectionIds";
26
45
  const data = {
27
46
  pageSize: 2147483647,
@@ -31,11 +50,13 @@ function listCollectionIds(project) {
31
50
  });
32
51
  }
33
52
  exports.listCollectionIds = listCollectionIds;
34
- async function deleteDocument(doc) {
53
+ async function deleteDocument(doc, allowEmulator = false) {
54
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
35
55
  return apiClient.delete(doc.name);
36
56
  }
37
57
  exports.deleteDocument = deleteDocument;
38
- async function deleteDocuments(project, docs) {
58
+ async function deleteDocuments(project, docs, allowEmulator = false) {
59
+ const apiClient = allowEmulator ? emuOrProdClient : prodOnlyClient;
39
60
  const url = "projects/" + project + "/databases/(default)/documents:commit";
40
61
  const writes = docs.map((doc) => {
41
62
  return { delete: doc.name };
@@ -45,3 +66,65 @@ async function deleteDocuments(project, docs) {
45
66
  return res.body.writeResults.length;
46
67
  }
47
68
  exports.deleteDocuments = deleteDocuments;
69
+ async function createBackupSchedule(project, databaseId, retention, dailyRecurrence, weeklyRecurrence) {
70
+ const url = `projects/${project}/databases/${databaseId}/backupSchedules`;
71
+ const data = {
72
+ retention: (0, proto_1.durationFromSeconds)(retention),
73
+ dailyRecurrence,
74
+ weeklyRecurrence,
75
+ };
76
+ (0, proto_1.assertOneOf)("BackupSchedule", data, "recurrence", "dailyRecurrence", "weeklyRecurrence");
77
+ const res = await prodOnlyClient.post(url, data);
78
+ return res.body;
79
+ }
80
+ exports.createBackupSchedule = createBackupSchedule;
81
+ async function updateBackupSchedule(backupScheduleName, retention) {
82
+ const data = {
83
+ retention: (0, proto_1.durationFromSeconds)(retention),
84
+ };
85
+ const res = await prodOnlyClient.patch(backupScheduleName, data);
86
+ return res.body;
87
+ }
88
+ exports.updateBackupSchedule = updateBackupSchedule;
89
+ async function deleteBackup(backupName) {
90
+ await prodOnlyClient.delete(backupName);
91
+ }
92
+ exports.deleteBackup = deleteBackup;
93
+ async function deleteBackupSchedule(backupScheduleName) {
94
+ await prodOnlyClient.delete(backupScheduleName);
95
+ }
96
+ exports.deleteBackupSchedule = deleteBackupSchedule;
97
+ async function listBackups(project, location) {
98
+ const url = `/projects/${project}/locations/${location}/backups`;
99
+ const res = await prodOnlyClient.get(url);
100
+ return res.body;
101
+ }
102
+ exports.listBackups = listBackups;
103
+ async function getBackup(backupName) {
104
+ const res = await prodOnlyClient.get(backupName);
105
+ const backup = res.body;
106
+ if (!backup) {
107
+ throw new error_1.FirebaseError("Not found");
108
+ }
109
+ return backup;
110
+ }
111
+ exports.getBackup = getBackup;
112
+ async function listBackupSchedules(project, database) {
113
+ const url = `/projects/${project}/databases/${database}/backupSchedules`;
114
+ const res = await prodOnlyClient.get(url);
115
+ const backupSchedules = res.body.backupSchedules;
116
+ if (!backupSchedules) {
117
+ return [];
118
+ }
119
+ return backupSchedules;
120
+ }
121
+ exports.listBackupSchedules = listBackupSchedules;
122
+ async function getBackupSchedule(backupScheduleName) {
123
+ const res = await prodOnlyClient.get(backupScheduleName);
124
+ const backupSchedule = res.body;
125
+ if (!backupSchedule) {
126
+ throw new error_1.FirebaseError("Not found");
127
+ }
128
+ return backupSchedule;
129
+ }
130
+ exports.getBackupSchedule = getBackupSchedule;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.onboardRollout = exports.createBackend = exports.onboardBackend = exports.doSetup = void 0;
3
+ exports.orchestrateRollout = exports.setDefaultTrafficPolicy = exports.createBackend = exports.doSetup = void 0;
4
4
  const clc = require("colorette");
5
5
  const repo = require("./repo");
6
6
  const poller = require("../../../operation-poller");
@@ -8,18 +8,21 @@ const apphosting = require("../../../gcp/apphosting");
8
8
  const utils_1 = require("../../../utils");
9
9
  const api_1 = require("../../../api");
10
10
  const apphosting_1 = require("../../../gcp/apphosting");
11
+ const resourceManager_1 = require("../../../gcp/resourceManager");
12
+ const iam_1 = require("../../../gcp/iam");
11
13
  const error_1 = require("../../../error");
12
14
  const prompt_1 = require("../../../prompt");
13
15
  const constants_1 = require("./constants");
14
16
  const ensureApiEnabled_1 = require("../../../ensureApiEnabled");
15
17
  const deploymentTool = require("../../../deploymentTool");
18
+ const DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME = "firebase-app-hosting-compute";
16
19
  const apphostingPollerOptions = {
17
20
  apiOrigin: api_1.apphostingOrigin,
18
21
  apiVersion: apphosting_1.API_VERSION,
19
22
  masterTimeout: 25 * 60 * 1000,
20
23
  maxBackoff: 10000,
21
24
  };
22
- async function doSetup(setup, projectId) {
25
+ async function doSetup(projectId, location, serviceAccount) {
23
26
  await Promise.all([
24
27
  (0, ensureApiEnabled_1.ensure)(projectId, "cloudbuild.googleapis.com", "apphosting", true),
25
28
  (0, ensureApiEnabled_1.ensure)(projectId, "secretmanager.googleapis.com", "apphosting", true),
@@ -27,57 +30,38 @@ async function doSetup(setup, projectId) {
27
30
  (0, ensureApiEnabled_1.ensure)(projectId, "artifactregistry.googleapis.com", "apphosting", true),
28
31
  ]);
29
32
  const allowedLocations = (await apphosting.listLocations(projectId)).map((loc) => loc.locationId);
30
- if (setup.location) {
31
- if (!allowedLocations.includes(setup.location)) {
32
- throw new error_1.FirebaseError(`Invalid location ${setup.location}. Valid choices are ${allowedLocations.join(", ")}`);
33
+ if (location) {
34
+ if (!allowedLocations.includes(location)) {
35
+ throw new error_1.FirebaseError(`Invalid location ${location}. Valid choices are ${allowedLocations.join(", ")}`);
33
36
  }
34
37
  }
35
38
  (0, utils_1.logBullet)("First we need a few details to create your backend.");
36
- const location = setup.location || (await promptLocation(projectId, allowedLocations));
39
+ location =
40
+ location ||
41
+ (await (0, prompt_1.promptOnce)({
42
+ name: "region",
43
+ type: "list",
44
+ default: constants_1.DEFAULT_REGION,
45
+ message: "Please select a region " +
46
+ `(${clc.yellow("info")}: Your region determines where your backend is located):\n`,
47
+ choices: allowedLocations.map((loc) => ({ value: loc })),
48
+ }));
37
49
  (0, utils_1.logSuccess)(`Region set to ${location}.\n`);
38
- let backendId;
39
- while (true) {
40
- backendId = await (0, prompt_1.promptOnce)({
41
- name: "backendId",
42
- type: "input",
43
- default: "my-web-app",
44
- message: "Create a name for your backend [1-30 characters]",
45
- });
46
- try {
47
- await apphosting.getBackend(projectId, location, backendId);
48
- }
49
- catch (err) {
50
- if (err.status === 404) {
51
- break;
52
- }
53
- throw new error_1.FirebaseError(`Failed to check if backend with id ${backendId} already exists in ${location}`, { original: err });
54
- }
55
- (0, utils_1.logWarning)(`Backend with id ${backendId} already exists in ${location}`);
56
- }
57
- const backend = await onboardBackend(projectId, location, backendId);
50
+ const backendId = await promptNewBackendId(projectId, location, {
51
+ name: "backendId",
52
+ type: "input",
53
+ default: "my-web-app",
54
+ message: "Create a name for your backend [1-30 characters]",
55
+ });
56
+ const cloudBuildConnRepo = await repo.linkGitHubRepository(projectId, location);
57
+ const backend = await createBackend(projectId, location, backendId, cloudBuildConnRepo, serviceAccount);
58
58
  const branch = await (0, prompt_1.promptOnce)({
59
59
  name: "branch",
60
60
  type: "input",
61
61
  default: "main",
62
62
  message: "Pick a branch for continuous deployment",
63
63
  });
64
- const traffic = {
65
- rolloutPolicy: {
66
- codebaseBranch: branch,
67
- stages: [
68
- {
69
- progression: "IMMEDIATE",
70
- targetPercent: 100,
71
- },
72
- ],
73
- },
74
- };
75
- const op = await apphosting.updateTraffic(projectId, location, backendId, traffic);
76
- await poller.pollOperation({
77
- ...apphostingPollerOptions,
78
- pollerName: `updateTraffic-${projectId}-${location}-${backendId}`,
79
- operationResourceName: op.name,
80
- });
64
+ await setDefaultTrafficPolicy(projectId, location, backendId, branch);
81
65
  const confirmRollout = await (0, prompt_1.promptOnce)({
82
66
  type: "confirm",
83
67
  name: "rollout",
@@ -89,68 +73,138 @@ async function doSetup(setup, projectId) {
89
73
  (0, utils_1.logSuccess)(`Your site will be deployed at:\n\thttps://${backend.uri}`);
90
74
  return;
91
75
  }
92
- const { build } = await onboardRollout(projectId, location, backendId, {
76
+ await orchestrateRollout(projectId, location, backendId, {
93
77
  source: {
94
78
  codebase: {
95
79
  branch,
96
80
  },
97
81
  },
98
82
  });
99
- if (build.state !== "READY") {
100
- if (!build.buildLogsUri) {
101
- throw new error_1.FirebaseError("Failed to build your app, but failed to get build logs as well. " +
102
- "This is an internal error and should be reported");
103
- }
104
- throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
105
- }
106
83
  (0, utils_1.logSuccess)(`Successfully created backend:\n\t${backend.name}`);
107
84
  (0, utils_1.logSuccess)(`Your site is now deployed at:\n\thttps://${backend.uri}`);
108
- (0, utils_1.logSuccess)(`View the rollout status by running:\n\tfirebase apphosting:backends:get ${backendId} --project ${projectId}`);
109
85
  }
110
86
  exports.doSetup = doSetup;
111
- async function promptLocation(projectId, locations) {
112
- return (await (0, prompt_1.promptOnce)({
113
- name: "region",
114
- type: "list",
115
- default: constants_1.DEFAULT_REGION,
116
- message: "Please select a region " +
117
- `(${clc.yellow("info")}: Your region determines where your backend is located):\n`,
118
- choices: locations.map((loc) => ({ value: loc })),
119
- }));
87
+ async function promptNewBackendId(projectId, location, prompt) {
88
+ while (true) {
89
+ const backendId = await (0, prompt_1.promptOnce)(prompt);
90
+ try {
91
+ await apphosting.getBackend(projectId, location, backendId);
92
+ }
93
+ catch (err) {
94
+ if (err.status === 404) {
95
+ return backendId;
96
+ }
97
+ throw new error_1.FirebaseError(`Failed to check if backend with id ${backendId} already exists in ${location}`, { original: err });
98
+ }
99
+ (0, utils_1.logWarning)(`Backend with id ${backendId} already exists in ${location}`);
100
+ }
120
101
  }
121
- function toBackend(cloudBuildConnRepo) {
122
- return {
102
+ function defaultComputeServiceAccountEmail(projectId) {
103
+ return `${DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME}@${projectId}.iam.gserviceaccount.com`;
104
+ }
105
+ async function createBackend(projectId, location, backendId, repository, serviceAccount) {
106
+ const defaultServiceAccount = defaultComputeServiceAccountEmail(projectId);
107
+ const backendReqBody = {
123
108
  servingLocality: "GLOBAL_ACCESS",
124
109
  codebase: {
125
- repository: `${cloudBuildConnRepo.name}`,
110
+ repository: `${repository.name}`,
126
111
  rootDirectory: "/",
127
112
  },
128
113
  labels: deploymentTool.labels(),
114
+ computeServiceAccount: serviceAccount || defaultServiceAccount,
129
115
  };
116
+ delete backendReqBody.computeServiceAccount;
117
+ async function createBackendAndPoll() {
118
+ const op = await apphosting.createBackend(projectId, location, backendReqBody, backendId);
119
+ return await poller.pollOperation({
120
+ ...apphostingPollerOptions,
121
+ pollerName: `create-${projectId}-${location}-${backendId}`,
122
+ operationResourceName: op.name,
123
+ });
124
+ }
125
+ try {
126
+ return await createBackendAndPoll();
127
+ }
128
+ catch (err) {
129
+ if (err.status === 403) {
130
+ if (err.message.includes(defaultServiceAccount)) {
131
+ await provisionDefaultComputeServiceAccount(projectId);
132
+ return await createBackendAndPoll();
133
+ }
134
+ else if (serviceAccount && err.message.includes(serviceAccount)) {
135
+ throw new error_1.FirebaseError(`Failed to create backend due to missing delegation permissions for ${serviceAccount}. Make sure you have the iam.serviceAccounts.actAs permission.`, { children: [err] });
136
+ }
137
+ }
138
+ throw err;
139
+ }
130
140
  }
131
- async function onboardBackend(projectId, location, backendId) {
132
- const cloudBuildConnRepo = await repo.linkGitHubRepository(projectId, location);
133
- const backendDetails = toBackend(cloudBuildConnRepo);
134
- return await createBackend(projectId, location, backendDetails, backendId);
141
+ exports.createBackend = createBackend;
142
+ async function provisionDefaultComputeServiceAccount(projectId) {
143
+ try {
144
+ await (0, iam_1.createServiceAccount)(projectId, DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME, "Firebase App Hosting compute service account", "Default service account used to run builds and deploys for Firebase App Hosting");
145
+ }
146
+ catch (err) {
147
+ if (err.status !== 409) {
148
+ throw err;
149
+ }
150
+ }
151
+ await (0, resourceManager_1.addServiceAccountToRoles)(projectId, defaultComputeServiceAccountEmail(projectId), [
152
+ "roles/firebaseapphosting.viewer",
153
+ "roles/artifactregistry.createOnPushWriter",
154
+ "roles/logging.logWriter",
155
+ "roles/storage.objectAdmin",
156
+ "roles/firebase.sdkAdminServiceAgent",
157
+ ], true);
135
158
  }
136
- exports.onboardBackend = onboardBackend;
137
- async function createBackend(projectId, location, backendReqBoby, backendId) {
138
- const op = await apphosting.createBackend(projectId, location, backendReqBoby, backendId);
139
- const backend = await poller.pollOperation({
159
+ async function setDefaultTrafficPolicy(projectId, location, backendId, codebaseBranch) {
160
+ const traffic = {
161
+ rolloutPolicy: {
162
+ codebaseBranch: codebaseBranch,
163
+ stages: [
164
+ {
165
+ progression: "IMMEDIATE",
166
+ targetPercent: 100,
167
+ },
168
+ ],
169
+ },
170
+ };
171
+ const op = await apphosting.updateTraffic(projectId, location, backendId, traffic);
172
+ await poller.pollOperation({
140
173
  ...apphostingPollerOptions,
141
- pollerName: `create-${projectId}-${location}-${backendId}`,
174
+ pollerName: `updateTraffic-${projectId}-${location}-${backendId}`,
142
175
  operationResourceName: op.name,
143
176
  });
144
- return backend;
145
177
  }
146
- exports.createBackend = createBackend;
147
- async function onboardRollout(projectId, location, backendId, buildInput) {
178
+ exports.setDefaultTrafficPolicy = setDefaultTrafficPolicy;
179
+ async function orchestrateRollout(projectId, location, backendId, buildInput) {
148
180
  (0, utils_1.logBullet)("Starting a new rollout... this may take a few minutes.");
149
181
  const buildId = await apphosting.getNextRolloutId(projectId, location, backendId, 1);
150
182
  const buildOp = await apphosting.createBuild(projectId, location, backendId, buildId, buildInput);
151
- const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, {
183
+ const rolloutBody = {
152
184
  build: `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`,
153
- });
185
+ };
186
+ let tries = 0;
187
+ let done = false;
188
+ while (!done) {
189
+ tries++;
190
+ try {
191
+ const validateOnly = true;
192
+ await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody, validateOnly);
193
+ done = true;
194
+ }
195
+ catch (err) {
196
+ if (err instanceof error_1.FirebaseError && err.status === 400) {
197
+ if (tries >= 5) {
198
+ throw err;
199
+ }
200
+ await new Promise((resolve) => setTimeout(resolve, 1000));
201
+ }
202
+ else {
203
+ throw err;
204
+ }
205
+ }
206
+ }
207
+ const rolloutOp = await apphosting.createRollout(projectId, location, backendId, buildId, rolloutBody);
154
208
  const rolloutPoll = poller.pollOperation({
155
209
  ...apphostingPollerOptions,
156
210
  pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${buildId}`,
@@ -163,6 +217,13 @@ async function onboardRollout(projectId, location, backendId, buildInput) {
163
217
  });
164
218
  const [rollout, build] = await Promise.all([rolloutPoll, buildPoll]);
165
219
  (0, utils_1.logSuccess)("Rollout completed.");
220
+ if (build.state !== "READY") {
221
+ if (!build.buildLogsUri) {
222
+ throw new error_1.FirebaseError("Failed to build your app, but failed to get build logs as well. " +
223
+ "This is an internal error and should be reported");
224
+ }
225
+ throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
226
+ }
166
227
  return { rollout, build };
167
228
  }
168
- exports.onboardRollout = onboardRollout;
229
+ exports.orchestrateRollout = orchestrateRollout;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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.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");
@@ -10,11 +10,13 @@ const api_1 = require("../../../api");
10
10
  const error_1 = require("../../../error");
11
11
  const prompt_1 = require("../../../prompt");
12
12
  const getProjectNumber_1 = require("../../../getProjectNumber");
13
+ const fuzzy = require("fuzzy");
14
+ const inquirer = require("inquirer");
13
15
  const APPHOSTING_CONN_PATTERN = /.+\/apphosting-github-conn-.+$/;
14
16
  const APPHOSTING_OAUTH_CONN_NAME = "apphosting-github-oauth";
15
17
  const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/connections\/(?<id>[^\/]+)$/;
16
18
  function parseConnectionName(name) {
17
- const match = name.match(CONNECTION_NAME_REGEX);
19
+ const match = CONNECTION_NAME_REGEX.exec(name);
18
20
  if (!match || typeof match.groups === undefined) {
19
21
  return;
20
22
  }
@@ -46,18 +48,21 @@ function generateConnectionId() {
46
48
  const randomHash = Math.random().toString(36).slice(6);
47
49
  return `apphosting-github-conn-${randomHash}`;
48
50
  }
51
+ const ADD_REPO_CHOICE = "@ADD_REPO";
52
+ const ADD_CONN_CHOICE = "@ADD_CONN";
53
+ const CONFIGURE_REMOTE_URI_CHOICES = [ADD_REPO_CHOICE, ADD_CONN_CHOICE];
49
54
  async function linkGitHubRepository(projectId, location) {
50
55
  utils.logBullet(clc.bold(`${clc.yellow("===")} Set up a GitHub connection`));
56
+ let oauthConn = await getOrCreateConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
57
+ while (oauthConn.installationState.stage === "PENDING_USER_OAUTH") {
58
+ oauthConn = await promptConnectionAuth(oauthConn);
59
+ }
51
60
  const existingConns = await listAppHostingConnections(projectId);
52
61
  if (existingConns.length < 1) {
53
62
  const grantSuccess = await promptSecretManagerAdminGrant(projectId);
54
63
  if (!grantSuccess) {
55
64
  throw new error_1.FirebaseError("Insufficient IAM permissions to create a new connection to GitHub");
56
65
  }
57
- let oauthConn = await getOrCreateConnection(projectId, location, APPHOSTING_OAUTH_CONN_NAME);
58
- while (oauthConn.installationState.stage === "PENDING_USER_OAUTH") {
59
- oauthConn = await promptConnectionAuth(oauthConn);
60
- }
61
66
  const connectionId = generateConnectionId();
62
67
  const conn = await createConnection(projectId, location, connectionId, {
63
68
  authorizerCredential: oauthConn.githubConfig?.authorizerCredential,
@@ -69,12 +74,25 @@ async function linkGitHubRepository(projectId, location) {
69
74
  existingConns.push(refreshedConn);
70
75
  }
71
76
  let { remoteUri, connection } = await promptRepositoryUri(projectId, existingConns);
72
- while (remoteUri === "") {
73
- await utils.openInBrowser("https://github.com/apps/google-cloud-build/installations/new");
74
- await (0, prompt_1.promptOnce)({
75
- type: "input",
76
- message: "Press ENTER once you have finished configuring your installation's access settings.",
77
- });
77
+ while (CONFIGURE_REMOTE_URI_CHOICES.includes(remoteUri)) {
78
+ if (remoteUri === ADD_REPO_CHOICE) {
79
+ await utils.openInBrowser("https://github.com/apps/google-cloud-build/installations/new");
80
+ await (0, prompt_1.promptOnce)({
81
+ type: "input",
82
+ message: "Press ENTER once you have provided the GitHub app installation with access to your desired repository.",
83
+ });
84
+ }
85
+ else if (remoteUri === ADD_CONN_CHOICE) {
86
+ const connectionId = generateConnectionId();
87
+ const conn = await createConnection(projectId, location, connectionId, {
88
+ authorizerCredential: oauthConn.githubConfig?.authorizerCredential,
89
+ });
90
+ let refreshedConn = conn;
91
+ while (refreshedConn.installationState.stage !== "COMPLETE") {
92
+ refreshedConn = await promptAppInstall(conn);
93
+ }
94
+ existingConns.push(refreshedConn);
95
+ }
78
96
  const selection = await promptRepositoryUri(projectId, existingConns);
79
97
  remoteUri = selection.remoteUri;
80
98
  connection = selection.connection;
@@ -91,28 +109,36 @@ async function linkGitHubRepository(projectId, location) {
91
109
  }
92
110
  exports.linkGitHubRepository = linkGitHubRepository;
93
111
  async function promptRepositoryUri(projectId, connections) {
94
- const remoteUriToConnection = {};
95
- for (const conn of connections) {
96
- const { location, id } = parseConnectionName(conn.name);
97
- const resp = await gcb.fetchLinkableRepositories(projectId, location, id);
98
- if (resp.repositories && resp.repositories.length > 0) {
99
- for (const repo of resp.repositories) {
100
- remoteUriToConnection[repo.remoteUri] = conn;
101
- }
102
- }
103
- }
104
- const choices = Object.keys(remoteUriToConnection).map((remoteUri) => ({
105
- name: extractRepoSlugFromUri(remoteUri) || remoteUri,
106
- value: remoteUri,
107
- }));
108
- choices.push({
109
- name: "Missing a repo? Select this option to configure your installation's access settings",
110
- value: "",
111
- });
112
+ const { repos, remoteUriToConnection } = await fetchAllRepositories(projectId, connections);
113
+ const searchRepos = (repos) => async (_, input = "") => {
114
+ return [
115
+ new inquirer.Separator(),
116
+ {
117
+ name: "Missing a repo? Select this option to configure your installation's access settings",
118
+ value: ADD_REPO_CHOICE,
119
+ },
120
+ {
121
+ name: "Missing an account or org? Select this option to create a new connection",
122
+ value: ADD_CONN_CHOICE,
123
+ },
124
+ new inquirer.Separator(),
125
+ ...fuzzy
126
+ .filter(input, repos, {
127
+ extract: (repo) => extractRepoSlugFromUri(repo.remoteUri) || "",
128
+ })
129
+ .map((result) => {
130
+ return {
131
+ name: extractRepoSlugFromUri(result.original.remoteUri) || "",
132
+ value: result.original.remoteUri,
133
+ };
134
+ }),
135
+ ];
136
+ };
112
137
  const remoteUri = await (0, prompt_1.promptOnce)({
113
- type: "list",
138
+ type: "autocomplete",
139
+ name: "remoteUri",
114
140
  message: "Which of the following repositories would you like to deploy?",
115
- choices,
141
+ source: searchRepos(repos),
116
142
  });
117
143
  return { remoteUri, connection: remoteUriToConnection[remoteUri] };
118
144
  }
@@ -223,3 +249,25 @@ async function listAppHostingConnections(projectId) {
223
249
  !conn.disabled);
224
250
  }
225
251
  exports.listAppHostingConnections = listAppHostingConnections;
252
+ async function fetchAllRepositories(projectId, connections) {
253
+ const repos = [];
254
+ const remoteUriToConnection = {};
255
+ const getNextPage = async (conn, pageToken = "") => {
256
+ const { location, id } = parseConnectionName(conn.name);
257
+ const resp = await gcb.fetchLinkableRepositories(projectId, location, id, pageToken);
258
+ if (resp.repositories && resp.repositories.length > 0) {
259
+ for (const repo of resp.repositories) {
260
+ repos.push(repo);
261
+ remoteUriToConnection[repo.remoteUri] = conn;
262
+ }
263
+ }
264
+ if (resp.nextPageToken) {
265
+ await getNextPage(conn, resp.nextPageToken);
266
+ }
267
+ };
268
+ for (const conn of connections) {
269
+ await getNextPage(conn);
270
+ }
271
+ return { repos, remoteUriToConnection };
272
+ }
273
+ exports.fetchAllRepositories = fetchAllRepositories;
@@ -160,6 +160,11 @@ function writeChannelActionYMLFile(ymlPath, secretName, projectId, script) {
160
160
  const workflowConfig = {
161
161
  name: "Deploy to Firebase Hosting on PR",
162
162
  on: "pull_request",
163
+ permissions: {
164
+ checks: "write",
165
+ contents: "read",
166
+ "pull-requests": "write",
167
+ },
163
168
  jobs: {
164
169
  ["build_and_preview"]: {
165
170
  if: "${{ github.event.pull_request.head.repo.full_name == github.repository }}",
package/lib/prompt.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.confirm = exports.promptOnce = exports.prompt = void 0;
4
4
  const inquirer = require("inquirer");
5
5
  const error_1 = require("./error");
6
+ inquirer.registerPrompt("autocomplete", require("inquirer-autocomplete-prompt"));
6
7
  async function prompt(options, questions) {
7
8
  const prompts = [];
8
9
  for (const question of questions) {