@strapi/cloud-cli 0.0.0-next.a64ced5364618f917adb31b8684b4e3c01c58862 → 0.0.0-next.ac654f8b8646bf964ebd39d4313c4afab0917a24

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 (68) hide show
  1. package/LICENSE +18 -3
  2. package/dist/bin.js +1 -0
  3. package/dist/bin.js.map +1 -1
  4. package/dist/index.js +1019 -324
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1021 -324
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/src/cloud/command.d.ts +3 -0
  9. package/dist/src/cloud/command.d.ts.map +1 -0
  10. package/dist/src/create-project/action.d.ts +1 -1
  11. package/dist/src/create-project/action.d.ts.map +1 -1
  12. package/dist/src/create-project/command.d.ts.map +1 -1
  13. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts +3 -0
  14. package/dist/src/create-project/utils/get-project-name-from-pkg.d.ts.map +1 -0
  15. package/dist/src/create-project/utils/project-questions.utils.d.ts +20 -0
  16. package/dist/src/create-project/utils/project-questions.utils.d.ts.map +1 -0
  17. package/dist/src/deploy-project/action.d.ts +5 -1
  18. package/dist/src/deploy-project/action.d.ts.map +1 -1
  19. package/dist/src/deploy-project/command.d.ts.map +1 -1
  20. package/dist/src/environment/command.d.ts +3 -0
  21. package/dist/src/environment/command.d.ts.map +1 -0
  22. package/dist/src/environment/link/action.d.ts +4 -0
  23. package/dist/src/environment/link/action.d.ts.map +1 -0
  24. package/dist/src/environment/link/command.d.ts +4 -0
  25. package/dist/src/environment/link/command.d.ts.map +1 -0
  26. package/dist/src/environment/link/index.d.ts +7 -0
  27. package/dist/src/environment/link/index.d.ts.map +1 -0
  28. package/dist/src/environment/list/action.d.ts +4 -0
  29. package/dist/src/environment/list/action.d.ts.map +1 -0
  30. package/dist/src/environment/list/command.d.ts +4 -0
  31. package/dist/src/environment/list/command.d.ts.map +1 -0
  32. package/dist/src/environment/list/index.d.ts +7 -0
  33. package/dist/src/environment/list/index.d.ts.map +1 -0
  34. package/dist/src/index.d.ts +4 -0
  35. package/dist/src/index.d.ts.map +1 -1
  36. package/dist/src/link/action.d.ts +4 -0
  37. package/dist/src/link/action.d.ts.map +1 -0
  38. package/dist/src/link/command.d.ts +7 -0
  39. package/dist/src/link/command.d.ts.map +1 -0
  40. package/dist/src/link/index.d.ts +7 -0
  41. package/dist/src/link/index.d.ts.map +1 -0
  42. package/dist/src/list-projects/action.d.ts +4 -0
  43. package/dist/src/list-projects/action.d.ts.map +1 -0
  44. package/dist/src/list-projects/command.d.ts +7 -0
  45. package/dist/src/list-projects/command.d.ts.map +1 -0
  46. package/dist/src/list-projects/index.d.ts +7 -0
  47. package/dist/src/list-projects/index.d.ts.map +1 -0
  48. package/dist/src/login/action.d.ts +2 -2
  49. package/dist/src/login/action.d.ts.map +1 -1
  50. package/dist/src/login/command.d.ts.map +1 -1
  51. package/dist/src/logout/action.d.ts.map +1 -1
  52. package/dist/src/logout/command.d.ts.map +1 -1
  53. package/dist/src/services/build-logs.d.ts.map +1 -1
  54. package/dist/src/services/cli-api.d.ts +67 -10
  55. package/dist/src/services/cli-api.d.ts.map +1 -1
  56. package/dist/src/services/strapi-info-save.d.ts +15 -2
  57. package/dist/src/services/strapi-info-save.d.ts.map +1 -1
  58. package/dist/src/services/token.d.ts +1 -1
  59. package/dist/src/services/token.d.ts.map +1 -1
  60. package/dist/src/types.d.ts +8 -1
  61. package/dist/src/types.d.ts.map +1 -1
  62. package/dist/src/utils/analytics.d.ts +4 -0
  63. package/dist/src/utils/analytics.d.ts.map +1 -0
  64. package/dist/src/utils/compress-files.d.ts.map +1 -1
  65. package/dist/src/utils/get-local-config.d.ts +6 -0
  66. package/dist/src/utils/get-local-config.d.ts.map +1 -0
  67. package/dist/src/utils/pkg.d.ts.map +1 -1
  68. package/package.json +11 -9
package/dist/index.js CHANGED
@@ -24,27 +24,28 @@ 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");
28
+ const boxen = require("boxen");
27
29
  const path = require("path");
28
30
  const chalk = require("chalk");
29
31
  const axios = require("axios");
30
32
  const crypto = require("node:crypto");
31
33
  const utils = require("@strapi/utils");
32
- const fs = require("fs");
33
34
  const tar = require("tar");
34
35
  const minimatch = require("minimatch");
35
- const inquirer = require("inquirer");
36
36
  const fp = require("lodash/fp");
37
37
  const os = require("os");
38
38
  const XDGAppPaths = require("xdg-app-paths");
39
+ const lodash = require("lodash");
39
40
  const jwksClient = require("jwks-rsa");
40
41
  const jwt = require("jsonwebtoken");
41
42
  const stringify = require("fast-safe-stringify");
42
43
  const ora = require("ora");
43
44
  const cliProgress = require("cli-progress");
44
- const EventSource = require("eventsource");
45
- const fs$1 = require("fs/promises");
46
45
  const pkgUp = require("pkg-up");
47
46
  const yup = require("yup");
