firebase-tools-with-isolate 13.11.2 → 13.16.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 (134) hide show
  1. package/lib/api.js +4 -2
  2. package/lib/apphosting/githubConnections.js +125 -37
  3. package/lib/apphosting/index.js +3 -8
  4. package/lib/auth.js +14 -15
  5. package/lib/bin/firebase.js +7 -5
  6. package/lib/commands/dataconnect-sdk-generate.js +5 -9
  7. package/lib/commands/dataconnect-services-list.js +1 -1
  8. package/lib/commands/deploy.js +10 -2
  9. package/lib/commands/ext-configure.js +1 -6
  10. package/lib/commands/ext-dev-init.js +27 -30
  11. package/lib/commands/ext-dev-upload.js +4 -6
  12. package/lib/commands/ext-info.js +3 -5
  13. package/lib/commands/ext-install.js +0 -5
  14. package/lib/commands/ext-uninstall.js +0 -5
  15. package/lib/commands/ext-update.js +0 -5
  16. package/lib/commands/firestore-backups-schedules-create.js +11 -14
  17. package/lib/commands/firestore-backups-schedules-list.js +1 -1
  18. package/lib/commands/firestore-backups-schedules-update.js +4 -3
  19. package/lib/commands/firestore-databases-create.js +24 -7
  20. package/lib/commands/firestore-databases-restore.js +4 -4
  21. package/lib/commands/firestore-databases-update.js +5 -6
  22. package/lib/commands/functions-secrets-set.js +9 -6
  23. package/lib/commands/help.js +2 -0
  24. package/lib/commands/hosting-channel-create.js +1 -1
  25. package/lib/commands/hosting-channel-delete.js +1 -1
  26. package/lib/commands/hosting-channel-deploy.js +1 -1
  27. package/lib/commands/hosting-clone.js +1 -2
  28. package/lib/commands/index.js +9 -11
  29. package/lib/commands/init.js +16 -12
  30. package/lib/commands/login.js +1 -2
  31. package/lib/commands/setup-emulators-dataconnect.js +22 -3
  32. package/lib/config.js +5 -0
  33. package/lib/crashlytics/buildToolsJarHelper.js +1 -1
  34. package/lib/dataconnect/client.js +57 -9
  35. package/lib/dataconnect/fileUtils.js +71 -7
  36. package/lib/dataconnect/filters.js +12 -1
  37. package/lib/dataconnect/load.js +9 -7
  38. package/lib/dataconnect/provisionCloudSql.js +5 -1
  39. package/lib/dataconnect/schemaMigration.js +21 -0
  40. package/lib/dataconnect/types.js +8 -1
  41. package/lib/deploy/dataconnect/prepare.js +16 -2
  42. package/lib/deploy/extensions/planner.js +52 -1
  43. package/lib/deploy/extensions/prepare.js +98 -23
  44. package/lib/deploy/extensions/release.js +6 -0
  45. package/lib/deploy/functions/build.js +15 -6
  46. package/lib/deploy/functions/deploy.js +12 -12
  47. package/lib/deploy/functions/params.js +5 -3
  48. package/lib/deploy/functions/prepare.js +8 -1
  49. package/lib/deploy/functions/release/index.js +4 -0
  50. package/lib/deploy/functions/runtimes/discovery/parsing.js +1 -1
  51. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +46 -0
  52. package/lib/emulator/adminSdkConfig.test.js +16 -0
  53. package/lib/emulator/constants.js +8 -0
  54. package/lib/emulator/controller.js +14 -10
  55. package/lib/emulator/dataconnectEmulator.js +122 -18
  56. package/lib/emulator/downloadableEmulators.js +24 -25
  57. package/lib/emulator/env.js +3 -0
  58. package/lib/emulator/eventarcEmulator.js +68 -18
  59. package/lib/emulator/functionsEmulator.js +119 -1
  60. package/lib/emulator/functionsEmulatorShared.js +20 -0
  61. package/lib/emulator/hub.js +1 -1
  62. package/lib/emulator/portUtils.js +10 -0
  63. package/lib/emulator/pubsubEmulator.js +1 -1
  64. package/lib/emulator/registry.js +2 -1
  65. package/lib/emulator/storage/apis/shared.js +2 -1
  66. package/lib/emulator/storage/persistence.js +5 -13
  67. package/lib/emulator/storage/rfc.js +9 -0
  68. package/lib/emulator/storage/rules/config.js +4 -2
  69. package/lib/emulator/taskQueue.js +348 -0
  70. package/lib/emulator/tasksEmulator.js +237 -0
  71. package/lib/emulator/types.js +3 -0
  72. package/lib/experiments.js +8 -3
  73. package/lib/extensions/askUserForEventsConfig.js +18 -8
  74. package/lib/extensions/askUserForParam.js +3 -2
  75. package/lib/extensions/change-log.js +2 -4
  76. package/lib/extensions/displayExtensionInfo.js +5 -10
  77. package/lib/extensions/extensionsApi.js +1 -1
  78. package/lib/extensions/extensionsHelper.js +30 -10
  79. package/lib/extensions/localHelper.js +1 -1
  80. package/lib/extensions/provisioningHelper.js +1 -1
  81. package/lib/extensions/refs.js +26 -11
  82. package/lib/extensions/runtimes/common.js +75 -0
  83. package/lib/extensions/types.js +56 -1
  84. package/lib/extensions/updateHelper.js +1 -2
  85. package/lib/extensions/warnings.js +2 -7
  86. package/lib/firestore/api-sort.test.js +74 -0
  87. package/lib/firestore/api.js +8 -7
  88. package/lib/firestore/backupUtils.test.js +18 -0
  89. package/lib/firestore/pretty-print.js +21 -1
  90. package/lib/firestore/pretty-print.test.js +61 -0
  91. package/lib/firestore/util.test.js +42 -0
  92. package/lib/frameworks/angular/utils.js +13 -5
  93. package/lib/frameworks/compose/discover/mockFileSystem.js +36 -0
  94. package/lib/frameworks/constants.js +1 -1
  95. package/lib/frameworks/index.js +2 -6
  96. package/lib/frameworks/next/constants.js +1 -1
  97. package/lib/frameworks/next/index.js +35 -15
  98. package/lib/frameworks/next/utils.js +53 -9
  99. package/lib/frameworks/nuxt/index.js +3 -3
  100. package/lib/functions/events/v2.js +2 -1
  101. package/lib/gcp/cloudsql/cloudsqladmin.js +6 -1
  102. package/lib/gcp/devConnect.js +36 -1
  103. package/lib/hosting/implicitInit.js +2 -2
  104. package/lib/init/features/dataconnect/index.js +104 -32
  105. package/lib/init/features/dataconnect/sdk.js +147 -0
  106. package/lib/init/features/firestore/indexes.js +2 -2
  107. package/lib/init/features/firestore/rules.js +2 -2
  108. package/lib/init/features/functions/javascript.js +6 -8
  109. package/lib/init/features/functions/python.js +4 -6
  110. package/lib/init/features/functions/typescript.js +8 -10
  111. package/lib/init/features/hosting/github.js +43 -21
  112. package/lib/init/features/hosting/index.js +3 -3
  113. package/lib/init/features/index.js +3 -1
  114. package/lib/init/features/storage.js +2 -2
  115. package/lib/init/index.js +1 -0
  116. package/lib/listFiles.js +1 -1
  117. package/lib/management/apps.js +2 -2
  118. package/lib/prompt.js +22 -1
  119. package/lib/rc.js +1 -0
  120. package/lib/requireAuth.js +8 -3
  121. package/lib/rulesDeploy.js +14 -12
  122. package/lib/templates.js +23 -0
  123. package/lib/utils.js +2 -2
  124. package/package.json +25 -24
  125. package/schema/connector-yaml.json +36 -4
  126. package/schema/dataconnect-yaml.json +4 -0
  127. package/schema/firebase-config.json +12 -8
  128. package/templates/_gitignore +3 -0
  129. package/templates/init/dataconnect/connector.yaml +15 -2
  130. package/templates/init/dataconnect/dataconnect.yaml +5 -4
  131. package/templates/init/dataconnect/mutations.gql +45 -25
  132. package/templates/init/dataconnect/queries.gql +69 -36
  133. package/templates/init/dataconnect/schema.gql +38 -21
  134. package/lib/extensions/billingMigrationHelper.js +0 -61
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TasksEmulator = exports.TaskQueueController = void 0;
4
+ const express = require("express");
5
+ const constants_1 = require("./constants");
6
+ const types_1 = require("./types");
7
+ const utils_1 = require("../utils");
8
+ const emulatorLogger_1 = require("./emulatorLogger");
9
+ const taskQueue_1 = require("./taskQueue");
10
+ const cors = require("cors");
11
+ const RETRY_CONFIG_DEFAULTS = {
12
+ maxAttempts: 3,
13
+ maxRetrySeconds: null,
14
+ maxBackoffSeconds: 60 * 60,
15
+ maxDoublings: 16,
16
+ minBackoffSeconds: 0.1,
17
+ };
18
+ const RATE_LIMITS_DEFAULT = {
19
+ maxConcurrentDispatches: 1000,
20
+ maxDispatchesPerSecond: 500,
21
+ };
22
+ class TaskQueueController {
23
+ constructor() {
24
+ this.queues = {};
25
+ this.tokenRefillIds = [];
26
+ this.running = false;
27
+ this.listenId = null;
28
+ }
29
+ enqueue(key, task) {
30
+ if (!this.queues[key]) {
31
+ throw new Error("Queue does not exist");
32
+ }
33
+ this.queues[key].enqueue(task);
34
+ }
35
+ delete(key, taskId) {
36
+ if (!this.queues[key]) {
37
+ throw new Error("Queue does not exist");
38
+ }
39
+ this.queues[key].delete(taskId);
40
+ }
41
+ createQueue(key, config) {
42
+ const newQueue = new taskQueue_1.TaskQueue(key, config);
43
+ const intervalID = setInterval(() => newQueue.refillTokens(), TaskQueueController.TOKEN_REFRESH_INTERVAL);
44
+ this.tokenRefillIds.push(intervalID);
45
+ this.queues[key] = newQueue;
46
+ }
47
+ listen() {
48
+ let shouldUpdate = false;
49
+ for (const [_key, queue] of Object.entries(this.queues)) {
50
+ shouldUpdate = shouldUpdate || queue.isActive();
51
+ }
52
+ if (shouldUpdate) {
53
+ this.updateQueues();
54
+ this.listenId = setTimeout(() => this.listen(), TaskQueueController.UPDATE_TIMEOUT);
55
+ }
56
+ else {
57
+ this.listenId = setTimeout(() => this.listen(), TaskQueueController.LISTEN_TIMEOUT);
58
+ }
59
+ }
60
+ updateQueues() {
61
+ for (const [_key, queue] of Object.entries(this.queues)) {
62
+ if (queue.isActive()) {
63
+ queue.dispatchTasks();
64
+ queue.processDispatch();
65
+ }
66
+ }
67
+ }
68
+ start() {
69
+ this.running = true;
70
+ this.listen();
71
+ }
72
+ stop() {
73
+ if (this.listenId) {
74
+ clearTimeout(this.listenId);
75
+ }
76
+ this.tokenRefillIds.forEach(clearInterval);
77
+ this.running = false;
78
+ }
79
+ isRunning() {
80
+ return this.running;
81
+ }
82
+ getStatistics() {
83
+ const stats = {};
84
+ for (const [key, queue] of Object.entries(this.queues)) {
85
+ stats[key] = queue.getStatistics();
86
+ }
87
+ return stats;
88
+ }
89
+ }
90
+ exports.TaskQueueController = TaskQueueController;
91
+ TaskQueueController.UPDATE_TIMEOUT = 0;
92
+ TaskQueueController.LISTEN_TIMEOUT = 1000;
93
+ TaskQueueController.TOKEN_REFRESH_INTERVAL = 1000;
94
+ class TasksEmulator {
95
+ constructor(args) {
96
+ this.args = args;
97
+ this.logger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.TASKS);
98
+ this.controller = new TaskQueueController();
99
+ }
100
+ validateQueueId(queueId) {
101
+ if (typeof queueId !== "string") {
102
+ return false;
103
+ }
104
+ if (queueId.length > 100) {
105
+ return false;
106
+ }
107
+ const regex = /^[A-Za-z0-9-]+$/;
108
+ return regex.test(queueId);
109
+ }
110
+ createHubServer() {
111
+ const hub = express();
112
+ const createTaskQueueRoute = `/projects/:project_id/locations/:location_id/queues/:queue_name`;
113
+ const createTaskQueueHandler = (req, res) => {
114
+ const projectId = req.params.project_id;
115
+ const locationId = req.params.location_id;
116
+ const queueName = req.params.queue_name;
117
+ if (!this.validateQueueId(queueName)) {
118
+ res.status(400).send("Invalid Queue ID");
119
+ return;
120
+ }
121
+ const key = `queue:${projectId}-${locationId}-${queueName}`;
122
+ this.logger.logLabeled("SUCCESS", "tasks", `Created queue with key: ${key}`);
123
+ const body = req.body;
124
+ const taskQueueConfig = {
125
+ retryConfig: {
126
+ maxAttempts: body.retryConfig?.maxAttempts ?? RETRY_CONFIG_DEFAULTS.maxAttempts,
127
+ maxRetrySeconds: body.retryConfig?.maxRetrySeconds ?? RETRY_CONFIG_DEFAULTS.maxRetrySeconds,
128
+ maxBackoffSeconds: body.retryConfig?.maxBackoffSeconds ?? RETRY_CONFIG_DEFAULTS.maxBackoffSeconds,
129
+ maxDoublings: body.retryConfig?.maxDoublings ?? RETRY_CONFIG_DEFAULTS.maxDoublings,
130
+ minBackoffSeconds: body.retryConfig?.minBackoffSeconds ?? RETRY_CONFIG_DEFAULTS.minBackoffSeconds,
131
+ },
132
+ rateLimits: {
133
+ maxConcurrentDispatches: body.rateLimits?.maxConcurrentDispatches ?? RATE_LIMITS_DEFAULT.maxConcurrentDispatches,
134
+ maxDispatchesPerSecond: body.rateLimits?.maxDispatchesPerSecond ?? RATE_LIMITS_DEFAULT.maxDispatchesPerSecond,
135
+ },
136
+ timeoutSeconds: body.timeoutSeconds ?? 10,
137
+ retry: body.retry ?? false,
138
+ defaultUri: body.defaultUri,
139
+ };
140
+ if (taskQueueConfig.rateLimits.maxConcurrentDispatches > 5000) {
141
+ res.status(400).send("cannot set maxConcurrentDispatches to a value over 5000");
142
+ return;
143
+ }
144
+ this.controller.createQueue(key, taskQueueConfig);
145
+ this.logger.log("DEBUG", `Created task queue ${key} with configuration: ${JSON.stringify(taskQueueConfig)}`);
146
+ res.status(200).send({ taskQueueConfig });
147
+ };
148
+ const enqueueTasksRoute = `/projects/:project_id/locations/:location_id/queues/:queue_name/tasks`;
149
+ const enqueueTasksHandler = (req, res) => {
150
+ if (!this.controller.isRunning()) {
151
+ this.controller.start();
152
+ }
153
+ const projectId = req.params.project_id;
154
+ const locationId = req.params.location_id;
155
+ const queueName = req.params.queue_name;
156
+ const queueKey = `queue:${projectId}-${locationId}-${queueName}`;
157
+ if (!this.controller.queues[queueKey]) {
158
+ this.logger.log("WARN", "Tried to queue a task into a non-existent queue");
159
+ res.status(404).send("Tried to queue a task from a non-existent queue");
160
+ return;
161
+ }
162
+ req.body.task.name =
163
+ req.body.task.name ??
164
+ `/projects/${projectId}/locations/${locationId}/queues/${queueName}/tasks/${Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)}`;
165
+ req.body.task.httpRequest.body = JSON.parse(atob(req.body.task.httpRequest.body));
166
+ const task = req.body.task;
167
+ try {
168
+ this.controller.enqueue(queueKey, task);
169
+ this.logger.log("DEBUG", `Enqueueing task ${task.name} onto ${queueKey}`);
170
+ res.status(200).send({ task: task });
171
+ }
172
+ catch (e) {
173
+ res.status(409).send("A task with the same name already exists");
174
+ }
175
+ };
176
+ const deleteTasksRoute = `/projects/:project_id/locations/:location_id/queues/:queue_name/tasks/:task_id`;
177
+ const deleteTasksHandler = (req, res) => {
178
+ const projectId = req.params.project_id;
179
+ const locationId = req.params.location_id;
180
+ const queueName = req.params.queue_name;
181
+ const taskId = req.params.task_id;
182
+ const queueKey = `queue:${projectId}-${locationId}-${queueName}`;
183
+ if (!this.controller.queues[queueKey]) {
184
+ this.logger.log("WARN", "Tried to remove a task from a non-existent queue");
185
+ res.status(404).send("Tried to remove a task from a non-existent queue");
186
+ return;
187
+ }
188
+ try {
189
+ const taskName = `projects/${projectId}/locations/${locationId}/queues/${queueName}/tasks/${taskId}`;
190
+ this.logger.log("DEBUG", `removing: ${taskName}`);
191
+ this.controller.delete(queueKey, taskName);
192
+ res.status(200).send({ res: "OK" });
193
+ }
194
+ catch (e) {
195
+ this.logger.log("WARN", "Tried to remove a task that doesn't exist");
196
+ res.status(404).send("Tried to remove a task that doesn't exist");
197
+ }
198
+ };
199
+ const getStatsRoute = `/queueStats`;
200
+ const getStatsHandler = (req, res) => {
201
+ res.json(this.controller.getStatistics());
202
+ };
203
+ hub.get([getStatsRoute], cors({ origin: true }), getStatsHandler);
204
+ hub.post([createTaskQueueRoute], express.json(), createTaskQueueHandler);
205
+ hub.post([enqueueTasksRoute], express.json(), enqueueTasksHandler);
206
+ hub.delete([deleteTasksRoute], express.json(), deleteTasksHandler);
207
+ return hub;
208
+ }
209
+ async start() {
210
+ const { host, port } = this.getInfo();
211
+ const server = this.createHubServer().listen(port, host);
212
+ this.destroyServer = (0, utils_1.createDestroyer)(server);
213
+ return Promise.resolve();
214
+ }
215
+ async connect() {
216
+ return Promise.resolve();
217
+ }
218
+ async stop() {
219
+ if (this.destroyServer) {
220
+ await this.destroyServer();
221
+ }
222
+ this.controller.stop();
223
+ }
224
+ getInfo() {
225
+ const host = this.args.host || constants_1.Constants.getDefaultHost();
226
+ const port = this.args.port || constants_1.Constants.getDefaultPort(types_1.Emulators.TASKS);
227
+ return {
228
+ name: this.getName(),
229
+ host,
230
+ port,
231
+ };
232
+ }
233
+ getName() {
234
+ return types_1.Emulators.TASKS;
235
+ }
236
+ }
237
+ exports.TasksEmulator = TasksEmulator;
@@ -16,6 +16,7 @@ var Emulators;
16
16
  Emulators["EXTENSIONS"] = "extensions";
