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

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 (57) hide show
  1. package/dist/index.js +774 -304
  2. package/dist/index.js.map +1 -1
  3. package/dist/index.mjs +776 -303
  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 +1 -1
  8. package/dist/src/create-project/action.d.ts.map +1 -1
  9. package/dist/src/create-project/command.d.ts.map +1 -1
  10. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  11. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  12. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  13. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  14. package/dist/src/deploy-project/action.d.ts +4 -1
  15. package/dist/src/deploy-project/action.d.ts.map +1 -1
  16. package/dist/src/deploy-project/command.d.ts.map +1 -1
  17. package/dist/src/environment/command.d.ts +3 -0
  18. package/dist/src/environment/command.d.ts.map +1 -0
  19. package/dist/src/environment/list/action.d.ts +4 -0
  20. package/dist/src/environment/list/action.d.ts.map +1 -0
  21. package/dist/src/environment/list/command.d.ts +4 -0
  22. package/dist/src/environment/list/command.d.ts.map +1 -0
  23. package/dist/src/environment/list/index.d.ts +7 -0
  24. package/dist/src/environment/list/index.d.ts.map +1 -0
  25. package/dist/src/index.d.ts +3 -0
  26. package/dist/src/index.d.ts.map +1 -1
  27. package/dist/src/link/action.d.ts +4 -0
  28. package/dist/src/link/action.d.ts.map +1 -0
  29. package/dist/src/link/command.d.ts +7 -0
  30. package/dist/src/link/command.d.ts.map +1 -0
  31. package/dist/src/link/index.d.ts +7 -0
  32. package/dist/src/link/index.d.ts.map +1 -0
  33. package/dist/src/list-projects/action.d.ts +4 -0
  34. package/dist/src/list-projects/action.d.ts.map +1 -0
  35. package/dist/src/list-projects/command.d.ts +7 -0
  36. package/dist/src/list-projects/command.d.ts.map +1 -0
  37. package/dist/src/list-projects/index.d.ts +7 -0
  38. package/dist/src/list-projects/index.d.ts.map +1 -0
  39. package/dist/src/login/action.d.ts +2 -2
  40. package/dist/src/login/action.d.ts.map +1 -1
  41. package/dist/src/login/command.d.ts.map +1 -1
  42. package/dist/src/logout/action.d.ts.map +1 -1
  43. package/dist/src/logout/command.d.ts.map +1 -1
  44. package/dist/src/services/build-logs.d.ts.map +1 -1
  45. package/dist/src/services/cli-api.d.ts +47 -7
  46. package/dist/src/services/cli-api.d.ts.map +1 -1
  47. package/dist/src/services/strapi-info-save.d.ts +1 -1
  48. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  49. package/dist/src/services/token.d.ts +1 -1
  50. package/dist/src/services/token.d.ts.map +1 -1
  51. package/dist/src/types.d.ts +5 -1
  52. package/dist/src/types.d.ts.map +1 -1
  53. package/dist/src/utils/analytics.d.ts +4 -0
  54. package/dist/src/utils/analytics.d.ts.map +1 -0
  55. package/dist/src/utils/compress-files.d.ts.map +1 -1
  56. package/dist/src/utils/pkg.d.ts.map +1 -1
  57. package/package.json +10 -9
package/dist/index.js CHANGED
@@ -24,15 +24,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
25
  const crypto$1 = require("crypto");
26
26
  const fse = require("fs-extra");
27
+ const inquirer = require("inquirer");
27
28
  const path = require("path");
28
29
  const chalk = require("chalk");
29
30
  const axios = require("axios");
30
31
  const crypto = require("node:crypto");
31
32
  const utils = require("@strapi/utils");
32
- const fs = require("fs");
33
33
  const tar = require("tar");
34
34
  const minimatch = require("minimatch");
35
- const inquirer = require("inquirer");
36
35
  const fp = require("lodash/fp");
37
36
  const os = require("os");
38
37
  const XDGAppPaths = require("xdg-app-paths");
@@ -41,10 +40,10 @@ 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");
46
+ const commander = require("commander");
48
47
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
48
  function _interopNamespace(e) {
50
49
  if (e && e.__esModule)
@@ -65,14 +64,13 @@ function _interopNamespace(e) {
65
64
  return Object.freeze(n);
66
65
  }
67
66
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto$1);
68
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
67
+ const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
68
+ const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
69
69
  const path__namespace = /* @__PURE__ */ _interopNamespace(path);
70
70
  const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
71
71
  const axios__default = /* @__PURE__ */ _interopDefault(axios);
72
72
  const crypto__namespace = /* @__PURE__ */ _interopNamespace(crypto);
73
- const fs__namespace = /* @__PURE__ */ _interopNamespace(fs);
74
73
  const tar__namespace = /* @__PURE__ */ _interopNamespace(tar);
75
- const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
76
74
  const os__default = /* @__PURE__ */ _interopDefault(os);
77
75
  const XDGAppPaths__default = /* @__PURE__ */ _interopDefault(XDGAppPaths);
78
76
  const jwksClient__default = /* @__PURE__ */ _interopDefault(jwksClient);
@@ -80,10 +78,9 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
78
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
79
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
80
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
- const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
81
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
82
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
83
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
84
  const apiConfig = {
88
85
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
86
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -102,23 +99,6 @@ const IGNORED_PATTERNS = [
102
99
  "**/.idea/**",
103
100
  "**/.vscode/**"
104
101
  ];
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
102
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
123
103
  ignorePatterns.push(...IGNORED_PATTERNS);
124
104
  const relativeFilePath = path__namespace.join(folderPath, file);
@@ -136,16 +116,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
136
116
  }
137
117
  return isIgnored;
138
118
  };
