firebase-tools 15.34.1 → 15.35.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 (73) hide show
  1. package/lib/api.js +2 -4
  2. package/lib/apphosting/constants.js +1 -4
  3. package/lib/apphosting/utils.js +0 -26
  4. package/lib/commands/apps-android-sha-create.js +1 -1
  5. package/lib/commands/apps-android-sha-delete.js +1 -1
  6. package/lib/commands/apps-android-sha-list.js +1 -1
  7. package/lib/commands/{crashlytics-onboard-web.js → crashlytics-setup.js} +5 -5
  8. package/lib/commands/crashlytics-sourcemap-upload.js +4 -0
  9. package/lib/commands/emulators-start.js +2 -2
  10. package/lib/commands/index.js +5 -6
  11. package/lib/commands/run-services-get.js +19 -0
  12. package/lib/commands/run-services-list.js +11 -0
  13. package/lib/crashlytics/alerts.js +1 -0
  14. package/lib/crashlytics/firebasetelemetry.js +5 -3
  15. package/lib/crashlytics/onboarding.js +15 -23
  16. package/lib/crashlytics/reports.js +46 -17
  17. package/lib/crashlytics/sourcemap.js +19 -5
  18. package/lib/dataconnect/dataplaneClient.js +0 -10
  19. package/lib/deploy/apphosting/deploy.js +20 -41
  20. package/lib/deploy/apphosting/localBuild.js +49 -0
  21. package/lib/deploy/apphosting/prepare.js +12 -25
  22. package/lib/deploy/apphosting/release.js +1 -1
  23. package/lib/deploy/apphosting/util.js +27 -4
  24. package/lib/deploy/functions/containerCleaner.js +1 -142
  25. package/lib/deploy/functions/functionsDeployHelper.js +0 -4
  26. package/lib/deploy/functions/release/fabricator.js +6 -3
  27. package/lib/deploy/functions/validate.js +1 -1
  28. package/lib/deploy/run/deploy.js +26 -43
  29. package/lib/deploy/run/get.js +30 -0
  30. package/lib/deploy/run/list.js +38 -0
  31. package/lib/deploy/run/prereqs.js +0 -3
  32. package/lib/deploy/run/util.js +9 -0
  33. package/lib/emulator/commandUtils.js +105 -23
  34. package/lib/emulator/dataconnect/pgliteServer.js +1 -0
  35. package/lib/emulator/downloadableEmulatorInfo.json +22 -22
  36. package/lib/emulator/downloadableEmulators.js +43 -5
  37. package/lib/emulator/firestoreEmulator.js +5 -0
  38. package/lib/emulator/functionsEmulator.js +22 -7
  39. package/lib/emulator/pubsubEmulator.js +64 -11
  40. package/lib/emulator/storage/rules/manager.js +31 -15
  41. package/lib/emulator/storage/rules/runtime.js +1 -0
  42. package/lib/emulator/taskQueue.js +5 -4
  43. package/lib/experiments.js +0 -5
  44. package/lib/extensions/emulator/specHelper.js +0 -4
  45. package/lib/extensions/extensionsApi.js +0 -8
  46. package/lib/extensions/extensionsHelper.js +1 -71
  47. package/lib/extensions/runtimes/common.js +0 -12
  48. package/lib/extensions/secretsUtils.js +0 -24
  49. package/lib/extensions/updateHelper.js +2 -88
  50. package/lib/frameworks/angular/utils.js +3 -2
  51. package/lib/frameworks/next/utils.js +0 -11
  52. package/lib/fsAsync.js +34 -20
  53. package/lib/functions/kits/install.js +37 -337
  54. package/lib/functions/kits/sources/directory.js +59 -0
  55. package/lib/functions/kits/sources/index.js +19 -0
  56. package/lib/functions/kits/sources/npm.js +274 -0
  57. package/lib/functions/kits/sources/types.js +12 -0
  58. package/lib/gcp/artifactregistry.js +0 -5
  59. package/lib/gcp/cloudlogging.js +0 -54
  60. package/lib/gcp/iam.js +0 -4
  61. package/lib/gcp/pubsub.js +0 -14
  62. package/lib/gcp/storage.js +2 -1
  63. package/lib/init/features/aitools/promptUpdater.js +3 -2
  64. package/lib/init/features/run.js +3 -7
  65. package/lib/mcp/errors.js +1 -1
  66. package/lib/mcp/resources/guides/crashlytics_reports.js +33 -71
  67. package/lib/mcp/tools/crashlytics/reports.js +25 -30
  68. package/lib/mcp/util/dataconnect/converter.js +0 -29
  69. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  70. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  71. package/package.json +9 -6
  72. package/lib/apphosting/repo.js +0 -243
  73. package/lib/deploy/hosting/args.js +0 -2
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getServiceSpec = getServiceSpec;
4
+ const clc = require("colorette");
5
+ const error_1 = require("../../error");
6
+ const run = require("../../gcp/run");
7
+ const runv2 = require("../../gcp/runv2");
8
+ const util_1 = require("./util");
9
+ async function getServiceSpec(projectId, serviceId, region) {
10
+ let matches = (await runv2.listServices(projectId, false)).filter((s) => {
11
+ const name = (0, util_1.parseServiceName)(s.name);
12
+ return name.serviceId === serviceId && (!region || name.region === region);
13
+ });
14
+ if (matches.length > 1) {
15
+ const unmanaged = matches.filter((s) => !(0, util_1.isManagedByAnotherProduct)(s));
16
+ if (unmanaged.length) {
17
+ matches = unmanaged;
18
+ }
19
+ }
20
+ if (!matches.length) {
21
+ throw new error_1.FirebaseError(`Cloud Run service ${serviceId} doesn't exist in ${region ?? `project ${projectId}`}. ` +
22
+ `See your services with ${clc.bold("firebase run:services:list")}.`);
23
+ }
24
+ if (matches.length > 1) {
25
+ const regions = matches.map((s) => (0, util_1.parseServiceName)(s.name).region);
26
+ throw new error_1.FirebaseError(`Cloud Run service ${serviceId} exists in more than one region: ${regions.join(", ")}. ` +
27
+ `Choose one with --region.`);
28
+ }
29
+ return run.getService(matches[0].name);
30
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listRunServices = listRunServices;
4
+ exports.serviceRows = serviceRows;
5
+ const Table = require("cli-table3");
6
+ const runv2 = require("../../gcp/runv2");
7
+ const logger_1 = require("../../logger");
8
+ const utils_1 = require("../../utils");
9
+ const util_1 = require("./util");
10
+ async function listRunServices(projectId) {
11
+ const allServices = await runv2.listServices(projectId, false);
12
+ const services = allServices.filter((s) => !(0, util_1.isManagedByAnotherProduct)(s));
13
+ if (services.length) {
14
+ const table = new Table({
15
+ head: ["Service ID", "Region", "Base Image"],
16
+ style: { head: ["green"] },
17
+ });
18
+ table.push(...serviceRows(services));
19
+ logger_1.logger.info(table.toString());
20
+ }
21
+ else {
22
+ logger_1.logger.info(`No Cloud Run services found in project ${projectId}.`);
23
+ }
24
+ const skipped = allServices.length - services.length;
25
+ if (skipped) {
26
+ (0, utils_1.logBullet)(`Not listed: ${skipped} ${skipped === 1 ? "service" : "services"} that another product, ` +
27
+ `like Cloud Functions or App Hosting, manages.`);
28
+ }
29
+ return services;
30
+ }
31
+ function serviceRows(services) {
32
+ const rows = services.map((service) => {
33
+ const { serviceId, region } = (0, util_1.parseServiceName)(service.name);
34
+ const baseImage = (0, util_1.mainContainer)(service.template)?.baseImageUri?.split("/").pop();
35
+ return [serviceId, region, baseImage || "None"];
36
+ });
37
+ return rows.sort(([idA, regionA], [idB, regionB]) => idA.localeCompare(idB) || regionA.localeCompare(regionB));
38
+ }
@@ -12,11 +12,8 @@ exports.RUN_PERMISSIONS = [
12
12
  "run.operations.get",
13
13
  "cloudbuild.builds.create",
14
14
  "cloudbuild.builds.get",
15
- "storage.buckets.get",
16
15
  "storage.buckets.list",
17
16
  "storage.buckets.create",
18
- "storage.buckets.update",
19
- "storage.objects.create",
20
17
  "artifactregistry.repositories.get",
21
18
  "artifactregistry.repositories.create",
22
19
  "artifactregistry.repositories.downloadArtifacts",
@@ -7,6 +7,8 @@ exports.findServices = findServices;
7
7
  exports.fullServiceName = fullServiceName;
8
8
  exports.getExistingService = getExistingService;
9
9
  exports.mainContainer = mainContainer;
10
+ exports.parseServiceName = parseServiceName;
11
+ exports.isManagedByAnotherProduct = isManagedByAnotherProduct;
10
12
  const error_1 = require("../../error");
11
13
  const runv2 = require("../../gcp/runv2");
12
14
  const utils_1 = require("../../utils");
@@ -73,3 +75,10 @@ async function getExistingService(projectId, region, serviceId) {
73
75
  function mainContainer(template) {
74
76
  return template?.containers?.[0];
75
77
  }
78
+ function parseServiceName(name) {
79
+ const parts = name.split("/");
80
+ return { region: parts[3], serviceId: parts[5] };
81
+ }
82
+ function isManagedByAnotherProduct(service) {
83
+ return !!service.labels?.[runv2.CLIENT_NAME_LABEL];
84
+ }
@@ -9,7 +9,11 @@ exports.parseInspectionPort = parseInspectionPort;
9
9
  exports.setExportOnExitOptions = setExportOnExitOptions;
10
10
  exports.shutdownWhenKilled = shutdownWhenKilled;
11
11
  exports.getListenOverview = getListenOverview;
12
+ exports.getListenSuffix = getListenSuffix;
12
13
  exports.emulatorExec = emulatorExec;
14
+ exports.resetJavaBinaryForTesting = resetJavaBinaryForTesting;
15
+ exports.hasResolvedJavaBinary = hasResolvedJavaBinary;
16
+ exports.getJavaBinary = getJavaBinary;
13
17
  exports.checkJavaMajorVersion = checkJavaMajorVersion;
14
18
  const clc = require("colorette");
15
19
  const childProcess = require("child_process");
@@ -289,6 +293,14 @@ function getListenOverview(emulator) {
289
293
  return `${info.host}:${info.port}`;
290
294
  }
291
295
  }
296
+ function getListenSuffix(emulator) {
297
+ const info = registry_1.EmulatorRegistry.get(emulator)?.getInfo();
298
+ const listen = getListenOverview(emulator);
299
+ if (!info || !listen || utils.connectableHostname(info.host) === info.host) {
300
+ return "";
301
+ }
302
+ return ` (listening on ${listen})`;
303
+ }
292
304
  async function emulatorExec(script, options) {
293
305
  const projectId = (0, projectUtils_1.getProjectId)(options);
294
306
  const extraEnv = {};
@@ -325,13 +337,50 @@ async function emulatorExec(script, options) {
325
337
  }
326
338
  }
327
339
  const JAVA_VERSION_REGEX = /version "([1-9][0-9]*)/;
340
+ const JAVA_HOME_REGEX = /^\s*java\.home\s*=\s*(.+)$/m;
328
341
  const JAVA_HINT = "Please make sure Java is installed and on your system PATH.";
329
- async function checkJavaMajorVersion() {
342
+ let resolvedJavaBinary;
343
+ function resetJavaBinaryForTesting() {
344
+ resolvedJavaBinary = undefined;
345
+ }
346
+ function hasResolvedJavaBinary() {
347
+ return Boolean(resolvedJavaBinary);
348
+ }
349
+ function getJavaFromJavaHome() {
350
+ const rawJavaHome = process.env.JAVA_HOME?.replace(/"/g, "").trim();
351
+ if (!rawJavaHome) {
352
+ return undefined;
353
+ }
354
+ const javaBinName = utils.IS_WINDOWS ? "java.exe" : "java";
355
+ const candidate = path.join(rawJavaHome, "bin", javaBinName);
356
+ return fsutils.fileExistsSync(candidate) ? candidate : undefined;
357
+ }
358
+ function getJavaBinary() {
359
+ if (!utils.IS_WINDOWS) {
360
+ return "java";
361
+ }
362
+ if (resolvedJavaBinary) {
363
+ return resolvedJavaBinary;
364
+ }
365
+ return getJavaFromJavaHome() || "java";
366
+ }
367
+ function spawnJavaVersionProcess(binary) {
368
+ const args = utils.IS_WINDOWS
369
+ ? [
370
+ "-Duser.language=en",
371
+ "-Dfile.encoding=UTF-8",
372
+ "-Dstdout.encoding=UTF-8",
373
+ "-Dstderr.encoding=UTF-8",
374
+ "-XshowSettings:properties",
375
+ "-version",
376
+ ]
377
+ : ["-Duser.language=en", "-Dfile.encoding=UTF-8", "-version"];
330
378
  return new Promise((resolve, reject) => {
331
379
  let child;
332
380
  try {
333
- child = childProcess.spawn("java", ["-Duser.language=en", "-Dfile.encoding=UTF-8", "-version"], {
334
- stdio: ["inherit", "pipe", "pipe"],
381
+ child = childProcess.spawn(binary, args, {
382
+ stdio: ["ignore", "pipe", "pipe"],
383
+ windowsHide: true,
335
384
  });
336
385
  }
337
386
  catch (err) {
@@ -343,12 +392,16 @@ async function checkJavaMajorVersion() {
343
392
  let error = "";
344
393
  child.stdout?.on("data", (data) => {
345
394
  const str = data.toString("utf8");
346
- logger_1.logger.debug(str);
395
+ if (!utils.IS_WINDOWS) {
396
+ logger_1.logger.debug(str);
397
+ }
347
398
  output += str;
348
399
  });
349
400
  child.stderr?.on("data", (data) => {
350
401
  const str = data.toString("utf8");
351
- logger_1.logger.debug(str);
402
+ if (!utils.IS_WINDOWS) {
403
+ logger_1.logger.debug(str);
404
+ }
352
405
  error += str;
353
406
  });
354
407
  child.once("error", (err) => {
@@ -367,29 +420,58 @@ async function checkJavaMajorVersion() {
367
420
  resolve(`${output}\n${error}`);
368
421
  }
369
422
  });
370
- }).then((output) => {
371
- let versionInt = -1;
372
- const match = JAVA_VERSION_REGEX.exec(output);
373
- if (match) {
374
- const version = match[1];
375
- versionInt = parseInt(version, 10);
376
- if (!versionInt) {
377
- utils.logLabeledWarning("emulators", `Failed to parse Java version. Got "${match[0]}".`, "warn");
378
- }
379
- else {
380
- logger_1.logger.debug(`Parsed Java major version: ${versionInt}`);
423
+ });
424
+ }
425
+ async function checkJavaMajorVersion() {
426
+ let output;
427
+ try {
428
+ output = await spawnJavaVersionProcess("java");
429
+ }
430
+ catch (err) {
431
+ const javaHomeBin = utils.IS_WINDOWS ? getJavaFromJavaHome() : undefined;
432
+ if (!javaHomeBin) {
433
+ throw err;
434
+ }
435
+ output = await spawnJavaVersionProcess(javaHomeBin);
436
+ }
437
+ if (utils.IS_WINDOWS) {
438
+ const javaHomeMatch = JAVA_HOME_REGEX.exec(output);
439
+ if (javaHomeMatch) {
440
+ const javaHome = javaHomeMatch[1].trim();
441
+ const candidate = path.join(javaHome, "bin", "java.exe");
442
+ if (fsutils.fileExistsSync(candidate)) {
443
+ resolvedJavaBinary = candidate;
444
+ logger_1.logger.debug(`Resolved Java binary from java.home: ${resolvedJavaBinary}`);
381
445
  }
382
446
  }
383
447
  else {
384
- logger_1.logger.debug("java -version outputs:", output);
385
- logger_1.logger.warn(`Failed to parse Java version.`);
448
+ const fallback = getJavaFromJavaHome();
449
+ if (fallback) {
450
+ resolvedJavaBinary = fallback;
451
+ }
386
452
  }
387
- const session = (0, track_1.emulatorSession)();
388
- if (session) {
389
- session.javaMajorVersion = versionInt;
453
+ }
454
+ let versionInt = -1;
455
+ const match = JAVA_VERSION_REGEX.exec(output);
456
+ if (match) {
457
+ const version = match[1];
458
+ versionInt = parseInt(version, 10);
459
+ if (!versionInt) {
460
+ utils.logLabeledWarning("emulators", `Failed to parse Java version. Got "${match[0]}".`, "warn");
390
461
  }
391
- return versionInt;
392
- });
462
+ else {
463
+ logger_1.logger.debug(`Parsed Java major version: ${versionInt}`);
464
+ }
465
+ }
466
+ else {
467
+ logger_1.logger.debug("java -version outputs:", output);
468
+ logger_1.logger.warn(`Failed to parse Java version.`);
469
+ }
470
+ const session = (0, track_1.emulatorSession)();
471
+ if (session) {
472
+ session.javaMajorVersion = versionInt;
473
+ }
474
+ return versionInt;
393
475
  }
394
476
  exports.MIN_SUPPORTED_JAVA_MAJOR_VERSION = 21;
395
477
  exports.JAVA_DEPRECATION_WARNING = "firebase-tools no longer supports Java version before 21. " +
@@ -194,6 +194,7 @@ class PostgresServer {
194
194
  }
195
195
  exports.PostgresServer = PostgresServer;
196
196
  async function fromNodeSocket(socket, options) {
197
+ socket.setNoDelay(true);
197
198
  const rs = node_stream_1.Readable.toWeb(socket);
198
199
  const ws = node_stream_1.Writable.toWeb(socket);
199
200
  const opts = options
@@ -54,36 +54,36 @@
54
54
  },
55
55
  "dataconnect": {
56
56
  "darwin": {
57
- "version": "3.4.24",
58
- "expectedSize": 35755952,
59
- "expectedChecksum": "faeb22190b0b8fdc20256d37eb48401f",
60
- "expectedChecksumSHA256": "c10461dfaf2e1fbe0f3f7883c77cc346427f56edc7a63c0bea9482c29c7c9e7f",
61
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-amd64-v3.4.24",
62
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.24"
57
+ "version": "3.4.25",
58
+ "expectedSize": 35760048,
59
+ "expectedChecksum": "357570277013f47df1908542d8de4adf",
60
+ "expectedChecksumSHA256": "28520242e277523b66da7ccc9e255e265547471896ee842d820c32ae4d861aa9",
61
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-amd64-v3.4.25",
62
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.25"
63
63
  },
64
64
  "darwin_arm64": {
65
- "version": "3.4.24",
65
+ "version": "3.4.25",
66
66
  "expectedSize": 33727618,
67
- "expectedChecksum": "310374c3d7e6242658dcdbd3a1e8d394",
68
- "expectedChecksumSHA256": "a59e26499e1cc3e1eba2c5187f8ac20bb555bebea3bb1f9d6785797814da59fb",
69
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-arm64-v3.4.24",
70
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.24"
67
+ "expectedChecksum": "f5326947b1de0dfb3d817292188be7ab",
68
+ "expectedChecksumSHA256": "11bf1a66434e32e63e39c2c0e758fc5aa1fcc8bf844062404f73a06e8509c9a9",
69
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-macos-arm64-v3.4.25",
70
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.25"
71
71
  },
72
72
  "win32": {
73
- "version": "3.4.24",
74
- "expectedSize": 35738112,
75
- "expectedChecksum": "a4e80670bcda4607c9a0917d17369ea5",
76
- "expectedChecksumSHA256": "a03e10d1df00f10cbe55df5c9ee9808bf627e339e83e5e642e5414e95a1985b0",
77
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-windows-amd64-v3.4.24",
78
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.24.exe"
73
+ "version": "3.4.25",
74
+ "expectedSize": 35740672,
75
+ "expectedChecksum": "da426d34d42478414d11dfa338c5574a",
76
+ "expectedChecksumSHA256": "ac73a8a4f6051382287bb91e5bdab25d500600c17be215ee6372f77586e7f8d6",
77
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-windows-amd64-v3.4.25",
78
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.25.exe"
79
79
  },
80
80
  "linux": {
81
- "version": "3.4.24",
81
+ "version": "3.4.25",
82
82
  "expectedSize": 34762914,
83
- "expectedChecksum": "6eb0f18c9647d7e57296c964c4ff4e18",
84
- "expectedChecksumSHA256": "e7cb1f453c6388bd434627d70e1455ae53a99e36a2bd3dd3885844e5d5cd1769",
85
- "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-linux-amd64-v3.4.24",
86
- "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.24"
83
+ "expectedChecksum": "1db9678c3c0f1461a9d6a4b0139da409",
84
+ "expectedChecksumSHA256": "6925e7484fc7357f99169411e72dfee490c8ec63de5a49c05fc8c53ad756d9e9",
85
+ "remoteUrl": "https://storage.googleapis.com/firemat-preview-drop/emulator/dataconnect-emulator-linux-amd64-v3.4.25",
86
+ "downloadPathRelativeToCacheDir": "dataconnect-emulator-3.4.25"
87
87
  }
88
88
  }
89
89
  }
@@ -25,6 +25,7 @@ const path = require("path");
25
25
  const os = require("os");
26
26
  const registry_1 = require("./registry");
27
27
  const download_1 = require("../emulator/download");
28
+ const commandUtils_1 = require("./commandUtils");
28
29
  const experiments = require("../experiments");
29
30
  const process = require("process");
30
31
  const emulatorUpdateDetails = require("./downloadableEmulatorInfo.json");
@@ -252,6 +253,14 @@ function getExecPath(name) {
252
253
  const details = getDownloadDetails(name);
253
254
  return details.binaryPath || details.downloadPath;
254
255
  }
256
+ function getPubsubJarPath() {
257
+ const details = getDownloadDetails(types_1.Emulators.PUBSUB);
258
+ return path.join(details.unzipDir || "", "pubsub-emulator", "lib", `cloud-pubsub-emulator-${details.version}-all.jar`);
259
+ }
260
+ function splitEnvOpts(value) {
261
+ const trimmed = value?.trim();
262
+ return trimmed ? trimmed.split(/\s+/) : [];
263
+ }
255
264
  function getLogFileName(name) {
256
265
  return `${name}-debug.log`;
257
266
  }
@@ -261,7 +270,16 @@ function _getCommand(emulator, args) {
261
270
  if (!args.port) {
262
271
  args.port = defaultPort;
263
272
  }
264
- const cmdLineArgs = baseCmd.args.slice();
273
+ const useDirectPubsubJarOnWindows = emulator === types_1.Emulators.PUBSUB && utils.IS_WINDOWS && !process.env.PUBSUB_EMULATOR_BINARY_PATH;
274
+ const cmdLineArgs = useDirectPubsubJarOnWindows
275
+ ? [
276
+ "-Duser.language=en",
277
+ ...splitEnvOpts(process.env.JAVA_OPTS),
278
+ ...splitEnvOpts(process.env.CLOUD_PUBSUB_EMULATOR_OPTS),
279
+ "-jar",
280
+ getPubsubJarPath(),
281
+ ]
282
+ : baseCmd.args.slice();
265
283
  if (baseCmd.binary === "java" &&
266
284
  utils.isRunningInWSL() &&
267
285
  (!args.host || !args.host.includes(":"))) {
@@ -286,12 +304,19 @@ function _getCommand(emulator, args) {
286
304
  cmdLineArgs.push(argKey, argVal);
287
305
  }
288
306
  });
307
+ let binary = baseCmd.binary;
308
+ if (baseCmd.binary === "java" || useDirectPubsubJarOnWindows) {
309
+ binary = (0, commandUtils_1.getJavaBinary)();
310
+ }
311
+ else if (emulator === types_1.Emulators.PUBSUB && process.env.PUBSUB_EMULATOR_BINARY_PATH) {
312
+ binary = getExecPath(types_1.Emulators.PUBSUB);
313
+ }
289
314
  return {
290
- binary: baseCmd.binary,
315
+ binary,
291
316
  args: cmdLineArgs,
292
317
  optionalArgs: baseCmd.optionalArgs,
293
318
  joinArgs: baseCmd.joinArgs,
294
- shell: baseCmd.shell,
319
+ shell: useDirectPubsubJarOnWindows ? false : baseCmd.shell,
295
320
  port: args.port,
296
321
  };
297
322
  }
@@ -307,7 +332,12 @@ async function _fatal(emulator, errorMsg) {
307
332
  }
308
333
  async function handleEmulatorProcessError(emulator, err, port) {
309
334
  const description = constants_1.Constants.description(emulator);
310
- if (err.path === "java" && err.code === "ENOENT") {
335
+ const isJavaBinaryError = err.path === "java" ||
336
+ path
337
+ .basename(String(err.path || ""))
338
+ .replace(/\.exe$/i, "")
339
+ .toLowerCase() === "java";
340
+ if (isJavaBinaryError && err.code === "ENOENT") {
311
341
  await _fatal(emulator, `${description} has exited because java is not installed, you can install it from https://openjdk.java.net/install/`);
312
342
  }
313
343
  else if (err.code === "EADDRINUSE") {
@@ -332,7 +362,7 @@ async function _runBinary(emulator, command, extraEnv) {
332
362
  const opts = {
333
363
  env: { ...process.env, ...extraEnv },
334
364
  detached: true,
335
- stdio: ["inherit", "pipe", "pipe"],
365
+ stdio: ["ignore", "pipe", "pipe"],
336
366
  };
337
367
  if (command.shell && utils.IS_WINDOWS) {
338
368
  opts.shell = true;
@@ -454,6 +484,14 @@ async function start(targetName, args, extraEnv = {}) {
454
484
  throw new error_1.FirebaseError("emulator not found");
455
485
  }
456
486
  }
487
+ if (targetName === types_1.Emulators.PUBSUB &&
488
+ utils.IS_WINDOWS &&
489
+ !process.env.PUBSUB_EMULATOR_BINARY_PATH &&
490
+ !(0, commandUtils_1.hasResolvedJavaBinary)()) {
491
+ await (0, commandUtils_1.checkJavaMajorVersion)().catch((err) => {
492
+ logger.log("DEBUG", `Failed to resolve Java binary for Pub/Sub emulator: ${String(err)}`);
493
+ });
494
+ }
457
495
  const command = _getCommand(targetName, args);
458
496
  logger.log("DEBUG", `Starting ${constants_1.Constants.description(targetName)} with command ${JSON.stringify(command)}`);
459
497
  return _runBinary(emulator, command, extraEnv);
@@ -21,6 +21,11 @@ class FirestoreEmulator {
21
21
  if (this.args.rules && this.args.project_id) {
22
22
  const rulesPath = this.args.rules;
23
23
  this.rulesWatcher = chokidar.watch(rulesPath, { persistent: true, ignoreInitial: true });
24
+ this.rulesWatcher.on("error", (err) => {
25
+ const message = err instanceof Error ? err.message : String(err);
26
+ utils.logLabeledWarning("firestore", `Could not watch ${rulesPath} for changes, so rules hot reloading is disabled: ${message}. ` +
27
+ "If your environment does not support file watching, set CHOKIDAR_USEPOLLING=1 to fall back to polling.");
28
+ });
24
29
  this.rulesWatcher.on("change", async () => {
25
30
  await new Promise((res) => setTimeout(res, 5));
26
31
  utils.logLabeledBullet("firestore", "Change detected, updating rules...");
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FunctionsEmulator = exports.TCPConn = exports.IPCConn = void 0;
4
+ exports.createIgnoredFilter = createIgnoredFilter;
4
5
  const fs = require("fs");
5
6
  const path = require("path");
6
7
  const express = require("express");
@@ -15,6 +16,7 @@ const track_1 = require("../track");
15
16
  const constants_1 = require("./constants");
16
17
  const types_1 = require("./types");
17
18
  const chokidar = require("chokidar");
19
+ const minimatch = require("minimatch");
18
20
  const portfinder = require("portfinder");
19
21
  const spawn = require("cross-spawn");
20
22
  const functionsEmulatorShared_1 = require("./functionsEmulatorShared");
@@ -64,6 +66,25 @@ class TCPConn {
64
66
  }
65
67
  }
66
68
  exports.TCPConn = TCPConn;
69
+ function createIgnoredFilter(ignore) {
70
+ const ignored = [
71
+ /(^|[\/\\])\../,
72
+ /.+\.log/,
73
+ /.+?[\\\/]node_modules[\\\/].+?/,
74
+ /.+?[\\\/]venv[\\\/].+?/,
75
+ ];
76
+ if (ignore) {
77
+ const minimatchInstances = ignore.map((pattern) => {
78
+ const p = pattern.startsWith("**/") ? pattern : `**/${pattern}`;
79
+ return new minimatch.Minimatch(p, { dot: true });
80
+ });
81
+ ignored.push((filePath) => {
82
+ const normalized = filePath.replace(/\\/g, "/");
83
+ return minimatchInstances.some((m) => m.match(normalized));
84
+ });
85
+ }
86
+ return ignored;
87
+ }
67
88
  class FunctionsEmulator {
68
89
  static getHttpFunctionUrl(projectId, name, region, info) {
69
90
  let url;
@@ -298,13 +319,7 @@ class FunctionsEmulator {
298
319
  }
299
320
  else {
300
321
  const watcher = chokidar.watch(backend.functionsDir, {
301
- ignored: [
302
- /(^|[\/\\])\../,
303
- /.+\.log/,
304
- /.+?[\\\/]node_modules[\\\/].+?/,
305
- /.+?[\\\/]venv[\\\/].+?/,
306
- ...(backend.ignore?.map((i) => `**/${i}`) ?? []),
307
- ],
322
+ ignored: createIgnoredFilter(backend.ignore),
308
323
  persistent: true,
309
324
  });
310
325
  this.watchers.push(watcher);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PubsubEmulator = void 0;
3
+ exports.PubsubEmulator = exports.SUBSCRIPTION_CLOSE_TIMEOUT_MS = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const pubsub_1 = require("@google-cloud/pubsub");
6
6
  const downloadableEmulators = require("./downloadableEmulators");
@@ -12,6 +12,24 @@ const registry_1 = require("./registry");
12
12
  const child_process_1 = require("child_process");
13
13
  const PUBSUB_KILL_COMMAND = "pubsub_pids=$(ps aux | grep '[p]ubsub-emulator' | awk '{print $2}');" +
14
14
  " if [ ! -z '$pubsub_pids' ]; then kill -9 $pubsub_pids; fi;";
15
+ exports.SUBSCRIPTION_CLOSE_TIMEOUT_MS = 2000;
16
+ async function withTimeout(promise, timeoutMs, timeoutMessage) {
17
+ let timer;
18
+ try {
19
+ const timeoutPromise = new Promise((_, reject) => {
20
+ timer = setTimeout(() => {
21
+ reject(new Error(timeoutMessage));
22
+ }, timeoutMs);
23
+ timer.unref?.();
24
+ });
25
+ return await Promise.race([promise, timeoutPromise]);
26
+ }
27
+ finally {
28
+ if (timer !== undefined) {
29
+ clearTimeout(timer);
30
+ }
31
+ }
32
+ }
15
33
  class PubsubEmulator {
16
34
  get pubsub() {
17
35
  if (!this._pubsub) {
@@ -36,13 +54,47 @@ class PubsubEmulator {
36
54
  }
37
55
  async stop() {
38
56
  try {
39
- await downloadableEmulators.stop(types_1.Emulators.PUBSUB);
57
+ const closePromises = Array.from(this.subscriptionForTopic.values()).map(async (sub) => {
58
+ try {
59
+ await withTimeout(sub.close(), exports.SUBSCRIPTION_CLOSE_TIMEOUT_MS, "Timed out waiting " +
60
+ exports.SUBSCRIPTION_CLOSE_TIMEOUT_MS +
61
+ "ms for subscription " +
62
+ sub.name +
63
+ " to close");
64
+ }
65
+ catch (err) {
66
+ this.logger.logLabeled("DEBUG", "pubsub", "Failed to close subscription " +
67
+ sub.name +
68
+ ": " +
69
+ (err instanceof Error ? err.message : String(err)));
70
+ }
71
+ });
72
+ await Promise.all(closePromises);
73
+ this.subscriptionForTopic.clear();
74
+ this.triggersForTopic.clear();
75
+ if (this._pubsub) {
76
+ try {
77
+ await withTimeout(this._pubsub.close(), exports.SUBSCRIPTION_CLOSE_TIMEOUT_MS, "Timed out waiting " + exports.SUBSCRIPTION_CLOSE_TIMEOUT_MS + "ms for pubsub client to close");
78
+ }
79
+ catch (err) {
80
+ this.logger.logLabeled("DEBUG", "pubsub", "Failed to close pubsub client: " + (err instanceof Error ? err.message : String(err)));
81
+ }
82
+ this._pubsub = undefined;
83
+ }
40
84
  }
41
- catch (e) {
42
- this.logger.logLabeled("DEBUG", "pubsub", JSON.stringify(e));
43
- if (process.platform !== "win32") {
44
- const buffer = (0, child_process_1.execSync)(PUBSUB_KILL_COMMAND);
45
- this.logger.logLabeled("DEBUG", "pubsub", "Pubsub kill output: " + JSON.stringify(buffer));
85
+ catch (err) {
86
+ this.logger.logLabeled("DEBUG", "pubsub", "Error during pubsub client cleanup: " + (err instanceof Error ? err.message : String(err)));
87
+ }
88
+ finally {
89
+ try {
90
+ await downloadableEmulators.stop(types_1.Emulators.PUBSUB);
91
+ }
92
+ catch (e) {
93
+ this.logger.logLabeled("DEBUG", "pubsub", e instanceof Error ? e.message : String(e));
94
+ if (process.platform !== "win32") {
95
+ const buffer = (0, child_process_1.execSync)(PUBSUB_KILL_COMMAND);
96
+ this.logger.logLabeled("DEBUG", "pubsub", "Pubsub kill output: " + JSON.stringify(buffer));
97
+ }
46
98
  }
47
99
  }
48
100
  }
@@ -95,16 +147,17 @@ class PubsubEmulator {
95
147
  }
96
148
  async addTrigger(topicName, triggerKey, signatureType) {
97
149
  this.logger.logLabeled("DEBUG", "pubsub", `addTrigger(${topicName}, ${triggerKey}, ${signatureType})`);
98
- const sub = await this.maybeCreateTopicAndSub(topicName);
99
150
  const triggers = this.triggersForTopic.get(topicName) || [];
100
- if (triggers.some((t) => t.triggerKey === triggerKey) &&
101
- this.subscriptionForTopic.has(topicName)) {
151
+ if (triggers.some((t) => t.triggerKey === triggerKey)) {
102
152
  this.logger.logLabeled("DEBUG", "pubsub", "Trigger already exists");
103
153
  return;
104
154
  }
155
+ if (!this.subscriptionForTopic.has(topicName)) {
156
+ const sub = await this.maybeCreateTopicAndSub(topicName);
157
+ this.subscriptionForTopic.set(topicName, sub);
158
+ }
105
159
  triggers.push({ triggerKey, signatureType });
106
160
  this.triggersForTopic.set(topicName, triggers);
107
- this.subscriptionForTopic.set(topicName, sub);
108
161
  }
109
162
  ensureFunctionsClient() {
110
163
  if (this.client !== undefined)