17
17
  Emulators["EVENTARC"] = "eventarc";
18
18
  Emulators["DATACONNECT"] = "dataconnect";
19
+ Emulators["TASKS"] = "tasks";
19
20
  })(Emulators = exports.Emulators || (exports.Emulators = {}));
20
21
  exports.DOWNLOADABLE_EMULATORS = [
21
22
  Emulators.FIRESTORE,
@@ -41,6 +42,7 @@ exports.ALL_SERVICE_EMULATORS = [
41
42
  Emulators.STORAGE,
42
43
  Emulators.EVENTARC,
43
44
  Emulators.DATACONNECT,
45
+ Emulators.TASKS,
44
46
  ].filter((v) => v);
45
47
  exports.EMULATORS_SUPPORTED_BY_FUNCTIONS = [
46
48
  Emulators.FIRESTORE,
@@ -48,6 +50,7 @@ exports.EMULATORS_SUPPORTED_BY_FUNCTIONS = [
48
50
  Emulators.PUBSUB,
49
51
  Emulators.STORAGE,
50
52
  Emulators.EVENTARC,
53
+ Emulators.TASKS,
51
54
  ];
52
55
  exports.EMULATORS_SUPPORTED_BY_UI = [
53
56
  Emulators.AUTH,
@@ -26,7 +26,7 @@ exports.ALL_EXPERIMENTS = experiments({
26
26
  "of deploys. This has been made an experiment due to backend bugs that are " +
27
27
  "temporarily causing failures in some regions with this optimization enabled",
28
28
  public: true,
29
- default: false,
29
+ default: true,
30
30
  },
31
31
  deletegcfartifacts: {
32
32
  shortDescription: `Add the ${(0, colorette_1.bold)("functions:deletegcfartifacts")} command to purge docker build images`,
@@ -92,8 +92,8 @@ exports.ALL_EXPERIMENTS = experiments({
92
92
  public: false,
93
93
  },
94
94
  dataconnect: {
95
- shortDescription: "Enable Data Connect related features.",
96
- fullDescription: "Enable Data Connect related features.",
95
+ shortDescription: "Deprecated. Previosuly, enabled Data Connect related features.",
96
+ fullDescription: "Deprecated. Previously, enabled Data Connect related features.",
97
97
  public: false,
98
98
  },
99
99
  genkit: {
@@ -102,6 +102,11 @@ exports.ALL_EXPERIMENTS = experiments({
102
102
  default: true,
103
103
  public: false,
104
104
  },
105
+ fdccompatiblemode: {
106
+ shortDescription: "Enable Data Connect schema migrations in Compatible Mode",
107
+ fullDescription: "Enable Data Connect schema migrations in Compatible Mode",
108
+ public: false,
109
+ },
105
110
  });
106
111
  function isValidExperiment(name) {
107
112
  return Object.keys(exports.ALL_EXPERIMENTS).includes(name);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.askForEventArcLocation = exports.askShouldCollectEventsConfig = exports.askForAllowedEventTypes = exports.askForEventsConfig = exports.checkAllowedEventTypesResponse = void 0;
3
+ exports.askForEventArcLocation = exports.EXTENSIONS_DEFAULT_EVENT_ARC_REGION = exports.ALLOWED_EVENT_ARC_REGIONS = exports.askShouldCollectEventsConfig = exports.askForAllowedEventTypes = exports.getEventArcChannel = exports.askForEventsConfig = exports.checkAllowedEventTypesResponse = void 0;
4
4
  const prompt_1 = require("../prompt");
5
5
  const extensionsApi = require("../extensions/extensionsApi");
6
6
  const utils = require("../utils");
@@ -22,7 +22,7 @@ function checkAllowedEventTypesResponse(response, validEvents) {
22
22
  }
23
23
  exports.checkAllowedEventTypesResponse = checkAllowedEventTypesResponse;
24
24
  async function askForEventsConfig(events, projectId, instanceId) {
25
- logger_1.logger.info(`\n${clc.bold("Enable Events")}: ${(0, marked_1.marked)("If you enable events, you can write custom event handlers ([https://firebase.google.com/docs/extensions/install-extensions#eventarc](https://firebase.google.com/docs/extensions/install-extensions#eventarc)) that respond to these events.\n\nYou can always enable or disable events later. Events will be emitted via Eventarc. Fees apply ([https://cloud.google.com/eventarc/pricing](https://cloud.google.com/eventarc/pricing)).")}`);
25
+ logger_1.logger.info(`\n${clc.bold("Enable Events")}: ${await (0, marked_1.marked)("If you enable events, you can write custom event handlers ([https://firebase.google.com/docs/extensions/install-extensions#eventarc](https://firebase.google.com/docs/extensions/install-extensions#eventarc)) that respond to these events.\n\nYou can always enable or disable events later. Events will be emitted via Eventarc. Fees apply ([https://cloud.google.com/eventarc/pricing](https://cloud.google.com/eventarc/pricing)).")}`);
26
26
  if (!(await askShouldCollectEventsConfig())) {
27
27
  return undefined;
28
28
  }
@@ -37,11 +37,15 @@ async function askForEventsConfig(events, projectId, instanceId) {
37
37
  const preselectedTypes = existingInstance?.config.allowedEventTypes ?? [];
38
38
  const oldLocation = existingInstance?.config.eventarcChannel?.split("/")[3];
39
39
  const location = await askForEventArcLocation(oldLocation);
40
- const channel = `projects/${projectId}/locations/${location}/channels/firebase`;
40
+ const channel = getEventArcChannel(projectId, location);
41
41
  const allowedEventTypes = await askForAllowedEventTypes(events, preselectedTypes);
42
42
  return { channel, allowedEventTypes };
43
43
  }
44
44
  exports.askForEventsConfig = askForEventsConfig;
45
+ function getEventArcChannel(projectId, location) {
46
+ return `projects/${projectId}/locations/${location}/channels/firebase`;
47
+ }
48
+ exports.getEventArcChannel = getEventArcChannel;
45
49
  async function askForAllowedEventTypes(eventDescriptors, preselectedTypes) {
46
50
  let valid = false;
47
51
  let response = [];
@@ -74,21 +78,27 @@ async function askShouldCollectEventsConfig() {
74
78
  });
75
79
  }
76
80
  exports.askShouldCollectEventsConfig = askShouldCollectEventsConfig;
81
+ exports.ALLOWED_EVENT_ARC_REGIONS = [
82
+ "us-central1",
83
+ "us-west1",
84
+ "europe-west4",
85
+ "asia-northeast1",
86
+ ];
87
+ exports.EXTENSIONS_DEFAULT_EVENT_ARC_REGION = "us-central1";
77
88
  async function askForEventArcLocation(preselectedLocation) {
78
89
  let valid = false;
79
- const allowedRegions = ["us-central1", "us-west1", "europe-west4", "asia-northeast1"];
80
90
  let location = "";
81
91
  while (!valid) {
82
92
  location = await (0, prompt_1.promptOnce)({
83
93
  name: "input",
84
94
  type: "list",
85
- default: preselectedLocation ?? "us-central1",
95
+ default: preselectedLocation ?? exports.EXTENSIONS_DEFAULT_EVENT_ARC_REGION,
86
96
  message: "Which location would you like the Eventarc channel to live in? We recommend using the default option. A channel location that differs from the extension's Cloud Functions location can incur egress cost.",
87
- choices: allowedRegions.map((e) => ({ checked: false, value: e })),
97
+ choices: exports.ALLOWED_EVENT_ARC_REGIONS.map((e) => ({ checked: false, value: e })),
88
98
  });
89
- valid = allowedRegions.includes(location);
99
+ valid = exports.ALLOWED_EVENT_ARC_REGIONS.includes(location);
90
100
  if (!valid) {
91
- utils.logWarning(`Unexpected EventArc region '${location}' was specified. Allowed regions: ${allowedRegions.join(", ")}`);
101
+ utils.logWarning(`Unexpected EventArc region '${location}' was specified. Allowed regions: ${exports.ALLOWED_EVENT_ARC_REGIONS.join(", ")}`);
92
102
  }
93
103
  }
94
104
  return location;
@@ -121,7 +121,7 @@ async function askForParam(args) {
121
121
  let secretLocations = [];
122
122
  const description = paramSpec.description || "";
123
123
  const label = paramSpec.label.trim();
124
- logger_1.logger.info(`\n${clc.bold(label)}${clc.bold(paramSpec.required ? "" : " (Optional)")}: ${(0, marked_1.marked)(description).trim()}`);
124
+ logger_1.logger.info(`\n${clc.bold(label)}${clc.bold(paramSpec.required ? "" : " (Optional)")}: ${(await (0, marked_1.marked)(description)).trim()}`);
125
125
  while (!valid) {
126
126
  switch (paramSpec.type) {
127
127
  case types_1.ParamType.SELECT:
@@ -254,7 +254,7 @@ async function promptReconfigureSecret(projectId, instanceId, paramSpec) {
254
254
  ],
255
255
  });
256
256
  switch (action) {
257
- case SecretUpdateAction.SET_NEW:
257
+ case SecretUpdateAction.SET_NEW: {
258
258
  let secret;
259
259
  let secretName;
260
260
  if (paramSpec.default) {
@@ -287,6 +287,7 @@ async function promptReconfigureSecret(projectId, instanceId, paramSpec) {
287
287
  else {
288
288
  return "";
289
289
  }
290
+ }
290
291
  case SecretUpdateAction.LEAVE:
291
292
  default:
292
293
  return paramSpec.default || "";
@@ -5,16 +5,14 @@ const clc = require("colorette");
5
5
  const marked_1 = require("marked");
6
6
  const path = require("path");
7
7
  const semver = require("semver");
8
- const TerminalRenderer = require("marked-terminal");
8
+ const marked_terminal_1 = require("marked-terminal");
9
9
  const Table = require("cli-table");
10
10
  const extensionsApi_1 = require("./extensionsApi");
11
11
  const localHelper_1 = require("./localHelper");
12
12
  const logger_1 = require("../logger");
13
13
  const refs = require("./refs");
14
14
  const utils_1 = require("../utils");
15
- marked_1.marked.setOptions({
16
- renderer: new TerminalRenderer(),
17
- });
15
+ marked_1.marked.use((0, marked_terminal_1.markedTerminal)());
18
16
  const EXTENSIONS_CHANGELOG = "CHANGELOG.md";
19
17
  const VERSION_LINE_REGEX = /##.+?(\d+\.\d+\.\d+(?:-((\d+|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(\d+|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?).*/;
20
18
  async function getReleaseNotesForUpdate(args) {
@@ -2,18 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.retrieveRoleInfo = exports.displayResources = exports.displayEvents = exports.displayExternalServices = exports.displayExtensionVersionInfo = void 0;
4
4
  const clc = require("colorette");
5
- const marked_1 = require("marked");
6
5
  const semver = require("semver");
7
- const TerminalRenderer = require("marked-terminal");
8
6
  const path = require("path");
9
7
  const refs = require("../extensions/refs");
10
8
  const logger_1 = require("../logger");
11
9
  const types_1 = require("./types");
12
10
  const iam = require("../gcp/iam");
13
11
  const secretsUtils_1 = require("./secretsUtils");
14
- marked_1.marked.setOptions({
15
- renderer: new TerminalRenderer(),
16
- });
17
12
  const TASKS_ROLE = "cloudtasks.enqueuer";
18
13
  const TASKS_API = "cloudtasks.googleapis.com";
19
14
  async function displayExtensionVersionInfo(args) {
@@ -54,7 +49,7 @@ async function displayExtensionVersionInfo(args) {
54
49
  if (extensionVersion.buildSourceUri) {
55
50
  const buildSourceUri = new URL(extensionVersion.buildSourceUri);
56
51
  buildSourceUri.pathname = path.join(buildSourceUri.pathname, extensionVersion.extensionRoot ?? "");
57
- lines.push(`${clc.bold("Source in GitHub:")} ${buildSourceUri}`);
52
+ lines.push(`${clc.bold("Source in GitHub:")} ${buildSourceUri.toString()}`);
58
53
  }
59
54
  else {
60
55
  lines.push(`${clc.bold("Source download URI:")} ${extensionVersion.sourceDownloadUri ?? "-"}`);
@@ -106,24 +101,24 @@ function displayResources(spec) {
106
101
  break;
107
102
  default:
108
103
  }
109
- return ` - ${clc.blue(`${resource.name} (${type})`)}${resource.description ? `: ${resource.description}` : ""}`;
104
+ return ` - ${clc.blueBright(`${resource.name} (${type})`)}${resource.description ? `: ${resource.description}` : ""}`;
110
105
  });
111
106
  lines.push(...new Set(spec.lifecycleEvents?.map((event) => {
112
- return ` - ${clc.blue(`${event.taskQueueTriggerFunction} (Cloud Task queue)`)}`;
107
+ return ` - ${clc.blueBright(`${event.taskQueueTriggerFunction} (Cloud Task queue)`)}`;
113
108
  })));
114
109
  lines.push(...spec.params
115
110
  .filter((param) => {
116
111
  return param.type === "SECRET";
117
112
  })
118
113
  .map((param) => {
119
- return ` - ${clc.blue(`${param.param} (Cloud Secret Manager secret)`)}`;
114
+ return ` - ${clc.blueBright(`${param.param} (Cloud Secret Manager secret)`)}`;
120
115
  }));
121
116
  return clc.bold("Resources created:\n") + (lines.length ? lines.join("\n") : " - None");
122
117
  }
123
118
  exports.displayResources = displayResources;
124
119
  async function retrieveRoleInfo(role) {
125
120
  const res = await iam.getRole(role);
126
- return ` - ${clc.yellow(res.title)}${res.description ? `: ${res.description}` : ""}`;
121
+ return ` - ${clc.yellow(res.title || res.name)}${res.description ? `: ${res.description}` : ""}`;
127
122
  }
128
123
  exports.retrieveRoleInfo = retrieveRoleInfo;
129
124
  async function displayRoles(roles) {
@@ -351,6 +351,6 @@ function refNotFoundError(ref) {
351
351
  return new error_1.FirebaseError(`The extension reference '${clc.bold(ref.version ? refs.toExtensionVersionRef(ref) : refs.toExtensionRef(ref))}' doesn't exist. This could happen for two reasons:\n` +
352
352
  ` -The publisher ID '${clc.bold(ref.publisherId)}' doesn't exist or could be misspelled\n` +
353
353
  ` -The name of the ${ref.version ? "extension version" : "extension"} '${clc.bold(ref.version ? `${ref.extensionId}@${ref.version}` : ref.extensionId)}' doesn't exist or could be misspelled\n\n` +
354
- `Please correct the extension reference and try again. If you meant to install an extension from a local source, please provide a relative path prefixed with '${clc.bold("./")}', '${clc.bold("../")}', or '${clc.bold("~/")}'.}`, { status: 404 });
354
+ `Please correct the extension reference and try again. If you meant to reference an extension from a local source, please provide a relative path prefixed with '${clc.bold("./")}', '${clc.bold("../")}', or '${clc.bold("~/")}'.}`, { status: 404 });
355
355
  }
356
356
  exports.refNotFoundError = refNotFoundError;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.diagnoseAndFixProject = exports.getSourceOrigin = exports.isLocalOrURLPath = exports.isLocalPath = exports.isUrlPath = exports.instanceIdExists = exports.promptForRepeatInstance = exports.promptForOfficialExtension = exports.displayReleaseNotes = exports.getPublisherProjectFromName = exports.createSourceFromLocation = exports.getMissingPublisherError = exports.uploadExtensionVersionFromLocalSource = exports.uploadExtensionVersionFromGitHubSource = exports.unpackExtensionState = exports.getNextVersionByStage = exports.ensureExtensionsPublisherApiEnabled = exports.ensureExtensionsApiEnabled = exports.promptForExtensionRoot = exports.promptForValidRepoURI = exports.promptForValidInstanceId = exports.validateSpec = exports.validateCommandLineParams = exports.populateDefaultParams = exports.substituteParams = exports.getFirebaseProjectParams = exports.getDBInstanceFromURL = exports.resourceTypeToNiceName = exports.AUTOPOULATED_PARAM_PLACEHOLDERS = exports.EXTENSIONS_BUCKET_NAME = exports.URL_REGEX = exports.logPrefix = exports.SourceOrigin = exports.SpecParamType = void 0;
3
+ exports.diagnoseAndFixProject = exports.getSourceOrigin = exports.isLocalOrURLPath = exports.isLocalPath = exports.isUrlPath = exports.instanceIdExists = exports.promptForRepeatInstance = exports.promptForOfficialExtension = exports.displayReleaseNotes = exports.getPublisherProjectFromName = exports.createSourceFromLocation = exports.getMissingPublisherError = exports.uploadExtensionVersionFromLocalSource = exports.uploadExtensionVersionFromGitHubSource = exports.unpackExtensionState = exports.getNextVersionByStage = exports.ensureExtensionsPublisherApiEnabled = exports.ensureExtensionsApiEnabled = exports.checkExtensionsApiEnabled = exports.promptForExtensionRoot = exports.promptForValidRepoURI = exports.promptForValidInstanceId = exports.validateSpec = exports.validateCommandLineParams = exports.populateDefaultParams = exports.substituteSecretParams = exports.substituteParams = exports.getFirebaseProjectParams = exports.getDBInstanceFromURL = exports.resourceTypeToNiceName = exports.AUTOPOULATED_PARAM_PLACEHOLDERS = exports.EXTENSIONS_BUCKET_NAME = exports.URL_REGEX = exports.logPrefix = exports.SourceOrigin = exports.SpecParamType = void 0;
4
4
  const clc = require("colorette");
5
5
  const ora = require("ora");
6
6
  const semver = require("semver");
@@ -9,11 +9,9 @@ const fs = require("fs-extra");
9
9
  const node_fetch_1 = require("node-fetch");
10
10
  const path = require("path");
11
11
  const marked_1 = require("marked");
12
+ const marked_terminal_1 = require("marked-terminal");
12
13
  const unzip_1 = require("./../unzip");
13
- const TerminalRenderer = require("marked-terminal");
14
- marked_1.marked.setOptions({
15
- renderer: new TerminalRenderer(),
16
- });
14
+ marked_1.marked.use((0, marked_terminal_1.markedTerminal)());
17
15
  const api_1 = require("../api");
18
16
  const archiveDirectory_1 = require("../archiveDirectory");
19
17
  const utils_1 = require("./utils");
@@ -127,6 +125,20 @@ function substituteParams(original, params) {
127
125
  return JSON.parse(s);
128
126
  }
129
127
  exports.substituteParams = substituteParams;
128
+ async function substituteSecretParams(projectNumber, params) {
129
+ const newParams = {};
130
+ for await (const [key, value] of Object.entries(params)) {
131
+ if (typeof value !== "string") {
132
+ newParams[key] =
133
+ `projects/${projectNumber}/secrets/${value.name}/versions/latest`;
134
+ }
135
+ else {
136
+ newParams[key] = value;
137
+ }
138
+ }
139
+ return newParams;
140
+ }
141
+ exports.substituteSecretParams = substituteSecretParams;
130
142
  function populateDefaultParams(paramVars, paramSpecs) {
131
143
  const newParams = paramVars;
132
144
  for (const param of paramSpecs) {
@@ -347,6 +359,14 @@ async function promptForReleaseStage(args) {
347
359
  }
348
360
  return stage;
349
361
  }
362
+ async function checkExtensionsApiEnabled(options) {
363
+ const projectId = (0, projectUtils_1.getProjectId)(options);
364
+ if (!projectId) {
365
+ return false;
366
+ }
367
+ return await (0, ensureApiEnabled_1.check)(projectId, (0, api_1.extensionsOrigin)(), "extensions", options.markdown);
368
+ }
369
+ exports.checkExtensionsApiEnabled = checkExtensionsApiEnabled;
350
370
  async function ensureExtensionsApiEnabled(options) {
351
371
  const projectId = (0, projectUtils_1.getProjectId)(options);
352
372
  if (!projectId) {
@@ -416,12 +436,12 @@ function validateReleaseNotes(rootDirectory, newVersion, extension) {
416
436
  catch (err) {
417
437
  throw new error_1.FirebaseError("No CHANGELOG.md file found. " +
418
438
  "Please create one and add an entry for this version. " +
419
- (0, marked_1.marked)("See https://firebase.google.com/docs/extensions/publishers/user-documentation#writing-changelog for more details."));
439
+ "See https://firebase.google.com/docs/extensions/publishers/user-documentation#writing-changelog for more details.");
420
440
  }
421
441
  if (!notes && !semver.prerelease(newVersion) && extension) {
422
442
  throw new error_1.FirebaseError(`No entry for version ${newVersion} found in CHANGELOG.md. ` +
423
443
  "Please add one so users know what has changed in this version. " +
424
- (0, marked_1.marked)("See https://firebase.google.com/docs/extensions/publishers/user-documentation#writing-changelog for more details."));
444
+ "See https://firebase.google.com/docs/extensions/publishers/user-documentation#writing-changelog for more details.");
425
445
  }
426
446
  return notes;
427
447
  }
@@ -472,7 +492,7 @@ function displayExtensionHeader(extensionRef, extension, extensionRoot) {
472
492
  }
473
493
  else {
474
494
  logger_1.logger.info(`\n${clc.bold("Extension:")} ${extensionRef}\n` +
475
- `${clc.bold("State:")} ${clc.bold(clc.blue("New"))}\n`);
495
+ `${clc.bold("State:")} ${clc.bold(clc.blueBright("New"))}\n`);
476
496
  }
477
497
  }
478
498
  async function fetchExtensionSource(repoUri, sourceRef, extensionRoot) {
@@ -698,7 +718,7 @@ async function uploadExtensionVersionFromLocalSource(args) {
698
718
  }
699
719
  exports.uploadExtensionVersionFromLocalSource = uploadExtensionVersionFromLocalSource;
700
720
  function getMissingPublisherError(publisherId) {
701
- return new error_1.FirebaseError((0, marked_1.marked)(`Couldn't find publisher ID '${clc.bold(publisherId)}'. Please ensure that you have registered this ID. For step-by-step instructions on getting started as a publisher, see https://firebase.google.com/docs/extensions/publishers/get-started.`));
721
+ return new error_1.FirebaseError(`Couldn't find publisher ID '${clc.bold(publisherId)}'. Please ensure that you have registered this ID. For step-by-step instructions on getting started as a publisher, see https://firebase.google.com/docs/extensions/publishers/get-started.`);
702
722
  }
703
723
  exports.getMissingPublisherError = getMissingPublisherError;
704
724
  async function createSourceFromLocation(projectId, sourceUri) {
@@ -793,7 +813,7 @@ async function instanceIdExists(projectId, instanceId) {
793
813
  if (err.status === 404) {
794
814
  return false;
795
815
  }
796
- const msg = `Unexpected error when checking if instance ID exists: ${err}`;
816
+ const msg = `Unexpected error when checking if instance ID exists: ${err.message}`;
797
817
  throw new error_1.FirebaseError(msg, {
798
818
  original: err,
799
819
  });
@@ -38,7 +38,7 @@ function readFile(pathToFile) {
38
38
  }
39
39
  catch (err) {
40
40
  if (err.code === "ENOENT") {
41
- throw new error_1.FirebaseError(`Could not find "${pathToFile}""`, { original: err });
41
+ throw new error_1.FirebaseError(`Could not find "${pathToFile}"`, { original: err });
42
42
  }
43
43
  throw new error_1.FirebaseError(`Failed to read file at "${pathToFile}"`, { original: err });
44
44
  }
@@ -64,7 +64,7 @@ async function checkProducts(projectId, usedProducts) {
64
64
  "without server-side code.\n";
65
65
  errorMessage += ` https://console.firebase.google.com/project/${projectId}/authentication/users`;
66
66
  }
67
- throw new error_1.FirebaseError((0, marked_1.marked)(errorMessage), { exit: 2 });
67
+ throw new error_1.FirebaseError(await (0, marked_1.marked)(errorMessage), { exit: 2 });
68
68
  }
69
69
  }
70
70
  function getUsedProducts(spec) {
@@ -7,13 +7,16 @@ const refRegex = new RegExp(/^([^/@\n]+)\/{1}([^/@\n]+)(@{1}([^\n]+)|)$/);
7
7
  function parse(refOrName) {
8
8
  const ret = parseRef(refOrName) || parseName(refOrName);
9
9
  if (!ret || !ret.publisherId || !ret.extensionId) {
10
- throw new error_1.FirebaseError(`Unable to parse ${refOrName} as an extension ref`);
10
+ throw new error_1.FirebaseError(`Unable to parse ${refOrName} as an extension ref.\n` +
11
+ "Expected format is either publisherId/extensionId@version or " +
12
+ "publishers/publisherId/extensions/extensionId/versions/version. If you " +
13
+ "are referring to a local extension directory, please ensure the directory exists.");
11
14
  }
12
15
  if (ret.version &&
13
16
  !semver.valid(ret.version) &&
14
17
  !semver.validRange(ret.version) &&
15
18
  !["latest", "latest-approved"].includes(ret.version)) {
16
- throw new error_1.FirebaseError(`Extension reference ${ret} contains an invalid version ${ret.version}.`);
19
+ throw new error_1.FirebaseError(`Extension reference ${JSON.stringify(ret, null, 2)} contains an invalid version ${ret.version}.`);
17
20
  }
18
21
  return ret;
19
22
  }
@@ -21,19 +24,31 @@ exports.parse = parse;
21
24
  function parseRef(ref) {
22
25
  const parts = refRegex.exec(ref);
23
26
  if (parts && (parts.length === 5 || parts.length === 7)) {
24
- const publisherId = parts[1];
25
- const extensionId = parts[2];
26
- const version = parts[4];
27
- return { publisherId, extensionId, version };
27
+ return {
28
+ publisherId: parts[1],
29
+ extensionId: parts[2],
30
+ version: parts[4],
31
+ };
28
32
  }
29
33
  }
30
34
  function parseName(name) {
31
35
  const parts = name.split("/");
32
- return {
33
- publisherId: parts[1],
34
- extensionId: parts[3],
35
- version: parts[5],
36
- };
36
+ if (parts[0] !== "publishers" || parts[2] !== "extensions") {
37
+ return;
38
+ }
39
+ if (parts.length === 4) {
40
+ return {
41
+ publisherId: parts[1],
42
+ extensionId: parts[3],
43
+ };
44
+ }
45
+ if (parts.length === 6 && parts[4] === "versions") {
46
+ return {
47
+ publisherId: parts[1],
48
+ extensionId: parts[3],
49
+ version: parts[5],
50
+ };
51
+ }
37
52
  }
38
53
  function toExtensionRef(ref) {
39
54
  return `${ref.publisherId}/${ref.extensionId}`;