firebase-tools-with-isolate 13.6.4 → 13.7.3

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 (80) hide show
  1. package/README.md +4 -6
  2. package/lib/api.js +1 -1
  3. package/lib/apphosting/app.js +88 -0
  4. package/lib/apphosting/config.js +97 -0
  5. package/lib/apphosting/githubConnections.js +265 -0
  6. package/lib/{init/features/apphosting → apphosting}/index.js +52 -26
  7. package/lib/{init/features/apphosting → apphosting}/repo.js +10 -10
  8. package/lib/apphosting/secrets/dialogs.js +170 -0
  9. package/lib/apphosting/secrets/index.js +97 -0
  10. package/lib/commands/apphosting-backends-create.js +7 -3
  11. package/lib/commands/apphosting-backends-delete.js +5 -4
  12. package/lib/commands/apphosting-backends-get.js +8 -8
  13. package/lib/commands/apphosting-backends-list.js +2 -2
  14. package/lib/commands/apphosting-secrets-access.js +24 -0
  15. package/lib/commands/apphosting-secrets-describe.js +29 -0
  16. package/lib/commands/apphosting-secrets-grantaccess.js +45 -0
  17. package/lib/commands/apphosting-secrets-set.js +56 -0
  18. package/lib/commands/firestore-databases-create.js +1 -0
  19. package/lib/commands/firestore-databases-restore.js +1 -0
  20. package/lib/commands/functions-secrets-access.js +2 -2
  21. package/lib/commands/functions-secrets-describe.js +14 -0
  22. package/lib/commands/functions-secrets-destroy.js +2 -2
  23. package/lib/commands/functions-secrets-get.js +3 -17
  24. package/lib/commands/functions-secrets-prune.js +2 -1
  25. package/lib/commands/functions-secrets-set.js +3 -19
  26. package/lib/commands/index.js +14 -6
  27. package/lib/deploy/firestore/prepare.js +4 -2
  28. package/lib/deploy/functions/checkIam.js +3 -6
  29. package/lib/deploy/functions/containerCleaner.js +1 -15
  30. package/lib/deploy/functions/deploy.js +2 -2
  31. package/lib/deploy/functions/params.js +2 -2
  32. package/lib/deploy/functions/prepare.js +13 -3
  33. package/lib/deploy/functions/pricing.js +2 -2
  34. package/lib/deploy/functions/prompts.js +39 -7
  35. package/lib/deploy/functions/release/fabricator.js +5 -5
  36. package/lib/deploy/functions/release/index.js +17 -2
  37. package/lib/deploy/functions/release/planner.js +11 -3
  38. package/lib/deploy/functions/runtimes/discovery/index.js +3 -3
  39. package/lib/deploy/functions/runtimes/index.js +6 -43
  40. package/lib/deploy/functions/runtimes/node/index.js +3 -2
  41. package/lib/deploy/functions/runtimes/node/parseRuntimeAndValidateSDK.js +15 -34
  42. package/lib/deploy/functions/runtimes/python/index.js +10 -7
  43. package/lib/deploy/functions/runtimes/supported/index.js +80 -0
  44. package/lib/deploy/functions/runtimes/supported/types.js +74 -0
  45. package/lib/deploy/functions/services/index.js +4 -0
  46. package/lib/downloadUtils.js +1 -0
  47. package/lib/emulator/controller.js +5 -1
  48. package/lib/emulator/functionsEmulator.js +2 -2
  49. package/lib/emulator/hub.js +5 -0
  50. package/lib/experiments.js +12 -0
  51. package/lib/extensions/emulator/specHelper.js +7 -6
  52. package/lib/extensions/extensionsApi.js +2 -2
  53. package/lib/extensions/localHelper.js +3 -3
  54. package/lib/firestore/pretty-print.js +5 -0
  55. package/lib/frameworks/astro/index.js +1 -1
  56. package/lib/frameworks/flutter/index.js +2 -2
  57. package/lib/frameworks/next/constants.js +2 -1
  58. package/lib/frameworks/next/index.js +22 -12
  59. package/lib/frameworks/next/utils.js +32 -3
  60. package/lib/functional.js +2 -2
  61. package/lib/functions/events/v2.js +7 -1
  62. package/lib/functions/secrets.js +40 -22
  63. package/lib/gcp/apphosting.js +14 -2
  64. package/lib/gcp/cloudbuild.js +7 -3
  65. package/lib/gcp/cloudfunctions.js +5 -5
  66. package/lib/gcp/cloudfunctionsv2.js +3 -3
  67. package/lib/gcp/cloudscheduler.js +2 -2
  68. package/lib/gcp/computeEngine.js +7 -0
  69. package/lib/gcp/devConnect.js +24 -11
  70. package/lib/gcp/iam.js +9 -1
  71. package/lib/gcp/secretManager.js +54 -6
  72. package/lib/gcp/serviceusage.js +24 -5
  73. package/lib/init/features/functions/python.js +4 -3
  74. package/lib/init/features/hosting/github.js +4 -5
  75. package/lib/init/features/index.js +1 -1
  76. package/lib/utils.js +23 -6
  77. package/package.json +4 -4
  78. package/schema/firebase-config.json +12 -2
  79. package/templates/init/functions/typescript/_eslintrc +1 -0
  80. /package/lib/{init/features/apphosting → apphosting}/constants.js +0 -0