139
- const readGitignore = (folderPath) => {
119
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
120
+ const arrayOfFiles = [];
121
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
122
+ for (const entry of entries) {
123
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
124
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
125
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
126
+ if (!isIgnored) {
127
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
128
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
129
+ arrayOfFiles.push(...subFiles);
130
+ } else {
131
+ arrayOfFiles.push(entryPath);
132
+ }
133
+ }
134
+ }
135
+ return arrayOfFiles;
136
+ };
137
+ const readGitignore = async (folderPath) => {
140
138
  const gitignorePath = path__namespace.resolve(folderPath, ".gitignore");
141
- if (!fs__namespace.existsSync(gitignorePath))
139
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
140
+ if (!pathExist)
142
141
  return [];
143
- const gitignoreContent = fs__namespace.readFileSync(gitignorePath, "utf8");
142
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, "utf8");
144
143
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
145
144
  };
146
145
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
147
- const ignorePatterns = readGitignore(folderToCompress);
148
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
146
+ const ignorePatterns = await readGitignore(folderToCompress);
147
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
149
148
  return tar__namespace.c(
150
149
  {
151
150
  gzip: true,
@@ -158,7 +157,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
158
157
  const CONFIG_FILENAME = "config.json";
159
158
  async function checkDirectoryExists(directoryPath) {
160
159
  try {
161
- const fsStat = await fse__default.default.lstat(directoryPath);
160
+ const fsStat = await fse__namespace.default.lstat(directoryPath);
162
161
  return fsStat.isDirectory();
163
162
  } catch (e) {
164
163
  return false;
@@ -166,14 +165,14 @@ async function checkDirectoryExists(directoryPath) {
166
165
  }
167
166
  async function getTmpStoragePath() {
168
167
  const storagePath = path__namespace.default.join(os__default.default.tmpdir(), APP_FOLDER_NAME);
169
- await fse__default.default.ensureDir(storagePath);
168
+ await fse__namespace.default.ensureDir(storagePath);
170
169
  return storagePath;
171
170
  }
172
171
  async function getConfigPath() {
173
172
  const configDirs = XDGAppPaths__default.default(APP_FOLDER_NAME).configDirs();
174
173
  const configPath = configDirs.find(checkDirectoryExists);
175
174
  if (!configPath) {
176
- await fse__default.default.ensureDir(configDirs[0]);
175
+ await fse__namespace.default.ensureDir(configDirs[0]);
177
176
  return configDirs[0];
178
177
  }
179
178
  return configPath;
@@ -181,9 +180,9 @@ async function getConfigPath() {
181
180
  async function getLocalConfig() {
182
181
  const configPath = await getConfigPath();
183
182
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
184
- await fse__default.default.ensureFile(configFilePath);
183
+ await fse__namespace.default.ensureFile(configFilePath);
185
184
  try {
186
- return await fse__default.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
185
+ return await fse__namespace.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
187
186
  } catch (e) {
188
187
  return {};
189
188
  }
@@ -191,10 +190,10 @@ async function getLocalConfig() {
191
190
  async function saveLocalConfig(data) {
192
191
  const configPath = await getConfigPath();
193
192
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
194
- await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
193
+ await fse__namespace.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
194
  }
196
195
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.1";
196
+ const version = "5.3.0";
198
197
  const description = "Commands to interact with the Strapi Cloud";
199
198
  const keywords = [
200
199
  "strapi",
@@ -235,17 +234,18 @@ const scripts = {
235
234
  build: "pack-up build",
236
235
  clean: "run -T rimraf ./dist",
237
236
  lint: "run -T eslint .",
237
+ "test:unit": "run -T jest",
238
238
  watch: "pack-up watch"
239
239
  };
240
240
  const dependencies = {
241
- "@strapi/utils": "4.25.1",
242
- axios: "1.6.0",
241
+ "@strapi/utils": "workspace:*",
242
+ axios: "1.7.4",
243
243
  chalk: "4.1.2",
244
244
  "cli-progress": "3.12.0",
245
245
  commander: "8.3.0",
246
246
  eventsource: "2.0.2",
247
247
  "fast-safe-stringify": "2.1.1",
248
- "fs-extra": "10.0.0",
248
+ "fs-extra": "11.2.0",
249
249
  inquirer: "8.2.5",
250
250
  jsonwebtoken: "9.0.0",
251
251
  "jwks-rsa": "3.1.0",
@@ -254,7 +254,7 @@ const dependencies = {
254
254
  open: "8.4.0",
255
255
  ora: "5.4.1",
256
256
  "pkg-up": "3.1.0",
257
- tar: "6.1.13",
257
+ tar: "6.2.1",
258
258
  "xdg-app-paths": "8.3.0",
259
259
  yup: "0.32.9"
260
260
  };
@@ -263,11 +263,11 @@ const devDependencies = {
263
263
  "@types/cli-progress": "3.11.5",
264
264
  "@types/eventsource": "1.1.15",
265
265
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.1",
267
- tsconfig: "4.25.1"
266
+ "eslint-config-custom": "workspace:*",
267
+ tsconfig: "workspace:*"
268
268
  };
269
269
  const engines = {
270
- node: ">=18.0.0 <=20.x.x",
270
+ node: ">=18.0.0 <=22.x.x",
271
271
  npm: ">=6.0.0"
272
272
  };
273
273
  const packageJson = {
@@ -317,7 +317,7 @@ async function cloudApiFactory({ logger }, token) {
317
317
  deploy({ filePath, project }, { onUploadProgress }) {
318
318
  return axiosCloudAPI.post(
319
319
  `/deploy/${project.name}`,
320
- { file: fse__default.default.createReadStream(filePath) },
320
+ { file: fse__namespace.default.createReadStream(filePath), targetEnvironment: project.targetEnvironment },
321
321
  {
322
322
  headers: {
323
323
  "Content-Type": "multipart/form-data"
@@ -360,8 +360,61 @@ async function cloudApiFactory({ logger }, token) {
360
360
  throw error;
361
361
  }
362
362
  },
363
- listProjects() {
364
- return axiosCloudAPI.get("/projects");
363
+ async listProjects() {
364
+ try {
365
+ const response = await axiosCloudAPI.get("/projects");
366
+ if (response.status !== 200) {
367
+ throw new Error("Error fetching cloud projects from the server.");
368
+ }
369
+ return response;
370
+ } catch (error) {
371
+ logger.debug(
372
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
373
+ );
374
+ throw error;
375
+ }
376
+ },
377
+ async listLinkProjects() {
378
+ try {
379
+ const response = await axiosCloudAPI.get("/projects-linkable");
380
+ if (response.status !== 200) {
381
+ throw new Error("Error fetching cloud projects from the server.");
382
+ }
383
+ return response;
384
+ } catch (error) {
385
+ logger.debug(
386
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
387
+ );
388
+ throw error;
389
+ }
390
+ },
391
+ async listEnvironments({ name: name2 }) {
392
+ try {
393
+ const response = await axiosCloudAPI.get(`/projects/${name2}/environments`);
394
+ if (response.status !== 200) {
395
+ throw new Error("Error fetching cloud environments from the server.");
396
+ }
397
+ return response;
398
+ } catch (error) {
399
+ logger.debug(
400
+ "🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again."
401
+ );
402
+ throw error;
403
+ }
404
+ },
405
+ async getProject({ name: name2 }) {
406
+ try {
407
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
408
+ if (response.status !== 200) {
409
+ throw new Error("Error fetching project's details.");
410
+ }
411
+ return response;
412
+ } catch (error) {
413
+ logger.debug(
414
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
415
+ );
416
+ throw error;
417
+ }
365
418
  },
366
419
  track(event, payload = {}) {
367
420
  return axiosCloudAPI.post("/track", {
@@ -376,18 +429,18 @@ async function save(data, { directoryPath } = {}) {
376
429
  const alreadyInFileData = await retrieve({ directoryPath });
377
430
  const storedData = { ...alreadyInFileData, ...data };
378
431
  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" });
432
+ await fse__namespace.default.ensureDir(path__namespace.default.dirname(pathToFile));
433
+ await fse__namespace.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
381
434
  }
382
435
  async function retrieve({
383
436
  directoryPath
384
437
  } = {}) {
385
438
  const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
386
- const pathExists = await fse__default.default.pathExists(pathToFile);
439
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
387
440
  if (!pathExists) {
388
441
  return {};
389
442
  }
390
- return fse__default.default.readJSON(pathToFile, { encoding: "utf8" });
443
+ return fse__namespace.default.readJSON(pathToFile, { encoding: "utf8" });
391
444
  }
392
445
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
393
446
  __proto__: null,
@@ -446,14 +499,17 @@ async function tokenServiceFactory({ logger }) {
446
499
  "There seems to be a problem with your login information. Please try logging in again."
447
500
  );
448
501
  }
502
+ return Promise.reject(new Error("Invalid token"));
449
503
  }
450
504
  return new Promise((resolve, reject) => {
451
505
  jwt__default.default.verify(idToken, getKey, (err) => {
452
506
  if (err) {
453
507
  reject(err);
454
- } else {
455
- resolve();
456
508
  }
509
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
510
+ reject(new Error("Token is expired"));
511
+ }
512
+ resolve();
457
513
  });
458
514
  });
459
515
  }
@@ -487,15 +543,15 @@ async function tokenServiceFactory({ logger }) {
487
543
  throw e;
488
544
  }
489
545
  }
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;
546
+ async function getValidToken(ctx, loginAction2) {
547
+ let token = await retrieveToken();
548
+ while (!token || !await isTokenValid(token)) {
549
+ logger.log(
550
+ 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."
551
+ );
552
+ if (!await loginAction2(ctx))
553
+ return null;
554
+ token = await retrieveToken();
499
555
  }
500
556
  return token;
501
557
  }
@@ -629,17 +685,257 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
629
685
  local: strapiInfoSave,
630
686
  tokenServiceFactory
631
687
  }, Symbol.toStringTag, { value: "Module" }));
632
- async function handleError(ctx, error) {
688
+ yup__namespace.object({
689
+ name: yup__namespace.string().required(),
690
+ exports: yup__namespace.lazy(
691
+ (value) => yup__namespace.object(
692
+ typeof value === "object" ? Object.entries(value).reduce(
693
+ (acc, [key, value2]) => {
694
+ if (typeof value2 === "object") {
695
+ acc[key] = yup__namespace.object({
696
+ types: yup__namespace.string().optional(),
697
+ source: yup__namespace.string().required(),
698
+ module: yup__namespace.string().optional(),
699
+ import: yup__namespace.string().required(),
700
+ require: yup__namespace.string().required(),
701
+ default: yup__namespace.string().required()
702
+ }).noUnknown(true);
703
+ } else {
704
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
705
+ }
706
+ return acc;
707
+ },
708
+ {}
709
+ ) : void 0
710
+ ).optional()
711
+ )
712
+ });
713
+ const loadPkg = async ({ cwd, logger }) => {
714
+ const pkgPath = await pkgUp__default.default({ cwd });
715
+ if (!pkgPath) {
716
+ throw new Error("Could not find a package.json in the current directory");
717
+ }
718
+ const buffer = await fse__namespace.readFile(pkgPath);
719
+ const pkg = JSON.parse(buffer.toString());
720
+ logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
721
+ return pkg;
722
+ };
723
+ async function getProjectNameFromPackageJson(ctx) {
724
+ try {
725
+ const packageJson2 = await loadPkg(ctx);
726
+ return packageJson2.name || "my-strapi-project";
727
+ } catch (e) {
728
+ return "my-strapi-project";
729
+ }
730
+ }
731
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
732
+ try {
733
+ await cloudApiService.track(eventName, eventData);
734
+ } catch (e) {
735
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
736
+ }
737
+ };
738
+ const openModule$1 = import("open");
739
+ async function promptLogin(ctx) {
740
+ const response = await inquirer__default.default.prompt([
741
+ {
742
+ type: "confirm",
743
+ name: "login",
744
+ message: "Would you like to login?"
745
+ }
746
+ ]);
747
+ if (response.login) {
748
+ const loginSuccessful = await loginAction(ctx);
749
+ return loginSuccessful;
750
+ }
751
+ return false;
752
+ }
753
+ async function loginAction(ctx) {
754
+ const { logger } = ctx;
633
755
  const tokenService = await tokenServiceFactory(ctx);
756
+ const existingToken = await tokenService.retrieveToken();
757
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
758
+ if (existingToken) {
759
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
760
+ if (isTokenValid) {
761
+ try {
762
+ const userInfo = await cloudApiService.getUserInfo();
763
+ const { email } = userInfo.data.data;
764
+ if (email) {
765
+ logger.log(`You are already logged into your account (${email}).`);
766
+ } else {
767
+ logger.log("You are already logged in.");
768
+ }
769
+ logger.log(
770
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
771
+ );
772
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
773
+ return true;
774
+ } catch (e) {
775
+ logger.debug("Failed to fetch user info", e);
776
+ }
777
+ }
778
+ }
779
+ let cliConfig2;
780
+ try {
781
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
782
+ const config = await cloudApiService.config();
783
+ cliConfig2 = config.data;
784
+ } catch (e) {
785
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
786
+ logger.debug(e);
787
+ return false;
788
+ }
789
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
790
+ logger.debug("🔐 Creating device authentication request...", {
791
+ client_id: cliConfig2.clientId,
792
+ scope: cliConfig2.scope,
793
+ audience: cliConfig2.audience
794
+ });
795
+ const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
796
+ client_id: cliConfig2.clientId,
797
+ scope: cliConfig2.scope,
798
+ audience: cliConfig2.audience
799
+ }).catch((e) => {
800
+ logger.error("There was an issue with the authentication process. Please try again.");
801
+ if (e.message) {
802
+ logger.debug(e.message, e);
803
+ } else {
804
+ logger.debug(e);
805
+ }
806
+ });
807
+ openModule$1.then((open) => {
808
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
809
+ logger.error("We encountered an issue opening the browser. Please try again later.");
810
+ logger.debug(e.message, e);
811
+ });
812
+ });
813
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
814
+ logger.log(
815
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
816
+ );
817
+ logger.log(
818
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
819
+ `
820
+ );
821
+ const tokenPayload = {
822
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
823
+ device_code: deviceAuthResponse.data.device_code,
824
+ client_id: cliConfig2.clientId
825
+ };
826
+ let isAuthenticated = false;
827
+ const authenticate = async () => {
828
+ const spinner = logger.spinner("Waiting for authentication");
829
+ spinner.start();
830
+ const spinnerFail = () => spinner.fail("Authentication failed!");
831
+ while (!isAuthenticated) {
832
+ try {
833
+ const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
834
+ const authTokenData = tokenResponse.data;
835
+ if (tokenResponse.status === 200) {
836
+ try {
837
+ logger.debug("🔐 Validating token...");
838
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
839
+ logger.debug("🔐 Token validation successful!");
840
+ } catch (e) {
841
+ logger.debug(e);
842
+ spinnerFail();
843
+ throw new Error("Unable to proceed: Token validation failed");
844
+ }
845
+ logger.debug("🔍 Fetching user information...");
846
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
847
+ await cloudApiServiceWithToken.getUserInfo();
848
+ logger.debug("🔍 User information fetched successfully!");
849
+ try {
850
+ logger.debug("📝 Saving login information...");
851
+ await tokenService.saveToken(authTokenData.access_token);
852
+ logger.debug("📝 Login information saved successfully!");
853
+ isAuthenticated = true;
854
+ } catch (e) {
855
+ logger.error(
856
+ "There was a problem saving your login information. Please try logging in again."
857
+ );
858
+ logger.debug(e);
859
+ spinnerFail();
860
+ return false;
861
+ }
862
+ }
863
+ } catch (e) {
864
+ if (e.message === "Unable to proceed: Token validation failed") {
865
+ logger.error(
866
+ "There seems to be a problem with your login information. Please try logging in again."
867
+ );
868
+ spinnerFail();
869
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
870
+ return false;
871
+ }
872
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
873
+ logger.debug(e);
874
+ spinnerFail();
875
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
876
+ return false;
877
+ }
878
+ await new Promise((resolve) => {
879
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
880
+ });
881
+ }
882
+ }
883
+ spinner.succeed("Authentication successful!");
884
+ logger.log("You are now logged into Strapi Cloud.");
885
+ logger.log(
886
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
887
+ );
888
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
889
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
890
+ };
891
+ await authenticate();
892
+ return isAuthenticated;
893
+ }
894
+ function questionDefaultValuesMapper(questionsMap) {
895
+ return (questions) => {
896
+ return questions.map((question) => {
897
+ const questionName = question.name;
898
+ if (questionName in questionsMap) {
899
+ const questionDefault = questionsMap[questionName];
900
+ if (typeof questionDefault === "function") {
901
+ return {
902
+ ...question,
903
+ default: questionDefault(question)
904
+ };
905
+ }
906
+ return {
907
+ ...question,
908
+ default: questionDefault
909
+ };
910
+ }
911
+ return question;
912
+ });
913
+ };
914
+ }
915
+ function getDefaultsFromQuestions(questions) {
916
+ return questions.reduce((acc, question) => {
917
+ if (question.default && question.name) {
918
+ return { ...acc, [question.name]: question.default };
919
+ }
920
+ return acc;
921
+ }, {});
922
+ }
923
+ function getProjectNodeVersionDefault(question) {
924
+ const currentNodeVersion = process.versions.node.split(".")[0];
925
+ if (question.type === "list" && Array.isArray(question.choices)) {
926
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
927
+ if (choice) {
928
+ return choice.value;
929
+ }
930
+ }
931
+ return question.default;
932
+ }
933
+ async function handleError(ctx, error) {
634
934
  const { logger } = ctx;
635
935
  logger.debug(error);
636
936
  if (error instanceof axios.AxiosError) {
637
937
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
638
938
  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
939
  case 403:
644
940
  logger.error(
645
941
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -665,28 +961,53 @@ async function handleError(ctx, error) {
665
961
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
666
962
  );
667
963
  }
668
- const action$3 = async (ctx) => {
964
+ async function createProject$1(ctx, cloudApi, projectInput) {
669
965
  const { logger } = ctx;
670
- const { getValidToken } = await tokenServiceFactory(ctx);
671
- const token = await getValidToken();
966
+ const spinner = logger.spinner("Setting up your project...").start();
967
+ try {
968
+ const { data } = await cloudApi.createProject(projectInput);
969
+ await save({ project: data });
970
+ spinner.succeed("Project created successfully!");
971
+ return data;
972
+ } catch (e) {
973
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
974
+ throw e;
975
+ }
976
+ }
977
+ const action$5 = async (ctx) => {
978
+ const { logger } = ctx;
979
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
980
+ const token = await getValidToken(ctx, promptLogin);
672
981
  if (!token) {
673
982
  return;
674
983
  }
675
984
  const cloudApi = await cloudApiFactory(ctx, token);
676
985
  const { data: config } = await cloudApi.config();
677
- const { questions, defaults: defaultValues } = config.projectCreation;
986
+ const projectName = await getProjectNameFromPackageJson(ctx);
987
+ const defaultAnswersMapper = questionDefaultValuesMapper({
988
+ name: projectName,
989
+ nodeVersion: getProjectNodeVersionDefault
990
+ });
991
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
992
+ const defaultValues = {
993
+ ...config.projectCreation.defaults,
994
+ ...getDefaultsFromQuestions(questions)
995
+ };
678
996
  const projectAnswersDefaulted = fp.defaults(defaultValues);
679
997
  const projectAnswers = await inquirer__default.default.prompt(questions);
680
998
  const projectInput = projectAnswersDefaulted(projectAnswers);
681
- const spinner = logger.spinner("Setting up your project...").start();
682
999
  try {
683
- const { data } = await cloudApi.createProject(projectInput);
684
- await save({ project: data });
685
- spinner.succeed("Project created successfully!");
686
- return data;
1000
+ return await createProject$1(ctx, cloudApi, projectInput);
687
1001
  } catch (e) {
688
- spinner.fail("Failed to create project on Strapi Cloud.");
689
- await handleError(ctx, e);
1002
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
1003
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
1004
+ await eraseToken();
1005
+ if (await promptLogin(ctx)) {
1006
+ return await createProject$1(ctx, cloudApi, projectInput);
1007
+ }
1008
+ } else {
1009
+ await handleError(ctx, e);
1010
+ }
690
1011
  }
691
1012
  };
692
1013
  function notificationServiceFactory({ logger }) {
@@ -720,38 +1041,6 @@ function notificationServiceFactory({ logger }) {
720
1041
  };
721
1042
  };
722
1043
  }
723
- yup__namespace.object({
724
- name: yup__namespace.string().required(),
725
- exports: yup__namespace.lazy(
726
- (value) => yup__namespace.object(
727
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
728
- if (typeof value2 === "object") {
729
- acc[key] = yup__namespace.object({
730
- types: yup__namespace.string().optional(),
731
- source: yup__namespace.string().required(),
732
- module: yup__namespace.string().optional(),
733
- import: yup__namespace.string().required(),
734
- require: yup__namespace.string().required(),
735
- default: yup__namespace.string().required()
736
- }).noUnknown(true);
737
- } else {
738
- acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
739
- }
740
- return acc;
741
- }, {}) : void 0
742
- ).optional()
743
- )
744
- });
745
- const loadPkg = async ({ cwd, logger }) => {
746
- const pkgPath = await pkgUp__default.default({ cwd });
747
- if (!pkgPath) {
748
- throw new Error("Could not find a package.json in the current directory");
749
- }
750
- const buffer = await fs__default.default.readFile(pkgPath);
751
- const pkg = JSON.parse(buffer.toString());
752
- logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
753
- return pkg;
754
- };
755
1044
  const buildLogsServiceFactory = ({ logger }) => {
756
1045
  return async (url, token, cliConfig2) => {
757
1046
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -805,6 +1094,7 @@ const buildLogsServiceFactory = ({ logger }) => {
805
1094
  if (retries > MAX_RETRIES) {
806
1095
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
807
1096
  es.close();
1097
+ clearExistingTimeout();
808
1098
  reject(new Error("Max retries reached"));
809
1099
  }
810
1100
  };
@@ -813,6 +1103,32 @@ const buildLogsServiceFactory = ({ logger }) => {
813
1103
  });
814
1104
  };
815
1105
  };
1106
+ const QUIT_OPTION$1 = "Quit";
1107
+ async function promptForEnvironment(environments) {
1108
+ const choices = environments.map((env) => ({ name: env, value: env }));
1109
+ const { selectedEnvironment } = await inquirer__default.default.prompt([
1110
+ {
1111
+ type: "list",
1112
+ name: "selectedEnvironment",
1113
+ message: "Select the environment to deploy:",
1114
+ choices: [...choices, { name: chalk__default.default.grey(`(${QUIT_OPTION$1})`), value: null }]
1115
+ }
1116
+ ]);
1117
+ if (selectedEnvironment === null) {
1118
+ process.exit(1);
1119
+ }
1120
+ const { confirm } = await inquirer__default.default.prompt([
1121
+ {
1122
+ type: "confirm",
1123
+ name: "confirm",
1124
+ message: `Do you want to proceed with deployment to ${chalk__default.default.cyan(selectedEnvironment)}?`
1125
+ }
1126
+ ]);
1127
+ if (!confirm) {
1128
+ process.exit(1);
1129
+ }
1130
+ return selectedEnvironment;
1131
+ }
816
1132
  async function upload(ctx, project, token, maxProjectFileSize) {
817
1133
  const cloudApi = await cloudApiFactory(ctx, token);
818
1134
  try {
@@ -847,13 +1163,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
847
1163
  process.exit(1);
848
1164
  }
849
1165
  const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
850
- const fileStats = await fse__default.default.stat(tarFilePath);
1166
+ const fileStats = await fse__namespace.default.stat(tarFilePath);
851
1167
  if (fileStats.size > maxProjectFileSize) {
852
1168
  ctx.logger.log(
853
1169
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
854
1170
  );
855
1171
  try {
856
- await fse__default.default.remove(tarFilePath);
1172
+ await fse__namespace.default.remove(tarFilePath);
857
1173
  } catch (e) {
858
1174
  ctx.logger.log("Unable to remove file: ", tarFilePath);
859
1175
  ctx.logger.debug(e);
@@ -879,20 +1195,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
879
1195
  return data.build_id;
880
1196
  } catch (e) {
881
1197
  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
- }
1198
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
893
1199
  ctx.logger.debug(e);
894
1200
  } finally {
895
- await fse__default.default.remove(tarFilePath);
1201
+ await fse__namespace.default.remove(tarFilePath);
896
1202
  }
897
1203
  process.exit(0);
898
1204
  } catch (e) {
@@ -901,11 +1207,11 @@ async function upload(ctx, project, token, maxProjectFileSize) {
901
1207
  process.exit(1);
902
1208
  }
903
1209
  }
904
- async function getProject(ctx) {
1210
+ async function getProject$1(ctx) {
905
1211
  const { project } = await retrieve();
906
1212
  if (!project) {
907
1213
  try {
908
- return await action$3(ctx);
1214
+ return await action$5(ctx);
909
1215
  } catch (e) {
910
1216
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
911
1217
  ctx.logger.debug(e);
@@ -914,25 +1220,75 @@ async function getProject(ctx) {
914
1220
  }
915
1221
  return project;
916
1222
  }
917
- const action$2 = async (ctx) => {
1223
+ async function getConfig({
1224
+ ctx,
1225
+ cloudApiService
1226
+ }) {
1227
+ try {
1228
+ const { data: cliConfig2 } = await cloudApiService.config();
1229
+ return cliConfig2;
1230
+ } catch (e) {
1231
+ ctx.logger.debug("Failed to get cli config", e);
1232
+ return null;
1233
+ }
1234
+ }
1235
+ const action$4 = async (ctx, opts) => {
918
1236
  const { getValidToken } = await tokenServiceFactory(ctx);
919
- const cloudApiService = await cloudApiFactory(ctx);
920
- const token = await getValidToken();
1237
+ const token = await getValidToken(ctx, promptLogin);
921
1238
  if (!token) {
922
1239
  return;
923
1240
  }
924
- const project = await getProject(ctx);
1241
+ const project = await getProject$1(ctx);
925
1242
  if (!project) {
926
1243
  return;
927
1244
  }
1245
+ const cloudApiService = await cloudApiFactory(ctx, token);
1246
+ let environments;
928
1247
  try {
929
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1248
+ const {
1249
+ data: { data: projectData, metadata }
1250
+ } = await cloudApiService.getProject({ name: project.name });
1251
+ const isProjectSuspended = projectData.suspendedAt;
1252
+ environments = projectData.environments;
1253
+ if (isProjectSuspended) {
1254
+ ctx.logger.log(
1255
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1256
+ );
1257
+ ctx.logger.log(chalk__default.default.underline(`${metadata.dashboardUrls.project}`));
1258
+ return;
1259
+ }
930
1260
  } catch (e) {
931
- ctx.logger.debug("Failed to track willDeploy", e);
1261
+ if (e instanceof axios.AxiosError && e.response?.data) {
1262
+ if (e.response.status === 404) {
1263
+ ctx.logger.warn(
1264
+ `The project associated with this folder does not exist in Strapi Cloud.
1265
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1266
+ "link"
1267
+ )} command before deploying.`
1268
+ );
1269
+ } else {
1270
+ ctx.logger.error(e.response.data);
1271
+ }
1272
+ } else {
1273
+ ctx.logger.error(
1274
+ "An error occurred while retrieving the project's information. Please try again later."
1275
+ );
1276
+ }
1277
+ ctx.logger.debug(e);
1278
+ return;
932
1279
  }
1280
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1281
+ projectInternalName: project.name
1282
+ });
933
1283
  const notificationService = notificationServiceFactory(ctx);
934
1284
  const buildLogsService = buildLogsServiceFactory(ctx);
935
- const { data: cliConfig2 } = await cloudApiService.config();
1285
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1286
+ if (!cliConfig2) {
1287
+ ctx.logger.error(
1288
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1289
+ );
1290
+ return;
1291
+ }
936
1292
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
937
1293
  if (Number.isNaN(maxSize)) {
938
1294
  ctx.logger.debug(
@@ -940,6 +1296,17 @@ const action$2 = async (ctx) => {
940
1296
  );
941
1297
  maxSize = 1e8;
942
1298
  }
1299
+ let targetEnvironment;
1300
+ if (opts.environment) {
1301
+ if (!environments.includes(opts.environment)) {
1302
+ ctx.logger.error(`Environment ${opts.environment} does not exist.`);
1303
+ return;
1304
+ }
1305
+ targetEnvironment = opts.environment;
1306
+ } else {
1307
+ targetEnvironment = environments.length > 1 ? await promptForEnvironment(environments) : environments[0];
1308
+ }
1309
+ project.targetEnvironment = targetEnvironment;
943
1310
  const buildId = await upload(ctx, project, token, maxSize);
944
1311
  if (!buildId) {
945
1312
  return;
@@ -954,10 +1321,11 @@ const action$2 = async (ctx) => {
954
1321
  chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
955
1322
  );
956
1323
  } catch (e) {
1324
+ ctx.logger.debug(e);
957
1325
  if (e instanceof Error) {
958
1326
  ctx.logger.error(e.message);
959
1327
  } else {
960
- throw e;
1328
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
961
1329
  }
962
1330
  }
963
1331
  };
@@ -988,186 +1356,175 @@ const runAction = (name2, action2) => (...args) => {
988
1356
  process.exit(1);
989
1357
  });
990
1358
  };
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));
1359
+ const command$6 = ({ ctx }) => {
1360
+ return commander.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").option("-e, --environment <name>", "Specify the environment to deploy").action((opts) => runAction("deploy", action$4)(ctx, opts));
993
1361
  };
994
1362
  const deployProject = {
995
1363
  name: "deploy-project",
996
1364
  description: "Deploy a Strapi Cloud project",
997
- action: action$2,
998
- command: command$3
1365
+ action: action$4,
1366
+ command: command$6
999
1367
  };
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);
1368
+ const QUIT_OPTION = "Quit";
1369
+ async function getExistingConfig(ctx) {
1370
+ try {
1371
+ return await retrieve();
1372
+ } catch (e) {
1373
+ ctx.logger.debug("Failed to get project config", e);
1374
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1375
+ return null;
1376
+ }
1377
+ }
1378
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1379
+ if (existingConfig && existingConfig.project) {
1380
+ const { shouldRelink } = await inquirer__default.default.prompt([
1381
+ {
1382
+ type: "confirm",
1383
+ name: "shouldRelink",
1384
+ message: `A project named ${chalk__default.default.cyan(
1385
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1386
+ )} is already linked to this local folder. Do you want to update the link?`,
1387
+ default: false
1031
1388
  }
1389
+ ]);
1390
+ if (!shouldRelink) {
1391
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1392
+ currentProjectName: existingConfig.project?.name
1393
+ });
1394
+ return false;
1032
1395
  }
1033
1396
  }
1034
- let cliConfig2;
1397
+ return true;
1398
+ }
1399
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1400
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1035
1401
  try {
1036
- logger.info("🔌 Connecting to the Strapi Cloud API...");
1037
- const config = await cloudApiService.config();
1038
- cliConfig2 = config.data;
1402
+ const {
1403
+ data: { data: projectList }
1404
+ } = await cloudApiService.listLinkProjects();
1405
+ spinner.succeed();
1406
+ if (!Array.isArray(projectList)) {
1407
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1408
+ return null;
1409
+ }
1410
+ const projects = projectList.filter(
1411
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1412
+ ).map((project) => {
1413
+ return {
1414
+ name: project.displayName,
1415
+ value: { name: project.name, displayName: project.displayName }
1416
+ };
1417
+ });
1418
+ if (projects.length === 0) {
1419
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud");
1420
+ return null;
1421
+ }
1422
+ return projects;
1039
1423
  } catch (e) {
1040
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
1041
- logger.debug(e);
1042
- return false;
1424
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1425
+ ctx.logger.debug("Failed to list projects", e);
1426
+ return null;
1043
1427
  }
1428
+ }
1429
+ async function getUserSelection(ctx, projects) {
1430
+ const { logger } = ctx;
1044
1431
  try {
1045
- await cloudApiService.track("willLoginAttempt", {});
1432
+ const answer = await inquirer__default.default.prompt([
1433
+ {
1434
+ type: "list",
1435
+ name: "linkProject",
1436
+ message: "Which project do you want to link?",
1437
+ choices: [...projects, { name: chalk__default.default.grey(`(${QUIT_OPTION})`), value: null }]
1438
+ }
1439
+ ]);
1440
+ if (!answer.linkProject) {
1441
+ return null;
1442
+ }
1443
+ return answer;
1046
1444
  } catch (e) {
1047
- logger.debug("Failed to track login attempt", e);
1445
+ logger.debug("Failed to get user input", e);
1446
+ logger.error("An error occurred while trying to get your input.");
1447
+ return null;
1048
1448
  }
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
- `
1449
+ }
1450
+ const action$3 = async (ctx) => {
1451
+ const { getValidToken } = await tokenServiceFactory(ctx);
1452
+ const token = await getValidToken(ctx, promptLogin);
1453
+ const { logger } = ctx;
1454
+ if (!token) {
1455
+ return;
1456
+ }
1457
+ const cloudApiService = await cloudApiFactory(ctx, token);
1458
+ const existingConfig = await getExistingConfig(ctx);
1459
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1460
+ if (!shouldRelink) {
1461
+ return;
1462
+ }
1463
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1464
+ const projects = await getProjectsList(
1465
+ ctx,
1466
+ cloudApiService,
1467
+ existingConfig
1079
1468
  );
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
- });
1469
+ if (!projects) {
1470
+ return;
1471
+ }
1472
+ const answer = await getUserSelection(ctx, projects);
1473
+ if (!answer) {
1474
+ return;
1475
+ }
1476
+ try {
1477
+ const { confirmAction } = await inquirer__default.default.prompt([
1478
+ {
1479
+ type: "confirm",
1480
+ name: "confirmAction",
1481
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1482
+ default: false
1140
1483
  }
1484
+ ]);
1485
+ if (!confirmAction) {
1486
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1487
+ cancelledProjectName: answer.linkProject.name,
1488
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1489
+ });
1490
+ return;
1141
1491
  }
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;
1492
+ await save({ project: answer.linkProject });
1493
+ logger.log(`Project ${chalk__default.default.cyan(answer.linkProject.displayName)} linked successfully.`);
1494
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1495
+ projectInternalName: answer.linkProject
1496
+ });
1497
+ } catch (e) {
1498
+ logger.debug("Failed to link project", e);
1499
+ logger.error("An error occurred while linking the project.");
1500
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1501
+ projectInternalName: answer.linkProject
1502
+ });
1503
+ }
1504
+ };
1505
+ const command$5 = ({ command: command2, ctx }) => {
1506
+ 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));
1156
1507
  };
