@strapi/cloud-cli 0.0.0-next.af9f5eed766381838931b23118affc1c765c5d88 → 0.0.0-next.aff9d09e4edf4d38b8a0de5abf83d79bedb28313

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 (44) hide show
  1. package/dist/index.js +761 -434
  2. package/dist/index.js.map +1 -1
  3. package/dist/index.mjs +763 -433
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/src/create-project/action.d.ts +1 -1
  6. package/dist/src/create-project/action.d.ts.map +1 -1
  7. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  8. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  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/index.d.ts +2 -0
  13. package/dist/src/index.d.ts.map +1 -1
  14. package/dist/src/link/action.d.ts +4 -0
  15. package/dist/src/link/action.d.ts.map +1 -0
  16. package/dist/src/link/command.d.ts +7 -0
  17. package/dist/src/link/command.d.ts.map +1 -0
  18. package/dist/src/link/index.d.ts +7 -0
  19. package/dist/src/link/index.d.ts.map +1 -0
  20. package/dist/src/list-projects/action.d.ts +4 -0
  21. package/dist/src/list-projects/action.d.ts.map +1 -0
  22. package/dist/src/list-projects/command.d.ts +7 -0
  23. package/dist/src/list-projects/command.d.ts.map +1 -0
  24. package/dist/src/list-projects/index.d.ts +7 -0
  25. package/dist/src/list-projects/index.d.ts.map +1 -0
  26. package/dist/src/login/action.d.ts +2 -2
  27. package/dist/src/login/action.d.ts.map +1 -1
  28. package/dist/src/logout/action.d.ts.map +1 -1
  29. package/dist/src/services/build-logs.d.ts.map +1 -1
  30. package/dist/src/services/cli-api.d.ts +35 -7
  31. package/dist/src/services/cli-api.d.ts.map +1 -1
  32. package/dist/src/services/strapi-info-save.d.ts +1 -1
  33. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  34. package/dist/src/services/token.d.ts +1 -1
  35. package/dist/src/services/token.d.ts.map +1 -1
  36. package/dist/src/types.d.ts +1 -0
  37. package/dist/src/types.d.ts.map +1 -1
  38. package/dist/src/utils/analytics.d.ts +4 -0
  39. package/dist/src/utils/analytics.d.ts.map +1 -0
  40. package/dist/src/utils/compress-files.d.ts.map +1 -1
  41. package/dist/src/utils/pkg.d.ts.map +1 -1
  42. package/package.json +6 -5
  43. package/dist/src/utils/tests/compress-files.test.d.ts +0 -2
  44. package/dist/src/utils/tests/compress-files.test.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -29,7 +29,6 @@ const chalk = require("chalk");
29
29
  const axios = require("axios");
30
30
  const crypto = require("node:crypto");
31
31
  const utils = require("@strapi/utils");
32
- const fs = require("fs");
33
32
  const tar = require("tar");
34
33
  const minimatch = require("minimatch");
35
34
  const inquirer = require("inquirer");
@@ -41,10 +40,9 @@ const jwt = require("jsonwebtoken");
41
40
  const stringify = require("fast-safe-stringify");
42
41
  const ora = require("ora");
43
42
  const cliProgress = require("cli-progress");
44
- const EventSource = require("eventsource");
45
- const fs$1 = require("fs/promises");
46
43
  const pkgUp = require("pkg-up");
47
44
  const yup = require("yup");
45
+ const EventSource = require("eventsource");
48
46
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
47
  function _interopNamespace(e) {
50
48
  if (e && e.__esModule)
@@ -65,12 +63,11 @@ function _interopNamespace(e) {
65
63
  return Object.freeze(n);
66
64
  }
67
65
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto$1);
68
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
66
+ const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
69
67
  const path__namespace = /* @__PURE__ */ _interopNamespace(path);
70
68
  const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
71
69
  const axios__default = /* @__PURE__ */ _interopDefault(axios);
72
70
  const crypto__namespace = /* @__PURE__ */ _interopNamespace(crypto);
73
- const fs__namespace = /* @__PURE__ */ _interopNamespace(fs);
74
71
  const tar__namespace = /* @__PURE__ */ _interopNamespace(tar);
75
72
  const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
76
73
  const os__default = /* @__PURE__ */ _interopDefault(os);
@@ -80,10 +77,9 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
77
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
78
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
79
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
- const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
80
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
81
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
82
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
83
  const apiConfig = {
88
84
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
85
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -102,23 +98,6 @@ const IGNORED_PATTERNS = [
102
98
  "**/.idea/**",
103
99
  "**/.vscode/**"
104
100
  ];
105
- const getFiles = (dirPath, ignorePatterns = [], arrayOfFiles = [], subfolder = "") => {
106
- const entries = fs__namespace.readdirSync(path__namespace.join(dirPath, subfolder));
107
- entries.forEach((entry) => {
108
- const entryPathFromRoot = path__namespace.join(subfolder, entry);
109
- const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
110
- const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
111
- if (isIgnored) {
112
- return;
113
- }
114
- if (fs__namespace.statSync(entryPath).isDirectory()) {
115
- getFiles(dirPath, ignorePatterns, arrayOfFiles, entryPathFromRoot);
116
- } else {
117
- arrayOfFiles.push(entryPath);
118
- }
119
- });
120
- return arrayOfFiles;
121
- };
122
101
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
123
102
  ignorePatterns.push(...IGNORED_PATTERNS);
124
103
  const relativeFilePath = path__namespace.join(folderPath, file);
@@ -136,16 +115,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
136
115
  }
137
116
  return isIgnored;
138
117
  };
139
- const readGitignore = (folderPath) => {
118
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
119
+ const arrayOfFiles = [];
120
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
121
+ for (const entry of entries) {
122
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
123
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
124
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
125
+ if (!isIgnored) {
126
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
127
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
128
+ arrayOfFiles.push(...subFiles);
129
+ } else {
130
+ arrayOfFiles.push(entryPath);
131
+ }
132
+ }
133
+ }
134
+ return arrayOfFiles;
135
+ };
136
+ const readGitignore = async (folderPath) => {
140
137
  const gitignorePath = path__namespace.resolve(folderPath, ".gitignore");
141
- if (!fs__namespace.existsSync(gitignorePath))
138
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
139
+ if (!pathExist)
142
140
  return [];
143
- const gitignoreContent = fs__namespace.readFileSync(gitignorePath, "utf8");
141
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, "utf8");
144
142
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
145
143
  };
