firebase-tools 15.34.2 → 15.36.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 (126) hide show
  1. package/lib/api.js +2 -4
  2. package/lib/appcheck/debugTokens.js +293 -0
  3. package/lib/appcheck/localConfig.js +191 -0
  4. package/lib/appdistribution/options-parser-util.js +1 -1
  5. package/lib/apphosting/constants.js +1 -4
  6. package/lib/apphosting/githubConnections.js +1 -1
  7. package/lib/apphosting/utils.js +0 -26
  8. package/lib/auth.js +8 -2
  9. package/lib/commands/appcheck-debugtokens-create.js +60 -35
  10. package/lib/commands/appcheck-debugtokens-delete.js +21 -7
  11. package/lib/commands/appcheck-debugtokens-list.js +37 -8
  12. package/lib/commands/appcheck-debugtokens-prune.js +59 -0
  13. package/lib/commands/crashlytics-heapdumps-status.js +1 -1
  14. package/lib/commands/{crashlytics-onboard-web.js → crashlytics-setup.js} +5 -5
  15. package/lib/commands/crashlytics-sourcemap-upload.js +4 -0
  16. package/lib/commands/deploy.js +1 -3
  17. package/lib/commands/emulators-start.js +2 -2
  18. package/lib/commands/hosting-channel-create.js +1 -3
  19. package/lib/commands/hosting-channel-delete.js +1 -3
  20. package/lib/commands/hosting-channel-deploy.js +1 -3
  21. package/lib/commands/hosting-channel-list.js +1 -3
  22. package/lib/commands/hosting-channel-open.js +1 -3
  23. package/lib/commands/hosting-clone.js +3 -5
  24. package/lib/commands/hosting-disable.js +2 -2
  25. package/lib/commands/hosting-sites-create.js +1 -3
  26. package/lib/commands/hosting-sites-delete.js +1 -3
  27. package/lib/commands/hosting-sites-get.js +1 -3
  28. package/lib/commands/hosting-sites-list.js +1 -3
  29. package/lib/commands/index.js +4 -2
  30. package/lib/commands/run-services-get.js +19 -0
  31. package/lib/commands/run-services-list.js +11 -0
  32. package/lib/crashlytics/alerts.js +1 -0
  33. package/lib/crashlytics/events.js +122 -1
  34. package/lib/crashlytics/filters.js +12 -6
  35. package/lib/crashlytics/firebasetelemetry.js +5 -3
  36. package/lib/crashlytics/onboarding.js +8 -7
  37. package/lib/crashlytics/profilingManager.js +14 -34
  38. package/lib/crashlytics/reports.js +46 -17
  39. package/lib/crashlytics/sourcemap.js +19 -5
  40. package/lib/crashlytics/utils.js +14 -0
  41. package/lib/database/import.js +5 -4
  42. package/lib/dataconnect/dataplaneClient.js +0 -10
  43. package/lib/dataconnect/names.js +3 -3
  44. package/lib/dataconnect/schemaMigration.js +1 -1
  45. package/lib/deploy/apphosting/deploy.js +20 -41
  46. package/lib/deploy/apphosting/localBuild.js +49 -0
  47. package/lib/deploy/apphosting/prepare.js +12 -25
  48. package/lib/deploy/apphosting/release.js +1 -1
  49. package/lib/deploy/apphosting/util.js +27 -4
  50. package/lib/deploy/functions/backend.js +0 -10
  51. package/lib/deploy/functions/cel.js +1 -1
  52. package/lib/deploy/functions/containerCleaner.js +1 -142
  53. package/lib/deploy/functions/functionsDeployHelper.js +0 -4
  54. package/lib/deploy/functions/release/reporter.js +0 -26
  55. package/lib/deploy/functions/runtimes/discovery/index.js +4 -1
  56. package/lib/deploy/functions/runtimes/discovery/v1alpha1.js +1 -1
  57. package/lib/deploy/functions/services/index.js +13 -11
  58. package/lib/deploy/functions/validate.js +1 -1
  59. package/lib/deploy/hosting/prepare.js +1 -3
  60. package/lib/deploy/lifecycleHooks.js +1 -1
  61. package/lib/deploy/run/deploy.js +26 -43
  62. package/lib/deploy/run/get.js +30 -0
  63. package/lib/deploy/run/list.js +38 -0
  64. package/lib/deploy/run/prereqs.js +0 -3
  65. package/lib/deploy/run/util.js +9 -0
  66. package/lib/emulator/auth/operations.js +2 -2
  67. package/lib/emulator/auth/server.js +4 -2
  68. package/lib/emulator/auth/widget_ui.js +1 -1
  69. package/lib/emulator/commandUtils.js +109 -24
  70. package/lib/emulator/databaseEmulator.js +16 -11
  71. package/lib/emulator/dataconnect/pgliteServer.js +31 -24
  72. package/lib/emulator/downloadableEmulatorInfo.json +24 -24
  73. package/lib/emulator/downloadableEmulators.js +45 -7
  74. package/lib/emulator/extensions/postinstall.js +6 -6
  75. package/lib/emulator/firestoreEmulator.js +21 -15
  76. package/lib/emulator/functionsEmulator.js +11 -7
  77. package/lib/emulator/functionsEmulatorRuntime.js +7 -2
  78. package/lib/emulator/hub.js +12 -8
  79. package/lib/emulator/shared/express.js +30 -0
  80. package/lib/emulator/storage/apis/firebase.js +11 -10
  81. package/lib/emulator/storage/apis/gcloud.js +21 -20
  82. package/lib/emulator/storage/files.js +1 -1
  83. package/lib/emulator/storage/rules/manager.js +15 -12
  84. package/lib/emulator/storage/rules/runtime.js +1 -0
  85. package/lib/emulator/storage/server.js +10 -5
  86. package/lib/extensions/extensionsApi.js +0 -8
  87. package/lib/extensions/extensionsHelper.js +3 -24
  88. package/lib/extensions/paramHelper.js +1 -1
  89. package/lib/extensions/provisioningHelper.js +1 -6
  90. package/lib/extensions/secretsUtils.js +0 -24
  91. package/lib/firestore/util.js +3 -3
  92. package/lib/frameworks/angular/utils.js +1 -1
  93. package/lib/frameworks/next/utils.js +1 -12
  94. package/lib/fsAsync.js +34 -20
  95. package/lib/functions/kits/install.js +233 -628
  96. package/lib/functions/kits/sources/directory.js +91 -0
  97. package/lib/functions/kits/sources/npm.js +324 -0
  98. package/lib/functions/kits/sources/types.js +12 -0
  99. package/lib/functionsConfig.js +0 -4
  100. package/lib/functionsShellCommandAction.js +1 -1
  101. package/lib/gcp/artifactregistry.js +0 -5
  102. package/lib/gcp/cloudfunctionsv2.js +0 -6
  103. package/lib/gcp/devConnect.js +2 -2
  104. package/lib/gcp/iam.js +0 -4
  105. package/lib/gcp/pubsub.js +0 -14
  106. package/lib/gcp/storage.js +2 -1
  107. package/lib/hosting/api.js +79 -0
  108. package/lib/hosting/proxy.js +4 -1
  109. package/lib/init/features/hosting/github.js +6 -4
  110. package/lib/init/features/hosting/index.js +4 -0
  111. package/lib/init/features/run.js +3 -7
  112. package/lib/mcp/apps/init/mcp-app.js +4 -1
  113. package/lib/mcp/index.js +8 -2
  114. package/lib/mcp/prompts/apptesting/run_test.js +3 -3
  115. package/lib/mcp/prompts/core/deploy.js +3 -3
  116. package/lib/mcp/resources/guides/crashlytics_reports.js +33 -71
  117. package/lib/mcp/resources/guides/init_ai.js +10 -10
  118. package/lib/mcp/tools/crashlytics/events.js +18 -93
  119. package/lib/mcp/tools/crashlytics/index.js +2 -0
  120. package/lib/mcp/tools/crashlytics/reports.js +26 -31
  121. package/lib/mcp/tools/crashlytics/setup.js +392 -0
  122. package/lib/tsconfig.compile.tsbuildinfo +1 -1
  123. package/lib/tsconfig.publish.tsbuildinfo +1 -1
  124. package/lib/utils.js +4 -10
  125. package/package.json +1 -2
  126. package/lib/deploy/hosting/args.js +0 -2
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateAndResolveDirectoryKit = validateAndResolveDirectoryKit;
4
+ exports.buildAndInstallDirectoryKit = buildAndInstallDirectoryKit;
5
+ exports.createDirectoryAdapter = createDirectoryAdapter;
6
+ const path = require("path");
7
+ const fs = require("fs-extra");
8
+ const error_1 = require("../../../error");
9
+ const spawn_1 = require("../../../init/spawn");
10
+ const utils_1 = require("../../../utils");
11
+ const projectConfig_1 = require("../../projectConfig");
12
+ const types_1 = require("./types");
13
+ async function validateAndResolveDirectoryKit(projectDir, rawDir) {
14
+ const absDirectoryPath = (0, utils_1.resolveWithin)(projectDir, rawDir, `Directory '${rawDir}' is outside of project directory. Function kit directory must be inside the project directory.`);
15
+ if (!(await fs.pathExists(absDirectoryPath))) {
16
+ throw new error_1.FirebaseError(`Directory '${rawDir}' does not exist.`);
17
+ }
18
+ const stat = await fs.stat(absDirectoryPath);
19
+ if (!stat.isDirectory()) {
20
+ throw new error_1.FirebaseError(`Directory '${rawDir}' is not a directory.`);
21
+ }
22
+ const packageJsonPath = path.join(absDirectoryPath, "package.json");
23
+ if (!(await fs.pathExists(packageJsonPath))) {
24
+ throw new error_1.FirebaseError(`Directory '${rawDir}' must contain a package.json file to be installed as a function kit.`);
25
+ }
26
+ let packageJson = {};
27
+ try {
28
+ packageJson = (await fs.readJson(packageJsonPath)) || {};
29
+ }
30
+ catch (err) {
31
+ throw new error_1.FirebaseError(`Failed to parse package.json in '${rawDir}': ${(0, error_1.getErrMsg)(err)}`);
32
+ }
33
+ const hasBuildScript = Boolean(packageJson?.scripts?.build);
34
+ let relSourcePath = path.relative(projectDir, absDirectoryPath);
35
+ if (!relSourcePath) {
36
+ relSourcePath = ".";
37
+ }
38
+ relSourcePath = relSourcePath.split(path.sep).join("/");
39
+ return {
40
+ absDirectoryPath,
41
+ relSourcePath,
42
+ hasBuildScript,
43
+ };
44
+ }
45
+ async function buildAndInstallDirectoryKit(absSourcePath, hasBuildScript) {
46
+ (0, utils_1.logLabeledBullet)("functions", "Running npm install...");
47
+ try {
48
+ await (0, spawn_1.wrapSpawn)("npm", ["install"], absSourcePath);
49
+ }
50
+ catch (err) {
51
+ throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
52
+ }
53
+ if (hasBuildScript) {
54
+ (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
55
+ try {
56
+ await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
57
+ }
58
+ catch (err) {
59
+ throw new error_1.FirebaseError(`TypeScript build failed: ${(0, error_1.getErrMsg)(err)}`);
60
+ }
61
+ }
62
+ }
63
+ function createDirectoryAdapter(config, directory) {
64
+ const absDir = path.isAbsolute(directory)
65
+ ? directory
66
+ : path.resolve(config.projectDir, directory);
67
+ let validated;
68
+ return {
69
+ defaultKitId: (0, types_1.sanitizeToKitId)(path.basename(absDir)) || "kit",
70
+ findExistingKit(existingFunctions) {
71
+ return existingFunctions.find((c) => (0, projectConfig_1.isKitConfig)(c) &&
72
+ !c.sourcePackage &&
73
+ path.resolve(config.projectDir, c.source) === absDir);
74
+ },
75
+ async validateAndConfirm() {
76
+ validated = await validateAndResolveDirectoryKit(config.projectDir, directory);
77
+ },
78
+ async prepareSource() {
79
+ if (!validated) {
80
+ validated = await validateAndResolveDirectoryKit(config.projectDir, directory);
81
+ }
82
+ await buildAndInstallDirectoryKit(validated.absDirectoryPath, validated.hasBuildScript);
83
+ return {
84
+ sourcePath: validated.relSourcePath,
85
+ ...(validated.hasBuildScript
86
+ ? { predeploy: ['npm --prefix "$RESOURCE_DIR" run build'] }
87
+ : {}),
88
+ };
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,324 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_TEMPLATE = exports.TEMPLATES = void 0;
4
+ exports.parseNpmPackageSpecifier = parseNpmPackageSpecifier;
5
+ exports.validateNpmPackageName = validateNpmPackageName;
6
+ exports.validateNpmPackageExists = validateNpmPackageExists;
7
+ exports.sanitizePackageNameToKitName = sanitizePackageNameToKitName;
8
+ exports.isThirdPartyPackage = isThirdPartyPackage;
9
+ exports.checkPackageHasShrinkwrap = checkPackageHasShrinkwrap;
10
+ exports.promptSecurityConfirmation = promptSecurityConfirmation;
11
+ exports.writeKitPackageJson = writeKitPackageJson;
12
+ exports.writeKitIndexTs = writeKitIndexTs;
13
+ exports.scaffoldKitFiles = scaffoldKitFiles;
14
+ exports.resolveSdkSpecifierToSave = resolveSdkSpecifierToSave;
15
+ exports.getKitPackagesToSave = getKitPackagesToSave;
16
+ exports.buildAndInstallKit = buildAndInstallKit;
17
+ exports.createNpmPackageAdapter = createNpmPackageAdapter;
18
+ const path = require("path");
19
+ const clc = require("colorette");
20
+ const fs = require("fs-extra");
21
+ const semver = require("semver");
22
+ const error_1 = require("../../../error");
23
+ const spawn_1 = require("../../../init/spawn");
24
+ const logger_1 = require("../../../logger");
25
+ const prompt_1 = require("../../../prompt");
26
+ const templates_1 = require("../../../templates");
27
+ const utils_1 = require("../../../utils");
28
+ const supported = require("../../../deploy/functions/runtimes/supported");
29
+ const projectConfig_1 = require("../../projectConfig");
30
+ const types_1 = require("./types");
31
+ exports.TEMPLATES = {
32
+ installation: "init/functions/typescript/index-kit.ts",
33
+ migration: "init/functions/typescript/index-kit-migration.ts",
34
+ };
35
+ exports.DEFAULT_TEMPLATE = "installation";
36
+ function parseNpmPackageSpecifier(rawPkg) {
37
+ const lastAt = rawPkg.lastIndexOf("@");
38
+ if (lastAt > 0) {
39
+ const version = rawPkg.substring(lastAt + 1);
40
+ return {
41
+ packageName: rawPkg.substring(0, lastAt),
42
+ ...(version ? { version } : {}),
43
+ };
44
+ }
45
+ return { packageName: rawPkg };
46
+ }
47
+ function validateNpmPackageName(packageNameOrSpecifier) {
48
+ const { packageName, version } = parseNpmPackageSpecifier(packageNameOrSpecifier);
49
+ const npmPackageRegex = /^(?:@[a-z0-9_.-]+\/[a-z0-9_.-]+|[a-z0-9_.-]+)$/i;
50
+ if (!packageName ||
51
+ packageName.length > 214 ||
52
+ !npmPackageRegex.test(packageName) ||
53
+ (packageNameOrSpecifier.lastIndexOf("@") > 0 && !version)) {
54
+ throw new error_1.FirebaseError(`Invalid NPM package name '${packageNameOrSpecifier}'. Package names must be valid npm package specifiers (e.g. 'my-kit' or '@scope/my-kit').`);
55
+ }
56
+ }
57
+ async function validateNpmPackageExists(rawPkgName) {
58
+ validateNpmPackageName(rawPkgName);
59
+ try {
60
+ const output = await (0, spawn_1.spawnWithOutput)("npm", ["view", rawPkgName, "version"]);
61
+ if (!output.trim()) {
62
+ throw new Error(`No version found for '${rawPkgName}'`);
63
+ }
64
+ }
65
+ catch (err) {
66
+ throw new error_1.FirebaseError(`NPM package '${rawPkgName}' could not be found in the npm registry. Please verify the package name and version.`, { original: err instanceof Error ? err : undefined });
67
+ }
68
+ }
69
+ function sanitizePackageNameToKitName(packageNameOrSpecifier) {
70
+ const { packageName } = parseNpmPackageSpecifier(packageNameOrSpecifier);
71
+ const parts = packageName.split("/");
72
+ const nameWithoutScope = parts[parts.length - 1] || packageName;
73
+ return (0, types_1.sanitizeToKitId)(nameWithoutScope);
74
+ }
75
+ function isThirdPartyPackage(packageNameOrSpecifier) {
76
+ const { packageName } = parseNpmPackageSpecifier(packageNameOrSpecifier);
77
+ return !packageName.startsWith("@firebase-function-kits/");
78
+ }
79
+ async function checkPackageHasShrinkwrap(rawPkgName) {
80
+ try {
81
+ const output = await (0, spawn_1.spawnWithOutput)("npm", ["pack", rawPkgName, "--dry-run", "--json"]);
82
+ const parsed = JSON.parse(output);
83
+ if (Array.isArray(parsed) && parsed.length > 0) {
84
+ const pkgInfo = parsed[0];
85
+ if (pkgInfo.hasShrinkwrap) {
86
+ return true;
87
+ }
88
+ if (Array.isArray(pkgInfo.files)) {
89
+ return pkgInfo.files.some((f) => f.path === "npm-shrinkwrap.json" || f.path === "npm-shrinkwrap.js");
90
+ }
91
+ }
92
+ }
93
+ catch (err) {
94
+ logger_1.logger.debug(`Failed to inspect package shrinkwrap for ${rawPkgName}: ${(0, error_1.getErrMsg)(err)}`);
95
+ }
96
+ return false;
97
+ }
98
+ async function promptSecurityConfirmation(options) {
99
+ const { rawPkgName, packageName, nonInteractive, force } = options;
100
+ const isThirdParty = isThirdPartyPackage(packageName);
101
+ if (isThirdParty) {
102
+ (0, utils_1.logLabeledWarning)("functions", `Package ${clc.bold(packageName)} is a third-party kit (outside the @firebase-function-kits scope).`);
103
+ }
104
+ const hasShrinkwrap = await checkPackageHasShrinkwrap(rawPkgName);
105
+ if (!hasShrinkwrap) {
106
+ (0, utils_1.logLabeledWarning)("functions", `Package ${clc.bold(packageName)} does not have an npm-shrinkwrap.json file. npm-shrinkwrap guarantees that you deploy the same version of dependencies that the publisher tested against. Since this kit does not have an npm-shrinkwrap, it is possible that deploys or updates may introduce bugs or vulnerabilities in newer dependency versions that the publisher did not test against.`);
107
+ }
108
+ if (isThirdParty || !hasShrinkwrap) {
109
+ let confirmMessage;
110
+ if (isThirdParty && !hasShrinkwrap) {
111
+ confirmMessage = `Are you sure you want to install the third-party kit ${packageName} without locked dependencies?`;
112
+ }
113
+ else if (isThirdParty) {
114
+ confirmMessage = `Are you sure you want to install the third-party kit ${packageName}?`;
115
+ }
116
+ else {
117
+ confirmMessage = `Are you sure you want to install ${packageName} without locked dependencies?`;
118
+ }
119
+ const confirmInstallation = await (0, prompt_1.confirm)({
120
+ message: confirmMessage,
121
+ default: false,
122
+ nonInteractive,
123
+ force,
124
+ });
125
+ if (!confirmInstallation) {
126
+ throw new error_1.FirebaseError("Installation cancelled.");
127
+ }
128
+ }
129
+ return isThirdParty;
130
+ }
131
+ async function writeKitPackageJson(config, sourcePath, kitId) {
132
+ const relPackageJsonPath = path.join(sourcePath, "package.json");
133
+ const absPackageJsonPath = config.path(relPackageJsonPath);
134
+ let pkgJson = {};
135
+ if (await fs.pathExists(absPackageJsonPath)) {
136
+ try {
137
+ pkgJson = (await fs.readJson(absPackageJsonPath)) || {};
138
+ }
139
+ catch (err) {
140
+ logger_1.logger.debug(`Failed to read existing package.json: ${(0, error_1.getErrMsg)(err)}`);
141
+ }
142
+ }
143
+ else {
144
+ const latestNodeVersion = supported.latest("nodejs").replace("nodejs", "");
145
+ const packageKitTemplate = (0, templates_1.readTemplateSync)("init/functions/typescript/package-kit.json");
146
+ const subbedTemplate = packageKitTemplate.replace(/{{RUNTIME}}/g, latestNodeVersion);
147
+ try {
148
+ pkgJson = JSON.parse(subbedTemplate);
149
+ }
150
+ catch (err) {
151
+ throw new error_1.FirebaseError("Failed to parse package-kit.json template: " + (0, error_1.getErrMsg)(err), {
152
+ original: err instanceof Error ? err : undefined,
153
+ });
154
+ }
155
+ }
156
+ pkgJson.name = `${kitId}-wrapper`;
157
+ await config.askWriteProjectFile(relPackageJsonPath, pkgJson);
158
+ }
159
+ async function writeKitIndexTs(options) {
160
+ const { config, sourcePath, packageName, templateType } = options;
161
+ const relIndexTsPath = path.join(sourcePath, "src", "index.ts");
162
+ const absIndexTsPath = config.path(relIndexTsPath);
163
+ if (!(await fs.pathExists(absIndexTsPath))) {
164
+ const template = (0, templates_1.readTemplateSync)(exports.TEMPLATES[templateType]);
165
+ const indexContent = template.replace(/{{PACKAGE_NAME}}/g, packageName);
166
+ await config.askWriteProjectFile(relIndexTsPath, indexContent);
167
+ }
168
+ }
169
+ async function scaffoldKitFiles(options) {
170
+ const { config, kitId, packageName, templateType = exports.DEFAULT_TEMPLATE } = options;
171
+ const sourcePath = path.join(types_1.FUNCTION_KITS_DIR, kitId, "source");
172
+ const absSourcePath = config.path(sourcePath);
173
+ await fs.ensureDir(absSourcePath);
174
+ await writeKitPackageJson(config, sourcePath, kitId);
175
+ await config.askWriteProjectFile(path.join(sourcePath, "tsconfig.json"), (0, templates_1.readTemplateSync)("init/functions/typescript/tsconfig.json"));
176
+ await config.askWriteProjectFile(path.join(sourcePath, ".gitignore"), (0, templates_1.readTemplateSync)("init/functions/typescript/_gitignore"));
177
+ await writeKitIndexTs({ config, sourcePath, packageName, templateType });
178
+ return { sourcePath, absSourcePath };
179
+ }
180
+ function resolveSdkSpecifierToSave(packageName, declaredVer, installedVer) {
181
+ const cleanVer = semver.clean(declaredVer);
182
+ if (cleanVer) {
183
+ return `${packageName}@=${installedVer || cleanVer}`;
184
+ }
185
+ if (declaredVer.trim().startsWith("~")) {
186
+ return installedVer ? `${packageName}@~${installedVer}` : `${packageName}@${declaredVer}`;
187
+ }
188
+ if (installedVer) {
189
+ return `${packageName}@^${installedVer}`;
190
+ }
191
+ return `${packageName}@${declaredVer}`;
192
+ }
193
+ async function getKitPackagesToSave(absSourcePath, packageName) {
194
+ const lockfilePath = path.join(absSourcePath, "package-lock.json");
195
+ let peerDeps = {};
196
+ let directDeps = {};
197
+ let installedFunctionsVer;
198
+ let installedAdminVer;
199
+ if (await fs.pathExists(lockfilePath)) {
200
+ try {
201
+ const lockfile = (await fs.readJson(lockfilePath));
202
+ const packages = lockfile?.packages || {};
203
+ const kitEntry = packages[`node_modules/${packageName}`] || {};
204
+ peerDeps = kitEntry.peerDependencies || {};
205
+ directDeps = kitEntry.dependencies || {};
206
+ installedFunctionsVer = packages["node_modules/firebase-functions"]?.version;
207
+ installedAdminVer = packages["node_modules/firebase-admin"]?.version;
208
+ }
209
+ catch (err) {
210
+ logger_1.logger.debug(`Failed to read package-lock.json: ${(0, error_1.getErrMsg)(err)}`);
211
+ }
212
+ }
213
+ if (Object.keys(peerDeps).length === 0 && Object.keys(directDeps).length === 0) {
214
+ const kitPkgJsonPath = path.join(absSourcePath, "node_modules", packageName, "package.json");
215
+ if (await fs.pathExists(kitPkgJsonPath)) {
216
+ try {
217
+ const kitPkgJson = (await fs.readJson(kitPkgJsonPath));
218
+ peerDeps = kitPkgJson?.peerDependencies || {};
219
+ directDeps = kitPkgJson?.dependencies || {};
220
+ }
221
+ catch (err) {
222
+ logger_1.logger.debug(`Failed to read kit package.json: ${(0, error_1.getErrMsg)(err)}`);
223
+ }
224
+ }
225
+ }
226
+ const declaredFunctionsVer = peerDeps["firebase-functions"] || directDeps["firebase-functions"];
227
+ if (!declaredFunctionsVer) {
228
+ throw new error_1.FirebaseError(`Package '${packageName}' is not a valid Function Kit: it must declare 'firebase-functions' as a dependency or peer dependency.`);
229
+ }
230
+ const packagesToSave = [
231
+ resolveSdkSpecifierToSave("firebase-functions", declaredFunctionsVer, installedFunctionsVer),
232
+ ];
233
+ const declaredAdminVer = peerDeps["firebase-admin"] || directDeps["firebase-admin"];
234
+ if (declaredAdminVer) {
235
+ packagesToSave.push(resolveSdkSpecifierToSave("firebase-admin", declaredAdminVer, installedAdminVer));
236
+ }
237
+ return packagesToSave;
238
+ }
239
+ async function buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty) {
240
+ const { packageName } = parseNpmPackageSpecifier(rawPkgName);
241
+ const installArgs = ["install", rawPkgName, "--save-prefix=^"];
242
+ if (isThirdParty) {
243
+ installArgs.push("--ignore-scripts");
244
+ }
245
+ (0, utils_1.logLabeledBullet)("functions", `Running npm ${installArgs.join(" ")}...`);
246
+ try {
247
+ await (0, spawn_1.wrapSpawn)("npm", installArgs, absSourcePath);
248
+ }
249
+ catch (err) {
250
+ throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
251
+ }
252
+ const packagesToSave = await getKitPackagesToSave(absSourcePath, packageName);
253
+ if (packagesToSave.length > 0) {
254
+ (0, utils_1.logLabeledBullet)("functions", `Saving resolved SDK dependencies: ${clc.bold(packagesToSave.join(", "))}...`);
255
+ const saveArgs = ["install", ...packagesToSave, "--save-prefix=^"];
256
+ if (isThirdParty) {
257
+ saveArgs.push("--ignore-scripts");
258
+ }
259
+ try {
260
+ await (0, spawn_1.wrapSpawn)("npm", saveArgs, absSourcePath);
261
+ }
262
+ catch (err) {
263
+ throw new error_1.FirebaseError(`Failed to install required SDK dependencies (${packagesToSave.join(", ")}): ${(0, error_1.getErrMsg)(err)}. ` +
264
+ "Verify that the kit's dependencies are compatible with the resolved Firebase SDK versions.", { original: err instanceof Error ? err : undefined });
265
+ }
266
+ }
267
+ (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
268
+ try {
269
+ await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
270
+ }
271
+ catch (err) {
272
+ throw new error_1.FirebaseError(`TypeScript build failed: ${(0, error_1.getErrMsg)(err)}`);
273
+ }
274
+ }
275
+ function createNpmPackageAdapter(options) {
276
+ validateNpmPackageName(options.package);
277
+ const { packageName } = parseNpmPackageSpecifier(options.package);
278
+ const templateType = options.template || exports.DEFAULT_TEMPLATE;
279
+ if (!(templateType in exports.TEMPLATES)) {
280
+ const validTemplates = Object.keys(exports.TEMPLATES)
281
+ .map((t) => `'${t}'`)
282
+ .join(" or ");
283
+ throw new error_1.FirebaseError(`Invalid template '${templateType}'. Template must be ${validTemplates}.`);
284
+ }
285
+ return {
286
+ defaultKitId: sanitizePackageNameToKitName(packageName) || "kit",
287
+ findExistingKit(existingFunctions) {
288
+ return existingFunctions.find((c) => (0, projectConfig_1.isKitConfig)(c) && c.sourcePackage?.name === packageName);
289
+ },
290
+ async validateAndConfirm() {
291
+ await validateNpmPackageExists(options.package);
292
+ await promptSecurityConfirmation({
293
+ rawPkgName: options.package,
294
+ packageName,
295
+ nonInteractive: options.nonInteractive,
296
+ force: options.force,
297
+ });
298
+ },
299
+ async prepareSource(kitId) {
300
+ const absKitDir = options.config.path(path.join(types_1.FUNCTION_KITS_DIR, kitId));
301
+ try {
302
+ const { sourcePath, absSourcePath } = await scaffoldKitFiles({
303
+ config: options.config,
304
+ kitId,
305
+ packageName,
306
+ templateType,
307
+ });
308
+ await buildAndInstallKit(absSourcePath, options.package, isThirdPartyPackage(packageName));
309
+ return {
310
+ sourcePath,
311
+ sourcePackage: { name: packageName },
312
+ predeploy: ['npm --prefix "$RESOURCE_DIR" run build'],
313
+ createdPaths: [absKitDir],
314
+ };
315
+ }
316
+ catch (err) {
317
+ await fs.remove(absKitDir).catch((cleanupErr) => {
318
+ logger_1.logger.debug(`Failed to clean up kit directory '${absKitDir}': ${(0, error_1.getErrMsg)(cleanupErr)}`);
319
+ });
320
+ throw err;
321
+ }
322
+ },
323
+ };
324
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_KIT_ID_LENGTH = exports.FUNCTION_KITS_DIR = void 0;
4
+ exports.sanitizeToKitId = sanitizeToKitId;
5
+ exports.FUNCTION_KITS_DIR = "function-kits";
6
+ exports.MAX_KIT_ID_LENGTH = 40;
7
+ function sanitizeToKitId(name) {
8
+ return name
9
+ .toLowerCase()
10
+ .replace(/[^a-z0-9_-]/g, "")
11
+ .slice(0, exports.MAX_KIT_ID_LENGTH);
12
+ }
@@ -6,7 +6,6 @@ exports.logFunctionsConfigDeprecationWarning = logFunctionsConfigDeprecationWarn
6
6
  exports.ensureLegacyRuntimeConfigCommandsEnabled = ensureLegacyRuntimeConfigCommandsEnabled;
7
7
  exports.ensureApi = ensureApi;
8
8
  exports.varNameToIds = varNameToIds;
9
- exports.idsToVarName = idsToVarName;
10
9
  exports.getAppEngineLocation = getAppEngineLocation;
11
10
  exports.getFirebaseConfig = getFirebaseConfig;
12
11
  exports.setVariablesRecursive = setVariablesRecursive;
@@ -89,9 +88,6 @@ function varNameToIds(varName) {
89
88
  variable: varName.match(new RegExp("/variables/(.+)"))[1],
90
89
  };
91
90
  }
92
- function idsToVarName(projectId, configId, varId) {
93
- return ["projects", projectId, "configs", configId, "variables", varId].join("/");
94
- }
95
91
  function getAppEngineLocation(config) {
96
92
  let appEngineLocation = config.locationId;
97
93
  if (appEngineLocation && appEngineLocation.match(/[^\d]$/)) {
@@ -103,7 +103,7 @@ const actionFunction = async (options) => {
103
103
  replServer.on("reset", initializeContext);
104
104
  return new Promise((resolve) => {
105
105
  replServer.on("exit", () => {
106
- return serveFunctions.stop().then(resolve).catch(resolve);
106
+ serveFunctions.stop().then(resolve).catch(resolve);
107
107
  });
108
108
  });
109
109
  });
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.API_VERSION = void 0;
4
4
  exports.ensureApiEnabled = ensureApiEnabled;
5
- exports.deletePackage = deletePackage;
6
5
  exports.getRepository = getRepository;
7
6
  exports.updateRepository = updateRepository;
8
7
  exports.ensureDockerRepository = ensureDockerRepository;
@@ -23,10 +22,6 @@ function ensureApiEnabled(projectId) {
23
22
  return api.ensure(projectId, (0, api_1.artifactRegistryDomain)(), "artifactregistry", true);
24
23
  }
25
24
  (0, metaprogramming_1.assertImplements)();
26
- async function deletePackage(name) {
27
- const res = await client.delete(name);
28
- return res.body;
29
- }
30
25
  async function getRepository(repoPath) {
31
26
  const res = await client.get(repoPath);
32
27
  return res.body;
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.API_VERSION = void 0;
4
4
  exports.generateUploadUrl = generateUploadUrl;
5
5
  exports.createFunction = createFunction;
6
- exports.getFunction = getFunction;
7
6
  exports.listAllFunctions = listAllFunctions;
8
7
  exports.updateFunction = updateFunction;
9
8
  exports.deleteFunction = deleteFunction;
@@ -92,11 +91,6 @@ async function createFunction(cloudFunction) {
92
91
  throw functionsOpLogReject(cloudFunction, "create", err);
93
92
  }
94
93
  }
95
- async function getFunction(projectId, location, functionId) {
96
- const name = `projects/${projectId}/locations/${location}/functions/${functionId}`;
97
- const res = await client.get(name);
98
- return res.body;
99
- }
100
94
  async function listAllFunctions(projectId) {
101
95
  return await listFunctionsInternal(projectId, "-");
102
96
  }
@@ -146,8 +146,8 @@ async function generateP4SA(projectNumber) {
146
146
  await (0, serviceusage_1.generateServiceIdentityAndPoll)(projectNumber, new URL(devConnectOrigin).hostname, "apphosting");
147
147
  }
148
148
  function extractGitRepositoryLinkComponents(path) {
149
- const connectionMatch = /connections\/([^\/]+)/.exec(path);
150
- const repositoryMatch = /gitRepositoryLinks\/([^\/]+)/.exec(path);
149
+ const connectionMatch = /connections\/([^/]+)/.exec(path);
150
+ const repositoryMatch = /gitRepositoryLinks\/([^/]+)/.exec(path);
151
151
  const connection = connectionMatch ? connectionMatch[1] : null;
152
152
  const gitRepoLink = repositoryMatch ? repositoryMatch[1] : null;
153
153
  return { connection, gitRepoLink };
package/lib/gcp/iam.js CHANGED
@@ -1,6 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDefaultCloudBuildServiceAgent = getDefaultCloudBuildServiceAgent;
4
3
  exports.createServiceAccount = createServiceAccount;
5
4
  exports.getServiceAccount = getServiceAccount;
6
5
  exports.createServiceAccountKey = createServiceAccountKey;
@@ -22,9 +21,6 @@ const error_1 = require("../error");
22
21
  const knownRoles = require("./knownRoles.json");
23
22
  const crypto = require("crypto");
24
23
  const apiClient = new apiv2_1.Client({ urlPrefix: (0, api_1.iamOrigin)(), apiVersion: "v1" });
25
- function getDefaultCloudBuildServiceAgent(projectNumber) {
26
- return `${projectNumber}@cloudbuild.gserviceaccount.com`;
27
- }
28
24
  async function createServiceAccount(projectId, accountId, description, displayName) {
29
25
  const response = await apiClient.post(`/projects/${projectId}/serviceAccounts`, {
30
26
  accountId,
package/lib/gcp/pubsub.js CHANGED
@@ -1,12 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createTopic = createTopic;
4
- exports.getTopic = getTopic;
5
- exports.updateTopic = updateTopic;
6
4
  exports.deleteTopic = deleteTopic;
7
5
  const apiv2_1 = require("../apiv2");
8
6
  const api_1 = require("../api");
9
- const proto = require("./proto");
10
7
  const API_VERSION = "v1";
11
8
  const client = new apiv2_1.Client({
12
9
  urlPrefix: (0, api_1.pubsubOrigin)(),
@@ -17,17 +14,6 @@ async function createTopic(topic) {
17
14
  const result = await client.put(topic.name, topic);
18
15
  return result.body;
19
16
  }
20
- async function getTopic(name) {
21
- const result = await client.get(name);
22
- return result.body;
23
- }
24
- async function updateTopic(topic) {
25
- const queryParams = {
26
- updateMask: proto.fieldMasks(topic).join(","),
27
- };
28
- const result = await client.patch(topic.name, topic, { queryParams });
29
- return result.body;
30
- }
31
17
  async function deleteTopic(name) {
32
18
  await client.delete(name);
33
19
  }
@@ -149,7 +149,7 @@ async function createBucket(projectId, req, projectPrivate) {
149
149
  async function patchBucket(bucketName, metadata) {
150
150
  try {
151
151
  const localAPIClient = new apiv2_1.Client({ urlPrefix: (0, api_1.storageOrigin)() });
152
- const mask = (0, proto_1.fieldMasks)(metadata, "labels", "acl", "defaultObjectAcl", "lifecycle", "cors");
152
+ const mask = (0, proto_1.fieldMasks)(metadata, "labels", "acl", "defaultObjectAcl", "lifecycle", "cors", "autoclass");
153
153
  const result = await localAPIClient.patch(`/storage/v1/b/${bucketName}`, metadata, { queryParams: { updateMask: mask.join(",") } });
154
154
  return result.body;
155
155
  }
@@ -197,6 +197,7 @@ async function upsertBucket(opts) {
197
197
  labels: {
198
198
  [opts.req.purposeLabel]: "true",
199
199
  },
200
+ ...(opts.req.autoclass ? { autoclass: opts.req.autoclass } : {}),
200
201
  }, true);
201
202
  return name;
202
203
  }
@@ -25,13 +25,19 @@ exports.cleanAuthState = cleanAuthState;
25
25
  exports.getSiteDomains = getSiteDomains;
26
26
  exports.getAllSiteDomains = getAllSiteDomains;
27
27
  exports.getDeploymentDomain = getDeploymentDomain;
28
+ exports.resetEnsureApiEnabledCacheForTests = resetEnsureApiEnabledCacheForTests;
29
+ exports.ensureApiEnabled = ensureApiEnabled;
30
+ const clc = require("colorette");
28
31
  const error_1 = require("../error");
29
32
  const api_1 = require("../api");
30
33
  const apiv2_1 = require("../apiv2");
34
+ const ensureApiEnabledModule = require("../ensureApiEnabled");
35
+ const logger_1 = require("../logger");
31
36
  const operationPoller = require("../operation-poller");
32
37
  const expireUtils_1 = require("../hosting/expireUtils");
33
38
  const auth_1 = require("../gcp/auth");
34
39
  const proto = require("../gcp/proto");
40
+ const utils = require("../utils");
35
41
  const utils_1 = require("../utils");
36
42
  const constants_1 = require("../emulator/constants");
37
43
  const ONE_WEEK_MS = 604800000;
@@ -313,3 +319,76 @@ async function getDeploymentDomain(projectId, siteId, hostingChannel) {
313
319
  });
314
320
  return site && (0, utils_1.getHostnameFromUrl)(site?.defaultUrl);
315
321
  }
322
+ const FAILED_API_CHECK_TTL_MS = 5 * 60 * 1000;
323
+ const failedApiChecks = new Map();
324
+ const inFlightApiChecks = new Map();
325
+ function resetEnsureApiEnabledCacheForTests() {
326
+ failedApiChecks.clear();
327
+ inFlightApiChecks.clear();
328
+ }
329
+ function isServiceUsagePermissionError(err) {
330
+ if ((0, error_1.getErrStatus)(err) === 403) {
331
+ return true;
332
+ }
333
+ if (!(0, error_1.isObject)(err)) {
334
+ return false;
335
+ }
336
+ const context = (0, error_1.isObject)(err.context) ? err.context : undefined;
337
+ const body = context && (0, error_1.isObject)(context.body) ? context.body : undefined;
338
+ const errorBody = body && (0, error_1.isObject)(body.error) ? body.error : undefined;
339
+ return errorBody?.status === "PERMISSION_DENIED" || errorBody?.code === 403;
340
+ }
341
+ function isServiceUsageEnableError(err, errMsg) {
342
+ if (errMsg.startsWith("Permissions denied enabling") || errMsg.includes(":enable")) {
343
+ return true;
344
+ }
345
+ if (!(0, error_1.isObject)(err) || !(0, error_1.isObject)(err.context) || !(0, error_1.isObject)(err.context.response)) {
346
+ return false;
347
+ }
348
+ const responseUrl = err.context.response.url;
349
+ return typeof responseUrl === "string" && responseUrl.includes(":enable");
350
+ }
351
+ async function ensureApiEnabled(projectId) {
352
+ const apiUri = (0, api_1.hostingApiOrigin)();
353
+ const apiName = (0, utils_1.getHostnameFromUrl)(apiUri) || apiUri;
354
+ const cacheKey = `${projectId}:${apiName}`;
355
+ const failedUntil = failedApiChecks.get(cacheKey);
356
+ if (failedUntil !== undefined) {
357
+ if (Date.now() < failedUntil) {
358
+ return;
359
+ }
360
+ failedApiChecks.delete(cacheKey);
361
+ }
362
+ const inFlight = inFlightApiChecks.get(cacheKey);
363
+ if (inFlight) {
364
+ return inFlight;
365
+ }
366
+ const checkPromise = (async () => {
367
+ try {
368
+ await ensureApiEnabledModule.ensure(projectId, apiUri, "hosting", true);
369
+ failedApiChecks.delete(cacheKey);
370
+ }
371
+ catch (err) {
372
+ const errMsg = (0, error_1.getErrMsg)(err);
373
+ logger_1.logger.debug(`[hosting] failed to ensure Hosting API is enabled: ${errMsg}`);
374
+ const enableUrl = ensureApiEnabledModule.enableApiURI(projectId, apiName);
375
+ if (isServiceUsagePermissionError(err)) {
376
+ failedApiChecks.set(cacheKey, Date.now() + FAILED_API_CHECK_TTL_MS);
377
+ if (isServiceUsageEnableError(err, errMsg)) {
378
+ utils.logLabeledWarning("hosting", clc.bold(`Unable to enable ${apiName} on project ${projectId}. Enable the API by visiting ${enableUrl}, or grant the caller the roles/serviceusage.serviceUsageAdmin role.`));
379
+ }
380
+ else {
381
+ utils.logLabeledWarning("hosting", clc.bold(`Unable to check whether ${apiName} is enabled on project ${projectId}. Grant the caller the roles/serviceusage.serviceUsageConsumer role to check API enablement, or ensure the API is enabled at ${enableUrl} if subsequent requests fail.`));
382
+ }
383
+ }
384
+ else {
385
+ utils.logLabeledWarning("hosting", clc.bold(`Unable to ensure that ${apiName} is enabled on project ${projectId}. Ensure it is enabled at ${enableUrl} if subsequent requests fail.`));
386
+ }
387
+ }
388
+ finally {
389
+ inFlightApiChecks.delete(cacheKey);
390
+ }
391
+ })();
392
+ inFlightApiChecks.set(cacheKey, checkPromise);
393
+ return checkPromise;
394
+ }