firebase-tools 15.24.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 (51) 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/command.js +11 -3
  6. package/lib/commands/ailogic-config-get.js +75 -0
  7. package/lib/commands/ailogic-config-set.js +109 -0
  8. package/lib/commands/ailogic-providers-disable.js +39 -0
  9. package/lib/commands/ailogic-providers-enable.js +28 -0
  10. package/lib/commands/ailogic-providers-list.js +29 -0
  11. package/lib/commands/appcheck-debugtokens-create.js +95 -0
  12. package/lib/commands/appcheck-debugtokens-delete.js +48 -0
  13. package/lib/commands/appcheck-debugtokens-list.js +35 -0
  14. package/lib/commands/apps-sdkconfig.js +2 -23
  15. package/lib/commands/database-get.js +1 -1
  16. package/lib/commands/index.js +15 -0
  17. package/lib/deploy/functions/build.js +93 -3
  18. package/lib/deploy/functions/params.js +45 -11
  19. package/lib/deploy/functions/prepare.js +22 -2
  20. package/lib/deploy/functions/runtimes/node/index.js +8 -7
  21. package/lib/deploy/functions/runtimes/node/versioning.js +8 -3
  22. package/lib/deploy/functions/validate.js +5 -2
  23. package/lib/deploy/hosting/uploader.js +2 -1
  24. package/lib/emulator/dataconnect/pgliteServer.js +2 -1
  25. package/lib/emulator/downloadableEmulatorInfo.json +6 -6
  26. package/lib/emulator/downloadableEmulators.js +1 -0
  27. package/lib/emulator/hubExport.js +2 -1
  28. package/lib/emulator/storage/apis/firebase.js +24 -5
  29. package/lib/emulator/storage/apis/gcloud.js +16 -6
  30. package/lib/emulator/storage/rules/runtime.js +45 -33
  31. package/lib/emulator/storage/server.js +2 -5
  32. package/lib/emulator/storage/upload.js +1 -0
  33. package/lib/ensureApiEnabled.js +8 -0
  34. package/lib/experiments.js +16 -0
  35. package/lib/extensions/warnings.js +64 -0
  36. package/lib/functions/env.js +22 -2
  37. package/lib/functions/secrets.js +4 -1
  38. package/lib/gcp/ailogic.js +165 -1
  39. package/lib/gcp/cloudfunctionsv2.js +7 -0
  40. package/lib/gcp/firedata.js +5 -1
  41. package/lib/gcp/serviceusage.js +26 -0
  42. package/lib/init/features/ailogic/index.js +3 -29
  43. package/lib/init/features/database.js +1 -1
  44. package/lib/management/apps.js +16 -5
  45. package/lib/mcp/onemcp/onemcp_server.js +28 -9
  46. package/lib/mcp/tools/core/get_security_rules.js +2 -1
  47. package/lib/profiler.js +1 -1
  48. package/lib/streamUtils.js +3 -0
  49. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  50. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  51. package/package.json +2 -2
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createCloudEndpoints = createCloudEndpoints;
4
4
  const express_1 = require("express");
5
+ const bodyParser = require("body-parser");
5
6
  const types_1 = require("../../types");
6
7
  const metadata_1 = require("../metadata");
7
8
  const shared_1 = require("./shared");