package/README.md CHANGED
@@ -16,17 +16,15 @@ clarity.
16
16
 
17
17
  It is probably best to install this as a local dependency on whatever package you want to deploy to Firebase, as opposed to using a global install. This way the forked binary does not interfere with the original one on your system, and you can easily use the fork on one project will still using the original one on others.
18
18
 
19
- ```bash
20
- npm install firebase-tools-with-isolate --save-dev
21
- ```
22
-
23
- Personally I would advise you to [try PNPM](https://pnpm.io/feature-comparison) for monorepo setups.
19
+ It is recommended to use `pnpm` over `npm` or `yarn`. Apart from being fast and
20
+ efficient, PNPM has better support for monorepos, and the the lockfile isolation
21
+ code is solid and works in parallel for multiple packages, [unlike NPM](https://github.com/0x80/isolate-package/README.md#npm)
24
22
 
25
23
  ```bash
26
24
  pnpm add firebase-tools-with-isolate -D
27
25
  ```
28
26
 
29
- At the moment, `isolate-package` only supports generating isolated lockfiles for PNPM and NPM, but if you depend on Yarn you can always choose to deploy to Firebase without a lockfile, similar to other workarounds people have been using.
27
+ Or run the equivalent for NPM or Yarn.
30
28
 
31
29
  > !! Do not forget to remove/uninstall the original `firebase-tools` package from your repository if you have it installed as a local dependency on your project, because otherwise that binary might get precedence over the forked one, and `npx firebase deploy` will execute the wrong one.
32
30
 
package/lib/api.js CHANGED
@@ -62,7 +62,7 @@ const cloudbuildOrigin = () => utils.envOverride("FIREBASE_CLOUDBUILD_URL", "htt
62
62
  exports.cloudbuildOrigin = cloudbuildOrigin;
63
63
  const developerConnectOrigin = () => utils.envOverride("FIREBASE_DEVELOPERCONNECT_URL", "https://developerconnect.googleapis.com");
64
64
  exports.developerConnectOrigin = developerConnectOrigin;
65
- const developerConnectP4SAOrigin = () => utils.envOverride("FIREBASE_DEVELOPERCONNECT_P4SA_URL", "gcp-sa-developerconnect.iam.gserviceaccount.com");
65
+ const developerConnectP4SAOrigin = () => utils.envOverride("FIREBASE_DEVELOPERCONNECT_P4SA_URL", "gcp-sa-devconnect.iam.gserviceaccount.com");
66
66
  exports.developerConnectP4SAOrigin = developerConnectP4SAOrigin;
67
67
  const cloudschedulerOrigin = () => utils.envOverride("FIREBASE_CLOUDSCHEDULER_URL", "https://cloudscheduler.googleapis.com");
68
68
  exports.cloudschedulerOrigin = cloudschedulerOrigin;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ const fuzzy = require("fuzzy");
3
+ const inquirer = require("inquirer");
4
+ const apps_1 = require("../management/apps");
5
+ const prompt_1 = require("../prompt");
6
+ const error_1 = require("../error");
7
+ const CREATE_NEW_FIREBASE_WEB_APP = "CREATE_NEW_WEB_APP";
8
+ const CONTINUE_WITHOUT_SELECTING_FIREBASE_WEB_APP = "CONTINUE_WITHOUT_SELECTING_FIREBASE_WEB_APP";
9
+ const webApps = {
10
+ CREATE_NEW_FIREBASE_WEB_APP,
11
+ CONTINUE_WITHOUT_SELECTING_FIREBASE_WEB_APP,
12
+ getOrCreateWebApp,
13
+ promptFirebaseWebApp,
14
+ };
15
+ async function getOrCreateWebApp(projectId, firebaseWebAppName, backendId) {
16
+ const webAppsInProject = await (0, apps_1.listFirebaseApps)(projectId, apps_1.AppPlatform.WEB);
17
+ if (webAppsInProject.length === 0) {
18
+ const { displayName, appId } = await createFirebaseWebApp(projectId, {
19
+ displayName: backendId,
20
+ });
21
+ return { name: displayName, id: appId };
22
+ }
23
+ const existingUserProjectWebApps = new Map(webAppsInProject.map((obj) => [
24
+ obj.displayName ?? obj.appId,
25
+ obj.appId,
26
+ ]));
27
+ if (firebaseWebAppName) {
28
+ if (existingUserProjectWebApps.get(firebaseWebAppName) === undefined) {
29
+ throw new error_1.FirebaseError(`The web app '${firebaseWebAppName}' does not exist in project ${projectId}`);
30
+ }
31
+ return { name: firebaseWebAppName, id: existingUserProjectWebApps.get(firebaseWebAppName) };
32
+ }
33
+ return await webApps.promptFirebaseWebApp(projectId, backendId, existingUserProjectWebApps);
34
+ }
35
+ async function promptFirebaseWebApp(projectId, backendId, existingUserProjectWebApps) {
36
+ const existingWebAppKeys = Array.from(existingUserProjectWebApps.keys());
37
+ const firebaseWebAppName = await (0, prompt_1.promptOnce)({
38
+ type: "autocomplete",
39
+ name: "app",
40
+ message: "Which of the following Firebase web apps would you like to associate your backend with?",
41
+ source: (_, input = "") => {
42
+ return new Promise((resolve) => resolve([
43
+ new inquirer.Separator(),
44
+ {
45
+ name: "Create a new Firebase web app.",
46
+ value: CREATE_NEW_FIREBASE_WEB_APP,
47
+ },
48
+ {
49
+ name: "Continue without a Firebase web app.",
50
+ value: CONTINUE_WITHOUT_SELECTING_FIREBASE_WEB_APP,
51
+ },
52
+ new inquirer.Separator(),
53
+ ...fuzzy.filter(input, existingWebAppKeys).map((result) => {
54
+ return result.original;
55
+ }),
56
+ ]));
57
+ },
58
+ });
59
+ if (firebaseWebAppName === CREATE_NEW_FIREBASE_WEB_APP) {
60
+ const newFirebaseWebApp = await createFirebaseWebApp(projectId, { displayName: backendId });
61
+ return { name: newFirebaseWebApp.displayName, id: newFirebaseWebApp.appId };
62
+ }
63
+ else if (firebaseWebAppName === CONTINUE_WITHOUT_SELECTING_FIREBASE_WEB_APP) {
64
+ return;
65
+ }
66
+ return { name: firebaseWebAppName, id: existingUserProjectWebApps.get(firebaseWebAppName) };
67
+ }
68
+ async function createFirebaseWebApp(projectId, options) {
69
+ try {
70
+ return await (0, apps_1.createWebApp)(projectId, options);
71
+ }
72
+ catch (e) {
73
+ if (isQuotaError(e)) {
74
+ throw new error_1.FirebaseError("Unable to create a new web app, the project has reached the quota for Firebase apps. Navigate to your Firebase console to manage or delete a Firebase app to continue. ", { original: e instanceof Error ? e : undefined });
75
+ }
76
+ throw new error_1.FirebaseError("Unable to create a Firebase web app", {
77
+ original: e instanceof Error ? e : undefined,
78
+ });
79
+ }
80
+ }
81
+ function isQuotaError(error) {
82
+ const original = error.original;
83
+ const code = original?.status ||
84
+ original?.context?.response?.statusCode ||
85
+ original?.context?.body?.error?.code;
86
+ return code === 429;
87
+ }
88
+ module.exports = webApps;
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.maybeAddSecretToYaml = exports.upsertEnv = exports.findEnv = exports.store = exports.load = exports.yamlPath = void 0;
4
+ const path_1 = require("path");
5
+ const fs_1 = require("fs");
6
+ const yaml = require("yaml");
7
+ const fs = require("../fsutils");
8
+ const prompt = require("../prompt");
9
+ const dialogs = require("./secrets/dialogs");
10
+ function yamlPath(cwd) {
11
+ let dir = cwd;
12
+ while (!fs.fileExistsSync((0, path_1.resolve)(dir, "apphosting.yaml"))) {
13
+ if (fs.fileExistsSync((0, path_1.resolve)(dir, "firebase.json"))) {
14
+ return null;
15
+ }
16
+ const parent = (0, path_1.dirname)(dir);
17
+ if (parent === dir) {
18
+ return null;
19
+ }
20
+ dir = parent;
21
+ }
22
+ return (0, path_1.resolve)(dir, "apphosting.yaml");
23
+ }
24
+ exports.yamlPath = yamlPath;
25
+ function load(yamlPath) {
26
+ const raw = fs.readFile(yamlPath);
27
+ return yaml.parseDocument(raw);
28
+ }
29
+ exports.load = load;
30
+ function store(yamlPath, document) {
31
+ (0, fs_1.writeFileSync)(yamlPath, document.toString());
32
+ }
33
+ exports.store = store;
34
+ function findEnv(document, variable) {
35
+ if (!document.has("env")) {
36
+ return undefined;
37
+ }
38
+ const envs = document.get("env");
39
+ for (const env of envs.items) {
40
+ if (env.get("variable") === variable) {
41
+ return env.toJSON();
42
+ }
43
+ }
44
+ return undefined;
45
+ }
46
+ exports.findEnv = findEnv;
47
+ function upsertEnv(document, env) {
48
+ if (!document.has("env")) {
49
+ document.set("env", document.createNode([env]));
50
+ return;
51
+ }
52
+ const envs = document.get("env");
53
+ const envYaml = document.createNode(env);
54
+ for (let i = 0; i < envs.items.length; i++) {
55
+ if (envs.items[i].get("variable") === env.variable) {
56
+ envs.set(i, envYaml);
57
+ return;
58
+ }
59
+ }
60
+ envs.add(envYaml);
61
+ }
62
+ exports.upsertEnv = upsertEnv;
63
+ async function maybeAddSecretToYaml(secretName) {
64
+ const dynamicDispatch = exports;
65
+ let path = dynamicDispatch.yamlPath(process.cwd());
66
+ let projectYaml;
67
+ if (path) {
68
+ projectYaml = dynamicDispatch.load(path);
69
+ }
70
+ else {
71
+ projectYaml = new yaml.Document();
72
+ }
73
+ if (dynamicDispatch.findEnv(projectYaml, secretName)) {
74
+ return;
75
+ }
76
+ const addToYaml = await prompt.confirm({
77
+ message: "Would you like to add this secret to apphosting.yaml?",
78
+ default: true,
79
+ });
80
+ if (!addToYaml) {
81
+ return;
82
+ }
83
+ if (!path) {
84
+ path = await prompt.promptOnce({
85
+ message: "It looks like you don't have an apphosting.yaml yet. Where would you like to store it?",
86
+ default: process.cwd(),
87
+ });
88
+ path = (0, path_1.join)(path, "apphosting.yaml");
89
+ }
90
+ const envName = await dialogs.envVarForSecret(secretName);
91
+ dynamicDispatch.upsertEnv(projectYaml, {
92
+ variable: envName,
93
+ secret: secretName,
94
+ });
95
+ dynamicDispatch.store(path, projectYaml);
96
+ }
97
+ exports.maybeAddSecretToYaml = maybeAddSecretToYaml;
@@ -0,0 +1,265 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchAllRepositories = exports.listAppHostingConnections = exports.getOrCreateRepository = exports.getOrCreateConnection = exports.createConnection = exports.ensureSecretManagerAdminGrant = exports.getOrCreateOauthConnection = exports.linkGitHubRepository = exports.generateRepositoryId = exports.extractRepoSlugFromUri = exports.parseConnectionName = void 0;
4
+ const clc = require("colorette");
5
+ const devConnect = require("../gcp/devConnect");
6
+ const rm = require("../gcp/resourceManager");
7
+ const poller = require("../operation-poller");
8
+ const utils = require("../utils");
9
+ const error_1 = require("../error");
10
+ const prompt_1 = require("../prompt");
11
+ const getProjectNumber_1 = require("../getProjectNumber");
12
+ const api_1 = require("../api");
13
+ const fuzzy = require("fuzzy");
14
+ const inquirer = require("inquirer");
15
+ const APPHOSTING_CONN_PATTERN = /.+\/apphosting-github-conn-.+$/;
16
+ const APPHOSTING_OAUTH_CONN_NAME = "apphosting-github-oauth";
17
+ const CONNECTION_NAME_REGEX = /^projects\/(?<projectId>[^\/]+)\/locations\/(?<location>[^\/]+)\/connections\/(?<id>[^\/]+)$/;
18
+ function parseConnectionName(name) {
19
+ const match = CONNECTION_NAME_REGEX.exec(name);
20
+ if (!match || typeof match.groups === undefined) {
21
+ return;
22
+ }
23
+ const { projectId, location, id } = match.groups;
24
+ return {
25
+ projectId,
26
+ location,
27
+ id,
28
+ };
29
+ }
30
+ exports.parseConnectionName = parseConnectionName;
31
+ const devConnectPollerOptions = {
32
+ apiOrigin: (0, api_1.developerConnectOrigin)(),
33
+ apiVersion: "v1",
34
+ masterTimeout: 25 * 60 * 1000,
35
+ maxBackoff: 10000,
36
+ };
37
+ function extractRepoSlugFromUri(cloneUri) {
38
+ const match = /github.com\/(.+).git/.exec(cloneUri);
39
+ if (!match) {
40
+ return undefined;
41
+ }
42
+ return match[1];
43
+ }
44
+ exports.extractRepoSlugFromUri = extractRepoSlugFromUri;
45
+ function generateRepositoryId(remoteUri) {
46
+ return extractRepoSlugFromUri(remoteUri)?.replaceAll("/", "-");
47
+ }
48
+ exports.generateRepositoryId = generateRepositoryId;
49
+ function generateConnectionId() {
50
+ const randomHash = Math.random().toString(36).slice(6);
51
+ return `apphosting-github-conn-${randomHash}`;
52
+ }
53
+ const ADD_CONN_CHOICE = "@ADD_CONN";
54
+ async function linkGitHubRepository(projectId, location) {
55
+ utils.logBullet(clc.bold(`${clc.yellow("===")} Set up a GitHub connection`));
56
+ const oauthConn = await getOrCreateOauthConnection(projectId, location);
57
+ const existingConns = await listAppHostingConnections(projectId);
58
+ if (existingConns.length === 0) {
59
+ existingConns.push(await createFullyInstalledConnection(projectId, location, generateConnectionId(), oauthConn));
60
+ }
61
+ let repoCloneUri;
62
+ let connection;
63
+ do {
64
+ if (repoCloneUri === ADD_CONN_CHOICE) {
65
+ existingConns.push(await createFullyInstalledConnection(projectId, location, generateConnectionId(), oauthConn, true));
66
+ }
67
+ const selection = await promptCloneUri(projectId, existingConns);
68
+ repoCloneUri = selection.cloneUri;
69
+ connection = selection.connection;
70
+ } while (repoCloneUri === ADD_CONN_CHOICE);
71
+ const { id: connectionId } = parseConnectionName(connection.name);
72
+ await getOrCreateConnection(projectId, location, connectionId, {
73
+ authorizerCredential: connection.githubConfig?.authorizerCredential,
74
+ appInstallationId: connection.githubConfig?.appInstallationId,
75
+ });
76
+ const repo = await getOrCreateRepository(projectId, location, connectionId, repoCloneUri);
77
+ utils.logSuccess(`Successfully linked GitHub repository at remote URI`);
78
+ utils.logSuccess(`\t${repo.cloneUri}`);
79
+ return repo;
80
+ }
81
+ exports.linkGitHubRepository = linkGitHubRepository;
82
+ async function createFullyInstalledConnection(projectId, location, connectionId, oauthConn, withNewInstallation = false) {
83
+ let conn = await createConnection(projectId, location, connectionId, {
84
+ appInstallationId: withNewInstallation ? undefined : oauthConn.githubConfig?.appInstallationId,
85
+ authorizerCredential: oauthConn.githubConfig?.authorizerCredential,
86
+ });
87
+ while (conn.installationState.stage !== "COMPLETE") {
88
+ utils.logBullet("Install the Firebase 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 Firebase GitHub app to access your GitHub repo.",
95
+ });
96
+ conn = await devConnect.getConnection(projectId, location, connectionId);
97
+ }
98
+ return conn;
99
+ }
100
+ async function getOrCreateOauthConnection(projectId, location) {
101
+ let conn;
102
+ try {
103
+ conn = await devConnect.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 Firebase GitHub app.");
116
+ utils.logBullet("Sign in to GitHub and authorize Firebase 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 devConnect.getConnection(projectId, location, id);
126
+ }
127
+ return conn;
128
+ }
129
+ exports.getOrCreateOauthConnection = getOrCreateOauthConnection;
130
+ async function promptCloneUri(projectId, connections) {
131
+ const { cloneUris, cloneUriToConnection } = await fetchAllRepositories(projectId, connections);
132
+ const cloneUri = await (0, prompt_1.promptOnce)({
133
+ type: "autocomplete",
134
+ name: "cloneUri",
135
+ message: "Which repository would you like to deploy?",
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, cloneUris, {
146
+ extract: (uri) => extractRepoSlugFromUri(uri) || "",
147
+ })
148
+ .map((result) => {
149
+ return {
150
+ name: extractRepoSlugFromUri(result.original) || "",
151
+ value: result.original,
152
+ };
153
+ }),
154
+ ]));
155
+ },
156
+ });
157
+ return { cloneUri, connection: cloneUriToConnection[cloneUri] };
158
+ }
159
+ async function ensureSecretManagerAdminGrant(projectId) {
160
+ const projectNumber = await (0, getProjectNumber_1.getProjectNumber)({ projectId });
161
+ const dcsaEmail = devConnect.serviceAgentEmail(projectNumber);
162
+ const alreadyGranted = await rm.serviceAccountHasRoles(projectId, dcsaEmail, ["roles/secretmanager.admin"], true);
163
+ if (alreadyGranted) {
164
+ utils.logBullet("secret manager admin role already granted");
165
+ return;
166
+ }
167
+ utils.logBullet("To create a new GitHub connection, Secret Manager Admin role (roles/secretmanager.admin) is required on the Developer Connect Service Agent.");
168
+ const grant = await (0, prompt_1.promptOnce)({
169
+ type: "confirm",
170
+ message: "Grant the required role to the Developer Connect Service Agent?",
171
+ });
172
+ if (!grant) {
173
+ utils.logBullet("You, or your project administrator, should run the following command to grant the required role:\n\n" +
174
+ "You, or your project adminstrator, can run the following command to grant the required role manually:\n\n" +
175
+ `\tgcloud projects add-iam-policy-binding ${projectId} \\\n` +
176
+ `\t --member="serviceAccount:${dcsaEmail} \\\n` +
177
+ `\t --role="roles/secretmanager.admin\n`);
178
+ throw new error_1.FirebaseError("Insufficient IAM permissions to create a new connection to GitHub");
179
+ }
180
+ try {
181
+ await rm.addServiceAccountToRoles(projectId, dcsaEmail, ["roles/secretmanager.admin"], true);
182
+ }
183
+ catch (e) {
184
+ if (e?.code === 400 || e?.status === 400) {
185
+ await devConnect.generateP4SA(projectNumber);
186
+ await rm.addServiceAccountToRoles(projectId, dcsaEmail, ["roles/secretmanager.admin"], true);
187
+ }
188
+ else {
189
+ throw e;
190
+ }
191
+ }
192
+ utils.logSuccess("Successfully granted the required role to the Developer Connect Service Agent!");
193
+ }
194
+ exports.ensureSecretManagerAdminGrant = ensureSecretManagerAdminGrant;
195
+ async function createConnection(projectId, location, connectionId, githubConfig) {
196
+ const op = await devConnect.createConnection(projectId, location, connectionId, githubConfig);
197
+ const conn = await poller.pollOperation({
198
+ ...devConnectPollerOptions,
199
+ pollerName: `create-${location}-${connectionId}`,
200
+ operationResourceName: op.name,
201
+ });
202
+ return conn;
203
+ }
204
+ exports.createConnection = createConnection;
205
+ async function getOrCreateConnection(projectId, location, connectionId, githubConfig) {
206
+ let conn;
207
+ try {
208
+ conn = await devConnect.getConnection(projectId, location, connectionId);
209
+ }
210
+ catch (err) {
211
+ if (err.status === 404) {
212
+ utils.logBullet("creating connection");
213
+ conn = await createConnection(projectId, location, connectionId, githubConfig);
214
+ }
215
+ else {
216
+ throw err;
217
+ }
218
+ }
219
+ return conn;
220
+ }
221
+ exports.getOrCreateConnection = getOrCreateConnection;
222
+ async function getOrCreateRepository(projectId, location, connectionId, cloneUri) {
223
+ const repositoryId = generateRepositoryId(cloneUri);
224
+ if (!repositoryId) {
225
+ throw new error_1.FirebaseError(`Failed to generate repositoryId for URI "${cloneUri}".`);
226
+ }
227
+ let repo;
228
+ try {
229
+ repo = await devConnect.getGitRepositoryLink(projectId, location, connectionId, repositoryId);
230
+ }
231
+ catch (err) {
232
+ if (err.status === 404) {
233
+ const op = await devConnect.createGitRepositoryLink(projectId, location, connectionId, repositoryId, cloneUri);
234
+ repo = await poller.pollOperation({
235
+ ...devConnectPollerOptions,
236
+ pollerName: `create-${location}-${connectionId}-${repositoryId}`,
237
+ operationResourceName: op.name,
238
+ });
239
+ }
240
+ else {
241
+ throw err;
242
+ }
243
+ }
244
+ return repo;
245
+ }
246
+ exports.getOrCreateRepository = getOrCreateRepository;
247
+ async function listAppHostingConnections(projectId) {
248
+ const conns = await devConnect.listAllConnections(projectId, "-");
249
+ return conns.filter((conn) => APPHOSTING_CONN_PATTERN.test(conn.name) &&
250
+ conn.installationState.stage === "COMPLETE" &&
251
+ !conn.disabled);
252
+ }
253
+ exports.listAppHostingConnections = listAppHostingConnections;
254
+ async function fetchAllRepositories(projectId, connections) {
255
+ const cloneUriToConnection = {};
256
+ for (const conn of connections) {
257
+ const { location, id } = parseConnectionName(conn.name);
258
+ const connectionRepos = await devConnect.listAllLinkableGitRepositories(projectId, location, id);
259
+ connectionRepos.forEach((repo) => {
260
+ cloneUriToConnection[repo.cloneUri] = conn;
261
+ });
262
+ }
263
+ return { cloneUris: Object.keys(cloneUriToConnection), cloneUriToConnection };
264
+ }
265
+ exports.fetchAllRepositories = fetchAllRepositories;
@@ -1,20 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.orchestrateRollout = exports.setDefaultTrafficPolicy = exports.createBackend = exports.doSetup = void 0;
4
- const clc = require("colorette");
3
+ exports.deleteBackendAndPoll = exports.orchestrateRollout = exports.setDefaultTrafficPolicy = exports.createBackend = exports.doSetup = void 0;
5
4
  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 resourceManager_1 = require("../../../gcp/resourceManager");