146
144
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
147
- const ignorePatterns = readGitignore(folderToCompress);
148
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
145
+ const ignorePatterns = await readGitignore(folderToCompress);
146
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
149
147
  return tar__namespace.c(
150
148
  {
151
149
  gzip: true,
@@ -158,7 +156,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
158
156
  const CONFIG_FILENAME = "config.json";
159
157
  async function checkDirectoryExists(directoryPath) {
160
158
  try {
161
- const fsStat = await fse__default.default.lstat(directoryPath);
159
+ const fsStat = await fse__namespace.default.lstat(directoryPath);
162
160
  return fsStat.isDirectory();
163
161
  } catch (e) {
164
162
  return false;
@@ -166,14 +164,14 @@ async function checkDirectoryExists(directoryPath) {
166
164
  }
167
165
  async function getTmpStoragePath() {
168
166
  const storagePath = path__namespace.default.join(os__default.default.tmpdir(), APP_FOLDER_NAME);
169
- await fse__default.default.ensureDir(storagePath);
167
+ await fse__namespace.default.ensureDir(storagePath);
170
168
  return storagePath;
171
169
  }
172
170
  async function getConfigPath() {
173
171
  const configDirs = XDGAppPaths__default.default(APP_FOLDER_NAME).configDirs();
174
172
  const configPath = configDirs.find(checkDirectoryExists);
175
173
  if (!configPath) {
176
- await fse__default.default.ensureDir(configDirs[0]);
174
+ await fse__namespace.default.ensureDir(configDirs[0]);
177
175
  return configDirs[0];
178
176
  }
179
177
  return configPath;
@@ -181,9 +179,9 @@ async function getConfigPath() {
181
179
  async function getLocalConfig() {
182
180
  const configPath = await getConfigPath();
183
181
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
184
- await fse__default.default.ensureFile(configFilePath);
182
+ await fse__namespace.default.ensureFile(configFilePath);
185
183
  try {
186
- return await fse__default.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
184
+ return await fse__namespace.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
187
185
  } catch (e) {
188
186
  return {};
189
187
  }
@@ -191,10 +189,10 @@ async function getLocalConfig() {
191
189
  async function saveLocalConfig(data) {
192
190
  const configPath = await getConfigPath();
193
191
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
194
- await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
192
+ await fse__namespace.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
193
  }
196
194
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.1";
195
+ const version = "4.25.8";
198
196
  const description = "Commands to interact with the Strapi Cloud";
199
197
  const keywords = [
200
198
  "strapi",
@@ -235,10 +233,11 @@ const scripts = {
235
233
  build: "pack-up build",
236
234
  clean: "run -T rimraf ./dist",
237
235
  lint: "run -T eslint .",
236
+ "test:unit": "run -T jest",
238
237
  watch: "pack-up watch"
239
238
  };
240
239
  const dependencies = {
241
- "@strapi/utils": "4.25.1",
240
+ "@strapi/utils": "4.25.8",
242
241
  axios: "1.6.0",
243
242
  chalk: "4.1.2",
244
243
  "cli-progress": "3.12.0",
@@ -263,8 +262,8 @@ const devDependencies = {
263
262
  "@types/cli-progress": "3.11.5",
264
263
  "@types/eventsource": "1.1.15",
265
264
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.1",
267
- tsconfig: "4.25.1"
265
+ "eslint-config-custom": "4.25.8",
266
+ tsconfig: "4.25.8"
268
267
  };
269
268
  const engines = {
270
269
  node: ">=18.0.0 <=20.x.x",
@@ -317,7 +316,7 @@ async function cloudApiFactory({ logger }, token) {
317
316
  deploy({ filePath, project }, { onUploadProgress }) {
318
317
  return axiosCloudAPI.post(
319
318
  `/deploy/${project.name}`,
320
- { file: fse__default.default.createReadStream(filePath) },
319
+ { file: fse__namespace.default.createReadStream(filePath) },
321
320
  {
322
321
  headers: {
323
322
  "Content-Type": "multipart/form-data"
@@ -360,8 +359,47 @@ async function cloudApiFactory({ logger }, token) {
360
359
  throw error;
361
360
  }
362
361
  },
363
- listProjects() {
364
- return axiosCloudAPI.get("/projects");
362
+ async listProjects() {
363
+ try {
364
+ const response = await axiosCloudAPI.get("/projects");
365
+ if (response.status !== 200) {
366
+ throw new Error("Error fetching cloud projects from the server.");
367
+ }
368
+ return response;
369
+ } catch (error) {
370
+ logger.debug(
371
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
372
+ );
373
+ throw error;
374
+ }
375
+ },
376
+ async listLinkProjects() {
377
+ try {
378
+ const response = await axiosCloudAPI.get("/projects/linkable");
379
+ if (response.status !== 200) {
380
+ throw new Error("Error fetching cloud projects from the server.");
381
+ }
382
+ return response;
383
+ } catch (error) {
384
+ logger.debug(
385
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
386
+ );
387
+ throw error;
388
+ }
389
+ },
390
+ async getProject({ name: name2 }) {
391
+ try {
392
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
393
+ if (response.status !== 200) {
394
+ throw new Error("Error fetching project's details.");
395
+ }
396
+ return response;
397
+ } catch (error) {
398
+ logger.debug(
399
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
400
+ );
401
+ throw error;
402
+ }
365
403
  },
366
404
  track(event, payload = {}) {
367
405
  return axiosCloudAPI.post("/track", {
@@ -376,18 +414,18 @@ async function save(data, { directoryPath } = {}) {
376
414
  const alreadyInFileData = await retrieve({ directoryPath });
377
415
  const storedData = { ...alreadyInFileData, ...data };
378
416
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
379
- await fse__default.default.ensureDir(path__namespace.default.dirname(pathToFile));
380
- await fse__default.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
417
+ await fse__namespace.default.ensureDir(path__namespace.default.dirname(pathToFile));
418
+ await fse__namespace.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
381
419
  }
382
420
  async function retrieve({
383
421
  directoryPath
384
422
  } = {}) {
385
423
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
386
- const pathExists = await fse__default.default.pathExists(pathToFile);
424
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
387
425
  if (!pathExists) {
388
426
  return {};
389
427
  }
390
- return fse__default.default.readJSON(pathToFile, { encoding: "utf8" });
428
+ return fse__namespace.default.readJSON(pathToFile, { encoding: "utf8" });
391
429
  }
392
430
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
393
431
  __proto__: null,
@@ -446,14 +484,17 @@ async function tokenServiceFactory({ logger }) {
446
484
  "There seems to be a problem with your login information. Please try logging in again."
447
485
  );
448
486
  }
487
+ return Promise.reject(new Error("Invalid token"));
449
488
  }
450
489
  return new Promise((resolve, reject) => {
451
490
  jwt__default.default.verify(idToken, getKey, (err) => {
452
491
  if (err) {
453
492
  reject(err);
454
- } else {
455
- resolve();
456
493
  }
494
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
495
+ reject(new Error("Token is expired"));
496
+ }
497
+ resolve();
457
498
  });
458
499
  });
459
500
  }
@@ -487,15 +528,15 @@ async function tokenServiceFactory({ logger }) {
487
528
  throw e;
488
529
  }
489
530
  }
490
- async function getValidToken() {
491
- const token = await retrieveToken();
492
- if (!token) {
493
- logger.log("No token found. Please login first.");
494
- return null;
495
- }
496
- if (!await isTokenValid(token)) {
497
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
498
- return null;
531
+ async function getValidToken(ctx, loginAction2) {
532
+ let token = await retrieveToken();
533
+ while (!token || !await isTokenValid(token)) {
534
+ logger.log(
535
+ token ? "Oops! Your token seems expired or invalid. Please login again." : "We couldn't find a valid token. You need to be logged in to use this feature."
536
+ );
537
+ if (!await loginAction2(ctx))
538
+ return null;
539
+ token = await retrieveToken();
499
540
  }
500
541
  return token;
501
542
  }
@@ -629,97 +670,6 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
629
670
  local: strapiInfoSave,
630
671
  tokenServiceFactory
631
672
  }, Symbol.toStringTag, { value: "Module" }));
632
- async function handleError(ctx, error) {
633
- const tokenService = await tokenServiceFactory(ctx);
634
- const { logger } = ctx;
635
- logger.debug(error);
636
- if (error instanceof axios.AxiosError) {
637
- const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
638
- switch (error.response?.status) {
639
- case 401:
640
- logger.error("Your session has expired. Please log in again.");
641
- await tokenService.eraseToken();
642
- return;
643
- case 403:
644
- logger.error(
645
- errorMessage || "You do not have permission to create a project. Please contact support for assistance."
646
- );
647
- return;
648
- case 400:
649
- logger.error(errorMessage || "Invalid input. Please check your inputs and try again.");
650
- return;
651
- case 503:
652
- logger.error(
653
- "Strapi Cloud project creation is currently unavailable. Please try again later."
654
- );
655
- return;
656
- default:
657
- if (errorMessage) {
658
- logger.error(errorMessage);
659
- return;
660
- }
661
- break;
662
- }
663
- }
664
- logger.error(
665
- "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
666
- );
667
- }
668
- const action$3 = async (ctx) => {
669
- const { logger } = ctx;
670
- const { getValidToken } = await tokenServiceFactory(ctx);
671
- const token = await getValidToken();
672
- if (!token) {
673
- return;
674
- }
675
- const cloudApi = await cloudApiFactory(ctx, token);
676
- const { data: config } = await cloudApi.config();
677
- const { questions, defaults: defaultValues } = config.projectCreation;
678
- const projectAnswersDefaulted = fp.defaults(defaultValues);
679
- const projectAnswers = await inquirer__default.default.prompt(questions);
680
- const projectInput = projectAnswersDefaulted(projectAnswers);
681
- const spinner = logger.spinner("Setting up your project...").start();
682
- try {
683
- const { data } = await cloudApi.createProject(projectInput);
684
- await save({ project: data });
685
- spinner.succeed("Project created successfully!");
686
- return data;
687
- } catch (e) {
688
- spinner.fail("Failed to create project on Strapi Cloud.");
689
- await handleError(ctx, e);
690
- }
691
- };
692
- function notificationServiceFactory({ logger }) {
693
- return (url, token, cliConfig2) => {
694
- const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
695
- const es = new EventSource__default.default(url, {
696
- headers: {
697
- Authorization: `Bearer ${token}`
698
- }
699
- });
700
- let timeoutId;
701
- const resetTimeout = () => {
702
- clearTimeout(timeoutId);
703
- timeoutId = setTimeout(() => {
704
- logger.log(
705
- "We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment."
706
- );
707
- es.close();
708
- }, CONN_TIMEOUT);
709
- };
710
- es.onopen = resetTimeout;
711
- es.onmessage = (event) => {
712
- resetTimeout();
713
- const data = JSON.parse(event.data);
714
- if (data.message) {
715
- logger.log(data.message);
716
- }
717
- if (data.event === "deploymentFinished" || data.event === "deploymentFailed") {
718
- es.close();
719
- }
720
- };
721
- };
722
- }
723
673
  yup__namespace.object({
724
674
  name: yup__namespace.string().required(),
725
675
  exports: yup__namespace.lazy(
@@ -747,113 +697,435 @@ const loadPkg = async ({ cwd, logger }) => {
747
697
  if (!pkgPath) {
748
698
  throw new Error("Could not find a package.json in the current directory");
749
699
  }
750
- const buffer = await fs__default.default.readFile(pkgPath);
700
+ const buffer = await fse__namespace.readFile(pkgPath);
751
701
  const pkg = JSON.parse(buffer.toString());
752
702
  logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
753
703
  return pkg;
754
704
  };
755
- const buildLogsServiceFactory = ({ logger }) => {
756
- return async (url, token, cliConfig2) => {
757
- const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
758
- const MAX_RETRIES = Number(cliConfig2.buildLogsMaxRetries);
759
- return new Promise((resolve, reject) => {
760
- let timeoutId = null;
761
- let retries = 0;
762
- const connect = (url2) => {
763
- const spinner = logger.spinner("Connecting to server to get build logs");
764
- spinner.start();
765
- const es = new EventSource__default.default(`${url2}`, {
766
- headers: {
767
- Authorization: `Bearer ${token}`
768
- }
769
- });
770
- const clearExistingTimeout = () => {
771
- if (timeoutId) {
772
- clearTimeout(timeoutId);
773
- }
774
- };
775
- const resetTimeout = () => {
776
- clearExistingTimeout();
777
- timeoutId = setTimeout(() => {
778
- if (spinner.isSpinning) {
779
- spinner.fail(
780
- "We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue."
781
- );
782
- }
783
- es.close();
784
- reject(new Error("Connection timed out"));
785
- }, CONN_TIMEOUT);
786
- };
787
- es.onopen = resetTimeout;
788
- es.addEventListener("finished", (event) => {
789
- const data = JSON.parse(event.data);
790
- logger.log(data.msg);
791
- es.close();
792
- clearExistingTimeout();
793
- resolve(null);
794
- });
795
- es.addEventListener("log", (event) => {
796
- if (spinner.isSpinning) {
797
- spinner.succeed();
798
- }
799
- resetTimeout();
800
- const data = JSON.parse(event.data);
801
- logger.log(data.msg);
802
- });
803
- es.onerror = async () => {
804
- retries += 1;
805
- if (retries > MAX_RETRIES) {
806
- spinner.fail("We were unable to connect to the server to get build logs at this time.");
807
- es.close();
808
- reject(new Error("Max retries reached"));
809
- }
810
- };
811
- };
812
- connect(url);
813
- });
814
- };
815
- };
816
- async function upload(ctx, project, token, maxProjectFileSize) {
817
- const cloudApi = await cloudApiFactory(ctx, token);
705
+ async function getProjectNameFromPackageJson(ctx) {
818
706
  try {
819
- const storagePath = await getTmpStoragePath();
820
- const projectFolder = path__namespace.default.resolve(process.cwd());
821
707
  const packageJson2 = await loadPkg(ctx);
822
- if (!packageJson2) {
823
- ctx.logger.error(
824
- "Unable to deploy the project. Please make sure the package.json file is correctly formatted."
825
- );
826
- return;
827
- }
828
- ctx.logger.log("📦 Compressing project...");
829
- const hashname = crypto__namespace.createHash("sha512").update(packageJson2.name).digest("hex");
830
- const compressedFilename = `${hashname}.tar.gz`;
831
- try {
832
- ctx.logger.debug(
833
- "Compression parameters\n",
834
- `Storage path: ${storagePath}
835
- `,
836
- `Project folder: ${projectFolder}
837
- `,
838
- `Compressed filename: ${compressedFilename}`
839
- );
840
- await compressFilesToTar(storagePath, projectFolder, compressedFilename);
841
- ctx.logger.log("📦 Project compressed successfully!");
842
- } catch (e) {
843
- ctx.logger.error(
844
- "⚠️ Project compression failed. Try again later or check for large/incompatible files."
845
- );
846
- ctx.logger.debug(e);
847
- process.exit(1);
708
+ return packageJson2.name || "my-strapi-project";
709
+ } catch (e) {
710
+ return "my-strapi-project";
711
+ }
712
+ }
713
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
714
+ try {
715
+ await cloudApiService.track(eventName, eventData);
716
+ } catch (e) {
717
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
718
+ }
719
+ };
720
+ const openModule$1 = import("open");
721
+ async function promptLogin(ctx) {
722
+ const response = await inquirer__default.default.prompt([
723
+ {
724
+ type: "confirm",
725
+ name: "login",
726
+ message: "Would you like to login?"
848
727
  }
849
- const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
850
- const fileStats = await fse__default.default.stat(tarFilePath);
851
- if (fileStats.size > maxProjectFileSize) {
852
- ctx.logger.log(
853
- "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
854
- );
728
+ ]);
729
+ if (response.login) {
730
+ const loginSuccessful = await loginAction(ctx);
731
+ return loginSuccessful;
732
+ }
733
+ return false;
734
+ }
735
+ async function loginAction(ctx) {
736
+ const { logger } = ctx;
737
+ const tokenService = await tokenServiceFactory(ctx);
738
+ const existingToken = await tokenService.retrieveToken();
739
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
740
+ if (existingToken) {
741
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
742
+ if (isTokenValid) {
855
743
  try {
856
- await fse__default.default.remove(tarFilePath);
744
+ const userInfo = await cloudApiService.getUserInfo();
745
+ const { email } = userInfo.data.data;
746
+ if (email) {
747
+ logger.log(`You are already logged into your account (${email}).`);
748
+ } else {
749
+ logger.log("You are already logged in.");
750
+ }
751
+ logger.log(
752
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
753
+ );
754
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
755
+ return true;
756
+ } catch (e) {
757
+ logger.debug("Failed to fetch user info", e);
758
+ }
759
+ }
760
+ }
761
+ let cliConfig2;
762
+ try {
763
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
764
+ const config = await cloudApiService.config();
765
+ cliConfig2 = config.data;
766
+ } catch (e) {
767
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
768
+ logger.debug(e);
769
+ return false;
770
+ }
771
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
772
+ logger.debug("🔐 Creating device authentication request...", {
773
+ client_id: cliConfig2.clientId,
774
+ scope: cliConfig2.scope,
775
+ audience: cliConfig2.audience
776
+ });
777
+ const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
778
+ client_id: cliConfig2.clientId,
779
+ scope: cliConfig2.scope,
780
+ audience: cliConfig2.audience
781
+ }).catch((e) => {
782
+ logger.error("There was an issue with the authentication process. Please try again.");
783
+ if (e.message) {
784
+ logger.debug(e.message, e);
785
+ } else {
786
+ logger.debug(e);
787
+ }
788
+ });
789
+ openModule$1.then((open) => {
790
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
791
+ logger.error("We encountered an issue opening the browser. Please try again later.");
792
+ logger.debug(e.message, e);
793
+ });
794
+ });
795
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
796
+ logger.log(
797
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
798
+ );
799
+ logger.log(
800
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
801
+ `
802
+ );
803
+ const tokenPayload = {
804
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
805
+ device_code: deviceAuthResponse.data.device_code,
806
+ client_id: cliConfig2.clientId
807
+ };
808
+ let isAuthenticated = false;
809
+ const authenticate = async () => {
810
+ const spinner = logger.spinner("Waiting for authentication");
811
+ spinner.start();
812
+ const spinnerFail = () => spinner.fail("Authentication failed!");
813
+ while (!isAuthenticated) {
814
+ try {
815
+ const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
816
+ const authTokenData = tokenResponse.data;
817
+ if (tokenResponse.status === 200) {
818
+ try {
819
+ logger.debug("🔐 Validating token...");
820
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
821
+ logger.debug("🔐 Token validation successful!");
822
+ } catch (e) {
823
+ logger.debug(e);
824
+ spinnerFail();
825
+ throw new Error("Unable to proceed: Token validation failed");
826
+ }
827
+ logger.debug("🔍 Fetching user information...");
828
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
829
+ await cloudApiServiceWithToken.getUserInfo();
830
+ logger.debug("🔍 User information fetched successfully!");
831
+ try {
832
+ logger.debug("📝 Saving login information...");
833
+ await tokenService.saveToken(authTokenData.access_token);
834
+ logger.debug("📝 Login information saved successfully!");
835
+ isAuthenticated = true;
836
+ } catch (e) {
837
+ logger.error(
838
+ "There was a problem saving your login information. Please try logging in again."
839
+ );
840
+ logger.debug(e);
841
+ spinnerFail();
842
+ return false;
843
+ }
844
+ }
845
+ } catch (e) {
846
+ if (e.message === "Unable to proceed: Token validation failed") {
847
+ logger.error(
848
+ "There seems to be a problem with your login information. Please try logging in again."
849
+ );
850
+ spinnerFail();
851
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
852
+ return false;
853
+ }
854
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
855
+ logger.debug(e);
856
+ spinnerFail();
857
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
858
+ return false;
859
+ }
860
+ await new Promise((resolve) => {
861
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
862
+ });
863
+ }
864
+ }
865
+ spinner.succeed("Authentication successful!");
866
+ logger.log("You are now logged into Strapi Cloud.");
867
+ logger.log(
868
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
869
+ );
870
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
871
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
872
+ };
873
+ await authenticate();
874
+ return isAuthenticated;
875
+ }
876
+ function questionDefaultValuesMapper(questionsMap) {
877
+ return (questions) => {
878
+ return questions.map((question) => {
879
+ const questionName = question.name;
880
+ if (questionName in questionsMap) {
881
+ const questionDefault = questionsMap[questionName];
882
+ if (typeof questionDefault === "function") {
883
+ return {
884
+ ...question,
885
+ default: questionDefault(question)
886
+ };
887
+ }
888
+ return {
889
+ ...question,
890
+ default: questionDefault
891
+ };
892
+ }
893
+ return question;
894
+ });
895
+ };
896
+ }
897
+ function getDefaultsFromQuestions(questions) {
898
+ return questions.reduce((acc, question) => {
899
+ if (question.default && question.name) {
900
+ return { ...acc, [question.name]: question.default };
901
+ }
902
+ return acc;
903
+ }, {});
904
+ }
905
+ function getProjectNodeVersionDefault(question) {
906
+ const currentNodeVersion = process.versions.node.split(".")[0];
907
+ if (question.type === "list" && Array.isArray(question.choices)) {
908
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
909
+ if (choice) {
910
+ return choice.value;
911
+ }
912
+ }
913
+ return question.default;
914
+ }
915
+ async function handleError(ctx, error) {
916
+ const { logger } = ctx;
917
+ logger.debug(error);
918
+ if (error instanceof axios.AxiosError) {
919
+ const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
920
+ switch (error.response?.status) {
921
+ case 403:
922
+ logger.error(
923
+ errorMessage || "You do not have permission to create a project. Please contact support for assistance."
924
+ );
925
+ return;
926
+ case 400:
927
+ logger.error(errorMessage || "Invalid input. Please check your inputs and try again.");
928
+ return;
929
+ case 503:
930
+ logger.error(
931
+ "Strapi Cloud project creation is currently unavailable. Please try again later."
932
+ );
933
+ return;
934
+ default:
935
+ if (errorMessage) {
936
+ logger.error(errorMessage);
937
+ return;
938
+ }
939
+ break;
940
+ }
941
+ }
942
+ logger.error(
943
+ "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
944
+ );
945
+ }
946
+ async function createProject$1(ctx, cloudApi, projectInput) {
947
+ const { logger } = ctx;
948
+ const spinner = logger.spinner("Setting up your project...").start();
949
+ try {
950
+ const { data } = await cloudApi.createProject(projectInput);
951
+ await save({ project: data });
952
+ spinner.succeed("Project created successfully!");
953
+ return data;
954
+ } catch (e) {
955
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
956
+ throw e;
957
+ }
958
+ }
959
+ const action$4 = async (ctx) => {
960
+ const { logger } = ctx;
961
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
962
+ const token = await getValidToken(ctx, promptLogin);
963
+ if (!token) {
964
+ return;
965
+ }
966
+ const cloudApi = await cloudApiFactory(ctx, token);
967
+ const { data: config } = await cloudApi.config();
968
+ const projectName = await getProjectNameFromPackageJson(ctx);
969
+ const defaultAnswersMapper = questionDefaultValuesMapper({
970
+ name: projectName,
971
+ nodeVersion: getProjectNodeVersionDefault
972
+ });
973
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
974
+ const defaultValues = {
975
+ ...config.projectCreation.defaults,
976
+ ...getDefaultsFromQuestions(questions)
977
+ };
978
+ const projectAnswersDefaulted = fp.defaults(defaultValues);
979
+ const projectAnswers = await inquirer__default.default.prompt(questions);
980
+ const projectInput = projectAnswersDefaulted(projectAnswers);
981
+ try {
982
+ return await createProject$1(ctx, cloudApi, projectInput);
983
+ } catch (e) {
984
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
985
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
986
+ await eraseToken();
987
+ if (await promptLogin(ctx)) {
988
+ return await createProject$1(ctx, cloudApi, projectInput);
989
+ }
990
+ } else {
991
+ await handleError(ctx, e);
992
+ }
993
+ }
994
+ };
995
+ function notificationServiceFactory({ logger }) {
996
+ return (url, token, cliConfig2) => {
997
+ const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
998
+ const es = new EventSource__default.default(url, {
999
+ headers: {
1000
+ Authorization: `Bearer ${token}`
1001
+ }
1002
+ });
1003
+ let timeoutId;
1004
+ const resetTimeout = () => {
1005
+ clearTimeout(timeoutId);
1006
+ timeoutId = setTimeout(() => {
1007
+ logger.log(
1008
+ "We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment."
1009
+ );
1010
+ es.close();
1011
+ }, CONN_TIMEOUT);
1012
+ };
1013
+ es.onopen = resetTimeout;
1014
+ es.onmessage = (event) => {
1015
+ resetTimeout();
1016
+ const data = JSON.parse(event.data);
1017
+ if (data.message) {
1018
+ logger.log(data.message);
1019
+ }
1020
+ if (data.event === "deploymentFinished" || data.event === "deploymentFailed") {
1021
+ es.close();
1022
+ }
1023
+ };
1024
+ };
1025
+ }
1026
+ const buildLogsServiceFactory = ({ logger }) => {
1027
+ return async (url, token, cliConfig2) => {
1028
+ const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
1029
+ const MAX_RETRIES = Number(cliConfig2.buildLogsMaxRetries);
1030
+ return new Promise((resolve, reject) => {
1031
+ let timeoutId = null;
1032
+ let retries = 0;
1033
+ const connect = (url2) => {
1034
+ const spinner = logger.spinner("Connecting to server to get build logs");
1035
+ spinner.start();
1036
+ const es = new EventSource__default.default(`${url2}`, {
1037
+ headers: {
1038
+ Authorization: `Bearer ${token}`
1039
+ }
1040
+ });
1041
+ const clearExistingTimeout = () => {
1042
+ if (timeoutId) {
1043
+ clearTimeout(timeoutId);
1044
+ }
1045
+ };
1046
+ const resetTimeout = () => {
1047
+ clearExistingTimeout();
1048
+ timeoutId = setTimeout(() => {
1049
+ if (spinner.isSpinning) {
1050
+ spinner.fail(
1051
+ "We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue."
1052
+ );
1053
+ }
1054
+ es.close();
1055
+ reject(new Error("Connection timed out"));
1056
+ }, CONN_TIMEOUT);
1057
+ };
1058
+ es.onopen = resetTimeout;
1059
+ es.addEventListener("finished", (event) => {
1060
+ const data = JSON.parse(event.data);
1061
+ logger.log(data.msg);
1062
+ es.close();
1063
+ clearExistingTimeout();
1064
+ resolve(null);
1065
+ });
1066
+ es.addEventListener("log", (event) => {
1067
+ if (spinner.isSpinning) {
1068
+ spinner.succeed();
1069
+ }
1070
+ resetTimeout();
1071
+ const data = JSON.parse(event.data);
1072
+ logger.log(data.msg);
1073
+ });
1074
+ es.onerror = async () => {
1075
+ retries += 1;
1076
+ if (retries > MAX_RETRIES) {
1077
+ spinner.fail("We were unable to connect to the server to get build logs at this time.");
1078
+ es.close();
1079
+ clearExistingTimeout();
1080
+ reject(new Error("Max retries reached"));
1081
+ }
1082
+ };
1083
+ };
1084
+ connect(url);
1085
+ });
1086
+ };
1087
+ };
1088
+ async function upload(ctx, project, token, maxProjectFileSize) {
1089
+ const cloudApi = await cloudApiFactory(ctx, token);
1090
+ try {
1091
+ const storagePath = await getTmpStoragePath();
1092
+ const projectFolder = path__namespace.default.resolve(process.cwd());
1093
+ const packageJson2 = await loadPkg(ctx);
1094
+ if (!packageJson2) {
1095
+ ctx.logger.error(
1096
+ "Unable to deploy the project. Please make sure the package.json file is correctly formatted."
1097
+ );
1098
+ return;
1099
+ }
1100
+ ctx.logger.log("📦 Compressing project...");
1101
+ const hashname = crypto__namespace.createHash("sha512").update(packageJson2.name).digest("hex");
1102
+ const compressedFilename = `${hashname}.tar.gz`;
1103
+ try {
1104
+ ctx.logger.debug(
1105
+ "Compression parameters\n",
1106
+ `Storage path: ${storagePath}
1107
+ `,
1108
+ `Project folder: ${projectFolder}
1109
+ `,
1110
+ `Compressed filename: ${compressedFilename}`
1111
+ );
1112
+ await compressFilesToTar(storagePath, projectFolder, compressedFilename);
1113
+ ctx.logger.log("📦 Project compressed successfully!");
1114
+ } catch (e) {
1115
+ ctx.logger.error(
1116
+ "⚠️ Project compression failed. Try again later or check for large/incompatible files."
1117
+ );
1118
+ ctx.logger.debug(e);
1119
+ process.exit(1);
1120
+ }
1121
+ const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
1122
+ const fileStats = await fse__namespace.default.stat(tarFilePath);
1123
+ if (fileStats.size > maxProjectFileSize) {
1124
+ ctx.logger.log(
1125
+ "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
1126
+ );
1127
+ try {
1128
+ await fse__namespace.default.remove(tarFilePath);
857
1129
  } catch (e) {
858
1130
  ctx.logger.log("Unable to remove file: ", tarFilePath);
859
1131
  ctx.logger.debug(e);
@@ -879,20 +1151,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
879
1151
  return data.build_id;
880
1152
  } catch (e) {
881
1153
  progressBar.stop();
882
- if (e instanceof axios.AxiosError && e.response?.data) {
883
- if (e.response.status === 404) {
884
- ctx.logger.error(
885
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
886
- );
887
- } else {
888
- ctx.logger.error(e.response.data);
889
- }
890
- } else {
891
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
892
- }
1154
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
893
1155
  ctx.logger.debug(e);
894
1156
  } finally {
895
- await fse__default.default.remove(tarFilePath);
1157
+ await fse__namespace.default.remove(tarFilePath);
896
1158
  }
897
1159
  process.exit(0);
898
1160
  } catch (e) {
@@ -905,7 +1167,7 @@ async function getProject(ctx) {
905
1167
  const { project } = await retrieve();
906
1168
  if (!project) {
907
1169
  try {
908
- return await action$3(ctx);
1170
+ return await action$4(ctx);
909
1171
  } catch (e) {
910
1172
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
911
1173
  ctx.logger.debug(e);
@@ -914,10 +1176,21 @@ async function getProject(ctx) {
914
1176
  }
915
1177
  return project;
916
1178
  }
917
- const action$2 = async (ctx) => {
1179
+ async function getConfig({
1180
+ ctx,
1181
+ cloudApiService
1182
+ }) {
1183
+ try {
1184
+ const { data: cliConfig2 } = await cloudApiService.config();
1185
+ return cliConfig2;
1186
+ } catch (e) {
1187
+ ctx.logger.debug("Failed to get cli config", e);
1188
+ return null;
1189
+ }
1190
+ }
1191
+ const action$3 = async (ctx) => {
918
1192
  const { getValidToken } = await tokenServiceFactory(ctx);
919
- const cloudApiService = await cloudApiFactory(ctx);
920
- const token = await getValidToken();
1193
+ const token = await getValidToken(ctx, promptLogin);
921
1194
  if (!token) {
922
1195
  return;
923
1196
  }
@@ -925,14 +1198,51 @@ const action$2 = async (ctx) => {
925
1198
  if (!project) {
926
1199
  return;
927
1200
  }
1201
+ const cloudApiService = await cloudApiFactory(ctx, token);
928
1202
  try {
929
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1203
+ const {
1204
+ data: { data: projectData, metadata }
1205
+ } = await cloudApiService.getProject({ name: project.name });
1206
+ const isProjectSuspended = projectData.suspendedAt;
1207
+ if (isProjectSuspended) {
1208
+ ctx.logger.log(
1209
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1210
+ );
1211
+ ctx.logger.log(chalk__default.default.underline(`${metadata.dashboardUrls.project}`));
1212
+ return;
1213
+ }
930
1214
  } catch (e) {
931
- ctx.logger.debug("Failed to track willDeploy", e);
1215
+ if (e instanceof axios.AxiosError && e.response?.data) {
1216
+ if (e.response.status === 404) {
1217
+ ctx.logger.warn(
1218
+ `The project associated with this folder does not exist in Strapi Cloud.
1219
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1220
+ "link"
1221
+ )} command before deploying.`
1222
+ );
1223
+ } else {
1224
+ ctx.logger.error(e.response.data);
1225
+ }
1226
+ } else {
1227
+ ctx.logger.error(
1228
+ "An error occurred while retrieving the project's information. Please try again later."
1229
+ );
1230
+ }
1231
+ ctx.logger.debug(e);
1232
+ return;
932
1233
  }
1234
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1235
+ projectInternalName: project.name
1236
+ });
933
1237
  const notificationService = notificationServiceFactory(ctx);
934
1238
  const buildLogsService = buildLogsServiceFactory(ctx);
935
- const { data: cliConfig2 } = await cloudApiService.config();
1239
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1240
+ if (!cliConfig2) {
1241
+ ctx.logger.error(
1242
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1243
+ );
1244
+ return;
1245
+ }
936
1246
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
937
1247
  if (Number.isNaN(maxSize)) {
938
1248
  ctx.logger.debug(
@@ -954,10 +1264,11 @@ const action$2 = async (ctx) => {
954
1264
  chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
955
1265
  );
956
1266
  } catch (e) {
1267
+ ctx.logger.debug(e);
957
1268
  if (e instanceof Error) {
958
1269
  ctx.logger.error(e.message);
959
1270
  } else {
960
- throw e;
1271
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
961
1272
  }
962
1273
  }
963
1274
  };
@@ -988,186 +1299,175 @@ const runAction = (name2, action2) => (...args) => {
988
1299
  process.exit(1);
989
1300
  });
990
1301
  };
991
- const command$3 = ({ command: command2, ctx }) => {
992
- 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));
1302
+ const command$5 = ({ command: command2, ctx }) => {
1303
+ 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$3)(ctx));
993
1304
  };
994
1305
  const deployProject = {
995
1306
  name: "deploy-project",
996
1307
  description: "Deploy a Strapi Cloud project",
997
- action: action$2,
998
- command: command$3
1308
+ action: action$3,
1309
+ command: command$5
999
1310
  };
1000
- const openModule$1 = import("open");
1001
- const action$1 = async (ctx) => {
1002
- const { logger } = ctx;
1003
- const tokenService = await tokenServiceFactory(ctx);
1004
- const existingToken = await tokenService.retrieveToken();
1005
- const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
1006
- const trackFailedLogin = async () => {
1007
- try {
1008
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
1009
- } catch (e) {
1010
- logger.debug("Failed to track failed login", e);
1011
- }
1012
- };
1013
- if (existingToken) {
1014
- const isTokenValid = await tokenService.isTokenValid(existingToken);
1015
- if (isTokenValid) {
1016
- try {
1017
- const userInfo = await cloudApiService.getUserInfo();
1018
- const { email } = userInfo.data.data;
1019
- if (email) {
1020
- logger.log(`You are already logged into your account (${email}).`);
1021
- } else {
1022
- logger.log("You are already logged in.");
1023
- }
1024
- logger.log(
1025
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1026
- );
1027
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1028
- return true;
1029
- } catch (e) {
1030
- logger.debug("Failed to fetch user info", e);
1311
+ const QUIT_OPTION = "Quit";
1312
+ async function getExistingConfig(ctx) {
1313
+ try {
1314
+ return await retrieve();
1315
+ } catch (e) {
1316
+ ctx.logger.debug("Failed to get project config", e);
1317
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1318
+ return null;
1319
+ }
1320
+ }
1321
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1322
+ if (existingConfig && existingConfig.project) {
1323
+ const { shouldRelink } = await inquirer__default.default.prompt([
1324
+ {
1325
+ type: "confirm",
1326
+ name: "shouldRelink",
1327
+ message: `A project named ${chalk__default.default.cyan(
1328
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1329
+ )} is already linked to this local folder. Do you want to update the link?`,
1330
+ default: false
1031
1331
  }
1332
+ ]);
1333
+ if (!shouldRelink) {
1334
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1335
+ currentProjectName: existingConfig.project?.name
1336
+ });
1337
+ return false;
1032
1338
  }
1033
1339
  }
1034
- let cliConfig2;
1340
+ return true;
1341
+ }
1342
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1343
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1035
1344
  try {
1036
- logger.info("🔌 Connecting to the Strapi Cloud API...");
1037
- const config = await cloudApiService.config();
1038
- cliConfig2 = config.data;
1345
+ const {
1346
+ data: { data: projectList }
1347
+ } = await cloudApiService.listLinkProjects();
1348
+ spinner.succeed();
1349
+ if (!Array.isArray(projectList)) {
1350
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1351
+ return null;
1352
+ }
1353
+ const projects = projectList.filter(
1354
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1355
+ ).map((project) => {
1356
+ return {
1357
+ name: project.displayName,
1358
+ value: { name: project.name, displayName: project.displayName }
1359
+ };
1360
+ });
1361
+ if (projects.length === 0) {
1362
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1363
+ return null;
1364
+ }
1365
+ return projects;
1039
1366
  } catch (e) {
1040
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
1041
- logger.debug(e);
1042
- return false;
1367
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1368
+ ctx.logger.debug("Failed to list projects", e);
1369
+ return null;
1043
1370
  }
1371
+ }
1372
+ async function getUserSelection(ctx, projects) {
1373
+ const { logger } = ctx;
1044
1374
  try {
1045
- await cloudApiService.track("willLoginAttempt", {});
1375
+ const answer = await inquirer__default.default.prompt([
1376
+ {
1377
+ type: "list",
1378
+ name: "linkProject",
1379
+ message: "Which project do you want to link?",
1380
+ choices: [...projects, { name: chalk__default.default.grey(`(${QUIT_OPTION})`), value: null }]
1381
+ }
1382
+ ]);
1383
+ if (!answer.linkProject) {
1384
+ return null;
1385
+ }
1386
+ return answer;
1046
1387
  } catch (e) {
1047
- logger.debug("Failed to track login attempt", e);
1388
+ logger.debug("Failed to get user input", e);
1389
+ logger.error("An error occurred while trying to get your input.");
1390
+ return null;
1048
1391
  }
1049
- logger.debug("🔐 Creating device authentication request...", {
1050
- client_id: cliConfig2.clientId,
1051
- scope: cliConfig2.scope,
1052
- audience: cliConfig2.audience
1053
- });
1054
- const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
1055
- client_id: cliConfig2.clientId,
1056
- scope: cliConfig2.scope,
1057
- audience: cliConfig2.audience
1058
- }).catch((e) => {
1059
- logger.error("There was an issue with the authentication process. Please try again.");
1060
- if (e.message) {
1061
- logger.debug(e.message, e);
1062
- } else {
1063
- logger.debug(e);
1064
- }
1065
- });
1066
- openModule$1.then((open) => {
1067
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
1068
- logger.error("We encountered an issue opening the browser. Please try again later.");
1069
- logger.debug(e.message, e);
1070
- });
1071
- });
1072
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1073
- logger.log(
1074
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1075
- );
1076
- logger.log(
1077
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1078
- `
1392
+ }
1393
+ const action$2 = async (ctx) => {
1394
+ const { getValidToken } = await tokenServiceFactory(ctx);
1395
+ const token = await getValidToken(ctx, promptLogin);
1396
+ const { logger } = ctx;
1397
+ if (!token) {
1398
+ return;
1399
+ }
1400
+ const cloudApiService = await cloudApiFactory(ctx, token);
1401
+ const existingConfig = await getExistingConfig(ctx);
1402
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1403
+ if (!shouldRelink) {
1404
+ return;
1405
+ }
1406
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1407
+ const projects = await getProjectsList(
1408
+ ctx,
1409
+ cloudApiService,
1410
+ existingConfig
1079
1411
  );
1080
- const tokenPayload = {
1081
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1082
- device_code: deviceAuthResponse.data.device_code,
1083
- client_id: cliConfig2.clientId
1084
- };
1085
- let isAuthenticated = false;
1086
- const authenticate = async () => {
1087
- const spinner = logger.spinner("Waiting for authentication");
1088
- spinner.start();
1089
- const spinnerFail = () => spinner.fail("Authentication failed!");
1090
- while (!isAuthenticated) {
1091
- try {
1092
- const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
1093
- const authTokenData = tokenResponse.data;
1094
- if (tokenResponse.status === 200) {
1095
- try {
1096
- logger.debug("🔐 Validating token...");
1097
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1098
- logger.debug("🔐 Token validation successful!");
1099
- } catch (e) {
1100
- logger.debug(e);
1101
- spinnerFail();
1102
- throw new Error("Unable to proceed: Token validation failed");
1103
- }
1104
- logger.debug("🔍 Fetching user information...");
1105
- const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
1106
- await cloudApiServiceWithToken.getUserInfo();
1107
- logger.debug("🔍 User information fetched successfully!");
1108
- try {
1109
- logger.debug("📝 Saving login information...");
1110
- await tokenService.saveToken(authTokenData.access_token);
1111
- logger.debug("📝 Login information saved successfully!");
1112
- isAuthenticated = true;
1113
- } catch (e) {
1114
- logger.error(
1115
- "There was a problem saving your login information. Please try logging in again."
1116
- );
1117
- logger.debug(e);
1118
- spinnerFail();
1119
- return false;
1120
- }
1121
- }
1122
- } catch (e) {
1123
- if (e.message === "Unable to proceed: Token validation failed") {
1124
- logger.error(
1125
- "There seems to be a problem with your login information. Please try logging in again."
1126
- );
1127
- spinnerFail();
1128
- await trackFailedLogin();
1129
- return false;
1130
- }
1131
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1132
- logger.debug(e);
1133
- spinnerFail();
1134
- await trackFailedLogin();
1135
- return false;
1136
- }
1137
- await new Promise((resolve) => {
1138
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1139
- });
1412
+ if (!projects) {
1413
+ return;
1414
+ }
1415
+ const answer = await getUserSelection(ctx, projects);
1416
+ if (!answer) {
1417
+ return;
1418
+ }
1419
+ try {
1420
+ const { confirmAction } = await inquirer__default.default.prompt([
1421
+ {
1422
+ type: "confirm",
1423
+ name: "confirmAction",
1424
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1425
+ default: false
1140
1426
  }
1427
+ ]);
1428
+ if (!confirmAction) {
1429
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1430
+ cancelledProjectName: answer.linkProject.name,
1431
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1432
+ });
1433
+ return;
1141
1434
  }
1142
- spinner.succeed("Authentication successful!");
1143
- logger.log("You are now logged into Strapi Cloud.");
1144
- logger.log(
1145
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1146
- );
1147
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1148
- try {
1149
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1150
- } catch (e) {
1151
- logger.debug("Failed to track login", e);
1152
- }
1153
- };
1154
- await authenticate();
1155
- return isAuthenticated;
1435
+ await save({ project: answer.linkProject });
1436
+ logger.log(`Project ${chalk__default.default.cyan(answer.linkProject.displayName)} linked successfully.`);
1437
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1438
+ projectInternalName: answer.linkProject
1439
+ });
1440
+ } catch (e) {
1441
+ logger.debug("Failed to link project", e);
1442
+ logger.error("An error occurred while linking the project.");
1443
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1444
+ projectInternalName: answer.linkProject
1445
+ });
1446
+ }
1156
1447
  };
1157
- const command$2 = ({ command: command2, ctx }) => {
1448
+ const command$4 = ({ command: command2, ctx }) => {
1449
+ 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$2)(ctx));
1450
+ };
1451
+ const link = {
1452
+ name: "link-project",
1453
+ description: "Link a local directory to a Strapi Cloud project",
1454
+ action: action$2,
1455
+ command: command$4
1456
+ };
1457
+ const command$3 = ({ command: command2, ctx }) => {
1158
1458
  command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1159
1459
  "after",
1160
1460
  "\nAfter running this command, you will be prompted to enter your authentication information."
1161
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1461
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1162
1462
  };
1163
1463
  const login = {
1164
1464
  name: "login",
1165
1465
  description: "Strapi Cloud Login",
1166
- action: action$1,
1167
- command: command$2
1466
+ action: loginAction,
1467
+ command: command$3
1168
1468
  };
1169
1469
  const openModule = import("open");
1170
- const action = async (ctx) => {
1470
+ const action$1 = async (ctx) => {
1171
1471
  const { logger } = ctx;
1172
1472
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1173
1473
  const token = await retrieveToken();
@@ -1197,37 +1497,64 @@ const action = async (ctx) => {
1197
1497
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1198
1498
  logger.debug(e);
1199
1499
  }
1200
- try {
1201
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1202
- } catch (e) {
1203
- logger.debug("Failed to track logout event", e);
1204
- }
1500
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1205
1501
  };
1206
- const command$1 = ({ command: command2, ctx }) => {
1207
- 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)(ctx));
1502
+ const command$2 = ({ command: command2, ctx }) => {
1503
+ 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));
1208
1504
  };
1209
1505
  const logout = {
1210
1506
  name: "logout",
1211
1507
  description: "Strapi Cloud Logout",
1212
- action,
1213
- command: command$1
1508
+ action: action$1,
1509
+ command: command$2
1214
1510
  };
1215
- const command = ({ command: command2, ctx }) => {
1216
- 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));
1511
+ const command$1 = ({ command: command2, ctx }) => {
1512
+ 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$4)(ctx));
1217
1513
  };
1218
1514
  const createProject = {
1219
1515
  name: "create-project",
1220
1516
  description: "Create a new project",
1221
- action: action$3,
1517
+ action: action$4,
1518
+ command: command$1
1519
+ };
1520
+ const action = async (ctx) => {
1521
+ const { getValidToken } = await tokenServiceFactory(ctx);
1522
+ const token = await getValidToken(ctx, promptLogin);
1523
+ const { logger } = ctx;
1524
+ if (!token) {
1525
+ return;
1526
+ }
1527
+ const cloudApiService = await cloudApiFactory(ctx, token);
1528
+ const spinner = logger.spinner("Fetching your projects...").start();
1529
+ try {
1530
+ const {
1531
+ data: { data: projectList }
1532
+ } = await cloudApiService.listProjects();
1533
+ spinner.succeed();
1534
+ logger.log(projectList);
1535
+ } catch (e) {
1536
+ ctx.logger.debug("Failed to list projects", e);
1537
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1538
+ }
1539
+ };
1540
+ const command = ({ command: command2, ctx }) => {
1541
+ 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)(ctx));
1542
+ };
1543
+ const listProjects = {
1544
+ name: "list-projects",
1545
+ description: "List Strapi Cloud projects",
1546
+ action,
1222
1547
  command
1223
1548
  };
1224
1549
  const cli = {
1225
1550
  deployProject,
1551
+ link,
1226
1552
  login,
1227
1553
  logout,
1228
- createProject
1554
+ createProject,
1555
+ listProjects
1229
1556
  };
1230
- const cloudCommands = [deployProject, login, logout];
1557
+ const cloudCommands = [deployProject, link, login, logout, listProjects];
1231
1558
  async function initCloudCLIConfig() {
1232
1559
  const localConfig = await getLocalConfig();
1233
1560
  if (!localConfig.deviceId) {