@@ -14,6 +15,14 @@ const request_1 = require("../../shared/request");
14
15
  function createCloudEndpoints(emulator) {
15
16
  const gcloudStorageAPI = (0, express_1.Router)();
16
17
  const { adminStorageLayer, uploadService } = emulator;
18
+ const postUploadMiddleware = (req, res, next) => {
19
+ const uploadType = req.query.uploadType || req.header("X-Goog-Upload-Protocol");
20
+ if (uploadType === "resumable" && !req.query.upload_id) {
21
+ (0, express_1.json)({ limit: "130mb" })(req, res, next);
22
+ return;
23
+ }
24
+ bodyParser.raw({ type: "*/*", limit: "130mb" })(req, res, next);
25
+ };
17
26
  if (process.env.STORAGE_EMULATOR_DEBUG) {
18
27
  gcloudStorageAPI.use((req, res, next) => {
19
28
  console.log("--------------INCOMING GCS REQUEST--------------");
@@ -53,7 +62,7 @@ function createCloudEndpoints(emulator) {
53
62
  next();
54
63
  });
55
64
  }
56
- gcloudStorageAPI.use(/.*\/b\/(.+?)\/.*/, (req, res, next) => {
65
+ gcloudStorageAPI.use(/.*\/b\/(.+?)\/.*/i, (req, res, next) => {
57
66
  adminStorageLayer.createBucket(req.params[0]);
58
67
  next();
59
68
  });
@@ -89,7 +98,7 @@ function createCloudEndpoints(emulator) {
89
98
  }
90
99
  return res.json(new metadata_1.CloudStorageObjectMetadata(getObjectResponse.metadata));
91
100
  });
92
- gcloudStorageAPI.patch("/b/:bucketId/o/:objectId", async (req, res) => {
101
+ gcloudStorageAPI.patch("/b/:bucketId/o/:objectId", (0, express_1.json)({ limit: "130mb" }), async (req, res) => {
93
102
  let updatedMetadata;
94
103
  try {
95
104
  updatedMetadata = await adminStorageLayer.updateObjectMetadata({
@@ -152,7 +161,7 @@ function createCloudEndpoints(emulator) {
152
161
  }
153
162
  return res.sendStatus(204);
154
163
  });
155
- gcloudStorageAPI.put("/upload/storage/v1/b/:bucketId/o", async (req, res) => {
164
+ gcloudStorageAPI.put("/upload/storage/v1/b/:bucketId/o", bodyParser.raw({ type: "*/*", limit: "130mb" }), async (req, res) => {
156
165
  if (!req.query.upload_id) {
157
166
  res.sendStatus(400);
158
167
  return;
@@ -184,7 +193,7 @@ function createCloudEndpoints(emulator) {
184
193
  }
185
194
  return res.json(new metadata_1.CloudStorageObjectMetadata(metadata));
186
195
  });
187
- gcloudStorageAPI.post("/b/:bucketId/o/:objectId/acl", async (req, res) => {
196
+ gcloudStorageAPI.post("/b/:bucketId/o/:objectId/acl", (0, express_1.json)({ limit: "130mb" }), async (req, res) => {
188
197
  emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.STORAGE).log("WARN_ONCE", "Cloud Storage ACLs are not supported in the Storage Emulator. All related methods will succeed, but have no effect.");
189
198
  let getObjectResponse;
190
199
  try {
@@ -218,7 +227,7 @@ function createCloudEndpoints(emulator) {
218
227
  generation: metadata.generation.toString(),
219
228
  });
220
229
  });
221
- gcloudStorageAPI.post("/upload/storage/v1/b/:bucketId/o", async (req, res) => {
230
+ gcloudStorageAPI.post("/upload/storage/v1/b/:bucketId/o", postUploadMiddleware, async (req, res) => {
222
231
  const uploadType = req.query.uploadType || req.header("X-Goog-Upload-Protocol");
223
232
  if (uploadType === "resumable") {
224
233
  const name = getIncomingFileNameFromRequest(req.query, req.body);
@@ -297,6 +306,7 @@ function createCloudEndpoints(emulator) {
297
306
  bucketId: req.params.bucketId,
298
307
  objectId: name.toString(),
299
308
  dataRaw: await (0, request_1.reqBodyToBuffer)(req),
309
+ contentType: req.header("content-type"),
300
310
  authorization: req.header("authorization"),
301
311
  });
302
312
  return await finalizeOneShotUpload(upload);
@@ -381,7 +391,7 @@ function createCloudEndpoints(emulator) {
381
391
  throw err;
382
392
  }
383
393
  });
384
- gcloudStorageAPI.post("/b/:bucketId/o/:objectId/:method(rewriteTo|copyTo)/b/:destBucketId/o/:destObjectId", (req, res, next) => {
394
+ gcloudStorageAPI.post("/b/:bucketId/o/:objectId/:method(rewriteTo|copyTo)/b/:destBucketId/o/:destObjectId", (0, express_1.json)({ limit: "130mb" }), (req, res, next) => {
385
395
  if (req.params.method === "rewriteTo" && req.query.rewriteToken) {
386
396
  return next();
387
397
  }
@@ -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
+ }
@@ -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) {