12
- const iam_1 = require("../../../gcp/iam");
13
- const error_1 = require("../../../error");
14
- const prompt_1 = require("../../../prompt");
5
+ const poller = require("../operation-poller");
6
+ const apphosting = require("../gcp/apphosting");
7
+ const githubConnections = require("./githubConnections");
8
+ const utils_1 = require("../utils");
9
+ const api_1 = require("../api");
10
+ const apphosting_1 = require("../gcp/apphosting");
11
+ const resourceManager_1 = require("../gcp/resourceManager");
12
+ const iam = require("../gcp/iam");
13
+ const error_1 = require("../error");
14
+ const prompt_1 = require("../prompt");
15
15
  const constants_1 = require("./constants");
16
- const ensureApiEnabled_1 = require("../../../ensureApiEnabled");
17
- const deploymentTool = require("../../../deploymentTool");
16
+ const ensureApiEnabled_1 = require("../ensureApiEnabled");
17
+ const deploymentTool = require("../deploymentTool");
18
+ const apps = require("./app");
18
19
  const DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME = "firebase-app-hosting-compute";
19
20
  const apphostingPollerOptions = {
20
21
  apiOrigin: (0, api_1.apphostingOrigin)(),
@@ -22,8 +23,9 @@ const apphostingPollerOptions = {
22
23
  masterTimeout: 25 * 60 * 1000,
23
24
  maxBackoff: 10000,
24
25
  };
25
- async function doSetup(projectId, location, serviceAccount) {
26
+ async function doSetup(projectId, webAppName, location, serviceAccount, withDevConnect) {
26
27
  await Promise.all([
28
+ ...(withDevConnect ? [(0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.developerConnectOrigin)(), "apphosting", true)] : []),
27
29
  (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudbuildOrigin)(), "apphosting", true),
28
30
  (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.secretManagerOrigin)(), "apphosting", true),
29
31
  (0, ensureApiEnabled_1.ensure)(projectId, (0, api_1.cloudRunApiOrigin)(), "apphosting", true),
@@ -35,15 +37,14 @@ async function doSetup(projectId, location, serviceAccount) {
35
37
  throw new error_1.FirebaseError(`Invalid location ${location}. Valid choices are ${allowedLocations.join(", ")}`);
36
38
  }
37
39
  }
38
- (0, utils_1.logBullet)("First we need a few details to create your backend.");
40
+ (0, utils_1.logBullet)("First we need a few details to create your backend.\n");
39
41
  location =
40
42
  location ||
41
43
  (await (0, prompt_1.promptOnce)({
42
44
  name: "region",
43
45
  type: "list",
44
46
  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
+ message: "Select a region to host your backend:\n",
47
48
  choices: allowedLocations.map((loc) => ({ value: loc })),
48
49
  }));
49
50
  (0, utils_1.logSuccess)(`Region set to ${location}.\n`);
@@ -53,8 +54,23 @@ async function doSetup(projectId, location, serviceAccount) {
53
54
  default: "my-web-app",
54
55
  message: "Create a name for your backend [1-30 characters]",
55
56
  });
