@strapi/cloud-cli 0.0.0-next.6785f47fadddb80404c824be0a0732c652850b45 → 0.0.0-next.6ed779c066310248c506ce3d2cdae97f59f700ef

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 (47) hide show
  1. package/dist/index.js +438 -109
  2. package/dist/index.js.map +1 -1
  3. package/dist/index.mjs +438 -108
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/src/cloud/command.d.ts +3 -0
  6. package/dist/src/cloud/command.d.ts.map +1 -0
  7. package/dist/src/create-project/action.d.ts.map +1 -1
  8. package/dist/src/create-project/command.d.ts.map +1 -1
  9. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  10. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  11. package/dist/src/deploy-project/action.d.ts.map +1 -1
  12. package/dist/src/deploy-project/command.d.ts.map +1 -1
  13. package/dist/src/environment/command.d.ts +3 -0
  14. package/dist/src/environment/command.d.ts.map +1 -0
  15. package/dist/src/environment/list/action.d.ts +4 -0
  16. package/dist/src/environment/list/action.d.ts.map +1 -0
  17. package/dist/src/environment/list/command.d.ts +4 -0
  18. package/dist/src/environment/list/command.d.ts.map +1 -0
  19. package/dist/src/environment/list/index.d.ts +7 -0
  20. package/dist/src/environment/list/index.d.ts.map +1 -0
  21. package/dist/src/index.d.ts +2 -0
  22. package/dist/src/index.d.ts.map +1 -1
  23. package/dist/src/link/action.d.ts +4 -0
  24. package/dist/src/link/action.d.ts.map +1 -0
  25. package/dist/src/link/command.d.ts +7 -0
  26. package/dist/src/link/command.d.ts.map +1 -0
  27. package/dist/src/link/index.d.ts +7 -0
  28. package/dist/src/link/index.d.ts.map +1 -0
  29. package/dist/src/login/action.d.ts.map +1 -1
  30. package/dist/src/login/command.d.ts.map +1 -1
  31. package/dist/src/logout/action.d.ts.map +1 -1
  32. package/dist/src/logout/command.d.ts.map +1 -1
  33. package/dist/src/services/build-logs.d.ts.map +1 -1
  34. package/dist/src/services/cli-api.d.ts +38 -6
  35. package/dist/src/services/cli-api.d.ts.map +1 -1
  36. package/dist/src/services/strapi-info-save.d.ts +1 -1
  37. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  38. package/dist/src/types.d.ts +5 -1
  39. package/dist/src/types.d.ts.map +1 -1
  40. package/dist/src/utils/analytics.d.ts +4 -0
  41. package/dist/src/utils/analytics.d.ts.map +1 -0
  42. package/dist/src/utils/pkg.d.ts.map +1 -1
  43. package/dist/src/utils/tests/compress-files.test.d.ts +2 -0
  44. package/dist/src/utils/tests/compress-files.test.d.ts.map +1 -0
  45. package/package.json +9 -9
  46. package/dist/src/create-project/utils/apply-default-name.d.ts +0 -7
  47. package/dist/src/create-project/utils/apply-default-name.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -20,8 +20,8 @@ import ora from "ora";
20
20
  import * as cliProgress from "cli-progress";
21
21
  import pkgUp from "pkg-up";
22
22
  import * as yup from "yup";
23
- import _ from "lodash";
24
23
  import EventSource from "eventsource";
