firebase-tools 15.23.0 → 15.25.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 (74) hide show
  1. package/lib/api.js +4 -2
  2. package/lib/appcheck/api.js +42 -0
  3. package/lib/appcheck/prompts.js +41 -0
  4. package/lib/appcheck/types.js +2 -0
  5. package/lib/bin/cli.js +9 -2
  6. package/lib/bin/progressiveHelp.js +126 -0
  7. package/lib/checkValidTargetFilters.js +1 -1
  8. package/lib/command.js +11 -10
  9. package/lib/commands/ailogic-config-get.js +75 -0
  10. package/lib/commands/ailogic-config-set.js +109 -0
  11. package/lib/commands/ailogic-providers-disable.js +39 -0
  12. package/lib/commands/ailogic-providers-enable.js +28 -0
  13. package/lib/commands/ailogic-providers-list.js +29 -0
  14. package/lib/commands/appcheck-debugtokens-create.js +95 -0
  15. package/lib/commands/appcheck-debugtokens-delete.js +48 -0
  16. package/lib/commands/appcheck-debugtokens-list.js +35 -0
  17. package/lib/commands/apps-sdkconfig.js +2 -23
  18. package/lib/commands/database-get.js +1 -1
  19. package/lib/commands/dataconnect-execute.js +1 -1
  20. package/lib/commands/deploy.js +27 -64
  21. package/lib/commands/index.js +15 -0
  22. package/lib/deploy/apphosting/index.js +26 -1
  23. package/lib/deploy/auth/index.js +18 -1
  24. package/lib/deploy/database/index.js +16 -1
  25. package/lib/deploy/dataconnect/index.js +19 -1
  26. package/lib/deploy/extensions/index.js +9 -1
  27. package/lib/deploy/firestore/index.js +20 -1
  28. package/lib/deploy/functions/build.js +93 -3
  29. package/lib/deploy/functions/index.js +33 -1
  30. package/lib/deploy/functions/params.js +68 -26
  31. package/lib/deploy/functions/prepare.js +34 -8
  32. package/lib/deploy/functions/prompts.js +19 -0
  33. package/lib/deploy/functions/release/index.js +19 -12
  34. package/lib/deploy/functions/release/lifecycle.js +38 -5
  35. package/lib/deploy/functions/release/planner.js +3 -1
  36. package/lib/deploy/functions/runtimes/node/index.js +8 -7
  37. package/lib/deploy/functions/runtimes/node/versioning.js +8 -3
  38. package/lib/deploy/functions/validate.js +5 -2
  39. package/lib/deploy/hosting/index.js +30 -1
  40. package/lib/deploy/hosting/uploader.js +2 -1
  41. package/lib/deploy/index.js +68 -8
  42. package/lib/deploy/remoteconfig/index.js +9 -1
  43. package/lib/deploy/storage/index.js +16 -1
  44. package/lib/emulator/dataconnect/pgliteServer.js +2 -1
  45. package/lib/emulator/downloadableEmulatorInfo.json +30 -30
  46. package/lib/emulator/downloadableEmulators.js +1 -0
  47. package/lib/emulator/hubExport.js +2 -1
  48. package/lib/emulator/storage/apis/firebase.js +24 -5
  49. package/lib/emulator/storage/apis/gcloud.js +16 -6
  50. package/lib/emulator/storage/rules/runtime.js +45 -33
  51. package/lib/emulator/storage/server.js +2 -5
  52. package/lib/emulator/storage/upload.js +1 -0
  53. package/lib/ensureApiEnabled.js +8 -0
  54. package/lib/experiments.js +16 -0
  55. package/lib/extensions/warnings.js +64 -0
  56. package/lib/frameworks/utils.js +50 -1
  57. package/lib/functions/env.js +22 -2
  58. package/lib/functions/secrets.js +4 -1
  59. package/lib/gcp/ailogic.js +165 -1
  60. package/lib/gcp/cloudfunctionsv2.js +7 -0
  61. package/lib/gcp/firedata.js +5 -1
  62. package/lib/gcp/serviceusage.js +26 -0
  63. package/lib/hosting/proxy.js +15 -3
  64. package/lib/index.js +0 -1
  65. package/lib/init/features/ailogic/index.js +3 -29
  66. package/lib/init/features/database.js +1 -1
  67. package/lib/management/apps.js +16 -5
  68. package/lib/mcp/onemcp/onemcp_server.js +28 -9
  69. package/lib/mcp/tools/core/get_security_rules.js +2 -1
  70. package/lib/profiler.js +1 -1
  71. package/lib/streamUtils.js +3 -0
  72. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  73. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  74. package/package.json +2 -2
@@ -66,6 +66,7 @@ class StorageRulesRuntime {
66
66
  this._requestCount = 0;
67
67
  this._requests = {};
68
68
  this._alive = false;
69
+ this._stdoutBuffer = "";
69
70
  }