56
- const cloudBuildConnRepo = await repo.linkGitHubRepository(projectId, location);
57
- const backend = await createBackend(projectId, location, backendId, cloudBuildConnRepo, serviceAccount);
57
+ const webApp = await apps.getOrCreateWebApp(projectId, webAppName, backendId);
58
+ if (webApp) {
59
+ (0, utils_1.logSuccess)(`Firebase web app set to ${webApp.name}.\n`);
60
+ }
61
+ else {
62
+ (0, utils_1.logWarning)(`Firebase web app not set`);
63
+ }
64
+ const gitRepositoryConnection = withDevConnect
65
+ ? await githubConnections.linkGitHubRepository(projectId, location)
66
+ : await repo.linkGitHubRepository(projectId, location);
67
+ const rootDir = await (0, prompt_1.promptOnce)({
68
+ name: "rootDir",
69
+ type: "input",
70
+ default: "/",
71
+ message: "Specify your app's root directory relative to your repository",
72
+ });
73
+ const backend = await createBackend(projectId, location, backendId, gitRepositoryConnection, serviceAccount, webApp?.id, rootDir);
58
74
  const branch = await (0, prompt_1.promptOnce)({
59
75
  name: "branch",
60
76
  type: "input",
@@ -70,7 +86,7 @@ async function doSetup(projectId, location, serviceAccount) {
70
86
  });
71
87
  if (!confirmRollout) {
72
88
  (0, utils_1.logSuccess)(`Successfully created backend:\n\t${backend.name}`);
73
- (0, utils_1.logSuccess)(`Your site will be deployed at:\n\thttps://${backend.uri}`);
89
+ (0, utils_1.logSuccess)(`Your backend will be deployed at:\n\thttps://${backend.uri}`);
74
90
  return;
75
91
  }
76
92
  await orchestrateRollout(projectId, location, backendId, {
@@ -81,7 +97,7 @@ async function doSetup(projectId, location, serviceAccount) {
81
97
  },
82
98
  });
83
99
  (0, utils_1.logSuccess)(`Successfully created backend:\n\t${backend.name}`);
84
- (0, utils_1.logSuccess)(`Your site is now deployed at:\n\thttps://${backend.uri}`);
100
+ (0, utils_1.logSuccess)(`Your backend is now deployed at:\n\thttps://${backend.uri}`);
85
101
  }