24
+ import { createCommand } from "commander";
25
25
  const apiConfig = {
26
26
  apiBaseUrl: env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
27
27
  dashboardBaseUrl: env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -134,7 +134,7 @@ async function saveLocalConfig(data) {
134
134
  await fse__default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
135
135
  }
136
136
  const name = "@strapi/cloud-cli";
137
- const version = "4.25.3";
137
+ const version = "5.1.0";
138
138
  const description = "Commands to interact with the Strapi Cloud";
139
139
  const keywords = [
140
140
  "strapi",
@@ -179,14 +179,14 @@ const scripts = {
179
179
  watch: "pack-up watch"
180
180
  };
181
181
  const dependencies = {
182
- "@strapi/utils": "4.25.3",
183
- axios: "1.6.0",
182
+ "@strapi/utils": "workspace:*",
183
+ axios: "1.7.4",
184
184
  chalk: "4.1.2",
185
185
  "cli-progress": "3.12.0",
186
186
  commander: "8.3.0",
187
187
  eventsource: "2.0.2",
188
188
  "fast-safe-stringify": "2.1.1",
189
- "fs-extra": "10.0.0",
189
+ "fs-extra": "11.2.0",
190
190
  inquirer: "8.2.5",
191
191
  jsonwebtoken: "9.0.0",
192
192
  "jwks-rsa": "3.1.0",
@@ -195,7 +195,7 @@ const dependencies = {
195
195
  open: "8.4.0",
196
196
  ora: "5.4.1",
197
197
  "pkg-up": "3.1.0",
198
- tar: "6.1.13",
198
+ tar: "6.2.1",
199
199
  "xdg-app-paths": "8.3.0",
200
200
  yup: "0.32.9"
201
201
  };
@@ -204,11 +204,11 @@ const devDependencies = {
204
204
  "@types/cli-progress": "3.11.5",
205
205
  "@types/eventsource": "1.1.15",
206
206
  "@types/lodash": "^4.14.191",
207
- "eslint-config-custom": "4.25.3",
208
- tsconfig: "4.25.3"
207
+ "eslint-config-custom": "workspace:*",
208
+ tsconfig: "workspace:*"
209
209
  };
210
210
  const engines = {
211
- node: ">=18.0.0 <=20.x.x",
211
+ node: ">=18.0.0 <=22.x.x",
212
212
  npm: ">=6.0.0"
213
213
  };
214
214
  const packageJson = {
@@ -315,6 +315,48 @@ async function cloudApiFactory({ logger }, token) {
315
315
  throw error;
316
316
  }
317
317
  },
318
+ async listLinkProjects() {
319
+ try {
320
+ const response = await axiosCloudAPI.get("/projects-linkable");
321
+ if (response.status !== 200) {
322
+ throw new Error("Error fetching cloud projects from the server.");
323
+ }
324
+ return response;
325
+ } catch (error) {
326
+ logger.debug(
327
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
328
+ );
329
+ throw error;
330
+ }
331
+ },
332
+ async listEnvironments({ name: name2 }) {
333
+ try {
334
+ const response = await axiosCloudAPI.get(`/projects/${name2}/environments`);
335
+ if (response.status !== 200) {
336
+ throw new Error("Error fetching cloud environments from the server.");
337
+ }
338
+ return response;
339
+ } catch (error) {
340
+ logger.debug(
341
+ "🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again."
342
+ );
343
+ throw error;
344
+ }
345
+ },
346
+ async getProject({ name: name2 }) {
347
+ try {
348
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
349
+ if (response.status !== 200) {
350
+ throw new Error("Error fetching project's details.");
351
+ }
352
+ return response;
353
+ } catch (error) {
354
+ logger.debug(
355
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
356
+ );
357
+ throw error;
358
+ }
359
+ },
318
360
  track(event, payload = {}) {
319
361
  return axiosCloudAPI.post("/track", {
320
362
  event,
@@ -588,21 +630,24 @@ yup.object({
588
630
  name: yup.string().required(),
589
631
  exports: yup.lazy(
590
632
  (value) => yup.object(
591
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
592
- if (typeof value2 === "object") {
593
- acc[key] = yup.object({
594
- types: yup.string().optional(),
595
- source: yup.string().required(),
596
- module: yup.string().optional(),
597
- import: yup.string().required(),
598
- require: yup.string().required(),
599
- default: yup.string().required()
600
- }).noUnknown(true);
601
- } else {
602
- acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
603
- }
604
- return acc;
605
- }, {}) : void 0
633
+ typeof value === "object" ? Object.entries(value).reduce(
634
+ (acc, [key, value2]) => {
635
+ if (typeof value2 === "object") {
636
+ acc[key] = yup.object({
637
+ types: yup.string().optional(),
638
+ source: yup.string().required(),
639
+ module: yup.string().optional(),
640
+ import: yup.string().required(),
641
+ require: yup.string().required(),
642
+ default: yup.string().required()
643
+ }).noUnknown(true);
644
+ } else {
645
+ acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
646
+ }
647
+ return acc;
648
+ },
649
+ {}
650
+ ) : void 0
606
651
  ).optional()
607
652
  )
608
653
  });
@@ -624,18 +669,13 @@ async function getProjectNameFromPackageJson(ctx) {
624
669
  return "my-strapi-project";
625
670
  }
626
671
  }
627
- function applyDefaultName(newDefaultName, questions, defaultValues) {
628
- const newDefaultValues = _.cloneDeep(defaultValues);
629
- newDefaultValues.name = newDefaultName;
630
- const newQuestions = questions.map((question) => {
631
- const questionCopy = _.cloneDeep(question);
632
- if (questionCopy.name === "name") {
633
- questionCopy.default = newDefaultName;
634
- }
635
- return questionCopy;
636
- });
637
- return { newQuestions, newDefaultValues };
638
- }
672
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
673
+ try {
674
+ await cloudApiService.track(eventName, eventData);
675
+ } catch (e) {
676
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
677
+ }
678
+ };
639
679
  const openModule$1 = import("open");
640
680
  async function promptLogin(ctx) {
641
681
  const response = await inquirer.prompt([
@@ -656,13 +696,6 @@ async function loginAction(ctx) {
656
696
  const tokenService = await tokenServiceFactory(ctx);
657
697
  const existingToken = await tokenService.retrieveToken();
658
698
  const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
659
- const trackFailedLogin = async () => {
660
- try {
661
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
662
- } catch (e) {
663
- logger.debug("Failed to track failed login", e);
664
- }
665
- };
666
699
  if (existingToken) {
667
700
  const isTokenValid = await tokenService.isTokenValid(existingToken);
668
701
  if (isTokenValid) {
@@ -694,11 +727,7 @@ async function loginAction(ctx) {
694
727
  logger.debug(e);
695
728
  return false;
696
729
  }
697
- try {
698
- await cloudApiService.track("willLoginAttempt", {});
699
- } catch (e) {
700
- logger.debug("Failed to track login attempt", e);
701
- }
730
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
702
731
  logger.debug("🔐 Creating device authentication request...", {
703
732
  client_id: cliConfig2.clientId,
704
733
  scope: cliConfig2.scope,
@@ -778,13 +807,13 @@ async function loginAction(ctx) {
778
807
  "There seems to be a problem with your login information. Please try logging in again."
779
808
  );
780
809
  spinnerFail();
781
- await trackFailedLogin();
810
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
782
811
  return false;
783
812
  }
784
813
  if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
785
814
  logger.debug(e);
786
815
  spinnerFail();
787
- await trackFailedLogin();
816
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
788
817
  return false;
789
818
  }
790
819
  await new Promise((resolve) => {
@@ -798,15 +827,50 @@ async function loginAction(ctx) {
798
827
  "To access your dashboard, please copy and paste the following URL into your web browser:"
799
828
  );
800
829
  logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
801
- try {
802
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
803
- } catch (e) {
804
- logger.debug("Failed to track login", e);
805
- }
830
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
806
831
  };
807
832
  await authenticate();
808
833
  return isAuthenticated;
809
834
  }
835
+ function questionDefaultValuesMapper(questionsMap) {
836
+ return (questions) => {
837
+ return questions.map((question) => {
838
+ const questionName = question.name;
839
+ if (questionName in questionsMap) {
840
+ const questionDefault = questionsMap[questionName];
841
+ if (typeof questionDefault === "function") {
842
+ return {
843
+ ...question,
844
+ default: questionDefault(question)
845
+ };
846
+ }
847
+ return {
848
+ ...question,
849
+ default: questionDefault
850
+ };
851
+ }
852
+ return question;
853
+ });
854
+ };
855
+ }
856
+ function getDefaultsFromQuestions(questions) {
857
+ return questions.reduce((acc, question) => {
858
+ if (question.default && question.name) {
859
+ return { ...acc, [question.name]: question.default };
860
+ }
861
+ return acc;
862
+ }, {});
863
+ }
864
+ function getProjectNodeVersionDefault(question) {
865
+ const currentNodeVersion = process.versions.node.split(".")[0];
866
+ if (question.type === "list" && Array.isArray(question.choices)) {
867
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
868
+ if (choice) {
869
+ return choice.value;
870
+ }
871
+ }
872
+ return question.default;
873
+ }
810
874
  async function handleError(ctx, error) {
811
875
  const { logger } = ctx;
812
876
  logger.debug(error);
@@ -851,7 +915,7 @@ async function createProject$1(ctx, cloudApi, projectInput) {
851
915
  throw e;
852
916
  }
853
917
  }
854
- const action$3 = async (ctx) => {
918
+ const action$5 = async (ctx) => {
855
919
  const { logger } = ctx;
856
920
  const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
857
921
  const token = await getValidToken(ctx, promptLogin);
@@ -860,11 +924,16 @@ const action$3 = async (ctx) => {
860
924
  }
861
925
  const cloudApi = await cloudApiFactory(ctx, token);
862
926
  const { data: config } = await cloudApi.config();
863
- const { newQuestions: questions, newDefaultValues: defaultValues } = applyDefaultName(
864
- await getProjectNameFromPackageJson(ctx),
865
- config.projectCreation.questions,
866
- config.projectCreation.defaults
867
- );
927
+ const projectName = await getProjectNameFromPackageJson(ctx);
928
+ const defaultAnswersMapper = questionDefaultValuesMapper({
929
+ name: projectName,
930
+ nodeVersion: getProjectNodeVersionDefault
931
+ });
932
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
933
+ const defaultValues = {
934
+ ...config.projectCreation.defaults,
935
+ ...getDefaultsFromQuestions(questions)
936
+ };
868
937
  const projectAnswersDefaulted = defaults(defaultValues);
869
938
  const projectAnswers = await inquirer.prompt(questions);
870
939
  const projectInput = projectAnswersDefaulted(projectAnswers);
@@ -966,6 +1035,7 @@ const buildLogsServiceFactory = ({ logger }) => {
966
1035
  if (retries > MAX_RETRIES) {
967
1036
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
968
1037
  es.close();
1038
+ clearExistingTimeout();
969
1039
  reject(new Error("Max retries reached"));
970
1040
  }
971
1041
  };
@@ -1040,17 +1110,7 @@ async function upload(ctx, project, token, maxProjectFileSize) {
1040
1110
  return data.build_id;
1041
1111
  } catch (e) {
1042
1112
  progressBar.stop();
1043
- if (e instanceof AxiosError && e.response?.data) {
1044
- if (e.response.status === 404) {
1045
- ctx.logger.error(
1046
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
1047
- );
1048
- } else {
1049
- ctx.logger.error(e.response.data);
1050
- }
1051
- } else {
1052
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1053
- }
1113
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1054
1114
  ctx.logger.debug(e);
1055
1115
  } finally {
1056
1116
  await fse__default.remove(tarFilePath);
@@ -1062,11 +1122,11 @@ async function upload(ctx, project, token, maxProjectFileSize) {
1062
1122
  process.exit(1);
1063
1123
  }
1064
1124
  }
1065
- async function getProject(ctx) {
1125
+ async function getProject$1(ctx) {
1066
1126
  const { project } = await retrieve();
1067
1127
  if (!project) {
1068
1128
  try {
1069
- return await action$3(ctx);
1129
+ return await action$5(ctx);
1070
1130
  } catch (e) {
1071
1131
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1072
1132
  ctx.logger.debug(e);
@@ -1075,25 +1135,73 @@ async function getProject(ctx) {
1075
1135
  }
1076
1136
  return project;
1077
1137
  }
1078
- const action$2 = async (ctx) => {
1138
+ async function getConfig({
1139
+ ctx,
1140
+ cloudApiService
1141
+ }) {
1142
+ try {
1143
+ const { data: cliConfig2 } = await cloudApiService.config();
1144
+ return cliConfig2;
1145
+ } catch (e) {
1146
+ ctx.logger.debug("Failed to get cli config", e);
1147
+ return null;
1148
+ }
1149
+ }
1150
+ const action$4 = async (ctx) => {
1079
1151
  const { getValidToken } = await tokenServiceFactory(ctx);
1080
1152
  const token = await getValidToken(ctx, promptLogin);
1081
1153
  if (!token) {
1082
1154
  return;
1083
1155
  }
1084
- const project = await getProject(ctx);
1156
+ const project = await getProject$1(ctx);
1085
1157
  if (!project) {
1086
1158
  return;
1087
1159
  }
1088
- const cloudApiService = await cloudApiFactory(ctx);
1160
+ const cloudApiService = await cloudApiFactory(ctx, token);
1089
1161
  try {
1090
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1162
+ const {
1163
+ data: { data: projectData, metadata }
1164
+ } = await cloudApiService.getProject({ name: project.name });
1165
+ const isProjectSuspended = projectData.suspendedAt;
1166
+ if (isProjectSuspended) {
1167
+ ctx.logger.log(
1168
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1169
+ );
1170
+ ctx.logger.log(chalk.underline(`${metadata.dashboardUrls.project}`));
1171
+ return;
1172
+ }
1091
1173
  } catch (e) {
1092
- ctx.logger.debug("Failed to track willDeploy", e);
1174
+ if (e instanceof AxiosError && e.response?.data) {
1175
+ if (e.response.status === 404) {
1176
+ ctx.logger.warn(
1177
+ `The project associated with this folder does not exist in Strapi Cloud.
1178
+ Please link your local project to an existing Strapi Cloud project using the ${chalk.cyan(
1179
+ "link"
1180
+ )} command before deploying.`
1181
+ );
1182
+ } else {
1183
+ ctx.logger.error(e.response.data);
1184
+ }
1185
+ } else {
1186
+ ctx.logger.error(
1187
+ "An error occurred while retrieving the project's information. Please try again later."
1188
+ );
1189
+ }
1190
+ ctx.logger.debug(e);
1191
+ return;
1093
1192
  }
1193
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1194
+ projectInternalName: project.name
1195
+ });
1094
1196
  const notificationService = notificationServiceFactory(ctx);
1095
1197
  const buildLogsService = buildLogsServiceFactory(ctx);
1096
- const { data: cliConfig2 } = await cloudApiService.config();
1198
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1199
+ if (!cliConfig2) {
1200
+ ctx.logger.error(
1201
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1202
+ );
1203
+ return;
1204
+ }
1097
1205
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
1098
1206
  if (Number.isNaN(maxSize)) {
1099
1207
  ctx.logger.debug(
@@ -1115,10 +1223,11 @@ const action$2 = async (ctx) => {
1115
1223
  chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
1116
1224
  );
1117
1225
  } catch (e) {
1226
+ ctx.logger.debug(e);
1118
1227
  if (e instanceof Error) {
1119
1228
  ctx.logger.error(e.message);
1120
1229
  } else {
1121
- throw e;
1230
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
1122
1231
  }
1123
1232
  }
1124
1233
  };
@@ -1149,17 +1258,163 @@ const runAction = (name2, action2) => (...args) => {
1149
1258
  process.exit(1);
1150
1259
  });
1151
1260
  };
1152
- const command$4 = ({ command: command2, ctx }) => {
1153
- command2.command("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$2)(ctx));
1261
+ const command$6 = ({ ctx }) => {
1262
+ return createCommand("cloud:deploy").alias("deploy").description("Deploy a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("deploy", action$4)(ctx));
1154
1263
  };
1155
1264
  const deployProject = {
1156
1265
  name: "deploy-project",
1157
1266
  description: "Deploy a Strapi Cloud project",
1158
- action: action$2,
1159
- command: command$4
1267
+ action: action$4,
1268
+ command: command$6
1160
1269
  };
1161
- const command$3 = ({ command: command2, ctx }) => {
1162
- command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1270
+ const QUIT_OPTION = "Quit";
1271
+ async function getExistingConfig(ctx) {
1272
+ try {
1273
+ return await retrieve();
1274
+ } catch (e) {
1275
+ ctx.logger.debug("Failed to get project config", e);
1276
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1277
+ return null;
1278
+ }
1279
+ }
1280
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1281
+ if (existingConfig && existingConfig.project) {
1282
+ const { shouldRelink } = await inquirer.prompt([
1283
+ {
1284
+ type: "confirm",
1285
+ name: "shouldRelink",
1286
+ message: `A project named ${chalk.cyan(
1287
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1288
+ )} is already linked to this local folder. Do you want to update the link?`,
1289
+ default: false
1290
+ }
1291
+ ]);
1292
+ if (!shouldRelink) {
1293
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1294
+ currentProjectName: existingConfig.project?.name
1295
+ });
1296
+ return false;
1297
+ }
1298
+ }
1299
+ return true;
1300
+ }
1301
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1302
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1303
+ try {
1304
+ const {
1305
+ data: { data: projectList }
1306
+ } = await cloudApiService.listLinkProjects();
1307
+ spinner.succeed();
1308
+ if (!Array.isArray(projectList)) {
1309
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1310
+ return null;
1311
+ }
1312
+ const projects = projectList.filter(
1313
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1314
+ ).map((project) => {
1315
+ return {
1316
+ name: project.displayName,
1317
+ value: { name: project.name, displayName: project.displayName }
1318
+ };
1319
+ });
1320
+ if (projects.length === 0) {
1321
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1322
+ return null;
1323
+ }
1324
+ return projects;
1325
+ } catch (e) {
1326
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1327
+ ctx.logger.debug("Failed to list projects", e);
1328
+ return null;
1329
+ }
1330
+ }
1331
+ async function getUserSelection(ctx, projects) {
1332
+ const { logger } = ctx;
1333
+ try {
1334
+ const answer = await inquirer.prompt([
1335
+ {
1336
+ type: "list",
1337
+ name: "linkProject",
1338
+ message: "Which project do you want to link?",
1339
+ choices: [...projects, { name: chalk.grey(`(${QUIT_OPTION})`), value: null }]
1340
+ }
1341
+ ]);
1342
+ if (!answer.linkProject) {
1343
+ return null;
1344
+ }
1345
+ return answer;
1346
+ } catch (e) {
1347
+ logger.debug("Failed to get user input", e);
1348
+ logger.error("An error occurred while trying to get your input.");
1349
+ return null;
1350
+ }
1351
+ }
1352
+ const action$3 = async (ctx) => {
1353
+ const { getValidToken } = await tokenServiceFactory(ctx);
1354
+ const token = await getValidToken(ctx, promptLogin);
1355
+ const { logger } = ctx;
1356
+ if (!token) {
1357
+ return;
1358
+ }
1359
+ const cloudApiService = await cloudApiFactory(ctx, token);
1360
+ const existingConfig = await getExistingConfig(ctx);
1361
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1362
+ if (!shouldRelink) {
1363
+ return;
1364
+ }
1365
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1366
+ const projects = await getProjectsList(
1367
+ ctx,
1368
+ cloudApiService,
1369
+ existingConfig
1370
+ );
1371
+ if (!projects) {
1372
+ return;
1373
+ }
1374
+ const answer = await getUserSelection(ctx, projects);
1375
+ if (!answer) {
1376
+ return;
1377
+ }
1378
+ try {
1379
+ const { confirmAction } = await inquirer.prompt([
1380
+ {
1381
+ type: "confirm",
1382
+ name: "confirmAction",
1383
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1384
+ default: false
1385
+ }
1386
+ ]);
1387
+ if (!confirmAction) {
1388
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1389
+ cancelledProjectName: answer.linkProject.name,
1390
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1391
+ });
1392
+ return;
1393
+ }
1394
+ await save({ project: answer.linkProject });
1395
+ logger.log(`Project ${chalk.cyan(answer.linkProject.displayName)} linked successfully.`);
1396
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1397
+ projectInternalName: answer.linkProject
1398
+ });
1399
+ } catch (e) {
1400
+ logger.debug("Failed to link project", e);
1401
+ logger.error("An error occurred while linking the project.");
1402
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1403
+ projectInternalName: answer.linkProject
1404
+ });
1405
+ }
1406
+ };
1407
+ const command$5 = ({ command: command2, ctx }) => {
1408
+ command2.command("cloud:link").alias("link").description("Link a local directory to a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("link", action$3)(ctx));
1409
+ };
1410
+ const link = {
1411
+ name: "link-project",
1412
+ description: "Link a local directory to a Strapi Cloud project",
1413
+ action: action$3,
1414
+ command: command$5
1415
+ };
1416
+ const command$4 = ({ ctx }) => {
1417
+ return createCommand("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1163
1418
  "after",
1164
1419
  "\nAfter running this command, you will be prompted to enter your authentication information."
1165
1420
  ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
@@ -1168,10 +1423,10 @@ const login = {
1168
1423
  name: "login",
1169
1424
  description: "Strapi Cloud Login",
1170
1425
  action: loginAction,
1171
- command: command$3
1426
+ command: command$4
1172
1427
  };
1173
1428
  const openModule = import("open");
1174
- const action$1 = async (ctx) => {
1429
+ const action$2 = async (ctx) => {
1175
1430
  const { logger } = ctx;
1176
1431
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1177
1432
  const token = await retrieveToken();
@@ -1201,31 +1456,27 @@ const action$1 = async (ctx) => {
1201
1456
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1202
1457
  logger.debug(e);
1203
1458
  }
1204
- try {
1205
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1206
- } catch (e) {
1207
- logger.debug("Failed to track logout event", e);
1208
- }
1459
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1209
1460
  };
1210
- const command$2 = ({ command: command2, ctx }) => {
1211
- command2.command("cloud:logout").alias("logout").description("Strapi Cloud Logout").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("logout", action$1)(ctx));
1461
+ const command$3 = ({ ctx }) => {
1462
+ return createCommand("cloud:logout").alias("logout").description("Strapi Cloud Logout").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("logout", action$2)(ctx));
1212
1463
  };
1213
1464
  const logout = {
1214
1465
  name: "logout",
1215
1466
  description: "Strapi Cloud Logout",
1216
- action: action$1,
1217
- command: command$2
1467
+ action: action$2,
1468
+ command: command$3
1218
1469
  };
1219
- const command$1 = ({ command: command2, ctx }) => {
1220
- command2.command("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$3)(ctx));
1470
+ const command$2 = ({ ctx }) => {
1471
+ return createCommand("cloud:create-project").description("Create a Strapi Cloud project").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("cloud:create-project", action$5)(ctx));
1221
1472
  };
1222
1473
  const createProject = {
1223
1474
  name: "create-project",
1224
1475
  description: "Create a new project",
1225
- action: action$3,
1226
- command: command$1
1476
+ action: action$5,
1477
+ command: command$2
1227
1478
  };
1228
- const action = async (ctx) => {
1479
+ const action$1 = async (ctx) => {
1229
1480
  const { getValidToken } = await tokenServiceFactory(ctx);
1230
1481
  const token = await getValidToken(ctx, promptLogin);
1231
1482
  const { logger } = ctx;
@@ -1245,23 +1496,99 @@ const action = async (ctx) => {
1245
1496
  spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1246
1497
  }
1247
1498
  };
1248
- const command = ({ command: command2, ctx }) => {
1249
- command2.command("cloud:projects").alias("projects").description("List Strapi Cloud projects").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("listProjects", action)(ctx));
1499
+ const command$1 = ({ command: command2, ctx }) => {
1500
+ command2.command("cloud:projects").alias("projects").description("List Strapi Cloud projects").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("projects", action$1)(ctx));
1250
1501
  };
1251
1502
  const listProjects = {
1252
1503
  name: "list-projects",
1253
1504
  description: "List Strapi Cloud projects",
1505
+ action: action$1,
1506
+ command: command$1
1507
+ };
1508
+ async function getProject(ctx) {
1509
+ const { project } = await retrieve();
1510
+ if (!project) {
1511
+ ctx.logger.warn(
1512
+ `
1513
+ We couldn't find a valid local project config.
1514
+ Please link your local project to an existing Strapi Cloud project using the ${chalk.cyan(
1515
+ "link"
1516
+ )} command`
1517
+ );
1518
+ process.exit(1);
1519
+ }
1520
+ return project;
1521
+ }
1522
+ const action = async (ctx) => {
1523
+ const { getValidToken } = await tokenServiceFactory(ctx);
1524
+ const token = await getValidToken(ctx, promptLogin);
1525
+ const { logger } = ctx;
1526
+ if (!token) {
1527
+ return;
1528
+ }
1529
+ const project = await getProject(ctx);
1530
+ if (!project) {
1531
+ ctx.logger.debug(`No valid local project configuration was found.`);
1532
+ return;
1533
+ }
1534
+ const cloudApiService = await cloudApiFactory(ctx, token);
1535
+ const spinner = logger.spinner("Fetching environments...").start();
1536
+ await trackEvent(ctx, cloudApiService, "willListEnvironment", {
1537
+ projectInternalName: project.name
1538
+ });
1539
+ try {
1540
+ const {
1541
+ data: { data: environmentsList }
1542
+ } = await cloudApiService.listEnvironments({ name: project.name });
1543
+ spinner.succeed();
1544
+ logger.log(environmentsList);
1545
+ await trackEvent(ctx, cloudApiService, "didListEnvironment", {
1546
+ projectInternalName: project.name
1547
+ });
1548
+ } catch (e) {
1549
+ if (e.response && e.response.status === 404) {
1550
+ spinner.succeed();
1551
+ logger.warn(
1552
+ `
1553
+ The project associated with this folder does not exist in Strapi Cloud.
1554
+ Please link your local project to an existing Strapi Cloud project using the ${chalk.cyan(
1555
+ "link"
1556
+ )} command`
1557
+ );
1558
+ } else {
1559
+ spinner.fail("An error occurred while fetching environments data from Strapi Cloud.");
1560
+ logger.debug("Failed to list environments", e);
1561
+ }
1562
+ await trackEvent(ctx, cloudApiService, "didNotListEnvironment", {
1563
+ projectInternalName: project.name
1564
+ });
1565
+ }
1566
+ };
1567
+ function defineCloudNamespace(command2) {
1568
+ return command2.command("cloud").description("Manage Strapi Cloud projects");
1569
+ }
1570
+ const command = ({ command: command2, ctx }) => {
1571
+ const cloud = defineCloudNamespace(command2);
1572
+ cloud.command("environments").description("Alias for cloud environment list").action(() => runAction("list", action)(ctx));
1573
+ const environment = cloud.command("environment").description("Manage environments for a Strapi Cloud project");
1574
+ environment.command("list").description("List Strapi Cloud project environments").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("list", action)(ctx));
1575
+ };
1576
+ const listEnvironments = {
1577
+ name: "list-environments",
1578
+ description: "List Strapi Cloud environments",
1254
1579
  action,
1255
1580
  command
1256
1581
  };
1257
1582
  const cli = {
1258
1583
  deployProject,
1584
+ link,
1259
1585
  login,
1260
1586
  logout,
1261
1587
  createProject,
1262
- listProjects
1588
+ listProjects,
1589
+ listEnvironments
1263
1590
  };
1264
- const cloudCommands = [deployProject, login, logout, listProjects];
1591
+ const cloudCommands = [deployProject, link, login, logout, listProjects, listEnvironments];
1265
1592
  async function initCloudCLIConfig() {
1266
1593
  const localConfig = await getLocalConfig();
1267
1594
  if (!localConfig.deviceId) {
@@ -1277,7 +1604,10 @@ async function buildStrapiCloudCommands({
1277
1604
  await initCloudCLIConfig();
1278
1605
  for (const cloudCommand of cloudCommands) {
1279
1606
  try {
1280
- await cloudCommand.command({ command: command2, ctx, argv });
1607
+ const subCommand = await cloudCommand.command({ command: command2, ctx, argv });
1608
+ if (subCommand) {
1609
+ command2.addCommand(subCommand);
1610
+ }
1281
1611
  } catch (e) {
1282
1612
  console.error(`Failed to load command ${cloudCommand.name}`, e);
1283
1613
  }