70
71
  get alive() {
71
72
  return this._alive;
@@ -121,37 +122,46 @@ class StorageRulesRuntime {
121
122
  }
122
123
  });
123
124
  this._childprocess.stdout?.on("data", (buf) => {
124
- const serializedRuntimeActionResponse = buf.toString("utf-8").trim();
125
- if (serializedRuntimeActionResponse !== "") {
126
- let rap;
127
- try {
128
- rap = JSON.parse(serializedRuntimeActionResponse);
129
- }
130
- catch (err) {
131
- emulatorLogger_1.EmulatorLogger.forEmulator(types_2.Emulators.STORAGE).log("INFO", serializedRuntimeActionResponse);
132
- return;
133
- }
134
- const id = rap.id ?? rap.server_request_id;
135
- if (id === undefined) {
136
- console.log(`Received no ID from server response ${serializedRuntimeActionResponse}`);
137
- return;
138
- }
139
- const request = this._requests[id];
140
- if (rap.status !== "ok" && !("action" in rap)) {
141
- console.warn(`[RULES] ${rap.status}: ${rap.message}`);
142
- rap.errors.forEach(console.warn.bind(console));
143
- return;
144
- }
145
- if (request) {
146
- request.handler(rap);
147
- }
148
- else {
149
- console.log(`No handler for event ${serializedRuntimeActionResponse}`);
150
- }
151
- }
125
+ this.handleRuntimeStdout(buf.toString("utf-8"));
152
126
  });
153
127
  return startPromise;
154
128
  }
