firebase-tools 15.32.0 → 15.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -191,13 +191,14 @@ function validateRequiredParameters(options) {
191
191
  case "MD5":
192
192
  case "SHA1":
193
193
  case "SHA256":
194
- case "SHA512":
194
+ case "SHA512": {
195
195
  roundsNum = parseInt(options.rounds, 10);
196
196
  const minRounds = hashAlgo === "MD5" ? 0 : 1;
197
197
  if (isNaN(roundsNum) || roundsNum < minRounds || roundsNum > 8192) {
198
198
  throw new error_1.FirebaseError(`Must provide valid rounds(${minRounds}..8192) for hash algorithm ${options.hashAlgo}`);
199
199
  }
200
200
  return { hashAlgo: hashAlgo, rounds: options.rounds, valid: true };
201
+ }
201
202
  case "PBKDF_SHA1":
202
203
  case "PBKDF2_SHA256":
203
204
  roundsNum = parseInt(options.rounds, 10);
@@ -205,7 +206,7 @@ function validateRequiredParameters(options) {
205
206
  throw new error_1.FirebaseError("Must provide valid rounds(0..120000) for hash algorithm " + options.hashAlgo);
206
207
  }
207
208
  return { hashAlgo: hashAlgo, rounds: options.rounds, valid: true };
208
- case "SCRYPT":
209
+ case "SCRYPT": {
209
210
  if (!options.hashKey || options.hashKey === "") {
210
211
  throw new error_1.FirebaseError("Must provide hash key(base64 encoded) for hash algorithm " + options.hashAlgo);
211
212
  }
@@ -229,9 +230,10 @@ function validateRequiredParameters(options) {
229
230
  memCost: options.memCost,
230
231
  valid: true,
231
232
  };
233
+ }
232
234
  case "BCRYPT":
233
235
  return { hashAlgo: hashAlgo, valid: true };
234
- case "STANDARD_SCRYPT":
236
+ case "STANDARD_SCRYPT": {
235
237
  const cpuMemCost = parseInt(options.memCost, 10);
236
238
  const parallelization = parseInt(options.parallelization, 10);
237
239
  const blockSize = parseInt(options.blockSize, 10);
@@ -244,6 +246,7 @@ function validateRequiredParameters(options) {
244
246
  blockSize: blockSize,
245
247
  dkLen: dkLen,
246
248
  };
249
+ }
247
250
  default:
248
251
  throw new error_1.FirebaseError("Unsupported hash algorithm " + clc.bold(options.hashAlgo));
249
252
  }
package/lib/api.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.rulesOrigin = exports.resourceManagerOrigin = exports.firebaseTelemetryAdminOrigin = exports.firebaseTelemetryOrigin = exports.crashlyticsApiOrigin = exports.messagingApiOrigin = exports.remoteConfigApiOrigin = exports.rtdbMetadataOrigin = exports.rtdbManagementOrigin = exports.realtimeOrigin = exports.extensionsTOSOrigin = exports.extensionsPublisherOrigin = exports.extensionsOrigin = exports.iamOrigin = exports.identityOrigin = exports.hostingOrigin = exports.googleOrigin = exports.pubsubOrigin = exports.cloudTasksOrigin = exports.cloudschedulerOrigin = exports.cloudbuildOrigin = exports.functionsDefaultRegion = exports.runOrigin = exports.functionsV2Origin = exports.functionsOrigin = exports.firestoreOrigin = exports.firestoreOriginOrEmulator = exports.firedataOrigin = exports.firebaseExtensionsRegistryOrigin = exports.firebaseApiOrigin = exports.eventarcOrigin = exports.consoleOrigin = exports.authManagementOrigin = exports.authOrigin = exports.apphostingGitHubAppInstallationURL = exports.apphostingP4SADomain = exports.apphostingOrigin = exports.appDistributionOrigin = exports.appCheckOrigin = exports.apiKeysOrigin = exports.artifactRegistryDomain = exports.developerConnectP4SADomain = exports.developerConnectOrigin = exports.containerRegistryDomain = exports.cloudMonitoringOrigin = exports.cloudloggingOrigin = exports.cloudbillingOrigin = exports.clientSecret = exports.clientId = exports.authProxyOrigin = void 0;
4
- exports.developerKnowledgeOrigin = exports.cloudTestingOrigin = exports.appTestingOrigin = exports.aiLogicProxyOrigin = exports.vertexAIOrigin = exports.cloudSQLAdminOrigin = exports.dataConnectLocalConnString = exports.dataconnectP4SADomain = exports.dataconnectOrigin = exports.githubClientSecret = exports.githubClientId = exports.computeOrigin = exports.secretManagerOrigin = exports.githubApiOrigin = exports.githubOrigin = exports.studioApiOrigin = exports.serviceUsageOrigin = exports.cloudRunApiOrigin = exports.hostingApiOrigin = exports.firebaseStorageOrigin = exports.storageOrigin = exports.runtimeconfigOrigin = void 0;
3
+ exports.runtimeconfigOrigin = exports.rulesOrigin = exports.resourceManagerOrigin = exports.firebaseTelemetryAdminOrigin = exports.crashlyticsApiOrigin = exports.messagingApiOrigin = exports.remoteConfigApiOrigin = exports.rtdbMetadataOrigin = exports.rtdbManagementOrigin = exports.realtimeOrigin = exports.extensionsTOSOrigin = exports.extensionsPublisherOrigin = exports.extensionsOrigin = exports.iamOrigin = exports.identityOrigin = exports.hostingOrigin = exports.googleOrigin = exports.pubsubOrigin = exports.cloudTasksOrigin = exports.cloudschedulerOrigin = exports.cloudbuildOrigin = exports.functionsDefaultRegion = exports.runOrigin = exports.functionsV2Origin = exports.functionsOrigin = exports.firestoreOrigin = exports.firestoreOriginOrEmulator = exports.firedataOrigin = exports.firebaseExtensionsRegistryOrigin = exports.firebaseApiOrigin = exports.eventarcOrigin = exports.consoleOrigin = exports.authManagementOrigin = exports.authOrigin = exports.apphostingGitHubAppInstallationURL = exports.apphostingP4SADomain = exports.apphostingOrigin = exports.appDistributionOrigin = exports.appCheckOrigin = exports.apiKeysOrigin = exports.artifactRegistryDomain = exports.developerConnectP4SADomain = exports.developerConnectOrigin = exports.containerRegistryDomain = exports.cloudMonitoringOrigin = exports.cloudloggingOrigin = exports.cloudbillingOrigin = exports.clientSecret = exports.clientId = exports.authProxyOrigin = void 0;
4
+ exports.developerKnowledgeOrigin = exports.cloudTestingOrigin = exports.appTestingOrigin = exports.aiLogicProxyOrigin = exports.vertexAIOrigin = exports.cloudSQLAdminOrigin = exports.dataConnectLocalConnString = exports.dataconnectP4SADomain = exports.dataconnectOrigin = exports.githubClientSecret = exports.githubClientId = exports.computeOrigin = exports.secretManagerOrigin = exports.githubApiOrigin = exports.githubOrigin = exports.studioApiOrigin = exports.serviceUsageOrigin = exports.cloudRunApiOrigin = exports.hostingApiOrigin = exports.firebaseStorageOrigin = exports.storageOrigin = void 0;
5
5
  exports.getScopes = getScopes;
