firebase-tools-with-isolate 12.9.1 → 13.0.2-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 (53) hide show
  1. package/README.md +3 -5
  2. package/lib/api.js +2 -2
  3. package/lib/apiv2.js +7 -0
  4. package/lib/auth.js +8 -4
  5. package/lib/commands/{frameworks-backends-create.js → apphosting-backends-create.js} +6 -3
  6. package/lib/commands/{frameworks-backends-delete.js → apphosting-backends-delete.js} +9 -7
  7. package/lib/commands/{frameworks-backends-get.js → apphosting-backends-get.js} +16 -27
  8. package/lib/commands/{frameworks-backends-list.js → apphosting-backends-list.js} +9 -19
  9. package/lib/commands/apphosting-builds-create.js +31 -0
  10. package/lib/commands/apphosting-builds-get.js +18 -0
  11. package/lib/commands/apphosting-rollouts-create.js +26 -0
  12. package/lib/commands/apphosting-rollouts-list.js +18 -0
  13. package/lib/commands/index.js +12 -7
  14. package/lib/commands/login-use.js +25 -6
  15. package/lib/config.js +10 -8
  16. package/lib/deploy/functions/runtimes/node/parseRuntimeAndValidateSDK.js +2 -2
  17. package/lib/deploy/functions/services/firestore.js +11 -1
  18. package/lib/deploy/lifecycleHooks.js +5 -0
  19. package/lib/fetchMOTD.js +1 -1
  20. package/lib/firestore/api.js +6 -6
  21. package/lib/frameworks/angular/index.js +5 -3
  22. package/lib/frameworks/angular/utils.js +33 -4
  23. package/lib/frameworks/astro/index.js +5 -2
  24. package/lib/frameworks/astro/utils.js +3 -2
  25. package/lib/frameworks/constants.js +37 -10
  26. package/lib/frameworks/index.js +12 -7
  27. package/lib/frameworks/next/index.js +28 -8
  28. package/lib/frameworks/next/utils.js +7 -3
  29. package/lib/frameworks/nuxt/index.js +15 -5
  30. package/lib/frameworks/nuxt2/index.js +5 -4
  31. package/lib/frameworks/sveltekit/index.js +2 -1
  32. package/lib/frameworks/utils.js +13 -9
  33. package/lib/frameworks/vite/index.js +18 -5
  34. package/lib/functionsShellCommandAction.js +3 -3
  35. package/lib/gcp/apphosting.js +89 -0
  36. package/lib/gcp/cloudbuild.js +28 -3
  37. package/lib/gcp/storage.js +11 -5
  38. package/lib/hosting/api.js +19 -1
  39. package/lib/hosting/runTags.js +2 -1
  40. package/lib/init/features/{frameworks → apphosting}/constants.js +1 -2
  41. package/lib/init/features/apphosting/index.js +147 -0
  42. package/lib/init/features/apphosting/repo.js +225 -0
  43. package/lib/init/features/hosting/index.js +1 -1
  44. package/lib/init/features/index.js +3 -3
  45. package/lib/init/index.js +0 -4
  46. package/lib/localFunction.js +77 -14
  47. package/lib/utils.js +50 -1
  48. package/package.json +10 -8
  49. package/templates/popup.html +64 -0
  50. package/lib/commands/ext-dev-publish.js +0 -32
  51. package/lib/gcp/frameworks.js +0 -40
  52. package/lib/init/features/frameworks/index.js +0 -120
  53. package/lib/init/features/frameworks/repo.js +0 -132
@@ -4,7 +4,6 @@ exports.actionFunction = void 0;
4
4
  const clc = require("colorette");
5
5
  const repl = require("repl");
6
6
  const _ = require("lodash");
7
- const request = require("request");
8
7
  const util = require("util");
9
8
  const shell = require("./emulator/functionsEmulatorShell");
10
9
  const commandUtils = require("./emulator/commandUtils");
@@ -16,6 +15,7 @@ const types_1 = require("./emulator/types");
16
15
  const hubClient_1 = require("./emulator/hubClient");
17
16
  const portUtils_1 = require("./emulator/portUtils");
18
17
  const constants_1 = require("./emulator/constants");
18
+ const localFunction_2 = require("./localFunction");
19
19
  const projectUtils_1 = require("./projectUtils");
20
20
  const serveFunctions = new functions_1.FunctionsServer();