1157
- const command$2 = ({ command: command2, ctx }) => {
1158
- command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1508
+ const link = {
1509
+ name: "link-project",
1510
+ description: "Link a local directory to a Strapi Cloud project",
1511
+ action: action$3,
1512
+ command: command$5
1513
+ };
1514
+ const command$4 = ({ ctx }) => {
1515
+ return commander.createCommand("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1159
1516
  "after",
1160
1517
  "\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));
1518
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1162
1519
  };
1163
1520
  const login = {
1164
1521
  name: "login",
1165
1522
  description: "Strapi Cloud Login",
1166
- action: action$1,
1167
- command: command$2
1523
+ action: loginAction,
1524
+ command: command$4
1168
1525
  };
1169
1526
  const openModule = import("open");
1170
- const action = async (ctx) => {
1527
+ const action$2 = async (ctx) => {
1171
1528
  const { logger } = ctx;
1172
1529
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1173
1530
  const token = await retrieveToken();
@@ -1197,37 +1554,147 @@ const action = async (ctx) => {
1197
1554
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1198
1555
  logger.debug(e);
1199
1556
  }
1200
- try {
1201
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1202
- } catch (e) {
1203
- logger.debug("Failed to track logout event", e);
1204
- }
1557
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1205
1558
  };
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));
1559
+ const command$3 = ({ ctx }) => {
1560
+ return commander.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));
1208
1561
  };