6
6
  exports.setScopes = setScopes;
7
7
  const constants_1 = require("./emulator/constants");
@@ -106,8 +106,6 @@ const messagingApiOrigin = () => utils.envOverride("FIREBASE_MESSAGING_CONFIG_UR
106
106
  exports.messagingApiOrigin = messagingApiOrigin;
107
107
  const crashlyticsApiOrigin = () => utils.envOverride("FIREBASE_CRASHLYTICS_URL", "https://firebasecrashlytics.googleapis.com");
108
108
  exports.crashlyticsApiOrigin = crashlyticsApiOrigin;
109
- const firebaseTelemetryOrigin = () => utils.envOverride("FIREBASE_TELEMETRY_URL", "https://firebasetelemetry.googleapis.com");
110
- exports.firebaseTelemetryOrigin = firebaseTelemetryOrigin;
111
109
  const firebaseTelemetryAdminOrigin = () => utils.envOverride("FIREBASE_TELEMETRY_ADMIN_URL", "https://firebasetelemetryadmin.googleapis.com");
112
110
  exports.firebaseTelemetryAdminOrigin = firebaseTelemetryAdminOrigin;
113
111
  const resourceManagerOrigin = () => utils.envOverride("FIREBASE_RESOURCEMANAGER_URL", "https://cloudresourcemanager.googleapis.com");
@@ -200,8 +200,13 @@ async function upsertSecret(project, secret, location) {
200
200
  existing = await gcsm.getSecret(project, secret);
201
201
  }
202
202
  catch (err) {
203
- if ((0, error_1.getErrStatus)(err) !== 404) {
204
- throw new error_1.FirebaseError("Unexpected error loading secret", { original: (0, error_1.getError)(err) });
203
+ const status = (0, error_1.getErrStatus)(err);
204
+ if (status !== 404) {
205
+ const original = (0, error_1.getError)(err);
206
+ throw new error_1.FirebaseError(`Unexpected error loading secret: ${original.message}`, {
207
+ original,
208
+ status,
209
+ });
205
210
  }
206
211
  await gcsm.createSecret(project, secret, gcsm.labels("apphosting"), location);
207
212
  return true;
package/lib/command.js CHANGED
@@ -272,7 +272,7 @@ class Command {
272
272
  const options = (0, lodash_1.last)(args);
273
273
  await this.prepare(options);
274
274
  if (this.name.startsWith("ext:") && experiments.isEnabled("extdeprecationwarnings")) {
275
- (0, warnings_1.showDeprecationWarningBefore)(this.name, options);
275
+ await (0, warnings_1.showDeprecationWarningBefore)(this.name, options, args);
276
276
  }
277
277
  for (const before of this.befores) {
278
278
  await before.fn(options, ...before.args);
package/lib/config.js CHANGED
@@ -298,6 +298,7 @@ Config.MATERIALIZE_TARGETS = [
298
298
  "apphosting",
299
299
  "auth",
300
300
  "ailogic",
301
+ "run",
301
302
  ];
302
303
  function stringifyContent(content) {
303
304
  if (typeof content === "string") {
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NOTIFICATION_CHANNELS_MASK_PATH = exports.EMAIL_CHANNEL_TYPE = exports.FIREBASE_EMAIL_CHANNEL_DISPLAY_NAME_SUFFIX = exports.FIREBASE_CHANNEL_LABEL = void 0;
4
+ exports.generateAlertPolicy = generateAlertPolicy;
5
+ exports.fetchFirebaseEmailChannel = fetchFirebaseEmailChannel;
6
+ exports.createEmailChannel = createEmailChannel;
7
+ exports.resolveEmailNotificationChannel = resolveEmailNotificationChannel;
8
+ exports.addChannelToPolicy = addChannelToPolicy;
9
+ exports.enableAlert = enableAlert;
10
+ exports.enableAlerts = enableAlerts;
11
+ const error_1 = require("../error");
12
+ const cloudmonitoring_1 = require("../gcp/cloudmonitoring");
13
+ const logger_1 = require("../logger");
14
+ const utils_1 = require("./utils");
15
+ exports.FIREBASE_CHANNEL_LABEL = "is_firebase_channel";
16
+ exports.FIREBASE_EMAIL_CHANNEL_DISPLAY_NAME_SUFFIX = " - for Firebase alerts";
17
+ exports.EMAIL_CHANNEL_TYPE = "email";
18
+ exports.NOTIFICATION_CHANNELS_MASK_PATH = "notification_channels";
19
+ async function generateAlertPolicy(projectId, appId, alertType) {
20
+ logger_1.logger.debug(`[crashlytics] generateAlertPolicy called with projectId: ${projectId}, appId: ${appId}, alertType: ${alertType}`);
21
+ try {
22
+ const response = await utils_1.CRASHLYTICS_API_CLIENT.request({
23
+ method: "POST",
24
+ headers: {
25
+ "Content-Type": "application/json",
26
+ },
27
+ path: `/projects/${projectId}/apps/${appId}:generateAlertPolicy`,
28
+ body: { alertType },
29
+ timeout: utils_1.TIMEOUT,
30
+ });
31
+ return response.body.alertPolicy;
32
+ }
33
+ catch (err) {
34
+ const status = (0, error_1.getErrStatus)(err);
35
+ const msg = (0, error_1.getErrMsg)(err);
36
+ throw new error_1.FirebaseError(`Failed to generate Crashlytics alert policy for ${alertType} on app ${appId} (status ${status}): ${msg}`, { original: (0, error_1.getError)(err), status });
37
+ }
38
+ }
39
+ async function fetchFirebaseEmailChannel(projectId, userEmail) {
40
+ const escapedEmail = userEmail.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
41
+ const filter = `type = "${exports.EMAIL_CHANNEL_TYPE}" AND ` +
42
+ `labels.email_address = "${escapedEmail}" AND ` +
43
+ `user_labels.${exports.FIREBASE_CHANNEL_LABEL} = "true"`;
44
+ const channels = await (0, cloudmonitoring_1.listNotificationChannels)(projectId, filter);
45
+ return channels[0];
46
+ }
47
+ async function createEmailChannel(projectId, userEmail) {
48
+ return await (0, cloudmonitoring_1.createNotificationChannel)(projectId, {
49
+ type: exports.EMAIL_CHANNEL_TYPE,
50
+ displayName: `${userEmail}${exports.FIREBASE_EMAIL_CHANNEL_DISPLAY_NAME_SUFFIX}`,
51
+ labels: {
52
+ email_address: userEmail,
53
+ },
54
+ userLabels: {
55
+ [exports.FIREBASE_CHANNEL_LABEL]: "true",
56
+ },
57
+ });
58
+ }
59
+ async function resolveEmailNotificationChannel(projectId, userEmail) {
60
+ const existingChannel = await fetchFirebaseEmailChannel(projectId, userEmail);
61
+ return existingChannel ?? (await createEmailChannel(projectId, userEmail));
62
+ }
63
+ function addChannelToPolicy(policy, channelName) {
64
+ const currentChannels = policy.notificationChannels ?? [];
65
+ if (currentChannels.includes(channelName)) {
66
+ return policy;
67
+ }
68
+ return {
69
+ ...policy,
70
+ notificationChannels: [...currentChannels, channelName],
71
+ };
72
+ }
73
+ async function enableAlert(projectId, appId, alertType, target) {
74
+ let channel;
75
+ if (!target.channelName && target.userEmail) {
76
+ channel = await resolveEmailNotificationChannel(projectId, target.userEmail);
77
+ }
78
+ else if (!target.channelName) {
79
+ throw new error_1.FirebaseError("Either channelName or userEmail must be specified to enable a Crashlytics alert.", { exit: 1 });
80
+ }
81
+ const channelName = target.channelName ?? channel?.name;
82
+ if (!channelName) {
83
+ throw new error_1.FirebaseError("Resolved notification channel is missing a resource name.", {
84
+ exit: 1,
85
+ });
86
+ }
87
+ const policyResourceName = await generateAlertPolicy(projectId, appId, alertType);
88
+ const targetPolicy = await (0, cloudmonitoring_1.getAlertPolicy)(policyResourceName);
89
+ const policyWithChannel = addChannelToPolicy(targetPolicy, channelName);
90
+ const updatedPolicy = policyWithChannel === targetPolicy
91
+ ? targetPolicy
92
+ : await (0, cloudmonitoring_1.updateAlertPolicy)(policyWithChannel, exports.NOTIFICATION_CHANNELS_MASK_PATH);
93
+ return { channel, policy: updatedPolicy };
94
+ }
95
+ async function enableAlerts(projectId, appId, alertTypes, userEmail) {
96
+ if (alertTypes.length === 0) {
97
+ return [];
98
+ }
99
+ const channel = await resolveEmailNotificationChannel(projectId, userEmail);
100
+ const channelName = channel.name;
101
+ if (!channelName) {
102
+ throw new error_1.FirebaseError("Notification channel for Crashlytics alerts is missing a name.", {
103
+ exit: 1,
104
+ });
105
+ }
106
+ const results = await Promise.allSettled(alertTypes.map(async (alertType) => {
107
+ const { policy } = await enableAlert(projectId, appId, alertType, {
108
+ channelName,
109
+ });
110
+ return policy;
111
+ }));
112
+ const policies = [];
113
+ for (const res of results) {
114
+ if (res.status === "fulfilled") {
115
+ policies.push(res.value);
116
+ }
117
+ else {
118
+ logger_1.logger.debug(`[crashlytics] Failed to enable alert: ${(0, error_1.getErrMsg)(res.reason)}`);
119
+ }
120
+ }
121
+ return policies;
122
+ }
@@ -4,16 +4,34 @@ exports.CRASHLYTICS_TELEMETRY_SERVICE = exports.CRASHLYTICS_TELEMETRY_RESOURCE_T
4
4
  exports.onboardCrashlyticsWeb = onboardCrashlyticsWeb;
5
5
  const ensureApiEnabled_1 = require("../ensureApiEnabled");
6
6
  const error_1 = require("../error");
7
+ const experiments = require("../experiments");
7
8
  const cloudbilling_1 = require("../gcp/cloudbilling");
8
9
  const cloudlogging_1 = require("../gcp/cloudlogging");
10
+ const alerts_1 = require("./alerts");
9
11
  const firebasetelemetry_1 = require("./firebasetelemetry");
12
+ const types_1 = require("./types");
10
13
  const utils_1 = require("../utils");
11
14
  const apikeys_1 = require("../gcp/apikeys");
12
15
  const apps_1 = require("../management/apps");
16
+ const logger_1 = require("../logger");
17
+ const prompt_1 = require("../prompt");
18
+ const requireAuth_1 = require("../requireAuth");
13
19
  exports.CRASHLYTICS_TELEMETRY_BUCKET_ID = "firebase-telemetry";
14
20
  exports.CRASHLYTICS_TELEMETRY_SINK_ID = "firebase-telemetry-routing";
15
21
  exports.CRASHLYTICS_TELEMETRY_RESOURCE_TYPE = "firebasetelemetry.googleapis.com/App";
16
22
  exports.CRASHLYTICS_TELEMETRY_SERVICE = "firebasetelemetry.googleapis.com";
23
+ async function resolveAuthenticatedUserEmail(options) {
24
+ if (options.user?.email) {
25
+ return options.user.email;
26
+ }
27
+ try {
28
+ return (await (0, requireAuth_1.requireAuth)(options)) ?? undefined;
29
+ }
30
+ catch (err) {
31
+ logger_1.logger.debug(`[crashlytics] Failed to resolve authenticated user email: ${(0, error_1.getErrMsg)(err)}`);
32
+ return undefined;
33
+ }
34
+ }
17
35
  async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
18
36
  const billingEnabled = await (0, cloudbilling_1.checkBillingEnabled)(projectId);
19
37
  if (!billingEnabled && options.nonInteractive) {
@@ -58,5 +76,40 @@ async function onboardCrashlyticsWeb(projectId, appId, options = {}) {
58
76
  (0, utils_1.logLabeledBullet)("crashlytics", "Configuring Crashlytics telemetry for web app...");
59
77
  const config = await (0, firebasetelemetry_1.createOrUpdateTelemetryConfig)(projectId, appId, `projects/${projectId}/locations/global/buckets/${exports.CRASHLYTICS_TELEMETRY_BUCKET_ID}`, 1);
60
78
  (0, utils_1.logLabeledSuccess)("crashlytics", "Crashlytics telemetry configured successfully.");
61
- return { bucket, sink, config };
79
+ if (!experiments.isEnabled("crashlyticsWebAlerts") || options.nonInteractive) {
80
+ return { bucket, sink, config };
81
+ }
82
+ const userEmail = await resolveAuthenticatedUserEmail(options);
83
+ if (!userEmail) {
84
+ (0, utils_1.logLabeledWarning)("crashlytics", "Unable to determine authenticated user email for alert setup. You can configure alerts later in the Firebase Console.");
85
+ return { bucket, sink, config };
86
+ }
87
+ const selectedAlerts = await (0, prompt_1.checkbox)({
88
+ message: "Which email alerts would you like to enable? (Optional)",
89
+ choices: [
90
+ {
91
+ name: "New issues (Notify when a new issue is detected)",
92
+ value: types_1.AlertType.ALERT_TYPE_NEW_ISSUE,
93
+ checked: true,
94
+ },
95
+ {
96
+ name: "Regressed issues (Notify when a closed issue reoccurs)",
97
+ value: types_1.AlertType.ALERT_TYPE_REGRESSED_ISSUE,
98
+ checked: true,
99
+ },
100
+ ],
101
+ });
102
+ if (selectedAlerts.length === 0) {
103
+ return { bucket, sink, config };
104
+ }
105
+ (0, utils_1.logLabeledBullet)("crashlytics", `Setting up Crashlytics email alerts for ${userEmail}...`);
106
+ try {
107
+ const alertPolicies = await (0, alerts_1.enableAlerts)(projectId, appId, selectedAlerts, userEmail);
108
+ (0, utils_1.logLabeledSuccess)("crashlytics", "Crashlytics email alerts configured successfully.");
109
+ return { bucket, sink, config, alertPolicies };
110
+ }
111
+ catch (err) {
112
+ (0, utils_1.logLabeledWarning)("crashlytics", (0, error_1.getErrMsg)(err));
113
+ return { bucket, sink, config };
114
+ }
62
115
  }
@@ -304,7 +304,7 @@ async function uploadMap(request, attemptsRemaining = 0) {
304
304
  const tmpArchive = await (0, archiveFile_1.archiveFile)(filePath, { archivedFileName: "mapping.js.map" });
305
305
  const appId = options.app || "";
306
306
  const gcsFile = `${appId}-${appVersion}-${normalizeFileName(obfuscatedPath)}.zip`;
307
- const uid = (0, utils_1.murmurHashV3)(`${appId}-${appVersion}-${obfuscatedPath}`);
307
+ const uid = (0, utils_1.murmurHashV3)(obfuscatedPath);
308
308
  const name = `projects/${projectId}/locations/global/mappingFiles/${uid}`;
309
309
  const stream = fs.createReadStream(tmpArchive);
310
310
  stream.on("error", (err) => {
@@ -316,15 +316,15 @@ async function uploadMap(request, attemptsRemaining = 0) {
316
316
  stream,
317
317
  }, bucketName);
318
318
  const fileUri = `gs://${bucket}/${object}`;
319
- logger_1.logger.debug(`Uploaded mapping file ${filePath} to ${fileUri}`);
319
+ logger_1.logger.debug(`Uploaded mapping file ${filePath} to GCS: ${fileUri}`);
320
320
  await registerSourceMap({
321
321
  name,
322
322
  appId,
323
323
  version: appVersion,
324
324
  obfuscatedFilePath: `/${obfuscatedPath}`,
325
325
  fileUri,
326
- });
327
- logger_1.logger.debug(`Registered mapping file ${filePath}`);
326
+ }, options);
327
+ logger_1.logger.debug(`Successfully registered source map in Firebase Telemetry for /${obfuscatedPath}`);
328
328
  return true;
329
329
  }
330
330
  catch (e) {
@@ -351,10 +351,45 @@ function isAlreadyExistsError(e) {
351
351
  return false;
352
352
  }
353
353
  const message = e.message.toLowerCase();
354
- const bodyMessage = (e.context?.body?.error?.message ?? "").toLowerCase();
354
+ const context = e.context;
355
+ const bodyMessage = (context?.body?.error?.message ?? "").toLowerCase();
355
356
  return message.includes("already exists") || bodyMessage.includes("already exists");
356
357
  }
357
- async function registerSourceMap(sourceMap) {
358
+ async function listAllMappingFiles(client, collectionPath) {
359
+ const cache = new Map();
360
+ let pageToken;
361
+ do {
362
+ const queryParams = {};
363
+ if (pageToken) {
364
+ queryParams.pageToken = pageToken;
365
+ }
366
+ const listResponse = await client.get(collectionPath, { queryParams });
367
+ for (const mappingFile of listResponse.body?.mappingFiles ?? []) {
368
+ if (mappingFile.obfuscatedFilePath && mappingFile.name) {
369
+ cache.set(mappingFile.obfuscatedFilePath, mappingFile.name);
370
+ }
371
+ }
372
+ pageToken = listResponse.body?.nextPageToken;
373
+ } while (pageToken);
374
+ return cache;
375
+ }
376
+ function getOrListAllMappingFiles(client, collectionPath, options) {
377
+ if (options) {
378
+ options.__mappingFilesCache ?? (options.__mappingFilesCache = listAllMappingFiles(client, collectionPath).catch((err) => {
379
+ delete options.__mappingFilesCache;
380
+ throw err;
381
+ }));
382
+ return options.__mappingFilesCache;
383
+ }
384
+ return listAllMappingFiles(client, collectionPath);
385
+ }
386
+ async function findExistingSourceMapName(client, sourceMap, options) {
387
+ const lastSlashIndex = sourceMap.name.lastIndexOf("/");
388
+ const collectionPath = lastSlashIndex === -1 ? sourceMap.name : sourceMap.name.slice(0, lastSlashIndex);
389
+ const cache = await getOrListAllMappingFiles(client, collectionPath, options);
390
+ return cache.get(sourceMap.obfuscatedFilePath);
391
+ }
392
+ async function registerSourceMap(sourceMap, options) {
358
393
  const client = new apiv2_1.Client({
359
394
  urlPrefix: "https://firebasetelemetryadmin.googleapis.com",
360
395
  auth: true,
@@ -362,7 +397,6 @@ async function registerSourceMap(sourceMap) {
362
397
  });
363
398
  const patchSourceMap = async () => {
364
399
  await client.patch(sourceMap.name, sourceMap, { queryParams: { allowMissing: "true" } });
365
- logger_1.logger.debug(`Registered source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry service`);
366
400
  };
367
401
  try {
368
402
  await patchSourceMap();
@@ -374,16 +408,17 @@ async function registerSourceMap(sourceMap) {
374
408
  }
375
409
  if (isAlreadyExistsError(e)) {
376
410
  try {
377
- logger_1.logger.debug(`Source map ${sourceMap.obfuscatedFilePath} already exists, deleting and re-registering`);
378
- await client.delete(sourceMap.name);
411
+ logger_1.logger.debug(`Source map ${sourceMap.obfuscatedFilePath} already exists, deleting and re-registering...`);
412
+ const existingName = (await findExistingSourceMapName(client, sourceMap, options)) ?? sourceMap.name;
413
+ await client.delete(existingName);
379
414
  await patchSourceMap();
380
415
  return;
381
416
  }
382
417
  catch (retryErr) {
383
- throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry service:\n${retryErr instanceof Error ? retryErr.message : String(retryErr)}`, { original: retryErr instanceof Error ? retryErr : undefined });
418
+ throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry:\n${retryErr instanceof Error ? retryErr.message : String(retryErr)}`, { original: retryErr instanceof Error ? retryErr : undefined });
384
419
  }
385
420
  }
386
421
  }
387
- throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry service:\n${e instanceof Error ? e.message : String(e)}`, { original: e instanceof Error ? e : undefined });
422
+ throw new error_1.FirebaseError(`Failed to register source map ${sourceMap.obfuscatedFilePath} with Firebase Telemetry:\n${e instanceof Error ? e.message : String(e)}`, { original: e instanceof Error ? e : undefined });
388
423
  }
389
424
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TimeGranularity = exports.ThreadState = exports.Signal = exports.State = exports.SessionEventType = exports.FormFactor = exports.TrackType = exports.ErrorType = void 0;
3
+ exports.AlertType = exports.TimeGranularity = exports.ThreadState = exports.Signal = exports.State = exports.SessionEventType = exports.FormFactor = exports.TrackType = exports.ErrorType = void 0;
4
4
  var ErrorType;
5
5
  (function (ErrorType) {
6
6
  ErrorType["ERROR_TYPE_UNSPECIFIED"] = "ERROR_TYPE_UNSPECIFIED";
@@ -65,3 +65,8 @@ var TimeGranularity;
65
65
  TimeGranularity["TIME_GRANULARITY_HOUR"] = "TIME_GRANULARITY_HOUR";
66
66
  TimeGranularity["TIME_GRANULARITY_DAY"] = "TIME_GRANULARITY_DAY";
67
67
  })(TimeGranularity || (exports.TimeGranularity = TimeGranularity = {}));
68
+ exports.AlertType = {
69
+ ALERT_TYPE_UNSPECIFIED: "ALERT_TYPE_UNSPECIFIED",
70
+ ALERT_TYPE_NEW_ISSUE: "ALERT_TYPE_NEW_ISSUE",
71
+ ALERT_TYPE_REGRESSED_ISSUE: "ALERT_TYPE_REGRESSED_ISSUE",
72
+ };
@@ -417,7 +417,7 @@ async function promptIntParam(param, resolvedDefault) {
417
417
  async function promptResourceString(prompt, input, projectId, resolvedDefault) {
418
418
  const notFound = new error_1.FirebaseError(`No instances of ${input.resource.type} found.`);
419
419
  switch (input.resource.type) {
420
- case "storage.googleapis.com/Bucket":
420
+ case "storage.googleapis.com/Bucket": {
421
421
  const buckets = (await (0, storage_1.listBuckets)(projectId)).map((b) => b.name);
422
422
  if (buckets.length === 0) {
423
423
  throw notFound;
@@ -430,6 +430,7 @@ async function promptResourceString(prompt, input, projectId, resolvedDefault) {
430
430
  },
431
431
  };
432
432
  return promptSelect(prompt, forgedInput, resolvedDefault, (res) => res);
433
+ }
433
434
  default:
434
435
  logger_1.logger.warn(`Warning: unknown resource type ${input.resource.type}; defaulting to raw text input...`);
435
436
  return promptText(prompt, { text: {} }, resolvedDefault, true, (res) => res);
@@ -438,7 +439,7 @@ async function promptResourceString(prompt, input, projectId, resolvedDefault) {
438
439
  async function promptResourceStrings(prompt, input, projectId, enforceNonEmpty) {
439
440
  const notFound = new error_1.FirebaseError(`No instances of ${input.resource.type} found.`);
440
441
  switch (input.resource.type) {
441
- case "storage.googleapis.com/Bucket":
442
+ case "storage.googleapis.com/Bucket": {
442
443
  const buckets = (await (0, storage_1.listBuckets)(projectId)).map((b) => b.name);
443
444
  if (buckets.length === 0) {
444
445
  throw notFound;
@@ -451,6 +452,7 @@ async function promptResourceStrings(prompt, input, projectId, enforceNonEmpty)
451
452
  },
452
453
  };
453
454
  return promptSelectMultiple(prompt, forgedInput, undefined, enforceNonEmpty, (res) => res);
455
+ }
454
456
  default:
455
457
  logger_1.logger.warn(`Warning: unknown resource type ${input.resource.type}; defaulting to raw text input...`);
456
458
  return promptText(prompt, { text: {} }, undefined, enforceNonEmpty, (res) => res.split(","));
@@ -660,7 +660,7 @@ function sendOobCode(state, reqBody, ctx) {
660
660
  (0, errors_1.assert)(reqBody.email, "MISSING_EMAIL");
661
661
  email = (0, utils_1.canonicalizeEmailAddress)(reqBody.email);
662
662
  break;
663
- case "PASSWORD_RESET":
663
+ case "PASSWORD_RESET": {
664
664
  mode = "resetPassword";
665
665
  (0, errors_1.assert)(reqBody.email, "MISSING_EMAIL");
666
666
  email = (0, utils_1.canonicalizeEmailAddress)(reqBody.email);
@@ -673,6 +673,7 @@ function sendOobCode(state, reqBody, ctx) {
673
673
  }
674
674
  (0, errors_1.assert)(maybeUser, "EMAIL_NOT_FOUND");
675
675
  break;
676
+ }
676
677
  case "VERIFY_EMAIL":
677
678
  mode = "verifyEmail";
678
679
  if (reqBody.returnOobLink && !reqBody.idToken) {
@@ -798,7 +799,7 @@ function setAccountInfoImpl(state, reqBody, { privileged = false, emulatorUrl =
798
799
  }
799
800
  break;
800
801
  }
801
- case "VERIFY_AND_CHANGE_EMAIL":
802
+ case "VERIFY_AND_CHANGE_EMAIL": {
802
803
  state.deleteOobCode(reqBody.oobCode);
803
804
  const maybeUser = state.getUserByEmail(oob.email);
804
805
  (0, errors_1.assert)(maybeUser, "INVALID_OOB_CODE");
@@ -811,6 +812,7 @@ function setAccountInfoImpl(state, reqBody, { privileged = false, emulatorUrl =
811
812
  newEmail = oob.newEmail;
812
813
  }
813
814
  break;
815
+ }
814
816
  case "RECOVER_EMAIL": {
815
817
  state.deleteOobCode(reqBody.oobCode);
816
818
  const maybeUser = state.getUserByInitialEmail(oob.email);
@@ -1954,12 +1956,13 @@ function fakeFetchUserInfoFromIdp(providerId, claims, samlResponse) {
1954
1956
  });
1955
1957
  break;
1956
1958
  }
1957
- case /^saml\./.exec(providerId)?.input:
1959
+ case /^saml\./.exec(providerId)?.input: {
1958
1960
  const nameId = samlResponse?.assertion?.subject?.nameId;
1959
1961
  response.email = nameId && (0, utils_1.isValidEmailAddress)(nameId) ? nameId : response.email;
1960
1962
  response.emailVerified = true;
1961
1963
  response.rawUserInfo = JSON.stringify(samlResponse?.assertion?.attributeStatements);
1962
1964
  break;
1965
+ }
1963
1966
  case /^oidc\./.exec(providerId)?.input:
1964
1967
  default:
1965
1968
  response.rawUserInfo = JSON.stringify(claims);
@@ -2256,11 +2259,12 @@ function processBlockingFunctionResponse(event, response) {
2256
2259
  case "emailVerified":
2257
2260
  updates[field] = !!userRecord[field];
2258
2261
  break;
2259
- case "customClaims":
2262
+ case "customClaims": {
2260
2263
  const customClaims = JSON.stringify(userRecord.customClaims);
2261
2264
  validateSerializedCustomClaims(customClaims);
2262
2265
  updates.customAttributes = customClaims;
2263
2266
  break;
2267
+ }
2264
2268
  case "sessionClaims":
2265
2269
  if (event !== state_1.BlockingFunctionEvents.BEFORE_SIGN_IN) {
2266
2270
  break;
@@ -17,6 +17,7 @@ class DatabaseEmulator {
17
17
  constructor(args) {
18
18
  this.args = args;
19
19
  this.importedNamespaces = [];
20
+ this.rulesWatchers = [];
20
21
  this.logger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.DATABASE);
21
22
  }
22
23
  async start() {
@@ -32,8 +33,9 @@ class DatabaseEmulator {
32
33
  this.logger.logLabeled("WARN_ONCE", "database", "Could not determine your Realtime Database instance name, so rules hot reloading is disabled.");
33
34
  continue;
34
35
  }
35
- this.rulesWatcher = chokidar.watch(c.rules, { persistent: true, ignoreInitial: true });
36
- this.rulesWatcher.on("change", async () => {
36
+ const watcher = chokidar.watch(c.rules, { persistent: true, ignoreInitial: true });
37
+ this.rulesWatchers.push(watcher);
38
+ watcher.on("change", async () => {
37
39
  await new Promise((res) => setTimeout(res, 5));
38
40
  this.logger.logLabeled("BULLET", "database", `Change detected, updating rules for ${c.instance}...`);
39
41
  try {
@@ -67,7 +69,9 @@ class DatabaseEmulator {
67
69
  }
68
70
  }
69
71
  }
70
- stop() {
72
+ async stop() {
73
+ await Promise.allSettled(this.rulesWatchers.map((w) => w.close()));
74
+ this.rulesWatchers = [];
71
75
  return downloadableEmulators.stop(types_1.Emulators.DATABASE);
72
76
  }
73
77
  getInfo() {
@@ -54,36 +54,36 @@
54
54
  },
55
55
  "dataconnect": {
56
56
  "darwin": {
57
- "version": "3.4.21",
58
- "expectedSize": 33807728,
59
- "expectedChecksum": "c9830bf36efd861a179a7d0f1b476d96",
60
- "expectedChecksumSHA256": "3862f23631fa99ea5114fd59b968b081bab5ac372867591b2d421864f4b30cf7",
61
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-amd64-v3.4.21",
62
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.21"
57
+ "version": "3.4.22",
58
+ "expectedSize": 33825952,
59
+ "expectedChecksum": "525d67a835615fae6dd2f0a2bfd4611c",
60
+ "expectedChecksumSHA256": "cb4e770c275e4b1202ecc5a05e5897636998ed7410f22c3fc594f4c17b0456b3",
61
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-amd64-v3.4.22",
62
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.22"
63
63
  },
64
64
  "darwin_arm64": {
65
- "version": "3.4.21",
66
- "expectedSize": 31900354,
67
- "expectedChecksum": "06baade26a1f16728b6278c5b39166a7",
68
- "expectedChecksumSHA256": "b5df8bb2c55535d77a07b90f4c8120975afb3bac39bacfc74cb945fb8e828378",
69
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-arm64-v3.4.21",
70
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.21"
65
+ "version": "3.4.22",
66
+ "expectedSize": 31935234,
67
+ "expectedChecksum": "f329037c0651536096e7233ead853857",
68
+ "expectedChecksumSHA256": "df4e0db2970d64e1176dda4875ca38ec4c20cc189bc80a758f462b638addda9c",
69
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-arm64-v3.4.22",
70
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.22"
71
71
  },
72
72
  "win32": {
73
- "version": "3.4.21",
74
- "expectedSize": 33837056,
75
- "expectedChecksum": "dbe075ff9320eb9783481f74beccafee",
76
- "expectedChecksumSHA256": "72ddbf8418f54d5e7827204ac3ac88c80a42e445ee0afd1a021cb2dad9196eb0",
77
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-windows-amd64-v3.4.21",
78
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.21.exe"
73
+ "version": "3.4.22",
74
+ "expectedSize": 33855488,
75
+ "expectedChecksum": "7cdc7e6b54e22b61b2b6426df10bdd02",
76
+ "expectedChecksumSHA256": "05454f691c6b2259d2b838e715952105e89dd73184f5eac7dbfe131804f2dc26",
77
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-windows-amd64-v3.4.22",
78
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.22.exe"
79
79
  },
80
80
  "linux": {
81
- "version": "3.4.21",
82
- "expectedSize": 32927928,
83
- "expectedChecksum": "5b42b3b114d52bec9962f5ba2f8548c7",
84
- "expectedChecksumSHA256": "504a5a751a4e3ac6851d6e5dc70caefee698570ead7fe2ef324019dc54c6c473",
85
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-linux-amd64-v3.4.21",
86
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.21"
81
+ "version": "3.4.22",
82
+ "expectedSize": 32948408,
83
+ "expectedChecksum": "7ba899a01fc2819c3235b57c1badaf6e",
84
+ "expectedChecksumSHA256": "2a6eb1ccb8b5419cf22f3fdf87d94b6caf1c6c573115fdcd9baa7ea78274c024",
85
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-linux-amd64-v3.4.22",
86
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.22"
87
87
  }
88
88
  }
89
89
  }
@@ -181,7 +181,7 @@ You can probably fix this by running "npm install ${systemLog.data.name}@latest"
181
181
  case "missing-package-json":
182
182
  this.log("WARN", `The Cloud Functions directory you specified does not have a "package.json" file, so we can't load it.`);
183
183
  break;
184
- case "function-code-resolution-failed":
184
+ case "function-code-resolution-failed": {
185
185
  this.log("WARN", systemLog.data.error);
186
186
  const helper = ["We were unable to load your functions code. (see above)"];
187
187
  if (systemLog.data.isPotentially.wrong_directory) {
@@ -195,6 +195,7 @@ You can probably fix this by running "npm install ${systemLog.data.name}@latest"
195
195
  }
196
196
  utils.logWarning(helper.join("\n"), "warn", this.data);
197
197
  break;
198
+ }
198
199
  case "function-runtimeconfig-json-invalid":
199
200
  this.log("WARN", "Found .runtimeconfig.json but the JSON format is invalid.");
200
201
  break;