47
+ const EventSource = require("eventsource");
48
+ const commander = require("commander");
48
49
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
49
50
  function _interopNamespace(e) {
50
51
  if (e && e.__esModule)
@@ -65,14 +66,14 @@ function _interopNamespace(e) {
65
66
  return Object.freeze(n);
66
67
  }
67
68
  const crypto__default = /* @__PURE__ */ _interopDefault(crypto$1);
68
- const fse__default = /* @__PURE__ */ _interopDefault(fse);
69
+ const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
70
+ const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
71
+ const boxen__default = /* @__PURE__ */ _interopDefault(boxen);
69
72
  const path__namespace = /* @__PURE__ */ _interopNamespace(path);
70
73
  const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
71
74
  const axios__default = /* @__PURE__ */ _interopDefault(axios);
72
75
  const crypto__namespace = /* @__PURE__ */ _interopNamespace(crypto);
73
- const fs__namespace = /* @__PURE__ */ _interopNamespace(fs);
74
76
  const tar__namespace = /* @__PURE__ */ _interopNamespace(tar);
75
- const inquirer__default = /* @__PURE__ */ _interopDefault(inquirer);
76
77
  const os__default = /* @__PURE__ */ _interopDefault(os);
77
78
  const XDGAppPaths__default = /* @__PURE__ */ _interopDefault(XDGAppPaths);
78
79
  const jwksClient__default = /* @__PURE__ */ _interopDefault(jwksClient);
@@ -80,10 +81,9 @@ const jwt__default = /* @__PURE__ */ _interopDefault(jwt);
80
81
  const stringify__default = /* @__PURE__ */ _interopDefault(stringify);
81
82
  const ora__default = /* @__PURE__ */ _interopDefault(ora);
82
83
  const cliProgress__namespace = /* @__PURE__ */ _interopNamespace(cliProgress);
83
- const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
84
- const fs__default = /* @__PURE__ */ _interopDefault(fs$1);
85
84
  const pkgUp__default = /* @__PURE__ */ _interopDefault(pkgUp);
86
85
  const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
86
+ const EventSource__default = /* @__PURE__ */ _interopDefault(EventSource);
87
87
  const apiConfig = {
88
88
  apiBaseUrl: utils.env("STRAPI_CLI_CLOUD_API", "https://cloud-cli-api.strapi.io"),
89
89
  dashboardBaseUrl: utils.env("STRAPI_CLI_CLOUD_DASHBOARD", "https://cloud.strapi.io")
@@ -102,23 +102,6 @@ const IGNORED_PATTERNS = [
102
102
  "**/.idea/**",
103
103
  "**/.vscode/**"
104
104
  ];
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
105
  const isIgnoredFile = (folderPath, file, ignorePatterns) => {
123
106
  ignorePatterns.push(...IGNORED_PATTERNS);
124
107
  const relativeFilePath = path__namespace.join(folderPath, file);
@@ -136,16 +119,35 @@ const isIgnoredFile = (folderPath, file, ignorePatterns) => {
136
119
  }
137
120
  return isIgnored;
138
121
  };
139
- const readGitignore = (folderPath) => {
122
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = "") => {
123
+ const arrayOfFiles = [];
124
+ const entries = await fse__namespace.readdir(path__namespace.join(dirPath, subfolder));
125
+ for (const entry of entries) {
126
+ const entryPathFromRoot = path__namespace.join(subfolder, entry);
127
+ const entryPath = path__namespace.relative(dirPath, entryPathFromRoot);
128
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
129
+ if (!isIgnored) {
130
+ if (fse__namespace.statSync(entryPath).isDirectory()) {
131
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
132
+ arrayOfFiles.push(...subFiles);
133
+ } else {
134
+ arrayOfFiles.push(entryPath);
135
+ }
136
+ }
137
+ }
138
+ return arrayOfFiles;
139
+ };
140
+ const readGitignore = async (folderPath) => {
140
141
  const gitignorePath = path__namespace.resolve(folderPath, ".gitignore");
141
- if (!fs__namespace.existsSync(gitignorePath))
142
+ const pathExist = await fse__namespace.pathExists(gitignorePath);
143
+ if (!pathExist)
142
144
  return [];
143
- const gitignoreContent = fs__namespace.readFileSync(gitignorePath, "utf8");
145
+ const gitignoreContent = await fse__namespace.readFile(gitignorePath, "utf8");
144
146
  return gitignoreContent.split(/\r?\n/).filter((line) => Boolean(line.trim()) && !line.startsWith("#"));
145
147
  };
146
148
  const compressFilesToTar = async (storagePath, folderToCompress, filename) => {
147
- const ignorePatterns = readGitignore(folderToCompress);
148
- const filesToCompress = getFiles(folderToCompress, ignorePatterns);
149
+ const ignorePatterns = await readGitignore(folderToCompress);
150
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
149
151
  return tar__namespace.c(
150
152
  {
151
153
  gzip: true,
@@ -158,7 +160,7 @@ const APP_FOLDER_NAME = "com.strapi.cli";
158
160
  const CONFIG_FILENAME = "config.json";
159
161
  async function checkDirectoryExists(directoryPath) {
160
162
  try {
161
- const fsStat = await fse__default.default.lstat(directoryPath);
163
+ const fsStat = await fse__namespace.default.lstat(directoryPath);
162
164
  return fsStat.isDirectory();
163
165
  } catch (e) {
164
166
  return false;
@@ -166,24 +168,24 @@ async function checkDirectoryExists(directoryPath) {
166
168
  }
167
169
  async function getTmpStoragePath() {
168
170
  const storagePath = path__namespace.default.join(os__default.default.tmpdir(), APP_FOLDER_NAME);
169
- await fse__default.default.ensureDir(storagePath);
171
+ await fse__namespace.default.ensureDir(storagePath);
170
172
  return storagePath;
171
173
  }
172
174
  async function getConfigPath() {
173
175
  const configDirs = XDGAppPaths__default.default(APP_FOLDER_NAME).configDirs();
174
176
  const configPath = configDirs.find(checkDirectoryExists);
175
177
  if (!configPath) {
176
- await fse__default.default.ensureDir(configDirs[0]);
178
+ await fse__namespace.default.ensureDir(configDirs[0]);
177
179
  return configDirs[0];
178
180
  }
179
181
  return configPath;
180
182
  }
181
- async function getLocalConfig() {
183
+ async function getLocalConfig$1() {
182
184
  const configPath = await getConfigPath();
183
185
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
184
- await fse__default.default.ensureFile(configFilePath);
186
+ await fse__namespace.default.ensureFile(configFilePath);
185
187
  try {
186
- return await fse__default.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
188
+ return await fse__namespace.default.readJSON(configFilePath, { encoding: "utf8", throws: true });
187
189
  } catch (e) {
188
190
  return {};
189
191
  }
@@ -191,10 +193,10 @@ async function getLocalConfig() {
191
193
  async function saveLocalConfig(data) {
192
194
  const configPath = await getConfigPath();
193
195
  const configFilePath = path__namespace.default.join(configPath, CONFIG_FILENAME);
194
- await fse__default.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
196
+ await fse__namespace.default.writeJson(configFilePath, data, { encoding: "utf8", spaces: 2, mode: 384 });
195
197
  }
196
198
  const name = "@strapi/cloud-cli";
197
- const version = "4.25.0";
199
+ const version = "5.4.0";
198
200
  const description = "Commands to interact with the Strapi Cloud";
199
201
  const keywords = [
200
202
  "strapi",
@@ -235,17 +237,19 @@ const scripts = {
235
237
  build: "pack-up build",
236
238
  clean: "run -T rimraf ./dist",
237
239
  lint: "run -T eslint .",
240
+ "test:unit": "run -T jest",
238
241
  watch: "pack-up watch"
239
242
  };
240
243
  const dependencies = {
241
- "@strapi/utils": "4.25.0",
242
- axios: "1.6.0",
244
+ "@strapi/utils": "5.4.0",
245
+ axios: "1.7.4",
246
+ boxen: "5.1.2",
243
247
  chalk: "4.1.2",
244
248
  "cli-progress": "3.12.0",
245
249
  commander: "8.3.0",
246
250
  eventsource: "2.0.2",
247
251
  "fast-safe-stringify": "2.1.1",
248
- "fs-extra": "10.0.0",
252
+ "fs-extra": "11.2.0",
249
253
  inquirer: "8.2.5",
250
254
  jsonwebtoken: "9.0.0",
251
255
  "jwks-rsa": "3.1.0",
@@ -254,7 +258,7 @@ const dependencies = {
254
258
  open: "8.4.0",
255
259
  ora: "5.4.1",
256
260
  "pkg-up": "3.1.0",
257
- tar: "6.1.13",
261
+ tar: "6.2.1",
258
262
  "xdg-app-paths": "8.3.0",
259
263
  yup: "0.32.9"
260
264
  };
@@ -263,13 +267,14 @@ const devDependencies = {
263
267
  "@types/cli-progress": "3.11.5",
264
268
  "@types/eventsource": "1.1.15",
265
269
  "@types/lodash": "^4.14.191",
266
- "eslint-config-custom": "4.25.0",
267
- tsconfig: "4.25.0"
270
+ "eslint-config-custom": "5.4.0",
271
+ tsconfig: "5.4.0"
268
272
  };
269
273
  const engines = {
270
- node: ">=18.0.0 <=20.x.x",
274
+ node: ">=18.0.0 <=22.x.x",
271
275
  npm: ">=6.0.0"
272
276
  };
277
+ const gitHead = "7d785703f52464577d077c4618cbe68b44f8a9cd";
273
278
  const packageJson = {
274
279
  name,
275
280
  version,
@@ -290,11 +295,12 @@ const packageJson = {
290
295
  scripts,
291
296
  dependencies,
292
297
  devDependencies,
293
- engines
298
+ engines,
299
+ gitHead
294
300
  };
295
301
  const VERSION = "v1";
296
- async function cloudApiFactory(token) {
297
- const localConfig = await getLocalConfig();
302
+ async function cloudApiFactory({ logger }, token) {
303
+ const localConfig = await getLocalConfig$1();
298
304
  const customHeaders = {
299
305
  "x-device-id": localConfig.deviceId,
300
306
  "x-app-version": packageJson.version,
@@ -317,7 +323,7 @@ async function cloudApiFactory(token) {
317
323
  deploy({ filePath, project }, { onUploadProgress }) {
318
324
  return axiosCloudAPI.post(
319
325
  `/deploy/${project.name}`,
320
- { file: fse__default.default.createReadStream(filePath) },
326
+ { file: fse__namespace.default.createReadStream(filePath), targetEnvironment: project.targetEnvironment },
321
327
  {
322
328
  headers: {
323
329
  "Content-Type": "multipart/form-data"
@@ -346,11 +352,89 @@ async function cloudApiFactory(token) {
346
352
  getUserInfo() {
347
353
  return axiosCloudAPI.get("/user");
348
354
  },
349
- config() {
350
- return axiosCloudAPI.get("/config");
355
+ async config() {
356
+ try {
357
+ const response = await axiosCloudAPI.get("/config");
358
+ if (response.status !== 200) {
359
+ throw new Error("Error fetching cloud CLI config from the server.");
360
+ }
361
+ return response;
362
+ } catch (error) {
363
+ logger.debug(
364
+ "🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again."
365
+ );
366
+ throw error;
367
+ }
368
+ },
369
+ async listProjects() {
370
+ try {
371
+ const response = await axiosCloudAPI.get("/projects");
372
+ if (response.status !== 200) {
373
+ throw new Error("Error fetching cloud projects from the server.");
374
+ }
375
+ return response;
376
+ } catch (error) {
377
+ logger.debug(
378
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
379
+ );
380
+ throw error;
381
+ }
382
+ },
383
+ async listLinkProjects() {
384
+ try {
385
+ const response = await axiosCloudAPI.get("/projects-linkable");
386
+ if (response.status !== 200) {
387
+ throw new Error("Error fetching cloud projects from the server.");
388
+ }
389
+ return response;
390
+ } catch (error) {
391
+ logger.debug(
392
+ "🥲 Oops! Couldn't retrieve your project's list from the server. Please try again."
393
+ );
394
+ throw error;
395
+ }
396
+ },
397
+ async listEnvironments({ name: name2 }) {
398
+ try {
399
+ const response = await axiosCloudAPI.get(`/projects/${name2}/environments`);
400
+ if (response.status !== 200) {
401
+ throw new Error("Error fetching cloud environments from the server.");
402
+ }
403
+ return response;
404
+ } catch (error) {
405
+ logger.debug(
406
+ "🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again."
407
+ );
408
+ throw error;
409
+ }
410
+ },
411
+ async listLinkEnvironments({ name: name2 }) {
412
+ try {
413
+ const response = await axiosCloudAPI.get(`/projects/${name2}/environments-linkable`);
414
+ if (response.status !== 200) {
415
+ throw new Error("Error fetching cloud environments from the server.");
416
+ }
417
+ return response;
418
+ } catch (error) {
419
+ logger.debug(
420
+ "🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again."
421
+ );
422
+ throw error;
423
+ }
351
424
  },
352
- listProjects() {
353
- return axiosCloudAPI.get("/projects");
425
+ async getProject({ name: name2 }) {
426
+ try {
427
+ const response = await axiosCloudAPI.get(`/projects/${name2}`);
428
+ if (response.status !== 200) {
429
+ throw new Error("Error fetching project's details.");
430
+ }
431
+ return response;
432
+ } catch (error) {
433
+ logger.debug(
434
+ "🥲 Oops! There was a problem retrieving your project's details. Please try again."
435
+ );
436
+ throw error;
437
+ }
354
438
  },
355
439
  track(event, payload = {}) {
356
440
  return axiosCloudAPI.post("/track", {
@@ -361,34 +445,51 @@ async function cloudApiFactory(token) {
361
445
  };
362
446
  }
363
447
  const LOCAL_SAVE_FILENAME = ".strapi-cloud.json";
448
+ const getFilePath = (directoryPath) => path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
364
449
  async function save(data, { directoryPath } = {}) {
365
- const alreadyInFileData = await retrieve({ directoryPath });
366
- const storedData = { ...alreadyInFileData, ...data };
367
- const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
368
- await fse__default.default.ensureDir(path__namespace.default.dirname(pathToFile));
369
- await fse__default.default.writeJson(pathToFile, storedData, { encoding: "utf8" });
450
+ const pathToFile = getFilePath(directoryPath);
451
+ await fse__namespace.default.ensureDir(path__namespace.default.dirname(pathToFile));
452
+ await fse__namespace.default.writeJson(pathToFile, data, { encoding: "utf8" });
370
453
  }
371
454
  async function retrieve({
372
455
  directoryPath
373
456
  } = {}) {
374
- const pathToFile = path__namespace.default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
375
- const pathExists = await fse__default.default.pathExists(pathToFile);
457
+ const pathToFile = getFilePath(directoryPath);
458
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
376
459
  if (!pathExists) {
377
460
  return {};
378
461
  }
379
- return fse__default.default.readJSON(pathToFile, { encoding: "utf8" });
462
+ return fse__namespace.default.readJSON(pathToFile, { encoding: "utf8" });
463
+ }
464
+ async function patch(patchData, { directoryPath } = {}) {
465
+ const pathToFile = getFilePath(directoryPath);
466
+ const existingData = await retrieve({ directoryPath });
467
+ if (!existingData) {
468
+ throw new Error("No configuration data found to patch.");
469
+ }
470
+ const newData = lodash.merge(existingData, patchData);
471
+ await fse__namespace.default.writeJson(pathToFile, newData, { encoding: "utf8" });
472
+ }
473
+ async function deleteConfig({ directoryPath } = {}) {
474
+ const pathToFile = getFilePath(directoryPath);
475
+ const pathExists = await fse__namespace.default.pathExists(pathToFile);
476
+ if (pathExists) {
477
+ await fse__namespace.default.remove(pathToFile);
478
+ }
380
479
  }
381
480
  const strapiInfoSave = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
382
481
  __proto__: null,
383
482
  LOCAL_SAVE_FILENAME,
483
+ deleteConfig,
484
+ patch,
384
485
  retrieve,
385
486
  save
386
487
  }, Symbol.toStringTag, { value: "Module" }));
387
488
  let cliConfig;
388
489
  async function tokenServiceFactory({ logger }) {
389
- const cloudApiService = await cloudApiFactory();
490
+ const cloudApiService = await cloudApiFactory({ logger });
390
491
  async function saveToken(str) {
391
- const appConfig = await getLocalConfig();
492
+ const appConfig = await getLocalConfig$1();
392
493
  if (!appConfig) {
393
494
  logger.error("There was a problem saving your token. Please try again.");
394
495
  return;
@@ -402,7 +503,7 @@ async function tokenServiceFactory({ logger }) {
402
503
  }
403
504
  }
404
505
  async function retrieveToken() {
405
- const appConfig = await getLocalConfig();
506
+ const appConfig = await getLocalConfig$1();
406
507
  if (appConfig.token) {
407
508
  if (await isTokenValid(appConfig.token)) {
408
509
  return appConfig.token;
@@ -435,14 +536,17 @@ async function tokenServiceFactory({ logger }) {
435
536
  "There seems to be a problem with your login information. Please try logging in again."
436
537
  );
437
538
  }
539
+ return Promise.reject(new Error("Invalid token"));
438
540
  }
439
541
  return new Promise((resolve, reject) => {
440
542
  jwt__default.default.verify(idToken, getKey, (err) => {
441
543
  if (err) {
442
544
  reject(err);
443
- } else {
444
- resolve();
445
545
  }
546
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1e3)) {
547
+ reject(new Error("Token is expired"));
548
+ }
549
+ resolve();
446
550
  });
447
551
  });
448
552
  }
@@ -461,7 +565,7 @@ async function tokenServiceFactory({ logger }) {
461
565
  }
462
566
  }
463
567
  async function eraseToken() {
464
- const appConfig = await getLocalConfig();
568
+ const appConfig = await getLocalConfig$1();
465
569
  if (!appConfig) {
466
570
  return;
467
571
  }
@@ -476,15 +580,15 @@ async function tokenServiceFactory({ logger }) {
476
580
  throw e;
477
581
  }
478
582
  }
479
- async function getValidToken() {
480
- const token = await retrieveToken();
481
- if (!token) {
482
- logger.log("No token found. Please login first.");
483
- return null;
484
- }
485
- if (!await isTokenValid(token)) {
486
- logger.log("Unable to proceed: Token is expired or not valid. Please login again.");
487
- return null;
583
+ async function getValidToken(ctx, loginAction2) {
584
+ let token = await retrieveToken();
585
+ while (!token || !await isTokenValid(token)) {
586
+ logger.log(
587
+ 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."
588
+ );
589
+ if (!await loginAction2(ctx))
590
+ return null;
591
+ token = await retrieveToken();
488
592
  }
489
593
  return token;
490
594
  }
@@ -618,17 +722,257 @@ const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.definePropert
618
722
  local: strapiInfoSave,
619
723
  tokenServiceFactory
620
724
  }, Symbol.toStringTag, { value: "Module" }));
621
- async function handleError(ctx, error) {
725
+ yup__namespace.object({
726
+ name: yup__namespace.string().required(),
727
+ exports: yup__namespace.lazy(
728
+ (value) => yup__namespace.object(
729
+ typeof value === "object" ? Object.entries(value).reduce(
730
+ (acc, [key, value2]) => {
731
+ if (typeof value2 === "object") {
732
+ acc[key] = yup__namespace.object({
733
+ types: yup__namespace.string().optional(),
734
+ source: yup__namespace.string().required(),
735
+ module: yup__namespace.string().optional(),
736
+ import: yup__namespace.string().required(),
737
+ require: yup__namespace.string().required(),
738
+ default: yup__namespace.string().required()
739
+ }).noUnknown(true);
740
+ } else {
741
+ acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
742
+ }
743
+ return acc;
744
+ },
745
+ {}
746
+ ) : void 0
747
+ ).optional()
748
+ )
749
+ });
750
+ const loadPkg = async ({ cwd, logger }) => {
751
+ const pkgPath = await pkgUp__default.default({ cwd });
752
+ if (!pkgPath) {
753
+ throw new Error("Could not find a package.json in the current directory");
754
+ }
755
+ const buffer = await fse__namespace.readFile(pkgPath);
756
+ const pkg = JSON.parse(buffer.toString());
757
+ logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
758
+ return pkg;
759
+ };
760
+ async function getProjectNameFromPackageJson(ctx) {
761
+ try {
762
+ const packageJson2 = await loadPkg(ctx);
763
+ return packageJson2.name || "my-strapi-project";
764
+ } catch (e) {
765
+ return "my-strapi-project";
766
+ }
767
+ }
768
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData) => {
769
+ try {
770
+ await cloudApiService.track(eventName, eventData);
771
+ } catch (e) {
772
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
773
+ }
774
+ };
775
+ const openModule$1 = import("open");
776
+ async function promptLogin(ctx) {
777
+ const response = await inquirer__default.default.prompt([
778
+ {
779
+ type: "confirm",
780
+ name: "login",
781
+ message: "Would you like to login?"
782
+ }
783
+ ]);
784
+ if (response.login) {
785
+ const loginSuccessful = await loginAction(ctx);
786
+ return loginSuccessful;
787
+ }
788
+ return false;
789
+ }
790
+ async function loginAction(ctx) {
791
+ const { logger } = ctx;
622
792
  const tokenService = await tokenServiceFactory(ctx);
793
+ const existingToken = await tokenService.retrieveToken();
794
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || void 0);
795
+ if (existingToken) {
796
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
797
+ if (isTokenValid) {
798
+ try {
799
+ const userInfo = await cloudApiService.getUserInfo();
800
+ const { email } = userInfo.data.data;
801
+ if (email) {
802
+ logger.log(`You are already logged into your account (${email}).`);
803
+ } else {
804
+ logger.log("You are already logged in.");
805
+ }
806
+ logger.log(
807
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
808
+ );
809
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
810
+ return true;
811
+ } catch (e) {
812
+ logger.debug("Failed to fetch user info", e);
813
+ }
814
+ }
815
+ }
816
+ let cliConfig2;
817
+ try {
818
+ logger.info("🔌 Connecting to the Strapi Cloud API...");
819
+ const config = await cloudApiService.config();
820
+ cliConfig2 = config.data;
821
+ } catch (e) {
822
+ logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
823
+ logger.debug(e);
824
+ return false;
825
+ }
826
+ await trackEvent(ctx, cloudApiService, "willLoginAttempt", {});
827
+ logger.debug("🔐 Creating device authentication request...", {
828
+ client_id: cliConfig2.clientId,
829
+ scope: cliConfig2.scope,
830
+ audience: cliConfig2.audience
831
+ });
832
+ const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
833
+ client_id: cliConfig2.clientId,
834
+ scope: cliConfig2.scope,
835
+ audience: cliConfig2.audience
836
+ }).catch((e) => {
837
+ logger.error("There was an issue with the authentication process. Please try again.");
838
+ if (e.message) {
839
+ logger.debug(e.message, e);
840
+ } else {
841
+ logger.debug(e);
842
+ }
843
+ });
844
+ openModule$1.then((open) => {
845
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
846
+ logger.error("We encountered an issue opening the browser. Please try again later.");
847
+ logger.debug(e.message, e);
848
+ });
849
+ });
850
+ logger.log("If a browser tab does not open automatically, please follow the next steps:");
851
+ logger.log(
852
+ `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
853
+ );
854
+ logger.log(
855
+ `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
856
+ `
857
+ );
858
+ const tokenPayload = {
859
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
860
+ device_code: deviceAuthResponse.data.device_code,
861
+ client_id: cliConfig2.clientId
862
+ };
863
+ let isAuthenticated = false;
864
+ const authenticate = async () => {
865
+ const spinner = logger.spinner("Waiting for authentication");
866
+ spinner.start();
867
+ const spinnerFail = () => spinner.fail("Authentication failed!");
868
+ while (!isAuthenticated) {
869
+ try {
870
+ const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
871
+ const authTokenData = tokenResponse.data;
872
+ if (tokenResponse.status === 200) {
873
+ try {
874
+ logger.debug("🔐 Validating token...");
875
+ await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
876
+ logger.debug("🔐 Token validation successful!");
877
+ } catch (e) {
878
+ logger.debug(e);
879
+ spinnerFail();
880
+ throw new Error("Unable to proceed: Token validation failed");
881
+ }
882
+ logger.debug("🔍 Fetching user information...");
883
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
884
+ await cloudApiServiceWithToken.getUserInfo();
885
+ logger.debug("🔍 User information fetched successfully!");
886
+ try {
887
+ logger.debug("📝 Saving login information...");
888
+ await tokenService.saveToken(authTokenData.access_token);
889
+ logger.debug("📝 Login information saved successfully!");
890
+ isAuthenticated = true;
891
+ } catch (e) {
892
+ logger.error(
893
+ "There was a problem saving your login information. Please try logging in again."
894
+ );
895
+ logger.debug(e);
896
+ spinnerFail();
897
+ return false;
898
+ }
899
+ }
900
+ } catch (e) {
901
+ if (e.message === "Unable to proceed: Token validation failed") {
902
+ logger.error(
903
+ "There seems to be a problem with your login information. Please try logging in again."
904
+ );
905
+ spinnerFail();
906
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
907
+ return false;
908
+ }
909
+ if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
910
+ logger.debug(e);
911
+ spinnerFail();
912
+ await trackEvent(ctx, cloudApiService, "didNotLogin", { loginMethod: "cli" });
913
+ return false;
914
+ }
915
+ await new Promise((resolve) => {
916
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
917
+ });
918
+ }
919
+ }
920
+ spinner.succeed("Authentication successful!");
921
+ logger.log("You are now logged into Strapi Cloud.");
922
+ logger.log(
923
+ "To access your dashboard, please copy and paste the following URL into your web browser:"
924
+ );
925
+ logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
926
+ await trackEvent(ctx, cloudApiService, "didLogin", { loginMethod: "cli" });
927
+ };
928
+ await authenticate();
929
+ return isAuthenticated;
930
+ }
931
+ function questionDefaultValuesMapper(questionsMap) {
932
+ return (questions) => {
933
+ return questions.map((question) => {
934
+ const questionName = question.name;
935
+ if (questionName in questionsMap) {
936
+ const questionDefault = questionsMap[questionName];
937
+ if (typeof questionDefault === "function") {
938
+ return {
939
+ ...question,
940
+ default: questionDefault(question)
941
+ };
942
+ }
943
+ return {
944
+ ...question,
945
+ default: questionDefault
946
+ };
947
+ }
948
+ return question;
949
+ });
950
+ };
951
+ }
952
+ function getDefaultsFromQuestions(questions) {
953
+ return questions.reduce((acc, question) => {
954
+ if (question.default && question.name) {
955
+ return { ...acc, [question.name]: question.default };
956
+ }
957
+ return acc;
958
+ }, {});
959
+ }
960
+ function getProjectNodeVersionDefault(question) {
961
+ const currentNodeVersion = process.versions.node.split(".")[0];
962
+ if (question.type === "list" && Array.isArray(question.choices)) {
963
+ const choice = question.choices.find((choice2) => choice2.value === currentNodeVersion);
964
+ if (choice) {
965
+ return choice.value;
966
+ }
967
+ }
968
+ return question.default;
969
+ }
970
+ async function handleError(ctx, error) {
623
971
  const { logger } = ctx;
624
972
  logger.debug(error);
625
973
  if (error instanceof axios.AxiosError) {
626
974
  const errorMessage = typeof error.response?.data === "string" ? error.response.data : null;
627
975
  switch (error.response?.status) {
628
- case 401:
629
- logger.error("Your session has expired. Please log in again.");
630
- await tokenService.eraseToken();
631
- return;
632
976
  case 403:
633
977
  logger.error(
634
978
  errorMessage || "You do not have permission to create a project. Please contact support for assistance."
@@ -654,19 +998,8 @@ async function handleError(ctx, error) {
654
998
  "We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance."
655
999
  );
656
1000
  }
657
- const action$3 = async (ctx) => {
1001
+ async function createProject$1(ctx, cloudApi, projectInput) {
658
1002
  const { logger } = ctx;
659
- const { getValidToken } = await tokenServiceFactory(ctx);
660
- const token = await getValidToken();
661
- if (!token) {
662
- return;
663
- }
664
- const cloudApi = await cloudApiFactory(token);
665
- const { data: config } = await cloudApi.config();
666
- const { questions, defaults: defaultValues } = config.projectCreation;
667
- const projectAnswersDefaulted = fp.defaults(defaultValues);
668
- const projectAnswers = await inquirer__default.default.prompt(questions);
669
- const projectInput = projectAnswersDefaulted(projectAnswers);
670
1003
  const spinner = logger.spinner("Setting up your project...").start();
671
1004
  try {
672
1005
  const { data } = await cloudApi.createProject(projectInput);
@@ -674,13 +1007,49 @@ const action$3 = async (ctx) => {
674
1007
  spinner.succeed("Project created successfully!");
675
1008
  return data;
676
1009
  } catch (e) {
677
- spinner.fail("Failed to create project on Strapi Cloud.");
678
- await handleError(ctx, e);
1010
+ spinner.fail("An error occurred while creating the project on Strapi Cloud.");
1011
+ throw e;
679
1012
  }
680
- };
681
- function notificationServiceFactory({ logger }) {
682
- return (url, token, cliConfig2) => {
683
- const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
1013
+ }
1014
+ const action$6 = async (ctx) => {
1015
+ const { logger } = ctx;
1016
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
1017
+ const token = await getValidToken(ctx, promptLogin);
1018
+ if (!token) {
1019
+ return;
1020
+ }
1021
+ const cloudApi = await cloudApiFactory(ctx, token);
1022
+ const { data: config } = await cloudApi.config();
1023
+ const projectName = await getProjectNameFromPackageJson(ctx);
1024
+ const defaultAnswersMapper = questionDefaultValuesMapper({
1025
+ name: projectName,
1026
+ nodeVersion: getProjectNodeVersionDefault
1027
+ });
1028
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
1029
+ const defaultValues = {
1030
+ ...config.projectCreation.defaults,
1031
+ ...getDefaultsFromQuestions(questions)
1032
+ };
1033
+ const projectAnswersDefaulted = fp.defaults(defaultValues);
1034
+ const projectAnswers = await inquirer__default.default.prompt(questions);
1035
+ const projectInput = projectAnswersDefaulted(projectAnswers);
1036
+ try {
1037
+ return await createProject$1(ctx, cloudApi, projectInput);
1038
+ } catch (e) {
1039
+ if (e instanceof axios.AxiosError && e.response?.status === 401) {
1040
+ logger.warn("Oops! Your session has expired. Please log in again to retry.");
1041
+ await eraseToken();
1042
+ if (await promptLogin(ctx)) {
1043
+ return await createProject$1(ctx, cloudApi, projectInput);
1044
+ }
1045
+ } else {
1046
+ await handleError(ctx, e);
1047
+ }
1048
+ }
1049
+ };
1050
+ function notificationServiceFactory({ logger }) {
1051
+ return (url, token, cliConfig2) => {
1052
+ const CONN_TIMEOUT = Number(cliConfig2.notificationsConnectionTimeout);
684
1053
  const es = new EventSource__default.default(url, {
685
1054
  headers: {
686
1055
  Authorization: `Bearer ${token}`
@@ -709,38 +1078,6 @@ function notificationServiceFactory({ logger }) {
709
1078
  };
710
1079
  };
711
1080
  }
712
- yup__namespace.object({
713
- name: yup__namespace.string().required(),
714
- exports: yup__namespace.lazy(
715
- (value) => yup__namespace.object(
716
- typeof value === "object" ? Object.entries(value).reduce((acc, [key, value2]) => {
717
- if (typeof value2 === "object") {
718
- acc[key] = yup__namespace.object({
719
- types: yup__namespace.string().optional(),
720
- source: yup__namespace.string().required(),
721
- module: yup__namespace.string().optional(),
722
- import: yup__namespace.string().required(),
723
- require: yup__namespace.string().required(),
724
- default: yup__namespace.string().required()
725
- }).noUnknown(true);
726
- } else {
727
- acc[key] = yup__namespace.string().matches(/^\.\/.*\.json$/).required();
728
- }
729
- return acc;
730
- }, {}) : void 0
731
- ).optional()
732
- )
733
- });
734
- const loadPkg = async ({ cwd, logger }) => {
735
- const pkgPath = await pkgUp__default.default({ cwd });
736
- if (!pkgPath) {
737
- throw new Error("Could not find a package.json in the current directory");
738
- }
739
- const buffer = await fs__default.default.readFile(pkgPath);
740
- const pkg = JSON.parse(buffer.toString());
741
- logger.debug("Loaded package.json:", os__default.default.EOL, pkg);
742
- return pkg;
743
- };
744
1081
  const buildLogsServiceFactory = ({ logger }) => {
745
1082
  return async (url, token, cliConfig2) => {
746
1083
  const CONN_TIMEOUT = Number(cliConfig2.buildLogsConnectionTimeout);
@@ -794,6 +1131,7 @@ const buildLogsServiceFactory = ({ logger }) => {
794
1131
  if (retries > MAX_RETRIES) {
795
1132
  spinner.fail("We were unable to connect to the server to get build logs at this time.");
796
1133
  es.close();
1134
+ clearExistingTimeout();
797
1135
  reject(new Error("Max retries reached"));
798
1136
  }
799
1137
  };
@@ -802,8 +1140,31 @@ const buildLogsServiceFactory = ({ logger }) => {
802
1140
  });
803
1141
  };
804
1142
  };
1143
+ const boxenOptions = {
1144
+ padding: 1,
1145
+ margin: 1,
1146
+ align: "center",
1147
+ borderColor: "yellow",
1148
+ borderStyle: "round"
1149
+ };
1150
+ const QUIT_OPTION$2 = "Quit";
1151
+ async function promptForEnvironment(environments) {
1152
+ const choices = environments.map((env) => ({ name: env, value: env }));
1153
+ const { selectedEnvironment } = await inquirer__default.default.prompt([
1154
+ {
1155
+ type: "list",
1156
+ name: "selectedEnvironment",
1157
+ message: "Select the environment to deploy:",
1158
+ choices: [...choices, { name: chalk__default.default.grey(`(${QUIT_OPTION$2})`), value: null }]
1159
+ }
1160
+ ]);
1161
+ if (selectedEnvironment === null) {
1162
+ process.exit(1);
1163
+ }
1164
+ return selectedEnvironment;
1165
+ }
805
1166
  async function upload(ctx, project, token, maxProjectFileSize) {
806
- const cloudApi = await cloudApiFactory(token);
1167
+ const cloudApi = await cloudApiFactory(ctx, token);
807
1168
  try {
808
1169
  const storagePath = await getTmpStoragePath();
809
1170
  const projectFolder = path__namespace.default.resolve(process.cwd());
@@ -836,13 +1197,13 @@ async function upload(ctx, project, token, maxProjectFileSize) {
836
1197
  process.exit(1);
837
1198
  }
838
1199
  const tarFilePath = path__namespace.default.resolve(storagePath, compressedFilename);
839
- const fileStats = await fse__default.default.stat(tarFilePath);
1200
+ const fileStats = await fse__namespace.default.stat(tarFilePath);
840
1201
  if (fileStats.size > maxProjectFileSize) {
841
1202
  ctx.logger.log(
842
1203
  "Unable to proceed: Your project is too big to be transferred, please use a git repo instead."
843
1204
  );
844
1205
  try {
845
- await fse__default.default.remove(tarFilePath);
1206
+ await fse__namespace.default.remove(tarFilePath);
846
1207
  } catch (e) {
847
1208
  ctx.logger.log("Unable to remove file: ", tarFilePath);
848
1209
  ctx.logger.debug(e);
@@ -868,20 +1229,10 @@ async function upload(ctx, project, token, maxProjectFileSize) {
868
1229
  return data.build_id;
869
1230
  } catch (e) {
870
1231
  progressBar.stop();
871
- if (e instanceof axios.AxiosError && e.response?.data) {
872
- if (e.response.status === 404) {
873
- ctx.logger.error(
874
- `The project does not exist. Remove the ${LOCAL_SAVE_FILENAME} file and try again.`
875
- );
876
- } else {
877
- ctx.logger.error(e.response.data);
878
- }
879
- } else {
880
- ctx.logger.error("An error occurred while deploying the project. Please try again later.");
881
- }
1232
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
882
1233
  ctx.logger.debug(e);
883
1234
  } finally {
884
- await fse__default.default.remove(tarFilePath);
1235
+ await fse__namespace.default.remove(tarFilePath);
885
1236
  }
886
1237
  process.exit(0);
887
1238
  } catch (e) {
@@ -894,7 +1245,7 @@ async function getProject(ctx) {
894
1245
  const { project } = await retrieve();
895
1246
  if (!project) {
896
1247
  try {
897
- return await action$3(ctx);
1248
+ return await action$6(ctx);
898
1249
  } catch (e) {
899
1250
  ctx.logger.error("An error occurred while deploying the project. Please try again later.");
900
1251
  ctx.logger.debug(e);
@@ -903,10 +1254,47 @@ async function getProject(ctx) {
903
1254
  }
904
1255
  return project;
905
1256
  }
906
- const action$2 = async (ctx) => {
1257
+ async function getConfig({
1258
+ ctx,
1259
+ cloudApiService
1260
+ }) {
1261
+ try {
1262
+ const { data: cliConfig2 } = await cloudApiService.config();
1263
+ return cliConfig2;
1264
+ } catch (e) {
1265
+ ctx.logger.debug("Failed to get cli config", e);
1266
+ return null;
1267
+ }
1268
+ }
1269
+ function validateEnvironment(ctx, environment, environments) {
1270
+ if (!environments.includes(environment)) {
1271
+ ctx.logger.error(`Environment ${environment} does not exist.`);
1272
+ process.exit(1);
1273
+ }
1274
+ }
1275
+ async function getTargetEnvironment(ctx, opts, project, environments) {
1276
+ if (opts.env) {
1277
+ validateEnvironment(ctx, opts.env, environments);
1278
+ return opts.env;
1279
+ }
1280
+ if (project.targetEnvironment) {
1281
+ return project.targetEnvironment;
1282
+ }
1283
+ if (environments.length > 1) {
1284
+ return promptForEnvironment(environments);
1285
+ }
1286
+ return environments[0];
1287
+ }
1288
+ function hasPendingOrLiveDeployment(environments, targetEnvironment) {
1289
+ const environment = environments.find((env) => env.name === targetEnvironment);
1290
+ if (!environment) {
1291
+ throw new Error(`Environment details ${targetEnvironment} not found.`);
1292
+ }
1293
+ return environment.hasPendingDeployment || environment.hasLiveDeployment || false;
1294
+ }
1295
+ const action$5 = async (ctx, opts) => {
907
1296
  const { getValidToken } = await tokenServiceFactory(ctx);
908
- const cloudApiService = await cloudApiFactory();
909
- const token = await getValidToken();
1297
+ const token = await getValidToken(ctx, promptLogin);
910
1298
  if (!token) {
911
1299
  return;
912
1300
  }
@@ -914,14 +1302,57 @@ const action$2 = async (ctx) => {
914
1302
  if (!project) {
915
1303
  return;
916
1304
  }
1305
+ const cloudApiService = await cloudApiFactory(ctx, token);
1306
+ let projectData;
1307
+ let environments;
1308
+ let environmentsDetails;
917
1309
  try {
918
- await cloudApiService.track("willDeployWithCLI", { projectInternalName: project.name });
1310
+ const {
1311
+ data: { data, metadata }
1312
+ } = await cloudApiService.getProject({ name: project.name });
1313
+ projectData = data;
1314
+ environments = projectData.environments;
1315
+ environmentsDetails = projectData.environmentsDetails;
1316
+ const isProjectSuspended = projectData.suspendedAt;
1317
+ if (isProjectSuspended) {
1318
+ ctx.logger.log(
1319
+ "\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: "
1320
+ );
1321
+ ctx.logger.log(chalk__default.default.underline(`${metadata.dashboardUrls.project}`));
1322
+ return;
1323
+ }
919
1324
  } catch (e) {
920
- ctx.logger.debug("Failed to track willDeploy", e);
1325
+ if (e instanceof axios.AxiosError && e.response?.data) {
1326
+ if (e.response.status === 404) {
1327
+ ctx.logger.warn(
1328
+ `The project associated with this folder does not exist in Strapi Cloud.
1329
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1330
+ "link"
1331
+ )} command before deploying.`
1332
+ );
1333
+ } else {
1334
+ ctx.logger.error(e.response.data);
1335
+ }
1336
+ } else {
1337
+ ctx.logger.error(
1338
+ "An error occurred while retrieving the project's information. Please try again later."
1339
+ );
1340
+ }
1341
+ ctx.logger.debug(e);
1342
+ return;
921
1343
  }
1344
+ await trackEvent(ctx, cloudApiService, "willDeployWithCLI", {
1345
+ projectInternalName: project.name
1346
+ });
922
1347
  const notificationService = notificationServiceFactory(ctx);
923
1348
  const buildLogsService = buildLogsServiceFactory(ctx);
924
- const { data: cliConfig2 } = await cloudApiService.config();
1349
+ const cliConfig2 = await getConfig({ ctx, cloudApiService });
1350
+ if (!cliConfig2) {
1351
+ ctx.logger.error(
1352
+ "An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later."
1353
+ );
1354
+ return;
1355
+ }
925
1356
  let maxSize = parseInt(cliConfig2.maxProjectFileSize, 10);
926
1357
  if (Number.isNaN(maxSize)) {
927
1358
  ctx.logger.debug(
@@ -929,11 +1360,34 @@ const action$2 = async (ctx) => {
929
1360
  );
930
1361
  maxSize = 1e8;
931
1362
  }
1363
+ project.targetEnvironment = await getTargetEnvironment(ctx, opts, project, environments);
1364
+ if (!opts.force) {
1365
+ const shouldDisplayWarning = hasPendingOrLiveDeployment(
1366
+ environmentsDetails,
1367
+ project.targetEnvironment
1368
+ );
1369
+ if (shouldDisplayWarning) {
1370
+ ctx.logger.log(boxen__default.default(cliConfig2.projectDeployment.confirmationText, boxenOptions));
1371
+ const { confirm } = await inquirer__default.default.prompt([
1372
+ {
1373
+ type: "confirm",
1374
+ name: "confirm",
1375
+ message: `Do you want to proceed with deployment to ${chalk__default.default.cyan(projectData.displayName)} on ${chalk__default.default.cyan(project.targetEnvironment)} environment?`
1376
+ }
1377
+ ]);
1378
+ if (!confirm) {
1379
+ process.exit(1);
1380
+ }
1381
+ }
1382
+ }
932
1383
  const buildId = await upload(ctx, project, token, maxSize);
933
1384
  if (!buildId) {
934
1385
  return;
935
1386
  }
936
1387
  try {
1388
+ ctx.logger.log(
1389
+ `🚀 Deploying project to ${chalk__default.default.cyan(project.targetEnvironment ?? `production`)} environment...`
1390
+ );
937
1391
  notificationService(`${apiConfig.apiBaseUrl}/notifications`, token, cliConfig2);
938
1392
  await buildLogsService(`${apiConfig.apiBaseUrl}/v1/logs/${buildId}`, token, cliConfig2);
939
1393
  ctx.logger.log(
@@ -943,10 +1397,11 @@ const action$2 = async (ctx) => {
943
1397
  chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`)
944
1398
  );
945
1399
  } catch (e) {
1400
+ ctx.logger.debug(e);
946
1401
  if (e instanceof Error) {
947
1402
  ctx.logger.error(e.message);
948
1403
  } else {
949
- throw e;
1404
+ ctx.logger.error("An error occurred while deploying the project. Please try again later.");
950
1405
  }
951
1406
  }
952
1407
  };
@@ -977,185 +1432,191 @@ const runAction = (name2, action2) => (...args) => {
977
1432
  process.exit(1);
978
1433
  });
979
1434
  };
980
- const command$3 = ({ command: command2, ctx }) => {
981
- 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));
1435
+ const command$7 = ({ ctx }) => {
1436
+ 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("-f, --force", "Skip confirmation to deploy").option("-e, --env <name>", "Specify the environment to deploy").action((opts) => runAction("deploy", action$5)(ctx, opts));
982
1437
  };
983
1438
  const deployProject = {
984
1439
  name: "deploy-project",
985
1440
  description: "Deploy a Strapi Cloud project",
986
- action: action$2,
987
- command: command$3
1441
+ action: action$5,
1442
+ command: command$7
988
1443
  };
989
- const openModule = import("open");
990
- const action$1 = async (ctx) => {
991
- const { logger } = ctx;
992
- const tokenService = await tokenServiceFactory(ctx);
993
- const existingToken = await tokenService.retrieveToken();
994
- const cloudApiService = await cloudApiFactory(existingToken || void 0);
995
- const trackFailedLogin = async () => {
996
- try {
997
- await cloudApiService.track("didNotLogin", { loginMethod: "cli" });
998
- } catch (e) {
999
- logger.debug("Failed to track failed login", e);
1000
- }
1001
- };
1002
- if (existingToken) {
1003
- const isTokenValid = await tokenService.isTokenValid(existingToken);
1004
- if (isTokenValid) {
1005
- try {
1006
- const userInfo = await cloudApiService.getUserInfo();
1007
- const { email } = userInfo.data.data;
1008
- if (email) {
1009
- logger.log(`You are already logged into your account (${email}).`);
1010
- } else {
1011
- logger.log("You are already logged in.");
1012
- }
1013
- logger.log(
1014
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1015
- );
1016
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1017
- return true;
1018
- } catch (e) {
1019
- logger.debug("Failed to fetch user info", e);
1444
+ async function getLocalConfig(ctx) {
1445
+ try {
1446
+ return await retrieve();
1447
+ } catch (e) {
1448
+ ctx.logger.debug("Failed to get project config", e);
1449
+ ctx.logger.error("An error occurred while retrieving config data from your local project.");
1450
+ return null;
1451
+ }
1452
+ }
1453
+ async function getLocalProject(ctx) {
1454
+ const localConfig = await getLocalConfig(ctx);
1455
+ if (!localConfig || !localConfig.project) {
1456
+ ctx.logger.warn(
1457
+ `
1458
+ We couldn't find a valid local project config.
1459
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1460
+ "link"
1461
+ )} command.`
1462
+ );
1463
+ process.exit(1);
1464
+ }
1465
+ return localConfig.project;
1466
+ }
1467
+ const QUIT_OPTION$1 = "Quit";
1468
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1469
+ if (existingConfig && existingConfig.project) {
1470
+ const { shouldRelink } = await inquirer__default.default.prompt([
1471
+ {
1472
+ type: "confirm",
1473
+ name: "shouldRelink",
1474
+ message: `A project named ${chalk__default.default.cyan(
1475
+ existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name
1476
+ )} is already linked to this local folder. Do you want to update the link?`,
1477
+ default: false
1020
1478
  }
1479
+ ]);
1480
+ if (!shouldRelink) {
1481
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1482
+ currentProjectName: existingConfig.project?.name
1483
+ });
1484
+ return false;
1021
1485
  }
1022
1486
  }
1023
- let cliConfig2;
1487
+ return true;
1488
+ }
1489
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1490
+ const spinner = ctx.logger.spinner("Fetching your projects...\n").start();
1024
1491
  try {
1025
- logger.info("🔌 Connecting to the Strapi Cloud API...");
1026
- const config = await cloudApiService.config();
1027
- cliConfig2 = config.data;
1492
+ const {
1493
+ data: { data: projectList }
1494
+ } = await cloudApiService.listLinkProjects();
1495
+ spinner.succeed();
1496
+ if (!Array.isArray(projectList)) {
1497
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud.");
1498
+ return null;
1499
+ }
1500
+ const projects = projectList.filter(
1501
+ (project) => !(project.isMaintainer || project.name === existingConfig?.project?.name)
1502
+ ).map((project) => {
1503
+ return {
1504
+ name: project.displayName,
1505
+ value: { name: project.name, displayName: project.displayName }
1506
+ };
1507
+ });
1508
+ if (projects.length === 0) {
1509
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud.");
1510
+ return null;
1511
+ }
1512
+ return projects;
1028
1513
  } catch (e) {
1029
- logger.error("🥲 Oops! Something went wrong while logging you in. Please try again.");
1030
- logger.debug(e);
1031
- return false;
1514
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1515
+ ctx.logger.debug("Failed to list projects", e);
1516
+ return null;
1032
1517
  }
1518
+ }
1519
+ async function getUserSelection(ctx, projects) {
1520
+ const { logger } = ctx;
1033
1521
  try {
1034
- await cloudApiService.track("willLoginAttempt", {});
1522
+ const answer = await inquirer__default.default.prompt([
1523
+ {
1524
+ type: "list",
1525
+ name: "linkProject",
1526
+ message: "Which project do you want to link?",
1527
+ choices: [...projects, { name: chalk__default.default.grey(`(${QUIT_OPTION$1})`), value: null }]
1528
+ }
1529
+ ]);
1530
+ if (!answer.linkProject) {
1531
+ return null;
1532
+ }
1533
+ return answer;
1035
1534
  } catch (e) {
1036
- logger.debug("Failed to track login attempt", e);
1535
+ logger.debug("Failed to get user input", e);
1536
+ logger.error("An error occurred while trying to get your input.");
1537
+ return null;
1037
1538
  }
1038
- logger.debug("🔐 Creating device authentication request...", {
1039
- client_id: cliConfig2.clientId,
1040
- scope: cliConfig2.scope,
1041
- audience: cliConfig2.audience
1042
- });
1043
- const deviceAuthResponse = await axios__default.default.post(cliConfig2.deviceCodeAuthUrl, {
1044
- client_id: cliConfig2.clientId,
1045
- scope: cliConfig2.scope,
1046
- audience: cliConfig2.audience
1047
- }).catch((e) => {
1048
- logger.error("There was an issue with the authentication process. Please try again.");
1049
- if (e.message) {
1050
- logger.debug(e.message, e);
1051
- } else {
1052
- logger.debug(e);
1053
- }
1054
- });
1055
- openModule.then((open) => {
1056
- open.default(deviceAuthResponse.data.verification_uri_complete).catch((e) => {
1057
- logger.error("We encountered an issue opening the browser. Please try again later.");
1058
- logger.debug(e.message, e);
1059
- });
1060
- });
1061
- logger.log("If a browser tab does not open automatically, please follow the next steps:");
1062
- logger.log(
1063
- `1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`
1064
- );
1065
- logger.log(
1066
- `2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.
1067
- `
1539
+ }
1540
+ const action$4 = async (ctx) => {
1541
+ const { getValidToken } = await tokenServiceFactory(ctx);
1542
+ const token = await getValidToken(ctx, promptLogin);
1543
+ const { logger } = ctx;
1544
+ if (!token) {
1545
+ return;
1546
+ }
1547
+ const cloudApiService = await cloudApiFactory(ctx, token);
1548
+ const existingConfig = await getLocalConfig(ctx);
1549
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1550
+ if (!shouldRelink) {
1551
+ return;
1552
+ }
1553
+ await trackEvent(ctx, cloudApiService, "willLinkProject", {});
1554
+ const projects = await getProjectsList(
1555
+ ctx,
1556
+ cloudApiService,
1557
+ existingConfig
1068
1558
  );
1069
- const tokenPayload = {
1070
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1071
- device_code: deviceAuthResponse.data.device_code,
1072
- client_id: cliConfig2.clientId
1073
- };
1074
- let isAuthenticated = false;
1075
- const authenticate = async () => {
1076
- const spinner = logger.spinner("Waiting for authentication");
1077
- spinner.start();
1078
- const spinnerFail = () => spinner.fail("Authentication failed!");
1079
- while (!isAuthenticated) {
1080
- try {
1081
- const tokenResponse = await axios__default.default.post(cliConfig2.tokenUrl, tokenPayload);
1082
- const authTokenData = tokenResponse.data;
1083
- if (tokenResponse.status === 200) {
1084
- try {
1085
- logger.debug("🔐 Validating token...");
1086
- await tokenService.validateToken(authTokenData.id_token, cliConfig2.jwksUrl);
1087
- logger.debug("🔐 Token validation successful!");
1088
- } catch (e) {
1089
- logger.debug(e);
1090
- spinnerFail();
1091
- throw new Error("Unable to proceed: Token validation failed");
1092
- }
1093
- logger.debug("🔍 Fetching user information...");
1094
- const cloudApiServiceWithToken = await cloudApiFactory(authTokenData.access_token);
1095
- await cloudApiServiceWithToken.getUserInfo();
1096
- logger.debug("🔍 User information fetched successfully!");
1097
- try {
1098
- logger.debug("📝 Saving login information...");
1099
- await tokenService.saveToken(authTokenData.access_token);
1100
- logger.debug("📝 Login information saved successfully!");
1101
- isAuthenticated = true;
1102
- } catch (e) {
1103
- logger.error(
1104
- "There was a problem saving your login information. Please try logging in again."
1105
- );
1106
- logger.debug(e);
1107
- spinnerFail();
1108
- return false;
1109
- }
1110
- }
1111
- } catch (e) {
1112
- if (e.message === "Unable to proceed: Token validation failed") {
1113
- logger.error(
1114
- "There seems to be a problem with your login information. Please try logging in again."
1115
- );
1116
- spinnerFail();
1117
- await trackFailedLogin();
1118
- return false;
1119
- }
1120
- if (e.response?.data.error && !["authorization_pending", "slow_down"].includes(e.response.data.error)) {
1121
- logger.debug(e);
1122
- spinnerFail();
1123
- await trackFailedLogin();
1124
- return false;
1125
- }
1126
- await new Promise((resolve) => {
1127
- setTimeout(resolve, deviceAuthResponse.data.interval * 1e3);
1128
- });
1559
+ if (!projects) {
1560
+ return;
1561
+ }
1562
+ const answer = await getUserSelection(ctx, projects);
1563
+ if (!answer) {
1564
+ return;
1565
+ }
1566
+ try {
1567
+ const { confirmAction } = await inquirer__default.default.prompt([
1568
+ {
1569
+ type: "confirm",
1570
+ name: "confirmAction",
1571
+ message: "Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:",
1572
+ default: false
1129
1573
  }
1574
+ ]);
1575
+ if (!confirmAction) {
1576
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1577
+ cancelledProjectName: answer.linkProject.name,
1578
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1579
+ });
1580
+ return;
1130
1581
  }
1131
- spinner.succeed("Authentication successful!");
1132
- logger.log("You are now logged into Strapi Cloud.");
1582
+ await save({ project: answer.linkProject });
1133
1583
  logger.log(
1134
- "To access your dashboard, please copy and paste the following URL into your web browser:"
1584
+ ` You have successfully linked your project to ${chalk__default.default.cyan(answer.linkProject.displayName)}. You are now able to deploy your project.`
1135
1585
  );
1136
- logger.log(chalk__default.default.underline(`${apiConfig.dashboardBaseUrl}/projects`));
1137
- try {
1138
- await cloudApiService.track("didLogin", { loginMethod: "cli" });
1139
- } catch (e) {
1140
- logger.debug("Failed to track login", e);
1141
- }
1142
- };
1143
- await authenticate();
1144
- return isAuthenticated;
1586
+ await trackEvent(ctx, cloudApiService, "didLinkProject", {
1587
+ projectInternalName: answer.linkProject
1588
+ });
1589
+ } catch (e) {
1590
+ logger.debug("Failed to link project", e);
1591
+ logger.error("An error occurred while linking the project.");
1592
+ await trackEvent(ctx, cloudApiService, "didNotLinkProject", {
1593
+ projectInternalName: answer.linkProject
1594
+ });
1595
+ }
1145
1596
  };
1146
- const command$2 = ({ command: command2, ctx }) => {
1147
- command2.command("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1597
+ const command$6 = ({ command: command2, ctx }) => {
1598
+ 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$4)(ctx));
1599
+ };
1600
+ const link = {
1601
+ name: "link-project",
1602
+ description: "Link a local directory to a Strapi Cloud project",
1603
+ action: action$4,
1604
+ command: command$6
1605
+ };
1606
+ const command$5 = ({ ctx }) => {
1607
+ return commander.createCommand("cloud:login").alias("login").description("Strapi Cloud Login").addHelpText(
1148
1608
  "after",
1149
1609
  "\nAfter running this command, you will be prompted to enter your authentication information."
1150
- ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", action$1)(ctx));
1610
+ ).option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("login", loginAction)(ctx));
1151
1611
  };
1152
1612
  const login = {
1153
1613
  name: "login",
1154
1614
  description: "Strapi Cloud Login",
1155
- action: action$1,
1156
- command: command$2
1615
+ action: loginAction,
1616
+ command: command$5
1157
1617
  };
1158
- const action = async (ctx) => {
1618
+ const openModule = import("open");
1619
+ const action$3 = async (ctx) => {
1159
1620
  const { logger } = ctx;
1160
1621
  const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1161
1622
  const token = await retrieveToken();
@@ -1163,9 +1624,21 @@ const action = async (ctx) => {
1163
1624
  logger.log("You're already logged out.");
1164
1625
  return;
1165
1626
  }
1166
- const cloudApiService = await cloudApiFactory(token);
1627
+ const cloudApiService = await cloudApiFactory(ctx, token);
1628
+ const config = await cloudApiService.config();
1629
+ const cliConfig2 = config.data;
1167
1630
  try {
1168
1631
  await eraseToken();
1632
+ openModule.then((open) => {
1633
+ open.default(
1634
+ `${cliConfig2.baseUrl}/oidc/logout?client_id=${encodeURIComponent(
1635
+ cliConfig2.clientId
1636
+ )}&logout_hint=${encodeURIComponent(token)}
1637
+ `
1638
+ ).catch((e) => {
1639
+ logger.debug(e.message, e);
1640
+ });
1641
+ });
1169
1642
  logger.log(
1170
1643
  "🔌 You have been logged out from the CLI. If you are on a shared computer, please make sure to log out from the Strapi Cloud Dashboard as well."
1171
1644
  );
@@ -1173,39 +1646,258 @@ const action = async (ctx) => {
1173
1646
  logger.error("🥲 Oops! Something went wrong while logging you out. Please try again.");
1174
1647
  logger.debug(e);
1175
1648
  }
1176
- try {
1177
- await cloudApiService.track("didLogout", { loginMethod: "cli" });
1178
- } catch (e) {
1179
- logger.debug("Failed to track logout event", e);
1180
- }
1649
+ await trackEvent(ctx, cloudApiService, "didLogout", { loginMethod: "cli" });
1181
1650
  };
1182
- const command$1 = ({ command: command2, ctx }) => {
1183
- 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));
1651
+ const command$4 = ({ ctx }) => {
1652
+ 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$3)(ctx));
1184
1653
  };
1185
1654
  const logout = {
1186
1655
  name: "logout",
1187
1656
  description: "Strapi Cloud Logout",
1188
- action,
1189
- command: command$1
1657
+ action: action$3,
1658
+ command: command$4
1190
1659
  };
1191
- const command = ({ command: command2, ctx }) => {
1192
- 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));
1660
+ const command$3 = ({ ctx }) => {
1661
+ 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$6)(ctx));
1193
1662
  };
1194
1663
  const createProject = {
1195
1664
  name: "create-project",
1196
1665
  description: "Create a new project",
1197
- action: action$3,
1666
+ action: action$6,
1667
+ command: command$3
1668
+ };
1669
+ const action$2 = async (ctx) => {
1670
+ const { getValidToken } = await tokenServiceFactory(ctx);
1671
+ const token = await getValidToken(ctx, promptLogin);
1672
+ const { logger } = ctx;
1673
+ if (!token) {
1674
+ return;
1675
+ }
1676
+ const cloudApiService = await cloudApiFactory(ctx, token);
1677
+ const spinner = logger.spinner("Fetching your projects...").start();
1678
+ try {
1679
+ const {
1680
+ data: { data: projectList }
1681
+ } = await cloudApiService.listProjects();
1682
+ spinner.succeed();
1683
+ logger.log(projectList);
1684
+ } catch (e) {
1685
+ ctx.logger.debug("Failed to list projects", e);
1686
+ spinner.fail("An error occurred while fetching your projects from Strapi Cloud.");
1687
+ }
1688
+ };
1689
+ const command$2 = ({ command: command2, ctx }) => {
1690
+ 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$2)(ctx));
1691
+ };
1692
+ const listProjects = {
1693
+ name: "list-projects",
1694
+ description: "List Strapi Cloud projects",
1695
+ action: action$2,
1696
+ command: command$2
1697
+ };
1698
+ const action$1 = async (ctx) => {
1699
+ const { getValidToken } = await tokenServiceFactory(ctx);
1700
+ const token = await getValidToken(ctx, promptLogin);
1701
+ const { logger } = ctx;
1702
+ if (!token) {
1703
+ return;
1704
+ }
1705
+ const project = await getLocalProject(ctx);
1706
+ if (!project) {
1707
+ ctx.logger.debug(`No valid local project configuration was found.`);
1708
+ return;
1709
+ }
1710
+ const cloudApiService = await cloudApiFactory(ctx, token);
1711
+ const spinner = logger.spinner("Fetching environments...").start();
1712
+ await trackEvent(ctx, cloudApiService, "willListEnvironment", {
1713
+ projectInternalName: project.name
1714
+ });
1715
+ try {
1716
+ const {
1717
+ data: { data: environmentsList }
1718
+ } = await cloudApiService.listEnvironments({ name: project.name });
1719
+ spinner.succeed();
1720
+ logger.log(environmentsList);
1721
+ await trackEvent(ctx, cloudApiService, "didListEnvironment", {
1722
+ projectInternalName: project.name
1723
+ });
1724
+ } catch (e) {
1725
+ if (e.response && e.response.status === 404) {
1726
+ spinner.succeed();
1727
+ logger.warn(
1728
+ `
1729
+ The project associated with this folder does not exist in Strapi Cloud.
1730
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1731
+ "link"
1732
+ )} command`
1733
+ );
1734
+ } else {
1735
+ spinner.fail("An error occurred while fetching environments data from Strapi Cloud.");
1736
+ logger.debug("Failed to list environments", e);
1737
+ }
1738
+ await trackEvent(ctx, cloudApiService, "didNotListEnvironment", {
1739
+ projectInternalName: project.name
1740
+ });
1741
+ }
1742
+ };
1743
+ function defineCloudNamespace(command2, ctx) {
1744
+ const cloud = command2.command("cloud").description("Manage Strapi Cloud projects");
1745
+ cloud.command("environments").description("Alias for cloud environment list").action(() => runAction("list", action$1)(ctx));
1746
+ return cloud;
1747
+ }
1748
+ let environmentCmd = null;
1749
+ const initializeEnvironmentCommand = (command2, ctx) => {
1750
+ if (!environmentCmd) {
1751
+ const cloud = defineCloudNamespace(command2, ctx);
1752
+ environmentCmd = cloud.command("environment").description("Manage environments");
1753
+ }
1754
+ return environmentCmd;
1755
+ };
1756
+ const command$1 = ({ command: command2, ctx }) => {
1757
+ const environmentCmd2 = initializeEnvironmentCommand(command2, ctx);
1758
+ 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$1)(ctx));
1759
+ };
1760
+ const listEnvironments = {
1761
+ name: "list-environments",
1762
+ description: "List Strapi Cloud environments",
1763
+ action: action$1,
1764
+ command: command$1
1765
+ };
1766
+ const QUIT_OPTION = "Quit";
1767
+ const action = async (ctx) => {
1768
+ const { getValidToken } = await tokenServiceFactory(ctx);
1769
+ const token = await getValidToken(ctx, promptLogin);
1770
+ const { logger } = ctx;
1771
+ if (!token) {
1772
+ return;
1773
+ }
1774
+ const project = await getLocalProject(ctx);
1775
+ if (!project) {
1776
+ logger.debug(`No valid local project configuration was found.`);
1777
+ return;
1778
+ }
1779
+ const cloudApiService = await cloudApiFactory(ctx, token);
1780
+ const environments = await getEnvironmentsList(ctx, cloudApiService, project);
1781
+ if (!environments) {
1782
+ logger.debug(`Fetching environments failed.`);
1783
+ return;
1784
+ }
1785
+ if (environments.length === 0) {
1786
+ logger.log(
1787
+ `The only available environment is already linked. You can add a new one from your project settings on the Strapi Cloud dashboard.`
1788
+ );
1789
+ return;
1790
+ }
1791
+ const answer = await promptUserForEnvironment(ctx, environments);
1792
+ if (!answer) {
1793
+ return;
1794
+ }
1795
+ await trackEvent(ctx, cloudApiService, "willLinkEnvironment", {
1796
+ projectName: project.name,
1797
+ environmentName: answer.targetEnvironment
1798
+ });
1799
+ try {
1800
+ await patch({ project: { targetEnvironment: answer.targetEnvironment } });
1801
+ } catch (e) {
1802
+ await trackEvent(ctx, cloudApiService, "didNotLinkEnvironment", {
1803
+ projectName: project.name,
1804
+ environmentName: answer.targetEnvironment
1805
+ });
1806
+ logger.debug("Failed to link environment", e);
1807
+ logger.error(
1808
+ "Failed to link the environment. If this issue persists, try re-linking your project or contact support."
1809
+ );
1810
+ process.exit(1);
1811
+ }
1812
+ logger.log(
1813
+ ` You have successfully linked your project to ${chalk__default.default.cyan(answer.targetEnvironment)}, on ${chalk__default.default.cyan(project.displayName)}. You are now able to deploy your project.`
1814
+ );
1815
+ await trackEvent(ctx, cloudApiService, "didLinkEnvironment", {
1816
+ projectName: project.name,
1817
+ environmentName: answer.targetEnvironment
1818
+ });
1819
+ };
1820
+ async function promptUserForEnvironment(ctx, environments) {
1821
+ const { logger } = ctx;
1822
+ try {
1823
+ const answer = await inquirer__default.default.prompt([
1824
+ {
1825
+ type: "list",
1826
+ name: "targetEnvironment",
1827
+ message: "Which environment do you want to link?",
1828
+ choices: [...environments, { name: chalk__default.default.grey(`(${QUIT_OPTION})`), value: null }]
1829
+ }
1830
+ ]);
1831
+ if (!answer.targetEnvironment) {
1832
+ return null;
1833
+ }
1834
+ return answer;
1835
+ } catch (e) {
1836
+ logger.debug("Failed to get user input", e);
1837
+ logger.error("An error occurred while trying to get your environment selection.");
1838
+ return null;
1839
+ }
1840
+ }
1841
+ async function getEnvironmentsList(ctx, cloudApiService, project) {
1842
+ const spinner = ctx.logger.spinner("Fetching environments...\n").start();
1843
+ try {
1844
+ const {
1845
+ data: { data: environmentsList }
1846
+ } = await cloudApiService.listLinkEnvironments({ name: project.name });
1847
+ if (!Array.isArray(environmentsList) || environmentsList.length === 0) {
1848
+ throw new Error("Environments not found in server response");
1849
+ }
1850
+ spinner.succeed();
1851
+ return environmentsList.filter(
1852
+ (environment) => environment.name !== project.targetEnvironment
1853
+ );
1854
+ } catch (e) {
1855
+ if (e.response && e.response.status === 404) {
1856
+ spinner.succeed();
1857
+ ctx.logger.warn(
1858
+ `
1859
+ The project associated with this folder does not exist in Strapi Cloud.
1860
+ Please link your local project to an existing Strapi Cloud project using the ${chalk__default.default.cyan(
1861
+ "link"
1862
+ )} command.`
1863
+ );
1864
+ } else {
1865
+ spinner.fail("An error occurred while fetching environments data from Strapi Cloud.");
1866
+ ctx.logger.debug("Failed to list environments", e);
1867
+ }
1868
+ }
1869
+ }
1870
+ const command = ({ command: command2, ctx }) => {
1871
+ const environmentCmd2 = initializeEnvironmentCommand(command2, ctx);
1872
+ environmentCmd2.command("link").description("Link project to a specific Strapi Cloud project environment").option("-d, --debug", "Enable debugging mode with verbose logs").option("-s, --silent", "Don't log anything").action(() => runAction("link", action)(ctx));
1873
+ };
1874
+ const linkEnvironment = {
1875
+ name: "link-environment",
1876
+ description: "Link Strapi Cloud environment to a local project",
1877
+ action,
1198
1878
  command
1199
1879
  };
1200
1880
  const cli = {
1201
1881
  deployProject,
1882
+ link,
1202
1883
  login,
1203
1884
  logout,
1204
- createProject
1885
+ createProject,
1886
+ linkEnvironment,
1887
+ listProjects,
1888
+ listEnvironments
1205
1889
  };
1206
- const cloudCommands = [deployProject, login, logout];
1890
+ const cloudCommands = [
1891
+ deployProject,
1892
+ link,
1893
+ login,
1894
+ logout,
1895
+ linkEnvironment,
1896
+ listProjects,
1897
+ listEnvironments
1898
+ ];
1207
1899
  async function initCloudCLIConfig() {
1208
- const localConfig = await getLocalConfig();
1900
+ const localConfig = await getLocalConfig$1();
1209
1901
  if (!localConfig.deviceId) {
1210
1902
  localConfig.deviceId = crypto__default.default.randomUUID();
1211
1903
  }
@@ -1219,7 +1911,10 @@ async function buildStrapiCloudCommands({
1219
1911
  await initCloudCLIConfig();
1220
1912
  for (const cloudCommand of cloudCommands) {
1221
1913
  try {
1222
- await cloudCommand.command({ command: command2, ctx, argv });
1914
+ const subCommand = await cloudCommand.command({ command: command2, ctx, argv });
1915
+ if (subCommand) {
1916
+ command2.addCommand(subCommand);
1917
+ }
1223
1918
  } catch (e) {
1224
1919
  console.error(`Failed to load command ${cloudCommand.name}`, e);
1225
1920
  }