21
21
  const actionFunction = async (options) => {
@@ -88,8 +88,8 @@ const actionFunction = async (options) => {
88
88
  }
89
89
  utils.logLabeledWarning("functions", `The following emulators are not running, calls to these services will affect production: ${clc.bold(otherEmulators.join(", "))}`);
90
90
  const writer = (output) => {
91
- if (output instanceof request.Request) {
92
- return "Sent request to function.";
91
+ if (output === localFunction_2.HTTPS_SENTINEL) {
92
+ return localFunction_2.HTTPS_SENTINEL;
93
93
  }
94
94
  return util.inspect(output);
95
95
  };
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureApiEnabled = exports.listLocations = exports.updateTraffic = exports.listRollouts = exports.createRollout = exports.createBuild = exports.getBuild = exports.deleteBackend = exports.listBackends = exports.getBackend = exports.createBackend = exports.API_VERSION = exports.API_HOST = void 0;
4
+ const proto = require("../gcp/proto");
5
+ const apiv2_1 = require("../apiv2");
6
+ const projectUtils_1 = require("../projectUtils");
7
+ const api_1 = require("../api");
8
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
9
+ exports.API_HOST = new URL(api_1.apphostingOrigin).host;
10
+ exports.API_VERSION = "v1alpha";
11
+ const client = new apiv2_1.Client({
12
+ urlPrefix: api_1.apphostingOrigin,
13
+ auth: true,
14
+ apiVersion: exports.API_VERSION,
15
+ });
16
+ async function createBackend(projectId, location, backendReqBoby, backendId) {
17
+ const res = await client.post(`projects/${projectId}/locations/${location}/backends`, backendReqBoby, { queryParams: { backendId } });
18
+ return res.body;
19
+ }
20
+ exports.createBackend = createBackend;
21
+ async function getBackend(projectId, location, backendId) {
22
+ const name = `projects/${projectId}/locations/${location}/backends/${backendId}`;
23
+ const res = await client.get(name);
24
+ return res.body;
25
+ }
26
+ exports.getBackend = getBackend;
27
+ async function listBackends(projectId, location) {
28
+ const name = `projects/${projectId}/locations/${location}/backends`;
29
+ const res = await client.get(name);
30
+ return res.body;
31
+ }
32
+ exports.listBackends = listBackends;
33
+ async function deleteBackend(projectId, location, backendId) {
34
+ const name = `projects/${projectId}/locations/${location}/backends/${backendId}`;
35
+ const res = await client.delete(name);
36
+ return res.body;
37
+ }
38
+ exports.deleteBackend = deleteBackend;
39
+ async function getBuild(projectId, location, backendId, buildId) {
40
+ const name = `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`;
41
+ const res = await client.get(name);
42
+ return res.body;
43
+ }
44
+ exports.getBuild = getBuild;
45
+ async function createBuild(projectId, location, backendId, buildId, buildInput) {
46
+ const res = await client.post(`projects/${projectId}/locations/${location}/backends/${backendId}/builds`, buildInput, { queryParams: { buildId } });
47
+ return res.body;
48
+ }
49
+ exports.createBuild = createBuild;
50
+ async function createRollout(projectId, location, backendId, rolloutId, rollout) {
51
+ const res = await client.post(`projects/${projectId}/locations/${location}/backends/${backendId}/rollouts`, rollout, { queryParams: { rolloutId } });
52
+ return res.body;
53
+ }
54
+ exports.createRollout = createRollout;
55
+ async function listRollouts(projectId, location, backendId) {
56
+ const res = await client.get(`projects/${projectId}/locations/${location}/backends/${backendId}/rollouts`);
57
+ return res.body.rollouts;
58
+ }
59
+ exports.listRollouts = listRollouts;
60
+ async function updateTraffic(projectId, location, backendId, traffic) {
61
+ const fieldMasks = proto.fieldMasks(traffic);
62
+ const queryParams = {
63
+ updateMask: fieldMasks.join(","),
64
+ };
65
+ const name = `projects/${projectId}/locations/${location}/backends/${backendId}/traffic`;
66
+ const res = await client.patch(name, { ...traffic, name }, {
67
+ queryParams,
68
+ });
69
+ return res.body;
70
+ }
71
+ exports.updateTraffic = updateTraffic;
72
+ async function listLocations(projectId) {
73
+ let pageToken;
74
+ let locations = [];
75
+ do {
76
+ const response = await client.get(`projects/${projectId}/locations`);
77
+ if (response.body.locations && response.body.locations.length > 0) {
78
+ locations = locations.concat(response.body.locations);
79
+ }
80
+ pageToken = response.body.nextPageToken;
81
+ } while (pageToken);
82
+ return locations;
83
+ }
84
+ exports.listLocations = listLocations;
85
+ async function ensureApiEnabled(options) {
86
+ const projectId = (0, projectUtils_1.needProjectId)(options);
87
+ return await (0, ensureApiEnabled_1.ensure)(projectId, exports.API_HOST, "frameworks", true);
88
+ }
89
+ exports.ensureApiEnabled = ensureApiEnabled;
@@ -1,15 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteRepository = exports.getRepository = exports.createRepository = exports.fetchLinkableRepositories = exports.deleteConnection = exports.getConnection = exports.createConnection = void 0;
3
+ exports.serviceAgentEmail = exports.deleteRepository = exports.getRepository = exports.createRepository = exports.fetchLinkableRepositories = exports.deleteConnection = exports.listConnections = exports.getConnection = exports.createConnection = void 0;
4
4
  const apiv2_1 = require("../apiv2");
5
5
  const api_1 = require("../api");
6
+ const PAGE_SIZE_MAX = 100;
6
7
  const client = new apiv2_1.Client({
7
8
  urlPrefix: api_1.cloudbuildOrigin,
8
9
  auth: true,
9
10
  apiVersion: "v2",
10
11
  });
11
- async function createConnection(projectId, location, connectionId) {
12
- const res = await client.post(`projects/${projectId}/locations/${location}/connections`, { githubConfig: {} }, { queryParams: { connectionId } });
12
+ async function createConnection(projectId, location, connectionId, githubConfig = {}) {
13
+ const res = await client.post(`projects/${projectId}/locations/${location}/connections`, { githubConfig }, { queryParams: { connectionId } });
13
14
  return res.body;
14
15
  }
15
16
  exports.createConnection = createConnection;
@@ -19,6 +20,26 @@ async function getConnection(projectId, location, connectionId) {
19
20
  return res.body;
20
21
  }
21
22
  exports.getConnection = getConnection;
23
+ async function listConnections(projectId, location) {
24
+ const conns = [];
25
+ const getNextPage = async (pageToken = "") => {
26
+ const res = await client.get(`/projects/${projectId}/locations/${location}/connections`, {
27
+ queryParams: {
28
+ pageSize: PAGE_SIZE_MAX,
29
+ pageToken,
30
+ },
31
+ });
32
+ if (Array.isArray(res.body.connections)) {
33
+ conns.push(...res.body.connections);
34
+ }
35
+ if (res.body.nextPageToken) {
36
+ await getNextPage(res.body.nextPageToken);
37
+ }
38
+ };
39
+ await getNextPage();
40
+ return conns;
41
+ }
42
+ exports.listConnections = listConnections;
22
43
  async function deleteConnection(projectId, location, connectionId) {
23
44
  const name = `projects/${projectId}/locations/${location}/connections/${connectionId}`;
24
45
  const res = await client.delete(name);
@@ -48,3 +69,7 @@ async function deleteRepository(projectId, location, connectionId, repositoryId)
48
69
  return res.body;
49
70
  }
50
71
  exports.deleteRepository = deleteRepository;
72
+ function serviceAgentEmail(projectNumber) {
73
+ return `service-${projectNumber}@gcp-sa-cloudbuild.iam.gserviceaccount.com`;
74
+ }
75
+ exports.serviceAgentEmail = serviceAgentEmail;
@@ -2,22 +2,28 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getServiceAccount = exports.listBuckets = exports.getBucket = exports.deleteObject = exports.uploadObject = exports.upload = exports.getDefaultBucket = void 0;
4
4
  const path = require("path");
5
+ const clc = require("colorette");
5
6
  const api_1 = require("../api");
6
7
  const apiv2_1 = require("../apiv2");
7
8
  const error_1 = require("../error");
8
9
  const logger_1 = require("../logger");
9
- const projects_1 = require("../management/projects");
10
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
10
11
  async function getDefaultBucket(projectId) {
12
+ await (0, ensureApiEnabled_1.ensure)(projectId, "firebasestorage.googleapis.com", "storage", false);
11
13
  try {
12
- const metadata = await (0, projects_1.getFirebaseProject)(projectId);
13
- if (!metadata.resources?.storageBucket) {
14
+ const localAPIClient = new apiv2_1.Client({ urlPrefix: api_1.firebaseStorageOrigin, apiVersion: "v1alpha" });
15
+ const response = await localAPIClient.get(`/projects/${projectId}/defaultBucket`);
16
+ if (!response.body?.bucket.name) {
14
17
  logger_1.logger.debug("Default storage bucket is undefined.");
15
18
  throw new error_1.FirebaseError("Your project is being set up. Please wait a minute before deploying again.");
16
19
  }
17
- return metadata.resources.storageBucket;
20
+ return response.body.bucket.name.split("/").pop();
18
21
  }
19
22
  catch (err) {
20
- logger_1.logger.info("\n\nThere was an issue deploying your functions. Verify that your project has a Google App Engine instance setup at https://console.cloud.google.com/appengine and try again. If this issue persists, please contact support.");
23
+ if (err?.status === 404) {
24
+ throw new error_1.FirebaseError(`Firebase Storage has not been set up on project '${clc.bold(projectId)}'. Go to https://console.firebase.google.com/project/${projectId}/storage and click 'Get Started' to set up Firebase Storage.`);
25
+ }
26
+ logger_1.logger.info("\n\nUnexpected error when fetching default storage bucket.");
21
27
  throw err;
22
28
  }
23
29
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAllSiteDomains = exports.getSiteDomains = exports.cleanAuthState = exports.getCleanDomains = exports.removeAuthDomain = exports.addAuthDomains = exports.deleteSite = exports.updateSite = exports.createSite = exports.getSite = exports.listSites = exports.createRelease = exports.cloneVersion = exports.listVersions = exports.updateVersion = exports.createVersion = exports.deleteChannel = exports.updateChannelTtl = exports.createChannel = exports.listChannels = exports.getChannel = exports.normalizeName = exports.SiteType = void 0;
3
+ exports.getDeploymentDomain = exports.getAllSiteDomains = exports.getSiteDomains = exports.cleanAuthState = exports.getCleanDomains = exports.removeAuthDomain = exports.addAuthDomains = exports.deleteSite = exports.updateSite = exports.createSite = exports.getSite = exports.listSites = exports.createRelease = exports.cloneVersion = exports.listVersions = exports.updateVersion = exports.createVersion = exports.deleteChannel = exports.updateChannelTtl = exports.createChannel = exports.listChannels = exports.getChannel = exports.normalizeName = exports.SiteType = void 0;
4
4
  const error_1 = require("../error");
5
5
  const api_1 = require("../api");
6
6
  const apiv2_1 = require("../apiv2");
@@ -8,6 +8,7 @@ const operationPoller = require("../operation-poller");
8
8
  const expireUtils_1 = require("../hosting/expireUtils");
9
9
  const auth_1 = require("../gcp/auth");
10
10
  const proto = require("../gcp/proto");
11
+ const utils_1 = require("../utils");
11
12
  const ONE_WEEK_MS = 604800000;
12
13
  var ReleaseType;
13
14
  (function (ReleaseType) {
@@ -170,6 +171,7 @@ async function getSite(project, site) {
170
171
  if (e instanceof error_1.FirebaseError && e.status === 404) {
171
172
  throw new error_1.FirebaseError(`could not find site "${site}" for project "${project}"`, {
172
173
  original: e,
174
+ status: e.status,
173
175
  });
174
176
  }
175
177
  throw e;
@@ -286,3 +288,19 @@ async function getAllSiteDomains(projectId, siteId) {
286
288
  return Array.from(allSiteDomains);
287
289
  }
288
290
  exports.getAllSiteDomains = getAllSiteDomains;
291
+ async function getDeploymentDomain(projectId, siteId, hostingChannel) {
292
+ if (hostingChannel) {
293
+ const channel = await getChannel(projectId, siteId, hostingChannel);
294
+ return channel && (0, utils_1.getHostnameFromUrl)(channel?.url);
295
+ }
296
+ const site = await getSite(projectId, siteId).catch((e) => {
297
+ if (e instanceof error_1.FirebaseError &&
298
+ e.original instanceof error_1.FirebaseError &&
299
+ e.original.status === 404) {
300
+ return null;
301
+ }
302
+ throw e;
303
+ });
304
+ return site && (0, utils_1.getHostnameFromUrl)(site?.defaultUrl);
305
+ }
306
+ exports.getDeploymentDomain = getDeploymentDomain;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ensureLatestRevisionTagged = exports.setRewriteTags = exports.setGarbageCollectionThreshold = exports.gcTagsForServices = exports.TODO_TAG_NAME = void 0;
4
+ const node_path_1 = require("node:path");
4
5
  const run = require("../gcp/run");
5
6
  const api = require("./api");
6
7
  const error_1 = require("../error");
@@ -9,7 +10,7 @@ exports.TODO_TAG_NAME = "this is an invalid tag name so it cannot be real";
9
10
  async function gcTagsForServices(project, services) {
10
11
  const validTagsByServiceByRegion = {};
11
12
  const sites = await api.listSites(project);
12
- const allVersionsNested = await Promise.all(sites.map((site) => api.listVersions(site.name)));
13
+ const allVersionsNested = await Promise.all(sites.map((site) => api.listVersions(node_path_1.posix.basename(site.name))));
13
14
  const activeVersions = [...(0, functional_1.flattenArray)(allVersionsNested)].filter((version) => {
14
15
  return version.status === "CREATED" || version.status === "FINALIZED";
15
16
  });
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ALLOWED_DEPLOY_METHODS = exports.DEFAULT_DEPLOY_METHOD = exports.ALLOWED_REGIONS = exports.DEFAULT_REGION = void 0;
3
+ exports.ALLOWED_DEPLOY_METHODS = exports.DEFAULT_DEPLOY_METHOD = exports.DEFAULT_REGION = void 0;
4
4
  exports.DEFAULT_REGION = "us-central1";
5
- exports.ALLOWED_REGIONS = [{ name: "us-central1 (Iowa)", value: "us-central1" }];
6
5
  exports.DEFAULT_DEPLOY_METHOD = "github";
7
6
  exports.ALLOWED_DEPLOY_METHODS = [{ name: "Deploy using github", value: "github" }];
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onboardRollout = exports.createBackend = exports.onboardBackend = exports.doSetup = void 0;
4
+ const clc = require("colorette");
5
+ const repo = require("./repo");
6
+ const poller = require("../../../operation-poller");
7
+ const apphosting = require("../../../gcp/apphosting");
8
+ const utils_1 = require("../../../utils");
9
+ const api_1 = require("../../../api");
10
+ const apphosting_1 = require("../../../gcp/apphosting");
11
+ const error_1 = require("../../../error");
12
+ const prompt_1 = require("../../../prompt");
13
+ const constants_1 = require("./constants");
14
+ const ensureApiEnabled_1 = require("../../../ensureApiEnabled");
15
+ const apphostingPollerOptions = {
16
+ apiOrigin: api_1.apphostingOrigin,
17
+ apiVersion: apphosting_1.API_VERSION,
18
+ masterTimeout: 25 * 60 * 1000,
19
+ maxBackoff: 10000,
20
+ };
21
+ async function doSetup(setup, projectId) {
22
+ await Promise.all([
23
+ (0, ensureApiEnabled_1.ensure)(projectId, "cloudbuild.googleapis.com", "apphosting", true),
24
+ (0, ensureApiEnabled_1.ensure)(projectId, "secretmanager.googleapis.com", "apphosting", true),
25
+ (0, ensureApiEnabled_1.ensure)(projectId, "run.googleapis.com", "apphosting", true),
26
+ (0, ensureApiEnabled_1.ensure)(projectId, "artifactregistry.googleapis.com", "apphosting", true),
27
+ ]);
28
+ const allowedLocations = (await apphosting.listLocations(projectId)).map((loc) => loc.locationId);
29
+ if (setup.location) {
30
+ if (!allowedLocations.includes(setup.location)) {
31
+ throw new error_1.FirebaseError(`Invalid location ${setup.location}. Valid choices are ${allowedLocations.join(", ")}`);
32
+ }
33
+ }
34
+ (0, utils_1.logBullet)("First we need a few details to create your backend.");
35
+ const location = setup.location || (await promptLocation(projectId, allowedLocations));
36
+ (0, utils_1.logSuccess)(`Region set to ${location}.\n`);
37
+ let backendId;
38
+ while (true) {
39
+ backendId = await (0, prompt_1.promptOnce)({
40
+ name: "backendId",
41
+ type: "input",
42
+ default: "my-web-app",
43
+ message: "Create a name for your backend [1-30 characters]",
44
+ });
45
+ try {
46
+ await apphosting.getBackend(projectId, location, backendId);
47
+ }
48
+ catch (err) {
49
+ if (err.status === 404) {
50
+ break;
51
+ }
52
+ throw new error_1.FirebaseError(`Failed to check if backend with id ${backendId} already exists in ${location}`, { original: err });
53
+ }
54
+ (0, utils_1.logWarning)(`Backend with id ${backendId} already exists in ${location}`);
55
+ }
56
+ const backend = await onboardBackend(projectId, location, backendId);
57
+ const confirmRollout = await (0, prompt_1.promptOnce)({
58
+ type: "confirm",
59
+ name: "rollout",
60
+ default: true,
61
+ message: "Do you want to deploy now?",
62
+ });
63
+ if (!confirmRollout) {
64
+ (0, utils_1.logSuccess)(`Successfully created backend:\n\t${backend.name}`);
65
+ (0, utils_1.logSuccess)(`Your site will be deployed at:\n\thttps://${backend.uri}`);
66
+ return;
67
+ }
68
+ const branch = await (0, prompt_1.promptOnce)({
69
+ name: "branch",
70
+ type: "input",
71
+ default: "main",
72
+ message: "Which branch do you want to deploy?",
73
+ });
74
+ const { build } = await onboardRollout(projectId, location, backendId, {
75
+ source: {
76
+ codebase: {
77
+ branch,
78
+ },
79
+ },
80
+ });
81
+ if (build.state !== "READY") {
82
+ throw new error_1.FirebaseError(`Failed to build your app. Please inspect the build logs at ${build.buildLogsUri}.`, { children: [build.error] });
83
+ }
84
+ (0, utils_1.logSuccess)(`Successfully created backend:\n\t${backend.name}`);
85
+ (0, utils_1.logSuccess)(`Your site is now deployed at:\n\thttps://${backend.uri}`);
86
+ (0, utils_1.logSuccess)(`View the rollout status by running:\n\tfirebase apphosting:backends:get ${backendId} --project ${projectId}`);
87
+ }
88
+ exports.doSetup = doSetup;
89
+ async function promptLocation(projectId, locations) {
90
+ return (await (0, prompt_1.promptOnce)({
91
+ name: "region",
92
+ type: "list",
93
+ default: constants_1.DEFAULT_REGION,
94
+ message: "Please select a region " +
95
+ `(${clc.yellow("info")}: Your region determines where your backend is located):\n`,
96
+ choices: locations.map((loc) => ({ value: loc })),
97
+ }));
98
+ }
99
+ function toBackend(cloudBuildConnRepo) {
100
+ return {
101
+ servingLocality: "GLOBAL_ACCESS",
102
+ codebase: {
103
+ repository: `${cloudBuildConnRepo.name}`,
104
+ rootDirectory: "/",
105
+ },
106
+ labels: {},
107
+ };
108
+ }
109
+ async function onboardBackend(projectId, location, backendId) {
110
+ const cloudBuildConnRepo = await repo.linkGitHubRepository(projectId, location);
111
+ const backendDetails = toBackend(cloudBuildConnRepo);
112
+ return await createBackend(projectId, location, backendDetails, backendId);
113
+ }
114
+ exports.onboardBackend = onboardBackend;
115
+ async function createBackend(projectId, location, backendReqBoby, backendId) {
116
+ const op = await apphosting.createBackend(projectId, location, backendReqBoby, backendId);
117
+ const backend = await poller.pollOperation({
118
+ ...apphostingPollerOptions,
119
+ pollerName: `create-${projectId}-${location}-${backendId}`,
120
+ operationResourceName: op.name,
121
+ });
122
+ return backend;
123
+ }
124
+ exports.createBackend = createBackend;
125
+ async function onboardRollout(projectId, location, backendId, buildInput) {
126
+ (0, utils_1.logBullet)("Starting a new rollout... this may take a few minutes.");
127
+ const buildId = (0, utils_1.generateId)();
128
+ const buildOp = await apphosting.createBuild(projectId, location, backendId, buildId, buildInput);
129
+ const rolloutId = (0, utils_1.generateId)();
130
+ const rolloutOp = await apphosting.createRollout(projectId, location, backendId, rolloutId, {
131
+ build: `projects/${projectId}/locations/${location}/backends/${backendId}/builds/${buildId}`,
132
+ });
133
+ const rolloutPoll = poller.pollOperation({
134
+ ...apphostingPollerOptions,
135
+ pollerName: `create-${projectId}-${location}-backend-${backendId}-rollout-${rolloutId}`,
136
+ operationResourceName: rolloutOp.name,
137
+ });
138
+ const buildPoll = poller.pollOperation({
139
+ ...apphostingPollerOptions,
140
+ pollerName: `create-${projectId}-${location}-backend-${backendId}-build-${buildId}`,
141
+ operationResourceName: buildOp.name,
142
+ });
143
+ const [rollout, build] = await Promise.all([rolloutPoll, buildPoll]);
144
+ (0, utils_1.logSuccess)("Rollout completed.");
145
+ return { rollout, build };
146
+ }
147
+ exports.onboardRollout = onboardRollout;
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.linkGitHubRepository = exports.parseConnectionName = void 0;
4
+ const clc = require("colorette");
5
+ const gcb = require("../../../gcp/cloudbuild");
6
+ const rm = require("../../../gcp/resourceManager");
7
+ const poller = require("../../../operation-poller");
8
+ const utils = require("../../../utils");
9
+ const api_1 = require("../../../api");
10
+ const error_1 = require("../../../error");
11
+ const prompt_1 = require("../../../prompt");
12
+ const getProjectNumber_1 = require("../../../getProjectNumber");
13
+ const APPHOSTING_CONN_PATTERN = /.+\/apphosting-github-conn-.+$/;
14
+ const APPHOSTING_OAUTH_CONN_NAME = "apphosting-github-oauth";
15
+ const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/connections\/(?<id>[^\/]+)$/;
16
+ function parseConnectionName(name) {
17
+ const match = name.match(CONNECTION_NAME_REGEX);
18
+ if (!match || typeof match.groups === undefined) {
19
+ return;
20
+ }
21
+ const { projectId, location, id } = match.groups;
22
+ return {
23
+ projectId,
24
+ location,
25
+ id,
26
+ };
27
+ }
28
+ exports.parseConnectionName = parseConnectionName;
29
+ const gcbPollerOptions = {
30
+ apiOrigin: api_1.cloudbuildOrigin,
31
+ apiVersion: "v2",
32
+ masterTimeout: 25 * 60 * 1000,
33
+ maxBackoff: 10000,
34
+ };
35
+ function extractRepoSlugFromUri(remoteUri) {
36
+ const match = /github.com\/(.+).git/.exec(remoteUri);
37
+ if (!match) {
38
+ return undefined;
39
+ }
40
+ return match[1];
41
+ }
42
+ function generateRepositoryId(remoteUri) {
43
+ return extractRepoSlugFromUri(remoteUri)?.replaceAll("/", "-");
44
+ }
45
+ function generateConnectionId() {
46
+ const randomHash = Math.random().toString(36).slice(6);
47
+ return `apphosting-github-conn-${randomHash}`;
48
+ }
49
+ async function linkGitHubRepository(projectId, location) {
50
+ utils.logBullet(clc.bold(`${clc.yellow("===")} Set up a GitHub connection`));
51
+ const existingConns = await listAppHostingConnections(projectId);
52
+ if (existingConns.length < 1) {
53
+ const grantSuccess = await promptSecretManagerAdminGrant(projectId);
54
+ if (!grantSuccess) {
55
+ throw new error_1.FirebaseError("Insufficient IAM permissions to create a new connection to GitHub");
56
+ }
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
+ const connectionId = generateConnectionId();
62
+ const conn = await createConnection(projectId, location, connectionId, {
63
+ authorizerCredential: oauthConn.githubConfig?.authorizerCredential,
64
+ });
65
+ let refreshedConn = conn;
66
+ while (refreshedConn.installationState.stage !== "COMPLETE") {
67
+ refreshedConn = await promptAppInstall(conn);
68
+ }
69
+ existingConns.push(refreshedConn);
70
+ }
71
+ 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
+ });
78
+ const selection = await promptRepositoryUri(projectId, existingConns);
79
+ remoteUri = selection.remoteUri;
80
+ connection = selection.connection;
81
+ }
82
+ const { id: connectionId } = parseConnectionName(connection.name);
83
+ await getOrCreateConnection(projectId, location, connectionId, {
84
+ authorizerCredential: connection.githubConfig?.authorizerCredential,
85
+ appInstallationId: connection.githubConfig?.appInstallationId,
86
+ });
87
+ const repo = await getOrCreateRepository(projectId, location, connectionId, remoteUri);
88
+ utils.logSuccess(`Successfully linked GitHub repository at remote URI`);
89
+ utils.logSuccess(`\t${remoteUri}`);
90
+ return repo;
91
+ }
92
+ exports.linkGitHubRepository = linkGitHubRepository;
93
+ 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 remoteUri = await (0, prompt_1.promptOnce)({
113
+ type: "list",
114
+ message: "Which of the following repositories would you like to deploy?",
115
+ choices,
116
+ });
117
+ return { remoteUri, connection: remoteUriToConnection[remoteUri] };
118
+ }
119
+ async function promptSecretManagerAdminGrant(projectId) {
120
+ const projectNumber = await (0, getProjectNumber_1.getProjectNumber)({ projectId });
121
+ const cbsaEmail = gcb.serviceAgentEmail(projectNumber);
122
+ const alreadyGranted = await rm.serviceAccountHasRoles(projectId, cbsaEmail, ["roles/secretmanager.admin"], true);
123
+ if (alreadyGranted) {
124
+ return true;
125
+ }
126
+ utils.logBullet("To create a new GitHub connection, Secret Manager Admin role (roles/secretmanager.admin) is required on the Cloud Build Service Agent.");
127
+ const grant = await (0, prompt_1.promptOnce)({
128
+ type: "confirm",
129
+ message: "Grant the required role to the Cloud Build Service Agent?",
130
+ });
131
+ if (!grant) {
132
+ utils.logBullet("You, or your project administrator, should run the following command to grant the required role:\n\n" +
133
+ "You, or your project adminstrator, can run the following command to grant the required role manually:\n\n" +
134
+ `\tgcloud projects add-iam-policy-binding ${projectId} \\\n` +
135
+ `\t --member="serviceAccount:${cbsaEmail} \\\n` +
136
+ `\t --role="roles/secretmanager.admin\n`);
137
+ return false;
138
+ }
139
+ await rm.addServiceAccountToRoles(projectId, cbsaEmail, ["roles/secretmanager.admin"], true);
140
+ utils.logSuccess("Successfully granted the required role to the Cloud Build Service Agent!");
141
+ return true;
142
+ }
143
+ async function promptConnectionAuth(conn) {
144
+ utils.logBullet("You must authorize the Cloud Build GitHub app.");
145
+ utils.logBullet("Sign in to GitHub and authorize Cloud Build GitHub app:");
146
+ const { url, cleanup } = await utils.openInBrowserPopup(conn.installationState.actionUri, "Authorize the GitHub app");
147
+ utils.logBullet(`\t${url}`);
148
+ await (0, prompt_1.promptOnce)({
149
+ type: "input",
150
+ message: "Press Enter once you have authorized the app",
151
+ });
152
+ cleanup();
153
+ const { projectId, location, id } = parseConnectionName(conn.name);
154
+ return await gcb.getConnection(projectId, location, id);
155
+ }
156
+ async function promptAppInstall(conn) {
157
+ utils.logBullet("Install the Cloud Build GitHub app to enable access to GitHub repositories");
158
+ const targetUri = conn.installationState.actionUri.replace("install_v2", "direct_install_v2");
159
+ utils.logBullet(targetUri);
160
+ await utils.openInBrowser(targetUri);
161
+ await (0, prompt_1.promptOnce)({
162
+ type: "input",
163
+ message: "Press Enter once you have installed or configured the Cloud Build GitHub app to access your GitHub repo.",
164
+ });
165
+ const { projectId, location, id } = parseConnectionName(conn.name);
166
+ return await gcb.getConnection(projectId, location, id);
167
+ }
168
+ async function createConnection(projectId, location, connectionId, githubConfig) {
169
+ const op = await gcb.createConnection(projectId, location, connectionId, githubConfig);
170
+ const conn = await poller.pollOperation({
171
+ ...gcbPollerOptions,
172
+ pollerName: `create-${location}-${connectionId}`,
173
+ operationResourceName: op.name,
174
+ });
175
+ return conn;
176
+ }
177
+ exports.createConnection = createConnection;
178
+ async function getOrCreateConnection(projectId, location, connectionId, githubConfig) {
179
+ let conn;
180
+ try {
181
+ conn = await gcb.getConnection(projectId, location, connectionId);
182
+ }
183
+ catch (err) {
184
+ if (err.status === 404) {
185
+ conn = await createConnection(projectId, location, connectionId, githubConfig);
186
+ }
187
+ else {
188
+ throw err;
189
+ }
190
+ }
191
+ return conn;
192
+ }
193
+ exports.getOrCreateConnection = getOrCreateConnection;
194
+ async function getOrCreateRepository(projectId, location, connectionId, remoteUri) {
195
+ const repositoryId = generateRepositoryId(remoteUri);
196
+ if (!repositoryId) {
197
+ throw new error_1.FirebaseError(`Failed to generate repositoryId for URI "${remoteUri}".`);
198
+ }
199
+ let repo;
200
+ try {
201
+ repo = await gcb.getRepository(projectId, location, connectionId, repositoryId);
202
+ }
203
+ catch (err) {
204
+ if (err.status === 404) {
205
+ const op = await gcb.createRepository(projectId, location, connectionId, repositoryId, remoteUri);
206
+ repo = await poller.pollOperation({
207
+ ...gcbPollerOptions,
208
+ pollerName: `create-${location}-${connectionId}-${repositoryId}`,
209
+ operationResourceName: op.name,
210
+ });
211
+ }
212
+ else {
213
+ throw err;
214
+ }
215
+ }
216
+ return repo;
217
+ }
218
+ exports.getOrCreateRepository = getOrCreateRepository;
219
+ async function listAppHostingConnections(projectId) {
220
+ const conns = await gcb.listConnections(projectId, "-");
221
+ return conns.filter((conn) => APPHOSTING_CONN_PATTERN.test(conn.name) &&
222
+ conn.installationState.stage === "COMPLETE" &&
223
+ !conn.disabled);
224
+ }
225
+ exports.listAppHostingConnections = listAppHostingConnections;
@@ -123,7 +123,7 @@ async function doSetup(setup, config, options) {
123
123
  type: "list",
124
124
  message: "In which region would you like to host server-side content, if applicable?",
125
125
  default: constants_1.DEFAULT_REGION,
126
- choices: constants_1.ALLOWED_SSR_REGIONS,
126
+ choices: constants_1.ALLOWED_SSR_REGIONS.filter((region) => region.recommended),
127
127
  }, setup.hosting);
128
128
  setup.config.hosting = {
129
129
  source: setup.hosting.source,