firebase-tools 15.30.1 → 15.30.3-main.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.
@@ -170,12 +170,18 @@ class FunctionsEmulator {
170
170
  else {
171
171
  triggerKey = `${this.args.projectId}:${event.eventType}`;
172
172
  }
173
- if (event.data.bucket) {
173
+ if (event.data?.bucket) {
174
174
  triggerKey += `:${event.data.bucket}`;
175
175
  }
176
176
  const triggers = this.multicastTriggers[triggerKey] || [];
177
177
  const { host, port } = this.getInfo();
178
- triggers.forEach((triggerId) => {
178
+ const eventTenantId = (0, functionsEmulatorShared_1.getEventTenantId)(event);
179
+ for (const triggerId of triggers) {
180
+ const record = this.getTriggerRecordByKey(triggerId);
181
+ const filterTenantId = record?.def?.eventTrigger?.eventFilters?.tenantid;
182
+ if (filterTenantId && filterTenantId !== eventTenantId) {
183
+ continue;
184
+ }
179
185
  const work = () => {
180
186
  return new Promise((resolve, reject) => {
181
187
  const trigReq = http.request({
@@ -193,7 +199,7 @@ class FunctionsEmulator {
193
199
  };
194
200
  work.type = `${triggerId}-${new Date().toISOString()}`;
195
201
  this.workQueue.submit(work);
196
- });
202
+ }
197
203
  res.json({ status: "multicast_acknowledged" });
198
204
  };
199
205
  const listBackendsHandler = (req, res) => {
@@ -378,7 +384,10 @@ class FunctionsEmulator {
378
384
  await this.args.extensionsEmulator.addDynamicExtensions(emulatableBackend.codebase, discoveredBuild);
379
385
  await this.loadDynamicExtensionBackends();
380
386
  }
381
- build.applyPrefix(discoveredBuild, emulatableBackend.prefix || "");
387
+ build.applyEndpointPrefix(discoveredBuild, emulatableBackend.prefix || "");
388
+ if (emulatableBackend.env?.FIREBASE_KIT_INSTANCE_ID) {
389
+ build.applyKitSecretRefPrefix(discoveredBuild, emulatableBackend.env.FIREBASE_KIT_INSTANCE_ID);
390
+ }
382
391
  const resolution = await (0, build_1.resolveBackend)({
383
392
  build: discoveredBuild,
384
393
  firebaseConfig: JSON.parse(firebaseConfig),
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EmulatedTrigger = exports.EVENTARC_SOURCE_ENV = void 0;
4
+ exports.getEventTenantId = getEventTenantId;
4
5
  exports.eventServiceImplemented = eventServiceImplemented;
5
6
  exports.prepareEndpoints = prepareEndpoints;
6
7
  exports.emulatedFunctionsFromEndpoints = emulatedFunctionsFromEndpoints;
@@ -36,7 +37,17 @@ const V2_EVENTS = [
36
37
  ...events.v2.STORAGE_EVENTS,
37
38
  ...events.v2.DATABASE_EVENTS,
38
39
  ...events.v2.FIRESTORE_EVENTS,
40
+ ...events.v2.AUTH_EVENTS,
39
41
  ];
42
+ function getEventTenantId(eventPayload) {
43
+ if (!eventPayload || typeof eventPayload !== "object") {
44
+ return undefined;
45
+ }
46
+ if (typeof eventPayload.tenantid === "string") {
47
+ return eventPayload.tenantid;
48
+ }
49
+ return undefined;
50
+ }
40
51
  exports.EVENTARC_SOURCE_ENV = "EVENTARC_CLOUD_EVENT_SOURCE";
41
52
  class EmulatedTrigger {
42
53
  constructor(definition, module) {
@@ -229,12 +240,12 @@ function getServiceFromEventType(eventType) {
229
240
  if (eventType.includes("firebasealerts")) {
230
241
  return constants_1.Constants.SERVICE_FIREALERTS;
231
242
  }
232
- if (eventType.includes("analytics")) {
233
- return constants_1.Constants.SERVICE_ANALYTICS;
234
- }
235
243
  if (eventType.includes("auth")) {
236
244
  return constants_1.Constants.SERVICE_AUTH;
237
245
  }
246
+ if (eventType.includes("analytics")) {
247
+ return constants_1.Constants.SERVICE_ANALYTICS;
248
+ }
238
249
  if (eventType.includes("crashlytics")) {
239
250
  return constants_1.Constants.SERVICE_CRASHLYTICS;
240
251
  }
@@ -224,7 +224,12 @@ exports.ALL_EXPERIMENTS = experiments({
224
224
  fdcapimigration: {
225
225
  shortDescription: "Enable the FDC API schema migration path.",
226
226
  fullDescription: "API based Schema Migration behind experimental flag.",
227
- default: true,
227
+ default: false,
228
+ public: false,
229
+ },
230
+ writeDefaultSecretBindings: {
231
+ shortDescription: "Write Cloud Secret Manager bindings to the default resource ID to .env.",
232
+ default: false,
228
233
  public: false,
229
234
  },
230
235
  });
@@ -121,16 +121,30 @@ function resolveMigratedMemory(liveSystemParams = {}, specSystemParams = []) {
121
121
  }
122
122
  return v2 ?? v1;
123
123
  }
124
+ function resolveLiveSecret(specParam, liveParams) {
125
+ const val = liveParams[specParam.param];
126
+ if (!val && !specParam.required) {
127
+ return undefined;
128
+ }
129
+ if (!val) {
130
+ throw new error_1.FirebaseError(`Secret ${specParam.param} was defined in the extension spec, but is missing in live deployed secrets.`, { exit: 1 });
131
+ }
132
+ return val;
133
+ }
124
134
  function functionsEnvFromInstance(instance) {
125
135
  const liveParams = instance.config?.params || {};
126
136
  const liveSystemParams = instance.config?.systemParams || {};
127
137
  const specParams = instance.config?.source?.spec?.params || [];
128
138
  const specSystemParams = instance.config?.source?.spec?.systemParams || [];
129
139
  const envs = {};
130
- specParams.forEach((specParam) => {
140
+ for (const specParam of specParams) {
131
141
  if (specParam.type === "SECRET") {
142
+ const val = resolveLiveSecret(specParam, liveParams);
143
+ if (!val) {
144
+ continue;
145
+ }
132
146
  const renamed = "FIREBASE_SECRET_REF_" + specParam.param;
133
- envs[renamed] = liveParams[specParam.param];
147
+ envs[renamed] = val;
134
148
  }
135
149
  else if (specParam.param in liveParams) {
136
150
  envs[specParam.param] = liveParams[specParam.param];
@@ -138,7 +152,7 @@ function functionsEnvFromInstance(instance) {
138
152
  else {
139
153
  envs[specParam.param] = specParam.default ?? "";
140
154
  }
141
- });
155
+ }
142
156
  for (const [sysParamName, sysParamValue] of Object.entries(liveSystemParams)) {
143
157
  if (MEMORY_PARAMS.has(sysParamName)) {
144
158
  continue;
@@ -181,12 +195,9 @@ async function secretsNeedingEjection(instance) {
181
195
  const liveParams = instance.config?.params || {};
182
196
  const secretParams = (instance.config?.source?.spec?.params ?? []).filter((p) => p.type === "SECRET");
183
197
  const checks = secretParams.map(async (specParam) => {
184
- const secretName = specParam.param;
185
- const resourceName = liveParams[secretName];
198
+ const resourceName = resolveLiveSecret(specParam, liveParams);
186
199
  if (!resourceName) {
187
- throw new error_1.FirebaseError("Secret " +
188
- secretName +
189
- " was defined in the extension spec, but is missing in live deployed secrets.", { exit: 1 });
200
+ return undefined;
190
201
  }
191
202
  const match = resourceName.match(secretManager_1.SECRET_VERSION_NAME_REGEX);
192
203
  if (!match?.groups) {
@@ -208,10 +219,9 @@ async function ejectSecretsFromInstance(instance) {
208
219
  if (specParam.type !== "SECRET") {
209
220
  continue;
210
221
  }
211
- const secretName = specParam.param;
212
- const resourceName = liveParams[secretName];
222
+ const resourceName = resolveLiveSecret(specParam, liveParams);
213
223
  if (!resourceName) {
214
- throw new error_1.FirebaseError(`Secret ${secretName} was defined in the extension spec, but is missing in live deployed secrets.`, { exit: 1 });
224
+ continue;
215
225
  }
216
226
  const match = resourceName.match(secretManager_1.SECRET_VERSION_NAME_REGEX);
217
227
  if (!match?.groups) {
@@ -1,48 +1,41 @@
1
1
  {
2
2
  "replacements": {
3
3
  "firebase/delete-user-data": {
4
- "status": "REPLACEMENT_AVAILABLE",
5
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/delete-user-data/README.md",
6
- "npmPackage": "@firebase-function-kits/delete-user-data"
4
+ "status": "PENDING_PUBLISHER",
5
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/delete-user-data/README.md"
7
6
  },
8
7
  "firebase/firestore-bigquery-export": {
9
8
  "status": "REPLACEMENT_AVAILABLE",
10
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-bigquery-export/README.md",
11
- "npmPackage": "@firebase-function-kits/firestore-bigquery-export"
9
+ "npmPackage": "@firebase-function-kits/firestore-bigquery-export",
10
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-bigquery-export/README.md"
12
11
  },
13
12
  "firebase/firestore-bundle-builder": {
14
13
  "status": "PENDING_PUBLISHER",
15
14
  "extensionRepositoryUrl": "https://github.com/firebase/firestore-bundle-builder/blob/master/README.md"
16
15
  },
17
16
  "firebase/firestore-counter": {
18
- "status": "REPLACEMENT_AVAILABLE",
19
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-counter/README.md",
20
- "npmPackage": "@firebase-function-kits/firestore-counter"
17
+ "status": "PENDING_PUBLISHER",
18
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-counter/README.md"
21
19
  },
22
20
  "firebase/firestore-send-email": {
23
- "status": "REPLACEMENT_AVAILABLE",
24
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-send-email/README.md",
25
- "npmPackage": "@firebase-function-kits/firestore-send-email"
21
+ "status": "PENDING_PUBLISHER",
22
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-send-email/README.md"
26
23
  },
27
24
  "firebase/firestore-shorten-urls-bitly": {
28
25
  "status": "PENDING_PUBLISHER",
29
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/main/firestore-shorten-urls-bitly/README.md",
30
- "npmPackage": "@firebase/firestore-shorten-urls-bitly"
26
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/main/firestore-shorten-urls-bitly/README.md"
31
27
  },
32
28
  "firebase/firestore-translate-text": {
33
- "status": "REPLACEMENT_AVAILABLE",
34
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-translate-text/README.md",
35
- "npmPackage": "@firebase-function-kits/firestore-translate-text"
29
+ "status": "PENDING_PUBLISHER",
30
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/firestore-translate-text/README.md"
36
31
  },
37
32
  "firebase/rtdb-limit-child-nodes": {
38
- "status": "REPLACEMENT_AVAILABLE",
39
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/rtdb-limit-child-nodes/README.md",
40
- "npmPackage": "@firebase-function-kits/rtdb-limit-child-nodes"
33
+ "status": "PENDING_PUBLISHER",
34
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/rtdb-limit-child-nodes/README.md"
41
35
  },
42
36
  "firebase/storage-resize-images": {
43
- "status": "REPLACEMENT_AVAILABLE",
44
- "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/storage-resize-images/README.md",
45
- "npmPackage": "@firebase-function-kits/storage-resize-images"
37
+ "status": "PENDING_PUBLISHER",
38
+ "extensionRepositoryUrl": "https://github.com/firebase/extensions/tree/kits/storage-resize-images/README.md"
46
39
  },
47
40
  "googlecloud/bigquery-firestore-export": {
48
41
  "status": "PENDING_PUBLISHER",
package/lib/fsutils.js CHANGED
@@ -5,10 +5,12 @@ exports.dirExistsSync = dirExistsSync;
5
5
  exports.readFile = readFile;
6
6
  exports.listFiles = listFiles;
7
7
  exports.moveAll = moveAll;
8
+ exports.removeDirectoryIfEmpty = removeDirectoryIfEmpty;
8
9
  const fs_1 = require("fs");
9
10
  const path = require("path");
11
+ const fs = require("fs-extra");
10
12
  const error_1 = require("./error");
11
- const fs_extra_1 = require("fs-extra");
13
+ const logger_1 = require("./logger");
12
14
  function fileExistsSync(path) {
13
15
  try {
14
16
  return (0, fs_1.statSync)(path).isFile();
@@ -56,6 +58,22 @@ function moveAll(srcDir, destDir) {
56
58
  const srcPath = path.join(srcDir, f);
57
59
  if (srcPath === destDir)
58
60
  continue;
59
- (0, fs_extra_1.moveSync)(srcPath, path.join(destDir, f));
61
+ fs.moveSync(srcPath, path.join(destDir, f));
62
+ }
63
+ }
64
+ async function removeDirectoryIfEmpty(absDirPath) {
65
+ try {
66
+ if (await fs.pathExists(absDirPath)) {
67
+ const stat = await fs.stat(absDirPath);
68
+ if (stat.isDirectory()) {
69
+ const entries = await fs.readdir(absDirPath);
70
+ if (entries.length === 0) {
71
+ await fs.remove(absDirPath);
72
+ }
73
+ }
74
+ }
75
+ }
76
+ catch (err) {
77
+ logger_1.logger.debug(`Failed to clean up directory '${absDirPath}' if empty: ${(0, error_1.getErrMsg)(err)}`);
60
78
  }
61
79
  }
@@ -24,6 +24,7 @@ exports.validateAndResolveDirectoryKit = validateAndResolveDirectoryKit;
24
24
  exports.buildAndInstallDirectoryKit = buildAndInstallDirectoryKit;
25
25
  exports.findKitConfig = findKitConfig;
26
26
  exports.addInstanceToKitConfig = addInstanceToKitConfig;
27
+ exports.revertFunctionsConfig = revertFunctionsConfig;
27
28
  exports.scaffoldKit = scaffoldKit;
28
29
  exports.addInstanceToKit = addInstanceToKit;
29
30
  exports.discoverKitBuild = discoverKitBuild;
@@ -56,9 +57,10 @@ const iam = require("../../gcp/iam");
56
57
  const functionsEnv = require("../env");
57
58
  const functionsConfig = require("../../functionsConfig");
58
59
  const prepare_1 = require("../../deploy/functions/prepare");
59
- const utils_2 = require("../../utils");
60
+ const functional_1 = require("../../functional");
60
61
  const env_1 = require("../env");
61
62
  const env_2 = require("./env");
63
+ const fsutils_1 = require("../../fsutils");
62
64
  exports.TEMPLATES = {
63
65
  installation: "init/functions/typescript/index-kit.ts",
64
66
  migration: "init/functions/typescript/index-kit-migration.ts",
@@ -540,6 +542,22 @@ function addInstanceToKitConfig(config, kitId, instanceId, configDirPath) {
540
542
  target.instances[instanceId] = configDirPath;
541
543
  config.writeProjectFile("firebase.json", config.src);
542
544
  }
545
+ function revertFunctionsConfig(options) {
546
+ try {
547
+ if (!(0, utils_1.deepEqual)(options.config.src.functions, options.originalFunctions)) {
548
+ if (options.originalFunctions === undefined) {
549
+ delete options.config.src.functions;
550
+ }
551
+ else {
552
+ options.config.src.functions = options.originalFunctions;
553
+ }
554
+ options.config.writeProjectFile("firebase.json", options.config.src);
555
+ }
556
+ }
557
+ catch (err) {
558
+ logger_1.logger.debug(`Failed to revert firebase.json: ${(0, error_1.getErrMsg)(err)}`);
559
+ }
560
+ }
543
561
  async function scaffoldKit(options) {
544
562
  const paths = await scaffoldKitFiles(options.config, options.kitId, options.instanceId, options.packageName, options.templateType);
545
563
  if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
@@ -611,6 +629,12 @@ async function promptAndWriteKitParams(options) {
611
629
  };
612
630
  const rawUserEnvs = functionsEnv.loadUserEnvs(userEnvOpt);
613
631
  const { userEnvs, secretRefs } = (0, prepare_1.partitionUserEnvs)(rawUserEnvs);
632
+ const parsedSecretRefs = (0, functional_1.mapObject)(secretRefs, (unparsed) => build.parseSecretRef(unparsed));
633
+ const secretPrefixForInstance = (0, projectConfig_1.addKitPrefix)(options.instanceId);
634
+ for (const secretParam of options.params.filter((p) => params.isSecretParam(p))) {
635
+ secretParam.resourceId = `${secretPrefixForInstance}-${secretParam.name}`;
636
+ }
637
+ build.applyEnvSecretBindingsToParams(options.params, parsedSecretRefs);
614
638
  let firebaseConfig = { projectId: options.projectId };
615
639
  try {
616
640
  firebaseConfig = await functionsConfig.getFirebaseConfig({ projectId: options.projectId });
@@ -625,10 +649,10 @@ async function promptAndWriteKitParams(options) {
625
649
  userEnvs: typedUserEnvs,
626
650
  codebase: options.instanceId,
627
651
  nonInteractive: options.nonInteractive,
628
- force: options.force,
629
652
  });
630
653
  functionsEnv.writeResolvedParams(resolvedEnvs, userEnvs, userEnvOpt);
631
- if (experiments.isEnabled("secretEnvParams")) {
654
+ if (experiments.isEnabled("secretEnvParams") &&
655
+ experiments.isEnabled("writeDefaultSecretBindings")) {
632
656
  functionsEnv.writeResolvedSecretRefs(resolvedSecretRefs, secretRefs, userEnvOpt);
633
657
  }
634
658
  }
@@ -637,9 +661,9 @@ async function printKitFirstDeployReport(options) {
637
661
  const prefix = (0, projectConfig_1.addKitPrefix)(options.instanceId);
638
662
  try {
639
663
  discoveredBuild = options.preDiscoveredBuild
640
- ? (0, utils_2.cloneDeep)(options.preDiscoveredBuild)
664
+ ? (0, utils_1.cloneDeep)(options.preDiscoveredBuild)
641
665
  : await discoverKitBuild(options, options.absSourcePath);
642
- build.applyPrefix(discoveredBuild, prefix);
666
+ build.applyEndpointPrefix(discoveredBuild, prefix);
643
667
  }
644
668
  catch (err) {
645
669
  logger_1.logger.debug(`Could not discover kit build for reporting: ${(0, error_1.getErrMsg)(err)}`);
@@ -687,7 +711,8 @@ async function printKitFirstDeployReport(options) {
687
711
  (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.")}`);
688
712
  }
689
713
  }
690
- async function addKitInstanceOrConfigureProject(options, existingKit, existingFunctionsInfo) {
714
+ async function addKitInstanceOrConfigureProject(options) {
715
+ const { existingKit, existingFunctionsInfo, createdPaths = [] } = options;
691
716
  const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
692
717
  const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
693
718
  ? options.project
@@ -735,6 +760,9 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
735
760
  if (action === "addInstance") {
736
761
  resultAction = "addedInstance";
737
762
  instanceId = await promptKitInstanceId(options.defaultInstanceId ?? existingKit.kit, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
763
+ const expectedConfigDirPath = path.join(exports.FUNCTION_KITS_DIR, existingKit.kit, `config-${instanceId}`);
764
+ absConfigDirPath = options.config.path(expectedConfigDirPath);
765
+ createdPaths.push(absConfigDirPath);
738
766
  const result = await addInstanceToKit({
739
767
  config: options.config,
740
768
  kitId: existingKit.kit,
@@ -756,6 +784,12 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
756
784
  throw new error_1.FirebaseError(`Configuration directory for instance '${instanceId}' not found in kit '${existingKit.kit}'.`);
757
785
  }
758
786
  absConfigDirPath = options.config.path(configDirPath);
787
+ if (projectId) {
788
+ const envPath = path.join(absConfigDirPath, `.env.${projectId}`);
789
+ if (!(await fs.pathExists(envPath))) {
790
+ createdPaths.push(envPath);
791
+ }
792
+ }
759
793
  if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
760
794
  await fs.ensureDir(absConfigDirPath);
761
795
  (0, env_2.seedKitInstanceEnv)({
@@ -793,7 +827,6 @@ async function addKitInstanceOrConfigureProject(options, existingKit, existingFu
793
827
  absSourcePath,
794
828
  instanceId,
795
829
  nonInteractive: options.nonInteractive,
796
- force: options.force,
797
830
  params: discoveredBuild.params,
798
831
  });
799
832
  }
@@ -897,80 +930,112 @@ async function installKitOrInstance(options) {
897
930
  if (options.directory && options.template) {
898
931
  throw new error_1.FirebaseError("Cannot specify --template with --directory.");
899
932
  }
900
- const existingFunctionsInfo = extractExistingFunctionsInfo(options.config.src.functions);
901
- const existingKit = findExistingKit(existingFunctionsInfo.existingFunctions, options);
902
- if (existingKit) {
903
- return addKitInstanceOrConfigureProject(options, existingKit, existingFunctionsInfo);
904
- }
905
- const source = options.directory
906
- ? await resolveDirectorySource(options)
907
- : await resolvePackageSource(options);
908
- const kitId = await promptKitId(source.defaultKitName, existingFunctionsInfo.existingKitIds, options.nonInteractive, options.kitId);
909
- const instanceId = await promptKitInstanceId(options.defaultInstanceId ?? kitId, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
910
- const { sourcePath, configDirPath, absSourcePath, absConfigDirPath } = await source.setup(kitId, instanceId);
911
- if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
912
- (0, env_2.seedKitInstanceEnv)({
913
- configDir: absConfigDirPath,
914
- functionsSource: absSourcePath,
915
- projectDir: options.config.projectDir,
916
- projectId: options.seedEnv.projectId,
917
- projectAlias: options.seedEnv.projectAlias,
918
- envs: options.seedEnv.envs,
919
- });
920
- }
921
- await source.buildAndInstall(absSourcePath);
922
- const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
923
- const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
924
- ? options.project
925
- : undefined;
926
- if (projectId) {
927
- fs.ensureFileSync(path.join(absConfigDirPath, `.env.${projectId}`));
928
- }
929
- let discoveredBuild;
930
- const shouldConfigure = options.configure !== false;
931
- if (shouldConfigure) {
932
- try {
933
- discoveredBuild = await discoverKitBuild({ ...options, instanceId }, absSourcePath);
933
+ const originalFunctions = (0, utils_1.cloneDeep)(options.config.src.functions);
934
+ const createdPaths = [];
935
+ let kitId;
936
+ try {
937
+ const existingFunctionsInfo = extractExistingFunctionsInfo(options.config.src.functions);
938
+ const existingKit = findExistingKit(existingFunctionsInfo.existingFunctions, options);
939
+ if (existingKit) {
940
+ kitId = existingKit.kit;
941
+ return await addKitInstanceOrConfigureProject({
942
+ ...options,
943
+ existingKit,
944
+ existingFunctionsInfo,
945
+ createdPaths,
946
+ });
934
947
  }
935
- catch (err) {
936
- logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
948
+ const source = options.directory
949
+ ? await resolveDirectorySource(options)
950
+ : await resolvePackageSource(options);
951
+ kitId = await promptKitId(source.defaultKitName, existingFunctionsInfo.existingKitIds, options.nonInteractive, options.kitId);
952
+ const instanceId = await promptKitInstanceId(options.defaultInstanceId ?? kitId, existingFunctionsInfo.existingInstanceIds, existingFunctionsInfo.existingCodebases, options.nonInteractive, options.instanceId);
953
+ const isPackageKit = !options.directory;
954
+ const absKitDir = options.config.path(path.join(exports.FUNCTION_KITS_DIR, kitId));
955
+ const expectedConfigDirPath = path.join(exports.FUNCTION_KITS_DIR, kitId, `config-${instanceId}`);
956
+ const absConfigDirPath = options.config.path(expectedConfigDirPath);
957
+ if (isPackageKit) {
958
+ createdPaths.push(absKitDir);
937
959
  }
938
- if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
939
- await promptAndWriteKitParams({
940
- config: options.config,
941
- projectId,
942
- projectAlias,
943
- absConfigDirPath,
944
- absSourcePath,
945
- instanceId,
946
- nonInteractive: options.nonInteractive,
947
- force: options.force,
948
- params: discoveredBuild.params,
960
+ else {
961
+ createdPaths.push(absConfigDirPath);
962
+ }
963
+ const setupResult = await source.setup(kitId, instanceId);
964
+ const { sourcePath, configDirPath, absSourcePath } = setupResult;
965
+ if (options.seedEnv?.envs && Object.keys(options.seedEnv.envs).length > 0) {
966
+ (0, env_2.seedKitInstanceEnv)({
967
+ configDir: setupResult.absConfigDirPath,
968
+ functionsSource: absSourcePath,
969
+ projectDir: options.config.projectDir,
970
+ projectId: options.seedEnv.projectId,
971
+ projectAlias: options.seedEnv.projectAlias,
972
+ envs: options.seedEnv.envs,
949
973
  });
950
974
  }
975
+ await source.buildAndInstall(absSourcePath);
976
+ const projectId = (0, projectUtils_1.getProjectId)(options) || options.projectId;
977
+ const projectAlias = options.rc?.hasProjects && options.project && options.rc.hasProjectAlias(options.project)
978
+ ? options.project
979
+ : undefined;
980
+ if (projectId) {
981
+ fs.ensureFileSync(path.join(setupResult.absConfigDirPath, `.env.${projectId}`));
982
+ }
983
+ let discoveredBuild;
984
+ const shouldConfigure = options.configure !== false;
985
+ if (shouldConfigure) {
986
+ try {
987
+ discoveredBuild = await discoverKitBuild({ ...options, instanceId }, absSourcePath);
988
+ }
989
+ catch (err) {
990
+ logger_1.logger.debug(`Could not discover kit build for params prompting: ${(0, error_1.getErrMsg)(err)}`);
991
+ }
992
+ if (discoveredBuild?.params && discoveredBuild.params.length > 0) {
993
+ await promptAndWriteKitParams({
994
+ config: options.config,
995
+ projectId,
996
+ projectAlias,
997
+ absConfigDirPath: setupResult.absConfigDirPath,
998
+ absSourcePath,
999
+ instanceId,
1000
+ nonInteractive: options.nonInteractive,
1001
+ params: discoveredBuild.params,
1002
+ });
1003
+ }
1004
+ }
1005
+ addKitToConfig(options.config, {
1006
+ kitId,
1007
+ instanceId,
1008
+ packageName: source.sourcePackageName,
1009
+ sourcePath,
1010
+ configDirPath,
1011
+ hasBuildScript: source.hasBuildScript,
1012
+ });
1013
+ (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
1014
+ await printKitFirstDeployReport({
1015
+ config: options.config,
1016
+ project: options.project,
1017
+ projectId: options.projectId,
1018
+ instanceId,
1019
+ absSourcePath,
1020
+ preDiscoveredBuild: discoveredBuild,
1021
+ });
1022
+ return {
1023
+ action: "installedKit",
1024
+ kitId,
1025
+ instanceId,
1026
+ sourcePath,
1027
+ configDirPath,
1028
+ };
1029
+ }
1030
+ catch (err) {
1031
+ await Promise.all(createdPaths.map((targetPath) => fs.remove(targetPath).catch((cleanupErr) => {
1032
+ logger_1.logger.debug(`Failed to clean up path '${targetPath}': ${(0, error_1.getErrMsg)(cleanupErr)}`);
1033
+ })));
1034
+ if (kitId) {
1035
+ await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(path.join(exports.FUNCTION_KITS_DIR, kitId)));
1036
+ }
1037
+ await (0, fsutils_1.removeDirectoryIfEmpty)(options.config.path(exports.FUNCTION_KITS_DIR));
1038
+ revertFunctionsConfig({ config: options.config, originalFunctions });
1039
+ throw err;
951
1040
  }
952
- addKitToConfig(options.config, {
953
- kitId,
954
- instanceId,
955
- packageName: source.sourcePackageName,
956
- sourcePath,
957
- configDirPath,
958
- hasBuildScript: source.hasBuildScript,
959
- });
960
- (0, utils_1.logLabeledSuccess)("functions", `Function kit ${clc.bold(kitId)} successfully installed.`);
961
- await printKitFirstDeployReport({
962
- config: options.config,
963
- project: options.project,
964
- projectId: options.projectId,
965
- instanceId,
966
- absSourcePath,
967
- preDiscoveredBuild: discoveredBuild,
968
- });
969
- return {
970
- action: "installedKit",
971
- kitId,
972
- instanceId,
973
- sourcePath,
974
- configDirPath,
975
- };
976
1041
  }