1209
1562
  const logout = {
1210
1563
  name: "logout",
1211
1564
  description: "Strapi Cloud Logout",
1212
- action,
1213
- command: command$1
1565
+ action: action$2,
1566
+ command: command$3
1214
1567
  };
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));
1568
+ const command$2 = ({ ctx }) => {
1569
+ return commander.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));
1217
1570
  };
1218
1571
  const createProject = {
1219
1572
  name: "create-project",
1220
1573
  description: "Create a new project",
1221
- action: action$3,
1574
+ action: action$5,
1575
+ command: command$2
1576
+ };
1577
+ const action$1 = async (ctx) => {
1578
+ const { getValidToken } = await tokenServiceFactory(ctx);
1579
+ const token = await getValidToken(ctx, promptLogin);
1580
+ const { logger } = ctx;
1581
+ if (!token) {
1582
+ return;
1583
+ }
1584
+ const cloudApiService = await cloudApiFactory(ctx, token);
1585
+ const spinner = logger.spinner("Fetching your projects...").start();
1586
+ try {
1587
+ const {
1588
+ data: { data: projectList }
1589
+ } = await cloudApiService.listProjects();
1590
+ spinner.succeed();
1591
+ logger.log(projectList);
1592
+ } catch (e) {
1593
+ ctx.logger.debug("Failed to list projects", e);
1594
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1595
+ }
1596
+ };
1597
+ const command$1 = ({ command: command2, ctx }) => {
1598
+ 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));
1599
+ };
1600
+ const listProjects = {
1601
+ name: "list-projects",
1602
+ description: "List Strapi Cloud projects",
1603
+ action: action$1,
1604
+ command: command$1
1605
+ };
1606
+ async function getProject(ctx) {
1607
+ const { project } = await retrieve();
1608
+ if (!project) {
1609
+ ctx.logger.warn(
1610
+ `
1611
+ We couldn't find a valid local project config.
1612
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1613
+ "link"
1614
+ )} command`
1615
+ );
1616
+ process.exit(1);
1617
+ }
1618
+ return project;
1619
+ }
1620
+ const action = async (ctx) => {
1621
+ const { getValidToken } = await tokenServiceFactory(ctx);
1622
+ const token = await getValidToken(ctx, promptLogin);
1623
+ const { logger } = ctx;
1624
+ if (!token) {
1625
+ return;
1626
+ }
1627
+ const project = await getProject(ctx);
1628
+ if (!project) {
1629
+ ctx.logger.debug(`No valid local project configuration was found.`);
1630
+ return;
1631
+ }
1632
+ const cloudApiService = await cloudApiFactory(ctx, token);
1633
+ const spinner = logger.spinner("Fetching environments...").start();
1634
+ await trackEvent(ctx, cloudApiService, "willListEnvironment", {
1635
+ projectInternalName: project.name
1636
+ });
1637
+ try {
1638
+ const {
1639
+ data: { data: environmentsList }
1640
+ } = await cloudApiService.listEnvironments({ name: project.name });
1641
+ spinner.succeed();
1642
+ logger.log(environmentsList);
1643
+ await trackEvent(ctx, cloudApiService, "didListEnvironment", {
1644
+ projectInternalName: project.name
1645
+ });
1646
+ } catch (e) {
1647
+ if (e.response && e.response.status === 404) {
1648
+ spinner.succeed();
1649
+ logger.warn(
1650
+ `
1651
+ The project associated with this folder does not exist in Strapi Cloud.
1652
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1653
+ "link"
1654
+ )} command`
1655
+ );
1656
+ } else {
1657
+ spinner.fail("An error occurred while fetching environments data from Strapi Cloud.");
1658
+ logger.debug("Failed to list environments", e);
1659
+ }
1660
+ await trackEvent(ctx, cloudApiService, "didNotListEnvironment", {
1661
+ projectInternalName: project.name
1662
+ });
1663
+ }
1664
+ };
1665
+ function defineCloudNamespace(command2, ctx) {
1666
+ const cloud = command2.command("cloud").description("Manage Strapi Cloud projects");
1667
+ cloud.command("environments").description("Alias for cloud environment list").action(() => runAction("list", action)(ctx));
1668
+ return cloud;
1669
+ }
1670
+ let environmentCmd = null;
1671
+ const initializeEnvironmentCommand = (command2, ctx) => {
1672
+ if (!environmentCmd) {
1673
+ const cloud = defineCloudNamespace(command2, ctx);
1674
+ environmentCmd = cloud.command("environment").description("Manage environments");
1675
+ }
1676
+ return environmentCmd;
1677
+ };
1678
+ const command = ({ command: command2, ctx }) => {
1679
+ const environmentCmd2 = initializeEnvironmentCommand(command2, ctx);
1680
+ environmentCmd2.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));
1681
+ };
1682
+ const listEnvironments = {
1683
+ name: "list-environments",
1684
+ description: "List Strapi Cloud environments",
1685
+ action,
1222
1686
  command
1223
1687
  };
1224
1688
  const cli = {
1225
1689
  deployProject,
1690
+ link,
1226
1691
  login,
1227
1692
  logout,
1228
- createProject
1693
+ createProject,
1694
+ listProjects,
1695
+ listEnvironments
1229
1696
  };
1230
- const cloudCommands = [deployProject, login, logout];
1697
+ const cloudCommands = [deployProject, link, login, logout, listProjects, listEnvironments];
1231
1698
  async function initCloudCLIConfig() {
1232
1699
  const localConfig = await getLocalConfig();
1233
1700
  if (!localConfig.deviceId) {
@@ -1243,7 +1710,10 @@ async function buildStrapiCloudCommands({
1243
1710
  await initCloudCLIConfig();
1244
1711
  for (const cloudCommand of cloudCommands) {
1245
1712
  try {
1246
- await cloudCommand.command({ command: command2, ctx, argv });
1713
+ const subCommand = await cloudCommand.command({ command: command2, ctx, argv });
1714
+ if (subCommand) {
1715
+ command2.addCommand(subCommand);
1716
+ }
1247
1717
  } catch (e) {
1248
1718
  console.error(`Failed to load command ${cloudCommand.name}`, e);
1249
1719
  }