firebase-tools 15.28.1 → 15.28.2

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.
@@ -0,0 +1,709 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FUNCTION_KITS_DIR = exports.DEFAULT_TEMPLATE = exports.TEMPLATES = void 0;
4
+ exports.generateUniqueId = generateUniqueId;
5
+ exports.parseNpmPackageSpecifier = parseNpmPackageSpecifier;
6
+ exports.validateNpmPackageName = validateNpmPackageName;
7
+ exports.sanitizePackageNameToKitName = sanitizePackageNameToKitName;
8
+ exports.isThirdPartyPackage = isThirdPartyPackage;
9
+ exports.checkPackageHasShrinkwrap = checkPackageHasShrinkwrap;
10
+ exports.isKitConfiguredForProject = isKitConfiguredForProject;
11
+ exports.extractExistingFunctionsInfo = extractExistingFunctionsInfo;
12
+ exports.promptKitInstanceId = promptKitInstanceId;
13
+ exports.promptKitId = promptKitId;
14
+ exports.promptSecurityConfirmation = promptSecurityConfirmation;
15
+ exports.promptExistingInstanceForProject = promptExistingInstanceForProject;
16
+ exports.writeKitPackageJson = writeKitPackageJson;
17
+ exports.writeKitIndexTs = writeKitIndexTs;
18
+ exports.scaffoldKitFiles = scaffoldKitFiles;
19
+ exports.buildAndInstallKit = buildAndInstallKit;
20
+ exports.addKitToConfig = addKitToConfig;
21
+ exports.validateAndResolveDirectoryKit = validateAndResolveDirectoryKit;
22
+ exports.buildAndInstallDirectoryKit = buildAndInstallDirectoryKit;
23
+ exports.findKitConfig = findKitConfig;
24
+ exports.addInstanceToKitConfig = addInstanceToKitConfig;
25
+ exports.scaffoldKit = scaffoldKit;
26
+ exports.addInstanceToKit = addInstanceToKit;
27
+ exports.discoverKitBuild = discoverKitBuild;
28
+ exports.printKitFirstDeployReport = printKitFirstDeployReport;
29
+ exports.addKitInstanceOrConfigureProject = addKitInstanceOrConfigureProject;
30
+ exports.findExistingKit = findExistingKit;
31
+ exports.resolvePackageSource = resolvePackageSource;
32
+ exports.resolveDirectorySource = resolveDirectorySource;
33
+ exports.installKitOrInstance = installKitOrInstance;
34
+ const crypto = require("crypto");
35
+ const path = require("path");
36
+ const clc = require("colorette");
37
+ const fs = require("fs-extra");
38
+ const error_1 = require("../../error");
39
+ const projectUtils_1 = require("../../projectUtils");
40
+ const utils_1 = require("../../utils");
41
+ const projectConfig_1 = require("../projectConfig");
42
+ const logger_1 = require("../../logger");
43
+ const prompt_1 = require("../../prompt");
44
+ const spawn_1 = require("../../init/spawn");
45
+ const templates_1 = require("../../templates");
46
+ const supported = require("../../deploy/functions/runtimes/supported");
47
+ const runtimes = require("../../deploy/functions/runtimes");
48
+ const build = require("../../deploy/functions/build");
49
+ const iam = require("../../gcp/iam");
50
+ const env_1 = require("../env");
51
+ const env_2 = require("./env");
52
+ exports.TEMPLATES = {
53
+ installation: "init/functions/typescript/index-kit.ts",
54
+ migration: "init/functions/typescript/index-kit-migration.ts",
55
+ };
56
+ exports.DEFAULT_TEMPLATE = "installation";
57
+ exports.FUNCTION_KITS_DIR = "function-kits";
58
+ function generateUniqueId(baseId, existingIds) {
59
+ if (!existingIds.has(baseId)) {
60
+ return baseId;
61
+ }
62
+ const prefix = baseId.slice(0, 35);
63
+ let candidate = "";
64
+ do {
65
+ const randomSuffix = crypto.randomBytes(2).toString("hex");
66
+ candidate = `${prefix}-${randomSuffix}`;
67
+ } while (existingIds.has(candidate));
68
+ return candidate;
69
+ }
70
+ function parseNpmPackageSpecifier(rawPkg) {
71
+ const lastAt = rawPkg.lastIndexOf("@");
72
+ if (lastAt > 0) {
73
+ return {
74
+ packageName: rawPkg.substring(0, lastAt),
75
+ version: rawPkg.substring(lastAt + 1),
76
+ };
77
+ }
78
+ return { packageName: rawPkg };
79
+ }
80
+ function validateNpmPackageName(packageName) {
81
+ const npmPackageRegex = /^(?:@[a-z0-9_.-]+\/[a-z0-9_.-]+|[a-z0-9_.-]+)$/i;
82
+ if (!packageName || packageName.length > 214 || !npmPackageRegex.test(packageName)) {
83
+ throw new error_1.FirebaseError(`Invalid NPM package name '${packageName}'. Package names must be valid npm package specifiers (e.g. 'my-kit' or '@scope/my-kit').`);
84
+ }
85
+ }
86
+ function sanitizePackageNameToKitName(packageName) {
87
+ const parts = packageName.split("/");
88
+ const nameWithoutScope = parts[parts.length - 1] || packageName;
89
+ const sanitized = nameWithoutScope.toLowerCase().replace(/[^a-z0-9_-]/g, "");
90
+ return sanitized.slice(0, 40);
91
+ }
92
+ function isThirdPartyPackage(packageName) {
93
+ return !packageName.startsWith("@firebase-function-kits/");
94
+ }
95
+ async function checkPackageHasShrinkwrap(rawPkgName) {
96
+ try {
97
+ const output = await (0, spawn_1.spawnWithOutput)("npm", ["pack", rawPkgName, "--dry-run", "--json"]);
98
+ const parsed = JSON.parse(output);
99
+ if (Array.isArray(parsed) && parsed.length > 0) {
100
+ const pkgInfo = parsed[0];
101
+ if (pkgInfo.hasShrinkwrap) {
102
+ return true;
103
+ }
104
+ if (Array.isArray(pkgInfo.files)) {
105
+ return pkgInfo.files.some((f) => f.path === "npm-shrinkwrap.json" || f.path === "npm-shrinkwrap.js");
106
+ }
107
+ }
108
+ }
109
+ catch (err) {
110
+ logger_1.logger.debug(`Failed to inspect package shrinkwrap for ${rawPkgName}: ${(0, error_1.getErrMsg)(err)}`);
111
+ }
112
+ return false;
113
+ }
114
+ function isKitConfiguredForProject(config, kit, projectId, projectAlias) {
115
+ return Object.values(kit.instances || {}).some((configDir) => (0, env_1.hasProjectEnv)(config.path(configDir), projectId, projectAlias));
116
+ }
117
+ function extractExistingFunctionsInfo(configFunctions) {
118
+ const existingFunctions = configFunctions && (!Array.isArray(configFunctions) || configFunctions.length > 0)
119
+ ? (0, projectConfig_1.normalizeAndValidate)(configFunctions)
120
+ : [];
121
+ const existingKitIds = new Set();
122
+ const existingCodebases = new Set();
123
+ const existingInstanceIds = new Set();
124
+ for (const c of existingFunctions) {
125
+ if ((0, projectConfig_1.isKitConfig)(c)) {
126
+ if (c.kit) {
127
+ existingKitIds.add(c.kit);
128
+ }
129
+ if (c.instances) {
130
+ for (const instId of Object.keys(c.instances)) {
131
+ existingInstanceIds.add(instId);
132
+ }
133
+ }
134
+ }
135
+ else if (c.codebase) {
136
+ existingCodebases.add(c.codebase);
137
+ }
138
+ }
139
+ return {
140
+ existingFunctions,
141
+ existingKitIds,
142
+ existingCodebases,
143
+ existingInstanceIds,
144
+ };
145
+ }
146
+ async function promptKitInstanceId(baseKitId, existingInstanceIds, existingCodebases, nonInteractive, customInstanceId) {
147
+ const instanceCollisions = new Set([...existingInstanceIds, ...existingCodebases]);
148
+ const defaultInstanceId = generateUniqueId(baseKitId, instanceCollisions);
149
+ if (customInstanceId) {
150
+ (0, projectConfig_1.validateKitInstanceId)(customInstanceId);
151
+ if (existingInstanceIds.has(customInstanceId)) {
152
+ throw new error_1.FirebaseError(`functions kit instance ID must be unique across all kits, but '${customInstanceId}' was used more than once.`);
153
+ }
154
+ if (existingCodebases.has(customInstanceId)) {
155
+ throw new error_1.FirebaseError(`functions codebase name and kit instance ID must be mutually exclusive, but '${customInstanceId}' was used as both a codebase name and a kit instance ID.`);
156
+ }
157
+ return customInstanceId;
158
+ }
159
+ const instanceId = await (0, prompt_1.input)({
160
+ message: "What would you like to name this instance?",
161
+ default: defaultInstanceId,
162
+ nonInteractive,
163
+ validate: (val) => {
164
+ try {
165
+ (0, projectConfig_1.validateKitInstanceId)(val);
166
+ }
167
+ catch (err) {
168
+ return (0, error_1.getErrMsg)(err);
169
+ }
170
+ if (existingInstanceIds.has(val)) {
171
+ return `functions kit instance ID must be unique across all kits, but '${val}' was used more than once.`;
172
+ }
173
+ if (existingCodebases.has(val)) {
174
+ return `functions codebase name and kit instance ID must be mutually exclusive, but '${val}' was used as both a codebase name and a kit instance ID.`;
175
+ }
176
+ return true;
177
+ },
178
+ });
179
+ (0, projectConfig_1.validateKitInstanceId)(instanceId);
180
+ if (existingInstanceIds.has(instanceId)) {
181
+ throw new error_1.FirebaseError(`functions kit instance ID must be unique across all kits, but '${instanceId}' was used more than once.`);
182
+ }
183
+ if (existingCodebases.has(instanceId)) {
184
+ throw new error_1.FirebaseError(`functions codebase name and kit instance ID must be mutually exclusive, but '${instanceId}' was used as both a codebase name and a kit instance ID.`);
185
+ }
186
+ return instanceId;
187
+ }
188
+ async function promptKitId(packageName, existingKitIds, nonInteractive, customKitId) {
189
+ const baseKitId = sanitizePackageNameToKitName(packageName) || "kit";
190
+ const defaultKitId = generateUniqueId(baseKitId, existingKitIds);
191
+ if (customKitId) {
192
+ (0, projectConfig_1.validateKit)(customKitId);
193
+ if (existingKitIds.has(customKitId)) {
194
+ throw new error_1.FirebaseError(`functions.kit must be unique but '${customKitId}' was used more than once.`);
195
+ }
196
+ return customKitId;
197
+ }
198
+ const kitId = await (0, prompt_1.input)({
199
+ message: "What would you like to name this kit?",
200
+ default: defaultKitId,
201
+ nonInteractive,
202
+ validate: (val) => {
203
+ try {
204
+ (0, projectConfig_1.validateKit)(val);
205
+ }
206
+ catch (err) {
207
+ return (0, error_1.getErrMsg)(err);
208
+ }
209
+ if (existingKitIds.has(val)) {
210
+ return `functions.kit must be unique but '${val}' was used more than once.`;
211
+ }
212
+ return true;
213
+ },
214
+ });
215
+ (0, projectConfig_1.validateKit)(kitId);
216
+ if (existingKitIds.has(kitId)) {
217
+ throw new error_1.FirebaseError(`functions.kit must be unique but '${kitId}' was used more than once.`);
218
+ }
219
+ return kitId;
220
+ }
221
+ async function promptSecurityConfirmation(rawPkgName, packageName, nonInteractive) {
222
+ const isThirdParty = isThirdPartyPackage(packageName);
223
+ if (isThirdParty) {
224
+ (0, utils_1.logLabeledWarning)("functions", `Package ${clc.bold(packageName)} is a third-party kit (outside the @firebase-function-kits scope).`);
225
+ }
226
+ const hasShrinkwrap = await checkPackageHasShrinkwrap(rawPkgName);
227
+ if (!hasShrinkwrap) {
228
+ (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.`);
229
+ }
230
+ if (isThirdParty || !hasShrinkwrap) {
231
+ let confirmMessage;
232
+ if (isThirdParty && !hasShrinkwrap) {
233
+ confirmMessage = `Are you sure you want to install the third-party kit ${packageName} without locked dependencies?`;
234
+ }
235
+ else if (isThirdParty) {
236
+ confirmMessage = `Are you sure you want to install the third-party kit ${packageName}?`;
237
+ }
238
+ else {
239
+ confirmMessage = `Are you sure you want to install ${packageName} without locked dependencies?`;
240
+ }
241
+ const confirmInstallation = await (0, prompt_1.confirm)({
242
+ message: confirmMessage,
243
+ default: false,
244
+ nonInteractive,
245
+ });
246
+ if (!confirmInstallation) {
247
+ throw new error_1.FirebaseError("Installation cancelled.");
248
+ }
249
+ }
250
+ return isThirdParty;
251
+ }
252
+ async function promptExistingInstanceForProject(options, existingKit) {
253
+ const instanceIds = Object.keys(existingKit.instances || {});
254
+ if (instanceIds.length === 0) {
255
+ throw new error_1.FirebaseError(`Kit '${existingKit.kit}' has no instances configured.`);
256
+ }
257
+ let selectedInstanceId = "<instance-name>";
258
+ if (instanceIds.length === 1) {
259
+ selectedInstanceId = instanceIds[0];
260
+ }
261
+ else if (!options.nonInteractive) {
262
+ selectedInstanceId = await (0, prompt_1.select)({
263
+ message: "Which instance would you like to configure for this project?",
264
+ choices: instanceIds.map((id) => ({ name: id, value: id })),
265
+ });
266
+ }
267
+ const targetProject = (0, projectUtils_1.getProjectId)(options) || options.project || "<project-name>";
268
+ (0, utils_1.logLabeledBullet)("functions", `To create a new instance in this project, deploy the instance dedicated to this project using\n` +
269
+ clc.bold(`firebase deploy --only functions:${selectedInstanceId} --project ${targetProject}`));
270
+ return selectedInstanceId;
271
+ }
272
+ async function writeKitPackageJson(config, sourcePath, kitId) {
273
+ const relPackageJsonPath = path.join(sourcePath, "package.json");
274
+ const absPackageJsonPath = config.path(relPackageJsonPath);
275
+ let pkgJson = {};
276
+ if (await fs.pathExists(absPackageJsonPath)) {
277
+ try {
278
+ pkgJson = (await fs.readJson(absPackageJsonPath));
279
+ }
280
+ catch (err) {
281
+ logger_1.logger.debug(`Failed to read existing package.json: ${(0, error_1.getErrMsg)(err)}`);
282
+ }
283
+ }
284
+ else {
285
+ const latestNodeVersion = supported.latest("nodejs").replace("nodejs", "");
286
+ const packageNoLintingTemplate = (0, templates_1.readTemplateSync)("init/functions/typescript/package.nolint.json");
287
+ const subbedTemplate = packageNoLintingTemplate.replace(/{{RUNTIME}}/g, latestNodeVersion);
288
+ try {
289
+ pkgJson = JSON.parse(subbedTemplate);
290
+ }
291
+ catch (err) {
292
+ throw new error_1.FirebaseError("Failed to parse package.nolint.json template: " + (0, error_1.getErrMsg)(err));
293
+ }
294
+ }
295
+ pkgJson.name = `${kitId}-wrapper`;
296
+ await config.askWriteProjectFile(relPackageJsonPath, pkgJson);
297
+ }
298
+ async function writeKitIndexTs(config, sourcePath, packageName, templateType) {
299
+ const relIndexTsPath = path.join(sourcePath, "src", "index.ts");
300
+ const absIndexTsPath = config.path(relIndexTsPath);
301
+ if (!(await fs.pathExists(absIndexTsPath))) {
302
+ const template = (0, templates_1.readTemplateSync)(exports.TEMPLATES[templateType]);
303
+ const indexContent = template.replace(/{{PACKAGE_NAME}}/g, packageName);
304
+ await config.askWriteProjectFile(relIndexTsPath, indexContent);
305
+ }
306
+ }
307
+ async function scaffoldKitFiles(config, kitId, instanceId, packageName, templateType = exports.DEFAULT_TEMPLATE) {
308
+ const sourcePath = path.join(exports.FUNCTION_KITS_DIR, kitId, "source");
309
+ const configDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
310
+ const absSourcePath = config.path(sourcePath);
311
+ const absConfigDirPath = config.path(configDirPath);
312
+ await fs.ensureDir(absSourcePath);
313
+ await fs.ensureDir(absConfigDirPath);
314
+ await writeKitPackageJson(config, sourcePath, kitId);
315
+ await config.askWriteProjectFile(path.join(sourcePath, "tsconfig.json"), (0, templates_1.readTemplateSync)("init/functions/typescript/tsconfig.json"));
316
+ await config.askWriteProjectFile(path.join(sourcePath, ".gitignore"), (0, templates_1.readTemplateSync)("init/functions/typescript/_gitignore"));
317
+ await writeKitIndexTs(config, sourcePath, packageName, templateType);
318
+ return { sourcePath, configDirPath, absSourcePath, absConfigDirPath };
319
+ }
320
+ async function buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty) {
321
+ const installArgs = ["install", rawPkgName, "--save-prefix=^"];
322
+ if (isThirdParty) {
323
+ installArgs.push("--ignore-scripts");
324
+ }
325
+ (0, utils_1.logLabeledBullet)("functions", `Running npm ${installArgs.join(" ")}...`);
326
+ try {
327
+ await (0, spawn_1.wrapSpawn)("npm", installArgs, absSourcePath);
328
+ }
329
+ catch (err) {
330
+ throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
331
+ }
332
+ (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
333
+ try {
334
+ await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
335
+ }
336
+ catch (err) {
337
+ throw new error_1.FirebaseError(`TypeScript build failed: ${(0, error_1.getErrMsg)(err)}`);
338
+ }
339
+ }
340
+ function addKitToConfig(config, options) {
341
+ const configSrc = config.src;
342
+ const newKitConfig = {
343
+ kit: options.kitId,
344
+ ...(options.packageName ? { sourcePackage: { name: options.packageName } } : {}),
345
+ source: options.sourcePath,
346
+ instances: {
347
+ [options.instanceId]: options.configDirPath,
348
+ },
349
+ ...(options.hasBuildScript ?? true
350
+ ? { predeploy: ['npm --prefix "$RESOURCE_DIR" run build'] }
351
+ : {}),
352
+ };
353
+ const functionsRaw = configSrc.functions;
354
+ if (!functionsRaw) {
355
+ configSrc.functions = [newKitConfig];
356
+ }
357
+ else if (Array.isArray(functionsRaw)) {
358
+ functionsRaw.push(newKitConfig);
359
+ }
360
+ else {
361
+ configSrc.functions = [functionsRaw, newKitConfig];
362
+ }
363
+ config.writeProjectFile("firebase.json", configSrc);
364
+ }
365
+ async function validateAndResolveDirectoryKit(projectDir, rawDir) {
366
+ const absDirectoryPath = (0, utils_1.resolveWithin)(projectDir, rawDir, `Directory '${rawDir}' is outside of project directory. Function kit directory must be inside the project directory.`);
367
+ if (!(await fs.pathExists(absDirectoryPath))) {
368
+ throw new error_1.FirebaseError(`Directory '${rawDir}' does not exist.`);
369
+ }
370
+ const stat = await fs.stat(absDirectoryPath);
371
+ if (!stat.isDirectory()) {
372
+ throw new error_1.FirebaseError(`Directory '${rawDir}' is not a directory.`);
373
+ }
374
+ const packageJsonPath = path.join(absDirectoryPath, "package.json");
375
+ if (!(await fs.pathExists(packageJsonPath))) {
376
+ throw new error_1.FirebaseError(`Directory '${rawDir}' must contain a package.json file to be installed as a function kit.`);
377
+ }
378
+ let packageJson = {};
379
+ try {
380
+ packageJson = (await fs.readJson(packageJsonPath));
381
+ }
382
+ catch (err) {
383
+ throw new error_1.FirebaseError(`Failed to parse package.json in '${rawDir}': ${(0, error_1.getErrMsg)(err)}`);
384
+ }
385
+ const hasBuildScript = Boolean(packageJson.scripts && packageJson.scripts.build);
386
+ let relSourcePath = path.relative(projectDir, absDirectoryPath);
387
+ if (!relSourcePath) {
388
+ relSourcePath = ".";
389
+ }
390
+ relSourcePath = relSourcePath.split(path.sep).join("/");
391
+ return {
392
+ absDirectoryPath,
393
+ relSourcePath,
394
+ hasBuildScript,
395
+ };
396
+ }
397
+ async function buildAndInstallDirectoryKit(absSourcePath, hasBuildScript) {
398
+ (0, utils_1.logLabeledBullet)("functions", "Running npm install...");
399
+ try {
400
+ await (0, spawn_1.wrapSpawn)("npm", ["install"], absSourcePath);
401
+ }
402
+ catch (err) {
403
+ throw new error_1.FirebaseError(`NPM install failed: ${(0, error_1.getErrMsg)(err)}`);
404
+ }
405
+ if (hasBuildScript) {
406
+ (0, utils_1.logLabeledBullet)("functions", "Building TypeScript source...");
407
+ try {
408
+ await (0, spawn_1.wrapSpawn)("npm", ["run", "build"], absSourcePath);
409
+ }
410
+ catch (err) {
411
+ throw new error_1.FirebaseError(`TypeScript build failed: ${(0, error_1.getErrMsg)(err)}`);
412
+ }
413
+ }
414
+ }
415
+ function findKitConfig(config, kitId) {
416
+ const functions = config.src.functions;
417
+ if (!functions) {
418
+ return undefined;
419
+ }
420
+ if (Array.isArray(functions)) {
421
+ return functions.find((f) => typeof f === "object" && f !== null && "kit" in f && f.kit === kitId);
422
+ }
423
+ if (typeof functions === "object" &&
424
+ "kit" in functions &&
425
+ functions.kit === kitId) {
426
+ return functions;
427
+ }
428
+ return undefined;
429
+ }
430
+ function addInstanceToKitConfig(config, kitId, instanceId, configDirPath) {
431
+ const target = findKitConfig(config, kitId);
432
+ if (!target) {
433
+ throw new error_1.FirebaseError(`Kit '${kitId}' not found in firebase.json.`);
434
+ }
435
+ target.instances = target.instances || {};
436
+ target.instances[instanceId] = configDirPath;
437
+ config.writeProjectFile("firebase.json", config.src);
438
+ }
439
+ async function scaffoldKit(options) {
440
+ const paths = await scaffoldKitFiles(options.config, options.kitId, options.instanceId, options.packageName, options.templateType);
441
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
442
+ (0, env_2.seedKitInstanceEnv)({
443
+ configDir: paths.absConfigDirPath,
444
+ functionsSource: paths.absSourcePath,
445
+ projectDir: options.config.projectDir,
446
+ projectId: options.seedEnv.projectId,
447
+ projectAlias: options.seedEnv.projectAlias,
448
+ envs: options.seedEnv.envs,
449
+ });
450
+ }
451
+ addKitToConfig(options.config, {
452
+ kitId: options.kitId,
453
+ instanceId: options.instanceId,
454
+ packageName: options.packageName,
455
+ sourcePath: paths.sourcePath,
456
+ configDirPath: paths.configDirPath,
457
+ });
458
+ return paths;
459
+ }
460
+ async function addInstanceToKit(options) {
461
+ const target = findKitConfig(options.config, options.kitId);
462
+ if (!target) {
463
+ throw new error_1.FirebaseError(`Kit '${options.kitId}' not found in firebase.json.`);
464
+ }
465
+ const configDirPath = path.join(exports.FUNCTION_KITS_DIR, options.kitId, `config-${options.instanceId}`);
466
+ const absConfigDirPath = options.config.path(configDirPath);
467
+ await fs.ensureDir(absConfigDirPath);
468
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
469
+ (0, env_2.seedKitInstanceEnv)({
470
+ configDir: absConfigDirPath,
471
+ functionsSource: options.config.path(target.source),
472
+ projectDir: options.config.projectDir,
473
+ projectId: options.seedEnv.projectId,
474
+ projectAlias: options.seedEnv.projectAlias,
475
+ envs: options.seedEnv.envs,
476
+ });
477
+ }
478
+ addInstanceToKitConfig(options.config, options.kitId, options.instanceId, configDirPath);
479
+ return { configDirPath, absConfigDirPath };
480
+ }
481
+ async function discoverKitBuild(options, absSourcePath) {
482
+ const projectId = (0, projectUtils_1.getProjectId)(options) || "";
483
+ const delegateContext = {
484
+ projectId,
485
+ sourceDir: absSourcePath,
486
+ projectDir: options.config?.projectDir || "",
487
+ runtime: supported.latest("nodejs"),
488
+ };
489
+ const runtimeDelegate = await runtimes.getRuntimeDelegate(delegateContext);
490
+ return runtimeDelegate.discoverBuild({}, {});
491
+ }
492
+ async function printKitFirstDeployReport(options, instanceId, absSourcePath) {
493
+ let discoveredBuild;
494
+ const prefix = (0, projectConfig_1.addKitPrefix)(instanceId);
495
+ try {
496
+ discoveredBuild = await discoverKitBuild(options, absSourcePath);
497
+ build.applyPrefix(discoveredBuild, prefix);
498
+ }
499
+ catch (err) {
500
+ logger_1.logger.debug(`Could not discover kit build for reporting: ${(0, error_1.getErrMsg)(err)}`);
501
+ return;
502
+ }
503
+ const formatScopedName = (name) => {
504
+ const fullPrefix = `${prefix}-`;
505
+ if (name.startsWith(fullPrefix)) {
506
+ return `${fullPrefix}${clc.bold(name.slice(fullPrefix.length))}`;
507
+ }
508
+ return clc.bold(name);
509
+ };
510
+ const functions = Object.keys(discoveredBuild.endpoints).sort().map(formatScopedName);
511
+ const taskQueues = Object.entries(discoveredBuild.endpoints)
512
+ .filter(([, endpoint]) => build.isTaskQueueTriggered(endpoint))
513
+ .map(([id]) => id)
514
+ .sort()
515
+ .map(formatScopedName);
516
+ const channelSet = new Set();
517
+ for (const endpoint of Object.values(discoveredBuild.endpoints)) {
518
+ if (build.isEventTriggered(endpoint) && endpoint.eventTrigger?.channel) {
519
+ channelSet.add(endpoint.eventTrigger.channel);
520
+ }
521
+ }
522
+ const eventarcChannels = Array.from(channelSet).sort();
523
+ const apis = (discoveredBuild.requiredAPIs || []).map((a) => a.api).sort();
524
+ const rawRoles = discoveredBuild.requiredRoles || [];
525
+ const roles = (await Promise.all(rawRoles.map((r) => iam.getRoleName(r)))).sort();
526
+ const printSection = (heading, items) => {
527
+ if (items.length > 0) {
528
+ (0, utils_1.logLabeledBullet)("functions", `${heading}\n` + items.map((item) => `- ${item}`).join("\n"));
529
+ }
530
+ };
531
+ printSection("At the first deploy, the following functions will be created in your project:", functions);
532
+ printSection("At the first deploy, the following Task Queues will be created in your project:", taskQueues);
533
+ printSection("At the first deploy, the following Eventarc channels will be created in your project:", eventarcChannels);
534
+ printSection("At the first deploy, the following APIs will be enabled in your project:", apis);
535
+ printSection("At the first deploy, the following roles will be granted to the kit service account:", roles);
536
+ const hasItems = functions.length > 0 ||
537
+ taskQueues.length > 0 ||
538
+ eventarcChannels.length > 0 ||
539
+ apis.length > 0 ||
540
+ roles.length > 0;
541
+ if (hasItems) {
542
+ (0, utils_1.logLabeledWarning)("functions", `${clc.bold("Please review the changes above. If you do not want them applied to your project, uninstall this kit before running firebase deploy.")}`);
543
+ }
544
+ }
545
+ async function addKitInstanceOrConfigureProject(options, existingKit, existingFunctionsInfo) {
546
+ const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
547
+ const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
548
+ ? options.project
549
+ : undefined;
550
+ const isConfiguredForProject = isKitConfiguredForProject(options.config, existingKit, projectId, projectAlias);
551
+ let action;
552
+ if (!isConfiguredForProject && !options.nonInteractive) {
553
+ const existingInstances = Object.keys(existingKit.instances || {}).join(", ");
554
+ action = await (0, prompt_1.select)({
555
+ message: `The following instances already exist, but are not configured for this project: ${existingInstances}. What would you like to do?`,
556
+ choices: [
557
+ {
558
+ name: "Add an instance to the existing kit",
559
+ value: "addInstance",
560
+ },
561
+ {
562
+ name: "Configure an existing instance for this project",
563
+ value: "addEnv",
564
+ },
565
+ ],
566
+ });
567
+ }
568
+ else {
569
+ if (isConfiguredForProject) {
570
+ (0, utils_1.logLabeledBullet)("functions", `This package is already installed as kit ${existingKit.kit}, creating a new instance.`);
571
+ }
572
+ action = "addInstance";
573
+ }
574
+ if (action === "addInstance") {
575
+ const instanceId = await promptKitInstanceId(existingKit.kit, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
576
+ const result = await addInstanceToKit({
577
+ config: options.config,
578
+ kitId: existingKit.kit,
579
+ instanceId,
580
+ seedEnv: options.seedEnv,
581
+ });
582
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit instance ${clc.bold(instanceId)} successfully added to kit ${clc.bold(existingKit.kit)}.`);
583
+ await printKitFirstDeployReport(options, instanceId, options.config.path(existingKit.source));
584
+ return {
585
+ action: "addedInstance",
586
+ kitId: existingKit.kit,
587
+ instanceId,
588
+ sourcePath: existingKit.source,
589
+ configDirPath: result.configDirPath,
590
+ };
591
+ }
592
+ const selectedInstanceId = await promptExistingInstanceForProject(options, existingKit);
593
+ return {
594
+ action: "configuredEnv",
595
+ kitId: existingKit.kit,
596
+ instanceId: selectedInstanceId,
597
+ };
598
+ }
599
+ function findExistingKit(existingFunctions, options) {
600
+ if (options.package) {
601
+ const { packageName } = parseNpmPackageSpecifier(options.package);
602
+ return existingFunctions.find((c) => (0, projectConfig_1.isKitConfig)(c) && c.sourcePackage?.name === packageName);
603
+ }
604
+ if (options.directory) {
605
+ const absDir = path.isAbsolute(options.directory)
606
+ ? options.directory
607
+ : path.resolve(options.config.projectDir, options.directory);
608
+ return existingFunctions.find((c) => (0, projectConfig_1.isKitConfig)(c) &&
609
+ !c.sourcePackage &&
610
+ path.resolve(options.config.projectDir, c.source) === absDir);
611
+ }
612
+ return undefined;
613
+ }
614
+ async function resolvePackageSource(options) {
615
+ const templateType = options.template || exports.DEFAULT_TEMPLATE;
616
+ if (!(templateType in exports.TEMPLATES)) {
617
+ const validTemplates = Object.keys(exports.TEMPLATES)
618
+ .map((t) => `'${t}'`)
619
+ .join(" or ");
620
+ throw new error_1.FirebaseError(`Invalid template '${templateType}'. Template must be ${validTemplates}.`);
621
+ }
622
+ const rawPkgName = options.package;
623
+ if (!rawPkgName) {
624
+ throw new error_1.FirebaseError("Set the --package option to a valid NPM package and try again.");
625
+ }
626
+ const { packageName } = parseNpmPackageSpecifier(rawPkgName);
627
+ validateNpmPackageName(packageName);
628
+ const isThirdParty = await promptSecurityConfirmation(rawPkgName, packageName, options.nonInteractive);
629
+ return {
630
+ defaultKitName: packageName,
631
+ sourcePackageName: packageName,
632
+ hasBuildScript: true,
633
+ setup: (kitId, instanceId) => scaffoldKitFiles(options.config, kitId, instanceId, packageName, templateType),
634
+ buildAndInstall: (absSourcePath) => buildAndInstallKit(absSourcePath, rawPkgName, isThirdParty),
635
+ };
636
+ }
637
+ async function resolveDirectorySource(options) {
638
+ if (!options.directory) {
639
+ throw new error_1.FirebaseError("Must specify --directory.");
640
+ }
641
+ const { absDirectoryPath, relSourcePath, hasBuildScript } = await validateAndResolveDirectoryKit(options.config.projectDir, options.directory);
642
+ return {
643
+ defaultKitName: path.basename(absDirectoryPath),
644
+ sourcePackageName: undefined,
645
+ hasBuildScript,
646
+ setup: async (kitId, instanceId) => {
647
+ const configDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
648
+ const absConfigDirPath = options.config.path(configDirPath);
649
+ await fs.ensureDir(absConfigDirPath);
650
+ return {
651
+ sourcePath: relSourcePath,
652
+ configDirPath,
653
+ absSourcePath: absDirectoryPath,
654
+ absConfigDirPath,
655
+ };
656
+ },
657
+ buildAndInstall: (absSourcePath) => buildAndInstallDirectoryKit(absSourcePath, hasBuildScript),
658
+ };
659
+ }
660
+ async function installKitOrInstance(options) {
661
+ if (options.package && options.directory) {
662
+ throw new error_1.FirebaseError("Cannot specify both --package and --directory. Please choose one.");
663
+ }
664
+ if (!options.package && !options.directory) {
665
+ throw new error_1.FirebaseError("Must specify either --package or --directory.");
666
+ }
667
+ if (options.directory && options.template) {
668
+ throw new error_1.FirebaseError("Cannot specify --template with --directory.");
669
+ }
670
+ const existingFunctionsInfo = extractExistingFunctionsInfo(options.config.src.functions);
671
+ const existingKit = findExistingKit(existingFunctionsInfo.existingFunctions, options);
672
+ if (existingKit) {
673
+ return addKitInstanceOrConfigureProject(options, existingKit, existingFunctionsInfo);
674
+ }
675
+ const source = options.directory
676
+ ? await resolveDirectorySource(options)
677
+ : await resolvePackageSource(options);
678
+ const kitId = await promptKitId(source.defaultKitName, existingFunctionsInfo.existingKitIds, options.nonInteractive, options.kitId);
679
+ const instanceId = await promptKitInstanceId(kitId, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
680
+ const { sourcePath, configDirPath, absSourcePath, absConfigDirPath } = await source.setup(kitId, instanceId);
681
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
682
+ (0, env_2.seedKitInstanceEnv)({
683
+ configDir: absConfigDirPath,
684
+ functionsSource: absSourcePath,
685
+ projectDir: options.config.projectDir,
686
+ projectId: options.seedEnv.projectId,
687
+ projectAlias: options.seedEnv.projectAlias,
688
+ envs: options.seedEnv.envs,
689
+ });
690
+ }
691
+ await source.buildAndInstall(absSourcePath);
692
+ addKitToConfig(options.config, {
693
+ kitId,
694
+ instanceId,
695
+ packageName: source.sourcePackageName,
696
+ sourcePath,
697
+ configDirPath,
698
+ hasBuildScript: source.hasBuildScript,
699
+ });
700
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
701
+ await printKitFirstDeployReport(options, instanceId, absSourcePath);
702
+ return {
703
+ action: "installedKit",
704
+ kitId,
705
+ instanceId,
706
+ sourcePath,
707
+ configDirPath,
708
+ };
709
+ }