firebase-tools-with-isolate 15.36.0 → 15.38.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 (104) hide show
  1. package/lib/accountExporter.js +1 -1
  2. package/lib/accountImporter.js +15 -10
  3. package/lib/apiv2.js +66 -12
  4. package/lib/appUtils.js +103 -40
  5. package/lib/appdistribution/client.js +5 -1
  6. package/lib/apptesting/parseTestFiles.js +1 -1
  7. package/lib/auth.js +1 -1
  8. package/lib/bin/progressiveHelp.js +1 -1
  9. package/lib/command.js +1 -2
  10. package/lib/commands/appdistribution-distribute.js +5 -3
  11. package/lib/commands/crashlytics-events-get.js +46 -0
  12. package/lib/commands/crashlytics-events-list.js +68 -0
  13. package/lib/commands/crashlytics-heapdumps-enable.js +3 -4
  14. package/lib/commands/crashlytics-heapdumps-status.js +5 -3
  15. package/lib/commands/crashlytics-issues-get.js +65 -0
  16. package/lib/commands/crashlytics-reports-get.js +267 -0
  17. package/lib/commands/crashlytics-reports-list.js +42 -0
  18. package/lib/commands/dataconnect-services-list.js +8 -2
  19. package/lib/commands/ext-dev-init.js +1 -1
  20. package/lib/commands/hosting-channel-open.js +4 -1
  21. package/lib/commands/index.js +10 -0
  22. package/lib/commands/open.js +3 -1
  23. package/lib/commands/serve.js +1 -1
  24. package/lib/commands/use.js +1 -1
  25. package/lib/config.js +1 -1
  26. package/lib/crashlytics/commandUtils.js +227 -0
  27. package/lib/crashlytics/events.js +71 -73
  28. package/lib/crashlytics/filters.js +1 -1
  29. package/lib/crashlytics/profilingManager.js +63 -16
  30. package/lib/crashlytics/reports.js +5 -1
  31. package/lib/dataconnect/client.js +14 -8
  32. package/lib/deploy/dataconnect/release.js +2 -2
  33. package/lib/deploy/firestore/prepare.js +23 -17
  34. package/lib/deploy/functions/cel.js +1 -1
  35. package/lib/deploy/functions/deploy.js +2 -1
  36. package/lib/deploy/functions/prepare.js +28 -0
  37. package/lib/deploy/functions/release/fabricator.js +27 -3
  38. package/lib/deploy/functions/release/planner.js +3 -0
  39. package/lib/deploy/functions/runtimes/discovery/parsing.js +1 -1
  40. package/lib/deploy/functions/runtimes/python/index.js +3 -0
  41. package/lib/deploy/functions/runtimes/supported/index.js +10 -4
  42. package/lib/deploy/functions/runtimes/supported/types.js +13 -1
  43. package/lib/deploy/run/deploy.js +40 -35
  44. package/lib/deploy/run/prereqs.js +0 -3
  45. package/lib/downloadUtils.js +2 -1
  46. package/lib/emulator/download.js +1 -0
  47. package/lib/emulator/downloadableEmulatorInfo.json +31 -31
  48. package/lib/emulator/downloadableEmulators.js +14 -2
  49. package/lib/emulator/events/types.js +0 -6
  50. package/lib/emulator/functionsEmulator.js +73 -1
  51. package/lib/emulator/functionsEmulatorRuntime.js +2 -2
  52. package/lib/emulator/storage/cloudFunctions.js +0 -1
  53. package/lib/emulator/storage/rules/runtime.js +0 -3
  54. package/lib/emulator/taskQueue.js +0 -12
  55. package/lib/experiments.js +10 -0
  56. package/lib/extensions/extensionsHelper.js +1 -4
  57. package/lib/extensions/listExtensions.js +1 -1
  58. package/lib/extensions/replacements.json +2 -1
  59. package/lib/firestore/delete.js +2 -3
  60. package/lib/firestore/fsConfig.js +100 -41
  61. package/lib/frameworks/next/constants.js +17 -14
  62. package/lib/frameworks/next/index.js +2 -2
  63. package/lib/frameworks/next/utils.js +6 -8
  64. package/lib/gcp/cloudbilling.js +2 -2
  65. package/lib/gcp/cloudbuild.js +0 -77
  66. package/lib/gcp/cloudscheduler.js +12 -0
  67. package/lib/gcp/cloudtasks.js +0 -4
  68. package/lib/gcp/devConnect.js +0 -6
  69. package/lib/gcp/iam.js +15 -1
  70. package/lib/gcp/resourceManager.js +1 -14
  71. package/lib/gcp/runv2.js +0 -27
  72. package/lib/gcp/secretManager.js +2 -2
  73. package/lib/gcp/storage.js +87 -4
  74. package/lib/hosting/api.js +29 -23
  75. package/lib/hosting/implicitInit.js +1 -1
  76. package/lib/hosting/proxy.js +1 -1
  77. package/lib/init/features/dataconnect/sdk.js +15 -5
  78. package/lib/init/features/firestore/rules.js +1 -1
  79. package/lib/init/features/functions/index.js +2 -2
  80. package/lib/init/features/functions/npm-dependencies.js +1 -1
  81. package/lib/init/features/storage/rules.js +1 -1
  82. package/lib/localFunction.js +3 -3
  83. package/lib/management/apps.js +7 -0
  84. package/lib/management/database.js +1 -1
  85. package/lib/mcp/apps/init/mcp-app.js +1 -1
  86. package/lib/mcp/apps/update_environment/mcp-app.js +1 -1
  87. package/lib/mcp/index.js +10 -4
  88. package/lib/mcp/tools/core/get_environment.js +1 -1
  89. package/lib/mcp/tools/crashlytics/events.js +2 -5
  90. package/lib/mcp/tools/crashlytics/reports.js +5 -14
  91. package/lib/mcp/util/apptesting/availability.js +3 -2
  92. package/lib/mcp/util/crashlytics/availability.js +59 -12
  93. package/lib/mcp/util/dataconnect/converter.js +1 -1
  94. package/lib/mcp/util.js +4 -0
  95. package/lib/profileReport.js +1 -1
  96. package/lib/profiler.js +1 -1
  97. package/lib/requireAuth.js +11 -7
  98. package/lib/rulesDeploy.js +0 -1
  99. package/lib/throttler/throttler.js +1 -1
  100. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  101. package/lib/utils.js +1 -1
  102. package/package.json +15 -12
  103. package/schema/firebase-config.json +9 -3
  104. package/standalone/package.json +6 -1
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VALID_FORM_FACTORS = exports.VALID_SIGNALS = exports.VALID_ERROR_TYPES = void 0;
4
+ exports.requireAppId = requireAppId;
5
+ exports.shortEventId = shortEventId;
6
+ exports.parsePositiveIntOption = parsePositiveIntOption;
7
+ exports.writeOutputFileIfRequested = writeOutputFileIfRequested;
8
+ exports.withEventFilterOptions = withEventFilterOptions;
9
+ exports.parseEventFilters = parseEventFilters;
10
+ const fs = require("fs-extra");
11
+ const error_1 = require("../error");
12
+ const logger_1 = require("../logger");
13
+ const prompt = require("../prompt");
14
+ const apps_1 = require("../management/apps");
15
+ const utils_1 = require("./utils");
16
+ const filters_1 = require("./filters");
17
+ exports.VALID_ERROR_TYPES = ["FATAL", "NON_FATAL", "ANR"];
18
+ exports.VALID_SIGNALS = [
19
+ "SIGNAL_EARLY",
20
+ "SIGNAL_FRESH",
21
+ "SIGNAL_REGRESSED",
22
+ "SIGNAL_REPETITIVE",
23
+ ];
24
+ exports.VALID_FORM_FACTORS = ["PHONE", "TABLET", "DESKTOP", "TV", "WATCH"];
25
+ function requireAppId(options) {
26
+ const appId = typeof options.app === "string" ? options.app.trim() : "";
27
+ if (!appId) {
28
+ throw new error_1.FirebaseError("Must specify '--app <appId>'. Run 'firebase apps:list' to find your Firebase App ID.", { exit: 1 });
29
+ }
30
+ return appId;
31
+ }
32
+ const EVENT_PATH_PATTERN = /\/events\/([^/]+)$/;
33
+ function shortEventId(sampleEvent) {
34
+ const path = sampleEvent?.split("?")[0].trim();
35
+ if (!path) {
36
+ return "";
37
+ }
38
+ if (!path.includes("/")) {
39
+ return path;
40
+ }
41
+ return path.match(EVENT_PATH_PATTERN)?.[1] || "";
42
+ }
43
+ function parsePositiveIntOption(value, flagName, bounds) {
44
+ const { defaultValue, max } = bounds;
45
+ if (value === undefined || value === "") {
46
+ return defaultValue;
47
+ }
48
+ const parsed = typeof value === "number" ? value : Number(String(value).trim());
49
+ if (!Number.isInteger(parsed) || parsed < 1) {
50
+ throw new error_1.FirebaseError(`'${flagName}' must be a positive integer.`, { exit: 1 });
51
+ }
52
+ if (max !== undefined && parsed > max) {
53
+ throw new error_1.FirebaseError(`'${flagName}' must be between 1 and ${max}.`, { exit: 1 });
54
+ }
55
+ return parsed;
56
+ }
57
+ async function writeOutputFileIfRequested(data, options) {
58
+ if (!options.output) {
59
+ return false;
60
+ }
61
+ if (typeof options.output !== "string" || !options.output.trim()) {
62
+ throw new error_1.FirebaseError("Must specify a file path for '-o, --output <path>'.", { exit: 1 });
63
+ }
64
+ const outputPath = options.output.trim();
65
+ if (fs.existsSync(outputPath)) {
66
+ const shouldOverwrite = await prompt.confirm({
67
+ message: `File ${outputPath} already exists. Overwrite?`,
68
+ force: options.force,
69
+ nonInteractive: options.nonInteractive,
70
+ });
71
+ if (!shouldOverwrite) {
72
+ logger_1.logger.info("Aborted writing output file.");
73
+ return true;
74
+ }
75
+ }
76
+ try {
77
+ fs.outputFileSync(outputPath, `${JSON.stringify(data, null, 2)}\n`, "utf8");
78
+ }
79
+ catch (err) {
80
+ throw new error_1.FirebaseError(`Failed to write output to ${outputPath}: ${(0, error_1.getErrMsg)(err)}`, {
81
+ exit: 1,
82
+ original: (0, error_1.getError)(err),
83
+ });
84
+ }
85
+ logger_1.logger.info(`Wrote output to ${outputPath}`);
86
+ return true;
87
+ }
88
+ function splitCommaSeparatedList(raw) {
89
+ if (!raw) {
90
+ return undefined;
91
+ }
92
+ const items = [];
93
+ let current = "";
94
+ let parenDepth = 0;
95
+ for (const ch of raw) {
96
+ if (ch === "," && parenDepth === 0) {
97
+ const trimmed = current.trim();
98
+ if (trimmed) {
99
+ items.push(trimmed);
100
+ }
101
+ current = "";
102
+ continue;
103
+ }
104
+ if (ch === "(") {
105
+ parenDepth++;
106
+ }
107
+ else if (ch === ")" && parenDepth > 0) {
108
+ parenDepth--;
109
+ }
110
+ current += ch;
111
+ }
112
+ const trimmed = current.trim();
113
+ if (trimmed) {
114
+ items.push(trimmed);
115
+ }
116
+ return items.length > 0 ? items : undefined;
117
+ }
118
+ function validateEnumList(values, validValues, flagName) {
119
+ if (!values) {
120
+ return undefined;
121
+ }
122
+ for (const val of values) {
123
+ if (!validValues.includes(val)) {
124
+ throw new error_1.FirebaseError(`Invalid value '${val}' for '${flagName}'. Valid values are: ${validValues.join(", ")}.`, { exit: 1 });
125
+ }
126
+ }
127
+ return values;
128
+ }
129
+ const ISO_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
130
+ const ISO_DATE_TIME_WITH_TZ = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i;
131
+ function parseTimeOption(raw, flagName) {
132
+ const value = raw?.trim();
133
+ if (!value) {
134
+ return undefined;
135
+ }
136
+ const isDateOnly = ISO_DATE_ONLY.test(value);
137
+ const date = isDateOnly || ISO_DATE_TIME_WITH_TZ.test(value)
138
+ ? new Date(isDateOnly ? `${value}T00:00:00Z` : value)
139
+ : undefined;
140
+ if (!date || isNaN(date.getTime())) {
141
+ throw new error_1.FirebaseError(`Invalid ${flagName} '${value}'. Use an ISO 8601 date or timestamp, ` +
142
+ `e.g. "2026-11-01" or "2026-11-01T08:00:00Z".`, { exit: 1 });
143
+ }
144
+ return date.toISOString();
145
+ }
146
+ function withEventFilterOptions(command) {
147
+ return command
148
+ .option("--issue-id <id>", "filter by Crashlytics issue ID")
149
+ .option("--variant-id <id>", "filter by issue variant ID (mobile only)")
150
+ .option("--versions <list>", 'comma-separated version display names (mobile: "2.4.0 (240)", web: "2.4.0")')
151
+ .option("--error-types <list>", "comma-separated error types: FATAL, NON_FATAL, ANR (mobile only; ANR is Android only)")
152
+ .option("--signals <list>", "comma-separated issue signals: SIGNAL_EARLY, SIGNAL_FRESH, SIGNAL_REGRESSED, SIGNAL_REPETITIVE (mobile only)")
153
+ .option("--os-names <list>", 'comma-separated operating system display names (e.g. "Android (14)")')
154
+ .option("--device-names <list>", 'comma-separated device display names (e.g. "Google (Pixel 8)", "Apple (iPhone16,2)", mobile only)')
155
+ .option("--device-form-factors <list>", "comma-separated device form factors: PHONE, TABLET, DESKTOP, TV, WATCH (mobile only)")
156
+ .option("--browser-names <list>", 'comma-separated browser display names (e.g. "Chrome (123)", web only)')
157
+ .option("--start-time <iso>", 'start of the time interval as an ISO 8601 date or timestamp (e.g. "2026-11-01" or "2026-11-01T08:00:00Z"); within the last 90 days, default: 7 days ago')
158
+ .option("--end-time <iso>", "end of the time interval as an ISO 8601 date or timestamp; requires --start-time (default: now)");
159
+ }
160
+ const MOBILE_ONLY_FLAGS = [
161
+ ["variantId", "--variant-id"],
162
+ ["errorTypes", "--error-types"],
163
+ ["signals", "--signals"],
164
+ ["deviceNames", "--device-names"],
165
+ ["deviceFormFactors", "--device-form-factors"],
166
+ ];
167
+ const WEB_ONLY_FLAGS = [
168
+ ["browserNames", "--browser-names"],
169
+ ];
170
+ function validatePlatformSpecificFlags(options, appId) {
171
+ const platform = (0, utils_1.parseAppPlatform)(appId);
172
+ if (!platform) {
173
+ return;
174
+ }
175
+ const isWeb = platform === apps_1.AppPlatform.WEB;
176
+ const used = (isWeb ? MOBILE_ONLY_FLAGS : WEB_ONLY_FLAGS)
177
+ .filter(([key]) => {
178
+ const value = options[key];
179
+ return typeof value === "string" && value.trim() !== "";
180
+ })
181
+ .map(([, flag]) => flag);
182
+ if (used.length > 0) {
183
+ throw new error_1.FirebaseError(`${used.join(", ")} ${used.length === 1 ? "is" : "are"} only supported for ` +
184
+ `${isWeb ? "Android and Apple" : "web"} apps, but ${appId} is ` +
185
+ `${isWeb ? "a web" : "an Android or Apple"} app.`, { exit: 1 });
186
+ }
187
+ }
188
+ function parseEventFilters(options, appId) {
189
+ validatePlatformSpecificFlags(options, appId);
190
+ const intervalStartTime = parseTimeOption(options.startTime, "--start-time");
191
+ const intervalEndTime = parseTimeOption(options.endTime, "--end-time");
192
+ if (intervalStartTime && intervalEndTime && intervalStartTime >= intervalEndTime) {
193
+ throw new error_1.FirebaseError("'--start-time' must be before '--end-time'.", { exit: 1 });
194
+ }
195
+ if (intervalEndTime && !intervalStartTime) {
196
+ throw new error_1.FirebaseError("'--end-time' requires '--start-time'.", { exit: 1 });
197
+ }
198
+ const filter = {
199
+ intervalStartTime,
200
+ intervalEndTime,
201
+ versionDisplayNames: splitCommaSeparatedList(options.versions),
202
+ issueId: options.issueId?.trim() || undefined,
203
+ issueVariantId: options.variantId?.trim() || undefined,
204
+ issueErrorTypes: validateEnumList(splitCommaSeparatedList(options.errorTypes), exports.VALID_ERROR_TYPES, "--error-types"),
205
+ issueSignals: validateEnumList(splitCommaSeparatedList(options.signals), exports.VALID_SIGNALS, "--signals"),
206
+ operatingSystemDisplayNames: splitCommaSeparatedList(options.osNames),
207
+ deviceDisplayNames: splitCommaSeparatedList(options.deviceNames),
208
+ deviceFormFactors: validateEnumList(splitCommaSeparatedList(options.deviceFormFactors), exports.VALID_FORM_FACTORS, "--device-form-factors"),
209
+ browserFilterDisplayNames: splitCommaSeparatedList(options.browserNames),
210
+ };
211
+ try {
212
+ return (0, filters_1.validateEventFilters)(filter, appId);
213
+ }
214
+ catch (err) {
215
+ if (err instanceof error_1.FirebaseError) {
216
+ if (err.message.includes("topVersions report")) {
217
+ throw new error_1.FirebaseError(`--versions must match pattern 'version (build)' (e.g. "2.4.0 (240)"). Run 'firebase crashlytics:reports:get --app ${appId} topVersions' to list valid version display names.`, { exit: 1 });
218
+ }
219
+ const message = err.message
220
+ .replace("intervalStartTime must be less than 90 days in the past", "'--start-time' must be within the last 90 days")
221
+ .replace(/^deviceDisplayNames/, "--device-names")
222
+ .replace(/^operatingSystemDisplayNames/, "--os-names");
223
+ throw new error_1.FirebaseError(message, { exit: 1 });
224
+ }
225
+ throw err;
226
+ }
227
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_MAX_FRAMES = exports.EVENT_DUMP_OPTIONS = void 0;
3
+ exports.DEFAULT_MAX_FRAMES = void 0;
4
4
  exports.listEvents = listEvents;
5
5
  exports.normalizeEventResourceName = normalizeEventResourceName;
6
6
  exports.batchGetEvents = batchGetEvents;
@@ -12,7 +12,7 @@ const error_1 = require("../error");
12
12
  const utils_1 = require("./utils");
13
13
  const types_1 = require("./types");
14
14
  const filters_1 = require("./filters");
15
- exports.EVENT_DUMP_OPTIONS = { lineWidth: 200 };
15
+ const EVENT_DUMP_OPTIONS = { lineWidth: 200 };
16
16
  exports.DEFAULT_MAX_FRAMES = 20;
17
17
  const DEFAULT_MAX_LOGS = 100;
18
18
  const DEFAULT_MAX_BREADCRUMBS = 10;
@@ -37,23 +37,23 @@ async function listEvents(appId, filter, pageSize = 1, filterExpression) {
37
37
  (_a = response.body).events ?? (_a.events = []);
38
38
  return response.body;
39
39
  }
40
+ function escapeRegExp(value) {
41
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
42
+ }
40
43
  function normalizeEventResourceName(appId, eventIdOrName) {
41
44
  const trimmed = eventIdOrName.trim();
42
45
  if (!trimmed) {
43
46
  throw new error_1.FirebaseError("Event ID cannot be empty.");
44
47
  }
45
48
  const requestProjectNumber = (0, utils_1.parseProjectNumber)(appId);
46
- const expectedPrefix = `projects/${requestProjectNumber}/apps/${appId}/events/`;
47
- if (trimmed.startsWith(expectedPrefix)) {
48
- const eventId = trimmed.slice(expectedPrefix.length);
49
- if (eventId && !eventId.includes("/")) {
50
- return trimmed;
51
- }
49
+ const fullNamePattern = new RegExp(`^projects/[^/]+/apps/${escapeRegExp(appId)}/events/[^/]+$`);
50
+ if (fullNamePattern.test(trimmed)) {
51
+ return trimmed;
52
52
  }
53
53
  if (trimmed.includes("/")) {
54
- throw new error_1.FirebaseError(`Invalid event resource name '${trimmed}'. Expected an event ID or '${expectedPrefix}{event_id}'.`);
54
+ throw new error_1.FirebaseError(`Invalid event resource name '${trimmed}'. Expected an event ID or 'projects/{project}/apps/${appId}/events/{event_id}'.`);
55
55
  }
56
- return `${expectedPrefix}${trimmed}`;
56
+ return `projects/${requestProjectNumber}/apps/${appId}/events/${trimmed}`;
57
57
  }
58
58
  async function batchGetEvents(appId, eventNames) {
59
59
  var _a;
@@ -101,69 +101,67 @@ function formatFrames(origFrames, maxFrames = exports.DEFAULT_MAX_FRAMES) {
101
101
  }
102
102
  return formatted;
103
103
  }
104
- function toText(event, options = {}) {
105
- if (!event) {
106
- return {};
107
- }
104
+ function toText(events, options = {}) {
108
105
  const { maxFrames = exports.DEFAULT_MAX_FRAMES, full = false } = options;
109
- const effectiveMaxFrames = full ? Infinity : maxFrames;
110
- const result = {};
111
- for (const [key, value] of Object.entries(event)) {
112
- if (key === "logs") {
113
- const logs = value || [];
114
- const slicedLogs = !full && logs.length > DEFAULT_MAX_LOGS ? logs.slice(logs.length - DEFAULT_MAX_LOGS) : logs;
115
- const logLines = slicedLogs.map((log) => `[${log.logTime}] ${log.message}`);
116
- result["logs"] = logLines.join("\n");
117
- }
118
- else if (key === "breadcrumbs") {
119
- const breadcrumbs = value || [];
120
- const slicedBreadcrumbs = !full && breadcrumbs.length > DEFAULT_MAX_BREADCRUMBS
121
- ? breadcrumbs.slice(-DEFAULT_MAX_BREADCRUMBS)
122
- : breadcrumbs;
123
- const breadcrumbLines = slicedBreadcrumbs.map((b) => {
124
- const paramString = Object.entries(b.params || {})
125
- .map(([k, v]) => `${k}: ${v}`)
126
- .join(", ");
127
- const params = paramString ? ` { ${paramString} }` : "";
128
- return `[${b.eventTime}] ${b.title}${params}`;
129
- });
130
- result["breadcrumbs"] = breadcrumbLines.join("\n");
131
- }
132
- else if (key === "threads") {
133
- let threads = value || [];
134
- if (!full &&
135
- (event.issue?.errorType === types_1.ErrorType.FATAL || event.issue?.errorType === types_1.ErrorType.ANR)) {
136
- threads = threads.filter((t) => t.crashed || t.blamed);
137
- }
138
- const threadStrings = threads.map((thread) => {
139
- const header = `Thread: ${thread.name || thread.threadId || ""}${thread.crashed ? " (crashed)" : ""}`;
140
- const frameStrings = formatFrames(thread.frames || [], effectiveMaxFrames);
141
- return [header, ...frameStrings].join("\n");
142
- });
143
- result["threads"] = threadStrings.join("\n\n");
144
- }
145
- else if (key === "exceptions") {
146
- const exceptions = value || [];
147
- const exceptionStrings = exceptions.map((exception) => {
148
- const header = exception.nested ? "Caused by: " : "";
149
- const exceptionHeader = `${header}${exception.type || ""}: ${exception.exceptionMessage || ""}`;
150
- const frameStrings = formatFrames(exception.frames || [], effectiveMaxFrames);
151
- return [exceptionHeader, ...frameStrings].join("\n");
152
- });
153
- result["exceptions"] = exceptionStrings.join("\n\n");
154
- }
155
- else if (key === "errors") {
156
- const errors = value || [];
157
- const errorStrings = errors.map((error) => {
158
- const header = `Error: ${error.title || "error"}`;
159
- const frameStrings = formatFrames(error.frames || [], effectiveMaxFrames);
160
- return [header, ...frameStrings].join("\n");
161
- });
162
- result["errors"] = errorStrings.join("\n\n");
163
- }
164
- else {
165
- result[key] = (0, js_yaml_1.dump)(value, exports.EVENT_DUMP_OPTIONS);
166
- }
106
+ const maxFramesPerTrace = full ? Infinity : maxFrames;
107
+ const formatted = events.map((event) => ({
108
+ ...event,
109
+ logs: event.logs && formatLogs(event.logs, full),
110
+ breadcrumbs: event.breadcrumbs && formatBreadcrumbs(event.breadcrumbs, full),
111
+ threads: event.threads && formatThreads(event, full, maxFramesPerTrace),
112
+ exceptions: event.exceptions && formatExceptions(event.exceptions, maxFramesPerTrace),
113
+ errors: event.errors && formatErrors(event.errors, maxFramesPerTrace),
114
+ }));
115
+ return (0, js_yaml_1.dump)(formatted, EVENT_DUMP_OPTIONS);
116
+ }
117
+ function formatLogs(logs, full) {
118
+ const sliced = !full && logs.length > DEFAULT_MAX_LOGS ? logs.slice(-DEFAULT_MAX_LOGS) : logs;
119
+ return sliced.map((log) => `[${log.logTime}] ${log.message}`).join("\n");
120
+ }
121
+ function formatBreadcrumbs(breadcrumbs, full) {
122
+ const sliced = !full && breadcrumbs.length > DEFAULT_MAX_BREADCRUMBS
123
+ ? breadcrumbs.slice(-DEFAULT_MAX_BREADCRUMBS)
124
+ : breadcrumbs;
125
+ return sliced
126
+ .map((b) => {
127
+ const paramString = Object.entries(b.params || {})
128
+ .map(([k, v]) => `${k}: ${v}`)
129
+ .join(", ");
130
+ const params = paramString ? ` { ${paramString} }` : "";
131
+ return `[${b.eventTime}] ${b.title}${params}`;
132
+ })
133
+ .join("\n");
134
+ }
135
+ function formatThreads(event, full, maxFrames) {
136
+ let threads = event.threads || [];
137
+ if (!full &&
138
+ (event.issue?.errorType === types_1.ErrorType.FATAL || event.issue?.errorType === types_1.ErrorType.ANR)) {
139
+ threads = threads.filter((t) => t.crashed || t.blamed);
167
140
  }
168
- return result;
141
+ return threads
142
+ .map((thread) => {
143
+ const threadName = thread.name?.trim() || String(thread.threadId ?? "").trim();
144
+ const header = ["Thread:", threadName, thread.crashed ? "(crashed)" : ""]
145
+ .filter(Boolean)
146
+ .join(" ");
147
+ return [header, ...formatFrames(thread.frames || [], maxFrames)].join("\n");
148
+ })
149
+ .join("\n\n");
150
+ }
151
+ function formatExceptions(exceptions, maxFrames) {
152
+ return exceptions
153
+ .map((exception) => {
154
+ const prefix = exception.nested ? "Caused by: " : "";
155
+ const header = `${prefix}${exception.type || ""}: ${exception.exceptionMessage || ""}`;
156
+ return [header, ...formatFrames(exception.frames || [], maxFrames)].join("\n");
157
+ })
158
+ .join("\n\n");
159
+ }
160
+ function formatErrors(errors, maxFrames) {
161
+ return errors
162
+ .map((error) => {
163
+ const header = `Error: ${error.title || "error"}`;
164
+ return [header, ...formatFrames(error.frames || [], maxFrames)].join("\n");
165
+ })
166
+ .join("\n\n");
169
167
  }
@@ -61,7 +61,7 @@ exports.EventFilterSchema = zod_1.z
61
61
  exports.FilterExpressionSchema = zod_1.z
62
62
  .string()
63
63
  .optional()
64
- .describe(`An AIP-160 filter expression for custom keys (e.g. 'custom_keys.env = "prod"', 'custom_keys.experiment_id:*', or combined with 'AND' across different keys and 'OR' across values of one key).`);
64
+ .describe(`An AIP-160 filter expression for custom keys (e.g. 'custom_keys.env = "prod"', 'custom_keys.experiment_id:*', or combined with 'AND' across different keys and 'OR' across values of one key). For reports, only supported on web apps; check the report's usage to see whether it supports filter_expression.`);
65
65
  const toolToParamMap = {
66
66
  intervalStartTime: "filter.interval.start_time",
67
67
  intervalEndTime: "filter.interval.end_time",
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEFAULT_LIFECYCLE_RULES = exports.DEFAULT_CORS_RULES = exports.DEFAULT_FILE_TTL_DAYS = exports.DEFAULT_BUCKET_LOCATION = exports.DEFAULT_CORS_ORIGINS = exports.HEAP_DUMP_BUCKET_PREFIX = exports.STORAGE_OBJECT_CREATOR_ROLE = exports.CRASHLYTICS_SERVICE_NAME = void 0;
3
+ exports.DEFAULT_IAM_CONFIGURATION = exports.DEFAULT_LIFECYCLE_RULES = exports.DEFAULT_CORS_RULES = exports.DEFAULT_FILE_TTL_DAYS = exports.DEFAULT_BUCKET_LOCATION = exports.DEFAULT_CORS_ORIGINS = exports.HEAP_DUMP_BUCKET_PREFIX = exports.STORAGE_OBJECT_CREATOR_ROLE = exports.CRASHLYTICS_SERVICE_NAME = void 0;
4
4
  exports.parseAndroidHashedId = parseAndroidHashedId;
5
5
  exports.createBucketName = createBucketName;
6
6
  exports.getCrashlyticsP4sa = getCrashlyticsP4sa;
7
+ exports.getCrashlyticsConsoleUrl = getCrashlyticsConsoleUrl;
8
+ exports.resolveAndroidApp = resolveAndroidApp;
7
9
  exports.resolveAndroidAppId = resolveAndroidAppId;
8
10
  exports.getProfilingManagerConfig = getProfilingManagerConfig;
9
11
  exports.updateProfilingManagerConfig = updateProfilingManagerConfig;
@@ -16,7 +18,6 @@ const logger_1 = require("../logger");
16
18
  const utils_1 = require("../utils");
17
19
  const utils_2 = require("./utils");
18
20
  const storage = require("../gcp/storage");
19
- const resourceManager = require("../gcp/resourceManager");
20
21
  const serviceusage = require("../gcp/serviceusage");
21
22
  const apps_1 = require("../management/apps");
22
23
  exports.CRASHLYTICS_SERVICE_NAME = "firebasecrashlytics.googleapis.com";
@@ -38,8 +39,24 @@ exports.DEFAULT_LIFECYCLE_RULES = [
38
39
  condition: { age: exports.DEFAULT_FILE_TTL_DAYS },
39
40
  },
40
41
  ];
42
+ exports.DEFAULT_IAM_CONFIGURATION = {
43
+ publicAccessPrevention: "enforced",
44
+ uniformBucketLevelAccess: { enabled: true },
45
+ };
41
46
  const ANDROID_APP_ID_REGEX = /^\d+:(\d+):android:([a-fA-F0-9]+)$/;
42
47
  const GCS_BUCKET_RESOURCE_PREFIX = "projects/_/buckets/";
48
+ function isAndroidAppMetadata(app) {
49
+ return (app.platform === apps_1.AppPlatform.ANDROID &&
50
+ "packageName" in app &&
51
+ typeof app.packageName === "string");
52
+ }
53
+ function toResolvedAndroidApp(app) {
54
+ const packageName = isAndroidAppMetadata(app) ? app.packageName.trim() : "";
55
+ return {
56
+ appId: app.appId,
57
+ ...(packageName ? { packageName } : {}),
58
+ };
59
+ }
43
60
  function parseAndroidHashedId(appId) {
44
61
  const match = ANDROID_APP_ID_REGEX.exec(appId);
45
62
  if (!match) {
@@ -55,18 +72,33 @@ function createBucketName(appId) {
55
72
  function getCrashlyticsP4sa(projectNumber) {
56
73
  return `service-${projectNumber}@gcp-sa-crashlytics.iam.gserviceaccount.com`;
57
74
  }
58
- async function resolveAndroidAppId(projectId, options) {
59
- if (options.app) {
60
- parseAndroidHashedId(options.app);
61
- return options.app;
75
+ function getCrashlyticsConsoleUrl(projectId, packageName) {
76
+ const trimmedPackageName = packageName?.trim();
77
+ if (!trimmedPackageName) {
78
+ return (0, utils_1.consoleUrl)(projectId, "/crashlytics");
79
+ }
80
+ return (0, utils_1.consoleUrl)(projectId, `/crashlytics/app/android:${trimmedPackageName}/issues`);
81
+ }
82
+ async function resolveAndroidApp(projectId, options) {
83
+ const requestedAppId = options.app;
84
+ if (requestedAppId) {
85
+ parseAndroidHashedId(requestedAppId);
62
86
  }
63
87
  const apps = await (0, apps_1.listFirebaseApps)(projectId, apps_1.AppPlatform.ANDROID);
88
+ if (requestedAppId) {
89
+ const matchedApp = apps.find((app) => app.appId.toLowerCase() === requestedAppId.toLowerCase());
90
+ if (!matchedApp) {
91
+ throw new error_1.FirebaseError(`Android app '${requestedAppId}' was not found in project '${projectId}'. ` +
92
+ "Run 'firebase apps:list ANDROID' to view valid Android app IDs for your project.", { exit: 1 });
93
+ }
94
+ return toResolvedAndroidApp(matchedApp);
95
+ }
64
96
  if (apps.length === 0) {
65
97
  throw new error_1.FirebaseError(`No Android apps found in project '${projectId}'. Heap dump collection is only supported for Android apps.\n` +
66
98
  "You can register an Android app using 'firebase apps:create ANDROID <package-name>'");
67
99
  }
68
100
  if (apps.length === 1) {
69
- return apps[0].appId;
101
+ return toResolvedAndroidApp(apps[0]);
70
102
  }
71
103
  if (options.nonInteractive) {
72
104
  throw new error_1.FirebaseError(`Project '${projectId}' has multiple Android apps. Please specify an app ID with '--app <appID>'.`);
@@ -74,7 +106,11 @@ async function resolveAndroidAppId(projectId, options) {
74
106
  const selectedApp = await (0, apps_1.selectAppInteractively)(apps, apps_1.AppPlatform.ANDROID, {
75
107
  message: "Select an Android app:",
76
108
  });
77
- return selectedApp.appId;
109
+ return toResolvedAndroidApp(selectedApp);
110
+ }
111
+ async function resolveAndroidAppId(projectId, options) {
112
+ const app = await resolveAndroidApp(projectId, options);
113
+ return app.appId;
78
114
  }
79
115
  async function getProfilingManagerConfig(appId) {
80
116
  const projectNumber = (0, utils_2.parseProjectNumber)(appId);
@@ -111,6 +147,9 @@ async function ensureHeapDumpStorageBucket(projectId, appId, location = exports.
111
147
  if (bucket.projectNumber && String(bucket.projectNumber) !== projectNumber) {
112
148
  throw new error_1.FirebaseError(`Cloud Storage bucket '${bucketName}' already exists and is owned by another project.`);
113
149
  }
150
+ if (bucket.location && bucket.location.trim().toLowerCase() !== location.trim().toLowerCase()) {
151
+ (0, utils_1.logLabeledWarning)("crashlytics", `Cloud Storage bucket '${bucketName}' already exists in ${bucket.location}; its location cannot be changed to '${location}' and will remain ${bucket.location}.`);
152
+ }
114
153
  const patchPayload = {};
115
154
  const hasConsoleCors = bucket.cors?.some((rule) => exports.DEFAULT_CORS_ORIGINS.every((origin) => rule.origin?.includes(origin)));
116
155
  if (!hasConsoleCors) {
@@ -122,6 +161,14 @@ async function ensureHeapDumpStorageBucket(projectId, appId, location = exports.
122
161
  rule: [...(bucket.lifecycle?.rule ?? []), ...exports.DEFAULT_LIFECYCLE_RULES],
123
162
  };
124
163
  }
164
+ const needsUbla = !bucket.iamConfiguration?.uniformBucketLevelAccess?.enabled;
165
+ const needsPap = bucket.iamConfiguration?.publicAccessPrevention !== "enforced";
166
+ if (needsUbla || needsPap) {
167
+ patchPayload.iamConfiguration = {
168
+ ...(needsPap ? { publicAccessPrevention: "enforced" } : {}),
169
+ ...(needsUbla ? { uniformBucketLevelAccess: { enabled: true } } : {}),
170
+ };
171
+ }
125
172
  if (Object.keys(patchPayload).length > 0) {
126
173
  logger_1.logger.debug(`[crashlytics] Bucket ${bucketName} found without full configuration. Patching ${Object.keys(patchPayload).join(", ")}.`);
127
174
  await storage.patchBucket(bucketName, patchPayload);
@@ -140,24 +187,24 @@ async function ensureHeapDumpStorageBucket(projectId, appId, location = exports.
140
187
  location,
141
188
  cors: exports.DEFAULT_CORS_RULES,
142
189
  lifecycle: { rule: exports.DEFAULT_LIFECYCLE_RULES },
143
- }, true);
190
+ iamConfiguration: exports.DEFAULT_IAM_CONFIGURATION,
191
+ });
144
192
  return bucketName;
145
193
  }
146
- async function ensureHeapDumpP4saRole(projectId, projectNumber) {
194
+ async function ensureHeapDumpP4saRole(projectNumber, bucketName) {
147
195
  await serviceusage.generateServiceIdentityAndPoll(projectNumber, exports.CRASHLYTICS_SERVICE_NAME, "crashlytics");
148
196
  const p4saEmail = getCrashlyticsP4sa(projectNumber);
149
- const hasRole = await resourceManager.serviceAccountHasRoles(projectId, p4saEmail, [exports.STORAGE_OBJECT_CREATOR_ROLE], true);
150
- if (!hasRole) {
151
- logger_1.logger.debug(`[crashlytics] Adding ${exports.STORAGE_OBJECT_CREATOR_ROLE} to ${p4saEmail}...`);
152
- await resourceManager.addServiceAccountToRoles(projectId, p4saEmail, [exports.STORAGE_OBJECT_CREATOR_ROLE], true);
153
- }
197
+ logger_1.logger.debug(`[crashlytics] Ensuring ${exports.STORAGE_OBJECT_CREATOR_ROLE} on bucket ${bucketName} for ${p4saEmail}...`);
198
+ await storage.addServiceAccountToBucketRoles(bucketName, p4saEmail, [
199
+ exports.STORAGE_OBJECT_CREATOR_ROLE,
200
+ ]);
154
201
  }
155
202
  async function enableHeapDumpCollection(projectId, appId, location = exports.DEFAULT_BUCKET_LOCATION) {
156
203
  const projectNumber = (0, utils_2.parseProjectNumber)(appId);
157
204
  (0, utils_1.logLabeledBullet)("crashlytics", "Configuring Google Cloud Storage bucket...");
158
205
  const bucketName = await ensureHeapDumpStorageBucket(projectId, appId, location);
159
206
  (0, utils_1.logLabeledBullet)("crashlytics", "Configuring service agent permissions...");
160
- await ensureHeapDumpP4saRole(projectId, projectNumber);
207
+ await ensureHeapDumpP4saRole(projectNumber, bucketName);
161
208
  (0, utils_1.logLabeledBullet)("crashlytics", "Enabling Crashlytics heap dump collection...");
162
209
  await updateProfilingManagerConfig(appId, {
163
210
  bucket: `${GCS_BUCKET_RESOURCE_PREFIX}${bucketName}`,
@@ -21,6 +21,7 @@ exports.ReportInputSchema = zod_1.z.object({
21
21
  appId: filters_1.ApplicationIdSchema,
22
22
  report: exports.CrashlyticsReportSchema,
23
23
  filter: filters_1.EventFilterSchema,
24
+ filterExpression: filters_1.FilterExpressionSchema,
24
25
  pageSize: zod_1.z.number().optional().describe("Number of rows to return").default(DEFAULT_PAGE_SIZE),
25
26
  granularity: exports.TimeGranularitySchema,
26
27
  });
@@ -60,7 +61,7 @@ async function listReports(appId) {
60
61
  (_a = response.body).reports ?? (_a.reports = []);
61
62
  return response.body;
62
63
  }
63
- async function getReport(reportName, appId, filter, pageSize = DEFAULT_PAGE_SIZE, granularity) {
64
+ async function getReport(reportName, appId, filter, pageSize = DEFAULT_PAGE_SIZE, granularity, filterExpression) {
64
65
  const requestProjectNumber = (0, utils_1.parseProjectNumber)(appId);
65
66
  let availableReports = exports.reportsCache.get(appId);
66
67
  if (!availableReports) {
@@ -84,6 +85,9 @@ async function getReport(reportName, appId, filter, pageSize = DEFAULT_PAGE_SIZE
84
85
  if (granularity) {
85
86
  queryParams.set("granularity", granularity);
86
87
  }
88
+ if (filterExpression) {
89
+ queryParams.set("filter_expression", filterExpression);
90
+ }
87
91
  logger_1.logger.debug(`[crashlytics] report ${reportName} called with appId: ${appId} filter: ${queryParams.toString()}, page_size: ${pageSize}`);
88
92
  const response = await utils_1.CRASHLYTICS_API_CLIENT.request({
89
93
  method: "GET",
@@ -29,8 +29,10 @@ async function listLocations(projectId) {
29
29
  const res = await dataconnectClient().get(`/projects/${projectId}/locations`);
30
30
  return res.body?.locations?.map((l) => l.locationId) ?? [];
31
31
  }
32
- async function getService(serviceName) {
33
- const res = await dataconnectClient().get(serviceName);
32
+ async function getService(serviceName, fields = []) {
33
+ const res = await dataconnectClient().get(serviceName, {
34
+ queryParams: fields.length ? { fields: fields.join(",") } : undefined,
35
+ });
34
36
  return res.body;
35
37
  }
36
38
  async function listAllServices(projectId) {
@@ -71,9 +73,11 @@ async function deleteService(serviceName) {
71
73
  });
72
74
  return pollRes;
73
75
  }
74
- async function getSchema(serviceName, schemaId = types.MAIN_SCHEMA_ID) {
76
+ async function getSchema(serviceName, schemaId = types.MAIN_SCHEMA_ID, fields = []) {
75
77
  try {
76
- const res = await dataconnectClient().get(`${serviceName}/schemas/${schemaId}`);
78
+ const res = await dataconnectClient().get(`${serviceName}/schemas/${schemaId}`, {
79
+ queryParams: fields.length ? { fields: fields.join(",") } : undefined,
80
+ });
77
81
  return res.body;
78
82
  }
79
83
  catch (err) {
@@ -90,7 +94,7 @@ async function listSchemas(serviceName, fields = []) {
90
94
  queryParams: {
91
95
  pageSize: PAGE_SIZE_MAX,
92
96
  pageToken,
93
- fields: fields.join(","),
97
+ ...(fields.length ? { fields: fields.join(",") } : {}),
94
98
  },
95
99
  });
96
100
  schemas.push(...(res.body.schemas || []));
@@ -127,8 +131,10 @@ async function deleteSchema(name) {
127
131
  });
128
132
  return;
129
133
  }
130
- async function getConnector(name) {
131
- const res = await dataconnectClient().get(name);
134
+ async function getConnector(name, fields = []) {
135
+ const res = await dataconnectClient().get(name, {
136
+ queryParams: fields.length ? { fields: fields.join(",") } : undefined,
137
+ });
132
138
  return res.body;
133
139
  }
134
140
  async function deleteConnector(name) {
@@ -147,7 +153,7 @@ async function listConnectors(serviceName, fields = []) {
147
153
  queryParams: {
148
154
  pageSize: PAGE_SIZE_MAX,
149
155
  pageToken,
150
- fields: fields.join(","),
156
+ ...(fields.length ? { fields: fields.join(",") } : {}),
151
157
  },
152
158
  });
153
159
  connectors.push(...(res.body.connectors || []));