129
+ handleRuntimeStdout(chunk) {
130
+ this._stdoutBuffer += chunk;
131
+ const lines = this._stdoutBuffer.split("\n");
132
+ this._stdoutBuffer = lines.pop() ?? "";
133
+ for (const rawLine of lines) {
134
+ const line = rawLine.trim();
135
+ if (line === "") {
136
+ continue;
137
+ }
138
+ let rap;
139
+ try {
140
+ rap = JSON.parse(line);
141
+ }
142
+ catch (err) {
143
+ emulatorLogger_1.EmulatorLogger.forEmulator(types_2.Emulators.STORAGE).log("INFO", line);
144
+ continue;
145
+ }
146
+ const id = rap.id ?? rap.server_request_id;
147
+ if (id === undefined) {
148
+ console.log(`Received no ID from server response ${line}`);
149
+ continue;
150
+ }
151
+ const request = this._requests[id];
152
+ if (rap.status !== "ok" && !("action" in rap)) {
153
+ console.warn(`[RULES] ${rap.status}: ${rap.message}`);
154
+ rap.errors.forEach(console.warn.bind(console));
155
+ continue;
156
+ }
157
+ if (request) {
158
+ request.handler(rap);
159
+ }
160
+ else {
161
+ console.log(`No handler for event ${line}`);
162
+ }
163
+ }
164
+ }
155
165
  stop() {
156
166
  emulatorLogger_1.EmulatorLogger.forEmulator(types_2.Emulators.STORAGE).log("DEBUG", "Stopping rules runtime.");
157
167
  return new Promise((resolve) => {
@@ -181,16 +191,18 @@ class StorageRulesRuntime {
181
191
  throw new error_1.FirebaseError("Attempted to send Cloud Storage rules request with stale id");
182
192
  }
183
193
  return new Promise((resolve) => {
184
- this._requests[runtimeActionRequest.id] = {
194
+ const requestId = runtimeActionRequest.id;
195
+ this._requests[requestId] = {
185
196
  request: runtimeActionRequest,
186
- handler: resolve,
197
+ handler: (rap) => {
198
+ delete this._requests[requestId];
199
+ resolve(rap);
200
+ },
187
201
  };
188
202
  const serializedRequest = JSON.stringify(runtimeActionRequest);
189
203
  lock.acquire(synchonizationKey, (done) => {
190
204
  this._childprocess?.stdin?.write(serializedRequest + "\n");
191
- setTimeout(() => {
192
- done();
193
- }, 15);
205
+ done();
194
206
  });
195
207
  });
196
208
  }
@@ -38,10 +38,7 @@ function createApp(defaultProjectId, emulator) {
38
38
  }));
39
39
  app.use(bodyParser.raw({ limit: "130mb", type: "application/x-www-form-urlencoded" }));
40
40
  app.use(bodyParser.raw({ limit: "130mb", type: "multipart/related" }));
41
- app.use(express.json({
42
- type: ["application/json"],
43
- }));
44
- app.post("/internal/export", async (req, res) => {
41
+ app.post("/internal/export", express.json({ limit: "130mb" }), async (req, res) => {
45
42
  const initiatedBy = req.body.initiatedBy || "unknown";
46
43
  const path = req.body.path;
47
44
  if (!path) {
@@ -51,7 +48,7 @@ function createApp(defaultProjectId, emulator) {
51
48
  await storageLayer.export(path, { initiatedBy });
52
49
  res.sendStatus(200);
53
50
  });
54
- app.put("/internal/setRules", async (req, res) => {
51
+ app.put("/internal/setRules", express.json({ limit: "130mb" }), async (req, res) => {
55
52
  const rulesRaw = req.body.rules;
56
53
  if (!(rulesRaw && Array.isArray(rulesRaw.files) && rulesRaw.files.length > 0)) {
57
54
  res.status(400).json({
@@ -38,6 +38,7 @@ class UploadService {
38
38
  objectId: request.objectId,
39
39
  uploadType: UploadType.MEDIA,
40
40
  dataRaw: request.dataRaw,
41
+ metadata: request.contentType ? { contentType: request.contentType } : undefined,
41
42
  authorization: request.authorization,
42
43
  });
43
44
  this._persistence.deleteFile(upload.path, true);
@@ -5,6 +5,7 @@ exports.check = check;
5
5
  exports.ensure = ensure;
6
6
  exports.bestEffortEnsure = bestEffortEnsure;
7
7
  exports.enableApiURI = enableApiURI;
8
+ exports.uncacheEnabledAPI = uncacheEnabledAPI;
8
9
  const colorette_1 = require("colorette");
9
10
  const track_1 = require("./track");
10
11
  const api_1 = require("./api");
@@ -140,3 +141,10 @@ function cacheEnabledAPI(projectId, apiName) {
140
141
  cache[projectId][apiName] = true;
141
142
  configstore_1.configstore.set(API_ENABLEMENT_CACHE_KEY, cache);
142
143
  }
144
+ function uncacheEnabledAPI(projectId, apiName) {
145
+ const cache = (configstore_1.configstore.get(API_ENABLEMENT_CACHE_KEY) || {});
146
+ if (cache[projectId]) {
147
+ delete cache[projectId][apiName];
148
+ configstore_1.configstore.set(API_ENABLEMENT_CACHE_KEY, cache);
149
+ }
150
+ }
@@ -115,6 +115,12 @@ exports.ALL_EXPERIMENTS = experiments({
115
115
  "These commands are not meant for public consumption and may break or disappear " +
116
116
  "without a notice.",
117
117
  },
118
+ ailogic: {
119
+ shortDescription: "Manage Firebase AI Logic from the CLI.",
120
+ fullDescription: "Enables the `firebase ailogic` command surface for managing Firebase AI Logic, " +
121
+ "starting with the Gemini API providers. These commands are in preview and may " +
122
+ "change until the underlying API is finalized.",
123
+ },
118
124
  apphosting: {
119
125
  shortDescription: "Allow CLI option for Frameworks",
120
126
  default: true,
@@ -186,6 +192,16 @@ exports.ALL_EXPERIMENTS = experiments({
186
192
  default: false,
187
193
  public: true,
188
194
  },
195
+ secretEnvParams: {
196
+ shortDescription: "Enable writing the backing resource binding for a Functions secret param to .env",
197
+ default: false,
198
+ public: false,
199
+ },
200
+ extdeprecationwarnings: {
201
+ shortDescription: "Show deprecation warnings for Firebase Extensions CLI commands.",
202
+ default: true,
203
+ public: true,
204
+ },
189
205
  });
190
206
  function isValidExperiment(name) {
191
207
  return Object.keys(exports.ALL_EXPERIMENTS).includes(name);
@@ -2,10 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.displayWarningsForDeploy = displayWarningsForDeploy;
4
4
  exports.outOfBandChangesWarning = outOfBandChangesWarning;
5
+ exports.isSilenced = isSilenced;
6
+ exports.showDeprecationWarningBefore = showDeprecationWarningBefore;
7
+ exports.showDeprecationWarningAfter = showDeprecationWarningAfter;
5
8
  const clc = require("colorette");
6
9
  const extensionsHelper_1 = require("./extensionsHelper");
7
10
  const deploymentSummary_1 = require("../deploy/extensions/deploymentSummary");
8
11
  const planner_1 = require("../deploy/extensions/planner");
12
+ const error_1 = require("../error");
9
13
  const logger_1 = require("../logger");
10
14
  const utils = require("../utils");
11
15
  const toListEntry = (i) => {
@@ -38,3 +42,63 @@ function outOfBandChangesWarning(instanceIds, isDynamic) {
38
42
  clc.bold(instanceIds.join("\n\t")) +
39
43
  `\nIf you proceed with this deployment, those changes will be overwritten.${extra}`);
40
44
  }
45
+ const FAQ_URL = "https://firebase.google.com/docs/extensions/faq-and-troubleshooting";
46
+ const WARN_BEFORE_COMMANDS = new Set([
47
+ "ext:install",
48
+ "ext:configure",
49
+ "ext:update",
50
+ "ext:sdk:install",
51
+ ]);
52
+ const WARN_STRONGLY_BEFORE_COMMANDS = new Set([
53
+ "ext:dev:init",
54
+ "ext:dev:upload",
55
+ "ext:dev:list",
56
+ "ext:dev:usage",
57
+ "ext:dev:undeprecate",
58
+ ]);
59
+ const WARN_AFTER_COMMANDS = new Set(["ext:list", "ext:info"]);
60
+ function isSilenced(options) {
61
+ const opts = options;
62
+ if (opts?.json ||
63
+ utils.getInheritedOption(options, "json") ||
64
+ opts?.nonInteractive ||
65
+ utils.getInheritedOption(options, "nonInteractive") ||
66
+ !process.stdout?.isTTY ||
67
+ opts?.quiet ||
68
+ utils.getInheritedOption(options, "quiet")) {
69
+ return true;
70
+ }
71
+ if (utils.isRunningInGithubAction() ||
72
+ (!!process.env.CI && process.env.CI !== "false") ||
73
+ !!process.env.BUILD_ID ||
74
+ !!process.env.TF_BUILD ||
75
+ !!process.env.GITHUB_ACTIONS) {
76
+ return true;
77
+ }
78
+ return false;
79
+ }
80
+ function showDeprecationWarningBefore(commandName, options) {
81
+ if (commandName === "ext:dev:register") {
82
+ throw new error_1.FirebaseError(`ext:dev:register is disabled. Registering new publisher profile IDs is no longer supported.\n` +
83
+ `The Firebase Extensions service will shut down on March 31, 2027.\n` +
84
+ `Learn more: ${FAQ_URL}`, { exit: 1 });
85
+ }
86
+ if (isSilenced(options)) {
87
+ return;
88
+ }
89
+ if (WARN_BEFORE_COMMANDS.has(commandName)) {
90
+ logger_1.logger.warn(clc.yellow(`⚠ Firebase Extensions will shut down on March 31, 2027. You will not be able to install or edit extensions after this date. Learn more: ${FAQ_URL}`));
91
+ }
92
+ else if (WARN_STRONGLY_BEFORE_COMMANDS.has(commandName)) {
93
+ logger_1.logger.warn(clc.yellow(`================================================================================\n` +
94
+ `⚠ Notice for Publishers: Firebase Extensions will shut down on March 31, 2027.\n` +
95
+ `Learn more: ${FAQ_URL}\n` +
96
+ `================================================================================`));
97
+ }
98
+ }
99
+ function showDeprecationWarningAfter(commandName, options) {
100
+ if (isSilenced(options) || !WARN_AFTER_COMMANDS.has(commandName)) {
101
+ return;
102
+ }
103
+ logger_1.logger.warn(clc.yellow(`⚠ Notice: Firebase Extensions will shut down on March 31, 2027. Learn more: ${FAQ_URL}`));
104
+ }
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_REQUEST_BODY_BYTES = void 0;
3
4
  exports.isUrl = isUrl;
4
5
  exports.readJSON = readJSON;
5
6
  exports.warnIfCustomBuildScript = warnIfCustomBuildScript;
6
7
  exports.proxyResponse = proxyResponse;
8
+ exports.bufferRequestBody = bufferRequestBody;
7
9
  exports.simpleProxy = simpleProxy;
8
10
  exports.getNpmRoot = getNpmRoot;
9
11
  exports.getNodeModuleBin = getNodeModuleBin;
@@ -86,12 +88,29 @@ function proxyResponse(req, res, next) {
86
88
  });
87
89
  return proxiedRes;
88
90
  }
91
+ exports.MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024;
92
+ async function bufferRequestBody(req) {
93
+ const chunks = [];
94
+ let total = 0;
95
+ for await (const chunk of req) {
96
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
97
+ total += buf.length;
98
+ if (total > exports.MAX_REQUEST_BODY_BYTES) {
99
+ throw new error_1.FirebaseError(`Request body exceeds the ${exports.MAX_REQUEST_BODY_BYTES} byte limit`, {
100
+ status: 413,
101
+ });
102
+ }
103
+ chunks.push(buf);
104
+ }
105
+ return Buffer.concat(chunks);
106
+ }
89
107
  function simpleProxy(hostOrRequestHandler) {
90
108
  const agent = new http_1.Agent({ keepAlive: true });
91
109
  const firebaseDefaultsJSON = process.env.__FIREBASE_DEFAULTS__;
92
110
  const authTokenSyncURL = firebaseDefaultsJSON && JSON.parse(firebaseDefaultsJSON)._authTokenSyncURL;
93
111
  return async (originalReq, originalRes, next) => {
94
112
  const { method, headers, url: path } = originalReq;
113
+ originalRes.on("error", (err) => logger_1.logger.debug("Response stream error:", method, path, err));
95
114
  if (!method || !path) {
96
115
  originalRes.end();
97
116
  return;
@@ -117,6 +136,31 @@ function simpleProxy(hostOrRequestHandler) {
117
136
  "X-Forwarded-Host": headers.host,
118
137
  },
119
138
  };
139
+ let rawBody;
140
+ if (!["GET", "HEAD"].includes(method)) {
141
+ try {
142
+ rawBody = await bufferRequestBody(originalReq);
143
+ }
144
+ catch (err) {
145
+ if (err instanceof error_1.FirebaseError && err.status === 413) {
146
+ originalRes.statusCode = 413;
147
+ originalRes.end();
148
+ return;
149
+ }
150
+ logger_1.logger.debug("Error buffering request body:", method, path, err);
151
+ if (originalRes.writable) {
152
+ originalRes.statusCode = 400;
153
+ originalRes.end();
154
+ }
155
+ else {
156
+ originalRes.destroy();
157
+ }
158
+ return;
159
+ }
160
+ originalReq.rawBody = rawBody;
161
+ opts.headers["content-length"] = rawBody.length.toString();
162
+ delete opts.headers["transfer-encoding"];
163
+ }
120
164
  const req = (0, http_1.request)(opts, (response) => {
121
165
  const { statusCode, statusMessage, headers } = response;
122
166
  if (statusCode === 404) {
@@ -127,11 +171,16 @@ function simpleProxy(hostOrRequestHandler) {
127
171
  response.pipe(originalRes);
128
172
  }
129
173
  });
130
- originalReq.pipe(req);
131
174
  req.on("error", (err) => {
132
175
  logger_1.logger.debug("Error encountered while proxying request:", method, path, err);
133
176
  originalRes.end();
134
177
  });
178
+ if (rawBody !== undefined) {
179
+ req.end(rawBody);
180
+ }
181
+ else {
182
+ originalReq.pipe(req);
183
+ }
135
184
  }
136
185
  else {
137
186
  const proxiedRes = proxyResponse(originalReq, originalRes, () => {
@@ -10,6 +10,7 @@ exports.checkForDuplicateKeys = checkForDuplicateKeys;
10
10
  exports.loadUserEnvs = loadUserEnvs;
11
11
  exports.loadFirebaseEnvs = loadFirebaseEnvs;
12
12
  exports.writeResolvedParams = writeResolvedParams;
13
+ exports.writeResolvedSecretRefs = writeResolvedSecretRefs;
13
14
  const clc = require("colorette");
14
15
  const fs = require("fs");
15
16
  const path = require("path");
@@ -17,7 +18,8 @@ const error_1 = require("../error");
17
18
  const logger_1 = require("../logger");
18
19
  const utils_1 = require("../utils");
19
20
  const FUNCTIONS_EMULATOR_DOTENV = ".env.local";
20
- const RESERVED_PREFIXES = ["X_GOOGLE_", "FIREBASE_", "EXT_"];
21
+ const RESERVED_PREFIXES = ["X_GOOGLE_", "FIREBASE_", "EXT_", "KIT_"];
22
+ const RESERVED_PREFIX_ALLOWLIST = ["FIREBASE_SECRET_REF_"];
21
23
  const RESERVED_KEYS = [
22
24
  "FIREBASE_CONFIG",
23
25
  "CLOUD_RUNTIME_CONFIG",
@@ -117,9 +119,15 @@ function validateKey(key) {
117
119
  throw new KeyValidationError(key, `Key ${key} must start with an uppercase ASCII letter or underscore` +
118
120
  ", and then consist of uppercase ASCII letters, digits, and underscores.");
119
121
  }
120
- if (RESERVED_PREFIXES.some((prefix) => key.startsWith(prefix))) {
122
+ if (keyConflictsWithReservedPrefixes(key)) {
121
123
  throw new KeyValidationError(key, `Key ${key} starts with a reserved prefix (${RESERVED_PREFIXES.join(" ")})`);
122
124
  }
125
+ if (RESERVED_PREFIX_ALLOWLIST.some((prefix) => key === prefix)) {
126
+ throw new KeyValidationError(key, `Key ${key} is a known prefix with an empty suffix`);
127
+ }
128
+ }
129
+ function keyConflictsWithReservedPrefixes(key) {
130
+ return RESERVED_PREFIXES.some((prefix) => key.startsWith(prefix) && !RESERVED_PREFIX_ALLOWLIST.some((known) => key.startsWith(known)));
123
131
  }
124
132
  function parseStrict(data) {
125
133
  const { envs, errors } = parse(data);
@@ -260,3 +268,15 @@ function writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt) {
260
268
  }
261
269
  writeUserEnvs(toWrite, userEnvOpt);
262
270
  }
271
+ function writeResolvedSecretRefs(resolvedSecretRefs, haveSecretRefs, userEnvOpt) {
272
+ const toWrite = {};
273
+ for (const secretName of Object.keys(resolvedSecretRefs)) {
274
+ const uppercaseName = secretName.toUpperCase();
275
+ const resolvedRef = resolvedSecretRefs[uppercaseName];
276
+ if (!Object.prototype.hasOwnProperty.call(haveSecretRefs, uppercaseName)) {
277
+ const reservedKey = "FIREBASE_SECRET_REF_" + uppercaseName;
278
+ toWrite[reservedKey] = resolvedRef;
279
+ }
280
+ }
281
+ writeUserEnvs(toWrite, userEnvOpt);
282
+ }
@@ -175,7 +175,10 @@ async function pruneSecrets(projectInfo, endpoints) {
175
175
  }
176
176
  if (secret.projectId === projectId || secret.projectId === projectNumber) {
177
177
  if (secret.version) {
178
- secrets.push({ ...secret, version: secret.version });
178
+ secrets.push({
179
+ ...secret,
180
+ version: secret.version,
181
+ });
179
182
  }
180
183
  }
181
184
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.client = exports.AI_LOGIC_TRIGGERS_TO_EVENTS = exports.AI_LOGIC_EVENTS_TO_TRIGGER = exports.AI_LOGIC_AFTER_GENERATE_CONTENT = exports.AI_LOGIC_BEFORE_GENERATE_CONTENT = exports.API_VERSION = void 0;
3
+ exports.PROVIDER_TYPES = exports.WRITABLE_CONFIG_PATHS = exports.client = exports.AI_LOGIC_TRIGGERS_TO_EVENTS = exports.AI_LOGIC_EVENTS_TO_TRIGGER = exports.AI_LOGIC_AFTER_GENERATE_CONTENT = exports.AI_LOGIC_BEFORE_GENERATE_CONTENT = exports.GLOBAL_LOCATION = exports.AILOGIC_LOGGING_PREFIX = exports.API_VERSION = void 0;
4
4
  exports.createTrigger = createTrigger;
5
5
  exports.getTrigger = getTrigger;
6
6
  exports.updateTrigger = updateTrigger;
@@ -8,10 +8,29 @@ exports.deleteTrigger = deleteTrigger;
8
8
  exports.listTriggers = listTriggers;
9
9
  exports.upsertBlockingFunction = upsertBlockingFunction;
10
10
  exports.deleteBlockingFunction = deleteBlockingFunction;
11
+ exports.assertKnownConfigPath = assertKnownConfigPath;
12
+ exports.isProviderType = isProviderType;
13
+ exports.parseProviderType = parseProviderType;
14
+ exports.getConfig = getConfig;
15
+ exports.updateConfig = updateConfig;
16
+ exports.enableProvider = enableProvider;
17
+ exports.disableProvider = disableProvider;
18
+ exports.listProviders = listProviders;
19
+ exports.isAILogicApiEnabled = isAILogicApiEnabled;
20
+ exports.ensureAILogicApiEnabled = ensureAILogicApiEnabled;
11
21
  const apiv2_1 = require("../apiv2");
12
22
  const api_1 = require("../api");
13
23
  const error_1 = require("../error");
24
+ const ensureApiEnabled = require("../ensureApiEnabled");
25
+ const serviceUsage = require("./serviceusage");
26
+ const colorette_1 = require("colorette");
27
+ const cloudbilling = require("./cloudbilling");
28
+ const iam = require("./iam");
29
+ const logger_1 = require("../logger");
30
+ const prompt_1 = require("../prompt");
14
31
  exports.API_VERSION = "v1beta";
32
+ exports.AILOGIC_LOGGING_PREFIX = "ailogic";
33
+ exports.GLOBAL_LOCATION = "global";
15
34
  exports.AI_LOGIC_BEFORE_GENERATE_CONTENT = "google.firebase.ailogic.v1.beforeGenerate";
16
35
  exports.AI_LOGIC_AFTER_GENERATE_CONTENT = "google.firebase.ailogic.v1.afterGenerate";
17
36
  exports.AI_LOGIC_EVENTS_TO_TRIGGER = {
@@ -110,3 +129,148 @@ async function deleteBlockingFunction(endpoint) {
110
129
  const location = endpoint.blockingTrigger.options?.regionalWebhook ? endpoint.region : "global";
111
130
  await deleteTrigger(endpoint.project, location, triggerId, true);
112
131
  }
132
+ exports.WRITABLE_CONFIG_PATHS = [
133
+ "security.auth-only",
134
+ "security.template-only",
135
+ "monitoring.state",
136
+ "monitoring.sample-rate-percentage",
137
+ ];
138
+ function assertKnownConfigPath(path, validPaths) {
139
+ if (!validPaths.includes(path)) {
140
+ throw new error_1.FirebaseError(`Unknown configuration path: ${path}\n\nValid paths:\n\n` +
141
+ validPaths.map((p) => ` ${p}`).join("\n"));
142
+ }
143
+ }
144
+ exports.PROVIDER_TYPES = ["gemini-developer-api", "gemini-agent-platform-api"];
145
+ function isProviderType(value) {
146
+ return exports.PROVIDER_TYPES.some((p) => p === value);
147
+ }
148
+ function parseProviderType(value) {
149
+ if (!isProviderType(value)) {
150
+ throw new error_1.FirebaseError(`Invalid provider type: ${(0, colorette_1.bold)(value)}. Must be one of: ${exports.PROVIDER_TYPES.map((p) => `'${p}'`).join(", ")}.`);
151
+ }
152
+ return value;
153
+ }
154
+ async function getConfig(projectId) {
155
+ const name = `projects/${projectId}/locations/${exports.GLOBAL_LOCATION}/config`;
156
+ const res = await exports.client.get(name);
157
+ return res.body;
158
+ }
159
+ async function updateConfig(projectId, config, updateMask) {
160
+ const name = `projects/${projectId}/locations/${exports.GLOBAL_LOCATION}/config`;
161
+ const queryParams = {};
162
+ if (updateMask && updateMask.length > 0) {
163
+ queryParams.updateMask = updateMask.join(",");
164
+ }
165
+ const res = await exports.client.patch(name, config, { queryParams });
166
+ return res.body;
167
+ }
168
+ async function enableProvider(projectId, providerType) {
169
+ if (providerType === "gemini-agent-platform-api") {
170
+ const billingEnabled = await cloudbilling.checkBillingEnabled(projectId);
171
+ if (!billingEnabled) {
172
+ throw new error_1.FirebaseError(`Your project ${(0, colorette_1.bold)(projectId)} must be on the Blaze (pay-as-you-go) plan to enable the Agent Platform. To upgrade, visit the following URL:\n\nhttps://console.firebase.google.com/project/${projectId}/usage/details`);
173
+ }
174
+ }
175
+ await ensureApiEnabled.ensure(projectId, "firebasevertexai.googleapis.com", exports.AILOGIC_LOGGING_PREFIX);
176
+ const providerApi = providerType === "gemini-developer-api"
177
+ ? "generativelanguage.googleapis.com"
178
+ : "aiplatform.googleapis.com";
179
+ await ensureApiEnabled.ensure(projectId, providerApi, exports.AILOGIC_LOGGING_PREFIX);
180
+ }
181
+ async function disableProvider(projectId, providerType) {
182
+ if (providerType === "gemini-developer-api") {
183
+ await serviceUsage.disableServiceAndPoll(projectId, "generativelanguage.googleapis.com", exports.AILOGIC_LOGGING_PREFIX);
184
+ const isVertexEnabled = await ensureApiEnabled.check(projectId, "aiplatform.googleapis.com", exports.AILOGIC_LOGGING_PREFIX, true);
185
+ if (!isVertexEnabled) {
186
+ await serviceUsage.disableServiceAndPoll(projectId, "firebasevertexai.googleapis.com", exports.AILOGIC_LOGGING_PREFIX);
187
+ }
188
+ }
189
+ else if (providerType === "gemini-agent-platform-api") {
190
+ await serviceUsage.disableServiceAndPoll(projectId, "aiplatform.googleapis.com", exports.AILOGIC_LOGGING_PREFIX);
191
+ const isDeveloperEnabled = await ensureApiEnabled.check(projectId, "generativelanguage.googleapis.com", exports.AILOGIC_LOGGING_PREFIX, true);
192
+ if (!isDeveloperEnabled) {
193
+ await serviceUsage.disableServiceAndPoll(projectId, "firebasevertexai.googleapis.com", exports.AILOGIC_LOGGING_PREFIX);
194
+ }
195
+ }
196
+ }
197
+ async function listProviders(projectId) {
198
+ const [isAILogicEnabled, isDeveloperEnabled, isVertexEnabled] = await Promise.all([
199
+ isAILogicApiEnabled(projectId),
200
+ ensureApiEnabled.check(projectId, "generativelanguage.googleapis.com", exports.AILOGIC_LOGGING_PREFIX, true),
201
+ ensureApiEnabled.check(projectId, "aiplatform.googleapis.com", exports.AILOGIC_LOGGING_PREFIX, true),
202
+ ]);
203
+ if (!isAILogicEnabled) {
204
+ return [];
205
+ }
206
+ const enabled = [];
207
+ if (isDeveloperEnabled) {
208
+ enabled.push("gemini-developer-api");
209
+ }
210
+ if (isVertexEnabled) {
211
+ enabled.push("gemini-agent-platform-api");
212
+ }
213
+ return enabled;
214
+ }
215
+ async function isAILogicApiEnabled(projectId) {
216
+ return ensureApiEnabled.check(projectId, "firebasevertexai.googleapis.com", exports.AILOGIC_LOGGING_PREFIX, true);
217
+ }
218
+ async function ensureAILogicApiEnabled(projectId, options) {
219
+ if (await isAILogicApiEnabled(projectId)) {
220
+ return;
221
+ }
222
+ if (options.nonInteractive) {
223
+ throw new error_1.FirebaseError(`The Firebase AI Logic API (firebasevertexai.googleapis.com) is not enabled on project ${projectId}.\n\n` +
224
+ `Enable Firebase AI Logic with one of the Gemini API providers by running:\n\n` +
225
+ ` firebase ailogic:providers:enable gemini-developer-api\n` +
226
+ ` firebase ailogic:providers:enable gemini-agent-platform-api\n\n` +
227
+ `Then run this command again.`);
228
+ }
229
+ const { missing } = await iam.testIamPermissions(projectId, ["serviceusage.services.enable"]);
230
+ if (missing.length > 0) {
231
+ throw new error_1.FirebaseError(`You do not have permission to enable the Firebase AI Logic API on project ${projectId}.\n\n` +
232
+ `Missing permission: ${missing.join(", ")}\n\n` +
233
+ `This permission is included in the Owner and Editor roles. Ask a project ` +
234
+ `administrator to enable the API or grant you the permission, then run this command again.`);
235
+ }
236
+ logger_1.logger.info(`The Firebase AI Logic API (firebasevertexai.googleapis.com) is not enabled on project ${projectId}.`);
237
+ const proceed = await (0, prompt_1.confirm)({
238
+ message: "Would you like to enable it now?",
239
+ default: true,
240
+ force: options.force,
241
+ });
242
+ if (!proceed) {
243
+ throw new error_1.FirebaseError("Command aborted.", { exit: 1 });
244
+ }
245
+ for (;;) {
246
+ const provider = await (0, prompt_1.select)({
247
+ message: "Which Gemini API provider do you want to enable?",
248
+ choices: [
249
+ { name: "gemini-developer-api", value: "gemini-developer-api" },
250
+ {
251
+ name: "gemini-agent-platform-api (requires the Blaze plan)",
252
+ value: "gemini-agent-platform-api",
253
+ },
254
+ { name: "cancel", value: "cancel" },
255
+ ],
256
+ });
257
+ if (provider === "cancel") {
258
+ throw new error_1.FirebaseError("Command aborted.", { exit: 1 });
259
+ }
260
+ if (provider === "gemini-agent-platform-api") {
261
+ const billingEnabled = await cloudbilling.checkBillingEnabled(projectId);
262
+ if (!billingEnabled) {
263
+ logger_1.logger.info(`\n${(0, colorette_1.bold)("Error:")} The gemini-agent-platform-api provider requires the pay-as-you-go (Blaze) plan.\n` +
264
+ `Project ${projectId} is on the Spark plan.\n\n` +
265
+ `Upgrade your plan at:\n\n` +
266
+ ` https://console.firebase.google.com/project/${projectId}/usage/details\n`);
267
+ continue;
268
+ }
269
+ }
270
+ logger_1.logger.info(`Enabling firebasevertexai.googleapis.com...`);
271
+ logger_1.logger.info(`Enabling provider ${provider}...`);
272
+ await enableProvider(projectId, provider);
273
+ logger_1.logger.info((0, colorette_1.bold)(`Successfully enabled Firebase AI Logic with provider: ${provider}`));
274
+ break;
275
+ }
276
+ }
@@ -188,6 +188,13 @@ function functionFromEndpoint(endpoint) {
188
188
  proto.convertIfPresent(gcfFunction.serviceConfig, endpoint, "availableCpu", "cpu", (cpu) => {
189
189
  return String(cpu);
190
190
  });
191
+ if (!gcfFunction.serviceConfig.environmentVariables) {
192
+ gcfFunction.serviceConfig.environmentVariables = {};
193
+ }
194
+ if (!endpoint.region) {
195
+ throw new error_1.FirebaseError(`Function ${endpoint.id} is missing the function region at deploy time. This should never happen`, { exit: 1 });
196
+ }
197
+ gcfFunction.serviceConfig.environmentVariables["FUNCTION_REGION"] = endpoint.region;
191
198
  if (endpoint.vpc) {
192
199
  if (endpoint.vpc.connector) {
193
200
  gcfFunction.serviceConfig.vpcConnector = endpoint.vpc.connector;
@@ -12,7 +12,11 @@ exports.APPHOSTING_TOS_ID = "APP_HOSTING_TOS";
12
12
  exports.APP_CHECK_TOS_ID = "APP_CHECK";
13
13
  exports.DATA_CONNECT_TOS_ID = "FIREBASE_DATA_CONNECT";
14
14
  async function getTosStatus() {
15
- const res = await client.get("accessmanagement/tos:getStatus");
15
+ const res = await client.request({
16
+ method: "GET",
17
+ path: "accessmanagement/tos:getStatus",
18
+ ignoreQuotaProject: true,
19
+ });
16
20
  return res.body;
17
21
  }
18
22
  function getAcceptanceStatus(response, tosId) {