86
102
  exports.doSetup = doSetup;
87
103
  async function promptNewBackendId(projectId, location, prompt) {
@@ -102,18 +118,19 @@ async function promptNewBackendId(projectId, location, prompt) {
102
118
  function defaultComputeServiceAccountEmail(projectId) {
103
119
  return `${DEFAULT_COMPUTE_SERVICE_ACCOUNT_NAME}@${projectId}.iam.gserviceaccount.com`;
104
120
  }
105
- async function createBackend(projectId, location, backendId, repository, serviceAccount) {
121
+ async function createBackend(projectId, location, backendId, repository, serviceAccount, webAppId, rootDir = "/") {
106
122
  const defaultServiceAccount = defaultComputeServiceAccountEmail(projectId);
107
123
  const backendReqBody = {
108
124
  servingLocality: "GLOBAL_ACCESS",
109
125
  codebase: {
110
126
  repository: `${repository.name}`,
111
- rootDirectory: "/",
127
+ rootDirectory: rootDir,
112
128
  },
113
129
  labels: deploymentTool.labels(),
114
- computeServiceAccount: serviceAccount || defaultServiceAccount,
130
+ serviceAccount: serviceAccount || defaultServiceAccount,
131
+ appId: webAppId,
115
132
  };
116
- delete backendReqBody.computeServiceAccount;
133
+ delete backendReqBody.serviceAccount;
117
134
  async function createBackendAndPoll() {
118
135
  const op = await apphosting.createBackend(projectId, location, backendReqBody, backendId);
119
136
  return await poller.pollOperation({
@@ -141,7 +158,7 @@ async function createBackend(projectId, location, backendId, repository, service
141
158
  exports.createBackend = createBackend;
142
159
  async function provisionDefaultComputeServiceAccount(projectId) {
143
160
  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");
161
+ await iam.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
162
  }
146
163
  catch (err) {
147
164
  if (err.status !== 409) {
@@ -227,3 +244,12 @@ async function orchestrateRollout(projectId, location, backendId, buildInput) {
227
244
  return { rollout, build };
228
245
  }
229
246
  exports.orchestrateRollout = orchestrateRollout;
247
+ async function deleteBackendAndPoll(projectId, location, backendId) {
248
+ const op = await apphosting.deleteBackend(projectId, location, backendId);
249
+ await poller.pollOperation({
250
+ ...apphostingPollerOptions,
251
+ pollerName: `delete-${projectId}-${location}-${backendId}`,
252
+ operationResourceName: op.name,
253
+ });
254
+ }
255
+ exports.deleteBackendAndPoll = deleteBackendAndPoll;