@strapi/cloud-cli 5.8.1 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1869 @@
1
+ import crypto$1 from 'crypto';
2
+ import * as fse from 'fs-extra';
3
+ import fse__default from 'fs-extra';
4
+ import inquirer from 'inquirer';
5
+ import boxen from 'boxen';
6
+ import * as path from 'path';
7
+ import path__default from 'path';
8
+ import chalk from 'chalk';
9
+ import axios, { AxiosError } from 'axios';
10
+ import * as crypto from 'node:crypto';
11
+ import { env } from '@strapi/utils';
12
+ import * as tar from 'tar';
13
+ import { minimatch } from 'minimatch';
14
+ import { defaults, has } from 'lodash/fp';
15
+ import os from 'os';
16
+ import XDGAppPaths from 'xdg-app-paths';
17
+ import { merge } from 'lodash';
18
+ import jwksClient from 'jwks-rsa';
19
+ import jwt from 'jsonwebtoken';
20
+ import stringify from 'fast-safe-stringify';
21
+ import ora from 'ora';
22
+ import * as cliProgress from 'cli-progress';
23
+ import pkgUp from 'pkg-up';
24
+ import * as yup from 'yup';
25
+ import EventSource from 'eventsource';
26
+ import { createCommand } from 'commander';
27
+
28
+ const apiConfig = {
29
+ apiBaseUrl: env('STRAPI_CLI_CLOUD_API', 'https://cloud-cli-api.strapi.io'),
30
+ dashboardBaseUrl: env('STRAPI_CLI_CLOUD_DASHBOARD', 'https://cloud.strapi.io')
31
+ };
32
+
33
+ const IGNORED_PATTERNS = [
34
+ '**/.git/**',
35
+ '**/node_modules/**',
36
+ '**/build/**',
37
+ '**/dist/**',
38
+ '**/.cache/**',
39
+ '**/.circleci/**',
40
+ '**/.github/**',
41
+ '**/.gitignore',
42
+ '**/.gitkeep',
43
+ '**/.gitlab-ci.yml',
44
+ '**/.idea/**',
45
+ '**/.vscode/**'
46
+ ];
47
+ const isIgnoredFile = (folderPath, file, ignorePatterns)=>{
48
+ ignorePatterns.push(...IGNORED_PATTERNS);
49
+ const relativeFilePath = path.join(folderPath, file);
50
+ let isIgnored = false;
51
+ for (const pattern of ignorePatterns){
52
+ if (pattern.startsWith('!')) {
53
+ if (minimatch(relativeFilePath, pattern.slice(1), {
54
+ matchBase: true,
55
+ dot: true
56
+ })) {
57
+ return false;
58
+ }
59
+ } else if (minimatch(relativeFilePath, pattern, {
60
+ matchBase: true,
61
+ dot: true
62
+ })) {
63
+ if (path.basename(file) !== '.gitkeep') {
64
+ isIgnored = true;
65
+ }
66
+ }
67
+ }
68
+ return isIgnored;
69
+ };
70
+ const getFiles = async (dirPath, ignorePatterns = [], subfolder = '')=>{
71
+ const arrayOfFiles = [];
72
+ const entries = await fse.readdir(path.join(dirPath, subfolder));
73
+ for (const entry of entries){
74
+ const entryPathFromRoot = path.join(subfolder, entry);
75
+ const entryPath = path.relative(dirPath, entryPathFromRoot);
76
+ const isIgnored = isIgnoredFile(dirPath, entryPathFromRoot, ignorePatterns);
77
+ if (!isIgnored) {
78
+ if (fse.statSync(entryPath).isDirectory()) {
79
+ const subFiles = await getFiles(dirPath, ignorePatterns, entryPathFromRoot);
80
+ arrayOfFiles.push(...subFiles);
81
+ } else {
82
+ arrayOfFiles.push(entryPath);
83
+ }
84
+ }
85
+ }
86
+ return arrayOfFiles;
87
+ };
88
+ const readGitignore = async (folderPath)=>{
89
+ const gitignorePath = path.resolve(folderPath, '.gitignore');
90
+ const pathExist = await fse.pathExists(gitignorePath);
91
+ if (!pathExist) return [];
92
+ const gitignoreContent = await fse.readFile(gitignorePath, 'utf8');
93
+ return gitignoreContent.split(/\r?\n/).filter((line)=>Boolean(line.trim()) && !line.startsWith('#'));
94
+ };
95
+ const compressFilesToTar = async (storagePath, folderToCompress, filename)=>{
96
+ const ignorePatterns = await readGitignore(folderToCompress);
97
+ const filesToCompress = await getFiles(folderToCompress, ignorePatterns);
98
+ return tar.c({
99
+ gzip: true,
100
+ file: path.resolve(storagePath, filename)
101
+ }, filesToCompress);
102
+ };
103
+
104
+ const APP_FOLDER_NAME = 'com.strapi.cli';
105
+ const CONFIG_FILENAME = 'config.json';
106
+ async function checkDirectoryExists(directoryPath) {
107
+ try {
108
+ const fsStat = await fse__default.lstat(directoryPath);
109
+ return fsStat.isDirectory();
110
+ } catch (e) {
111
+ return false;
112
+ }
113
+ }
114
+ // Determine storage path based on the operating system
115
+ async function getTmpStoragePath() {
116
+ const storagePath = path__default.join(os.tmpdir(), APP_FOLDER_NAME);
117
+ await fse__default.ensureDir(storagePath);
118
+ return storagePath;
119
+ }
120
+ async function getConfigPath() {
121
+ const configDirs = XDGAppPaths(APP_FOLDER_NAME).configDirs();
122
+ const configPath = configDirs.find(checkDirectoryExists);
123
+ if (!configPath) {
124
+ await fse__default.ensureDir(configDirs[0]);
125
+ return configDirs[0];
126
+ }
127
+ return configPath;
128
+ }
129
+ async function getLocalConfig$1() {
130
+ const configPath = await getConfigPath();
131
+ const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
132
+ await fse__default.ensureFile(configFilePath);
133
+ try {
134
+ return await fse__default.readJSON(configFilePath, {
135
+ encoding: 'utf8',
136
+ throws: true
137
+ });
138
+ } catch (e) {
139
+ return {};
140
+ }
141
+ }
142
+ async function saveLocalConfig(data) {
143
+ const configPath = await getConfigPath();
144
+ const configFilePath = path__default.join(configPath, CONFIG_FILENAME);
145
+ await fse__default.writeJson(configFilePath, data, {
146
+ encoding: 'utf8',
147
+ spaces: 2,
148
+ mode: 0o600
149
+ });
150
+ }
151
+
152
+ var name = "@strapi/cloud-cli";
153
+ var version = "5.9.0";
154
+ var description = "Commands to interact with the Strapi Cloud";
155
+ var keywords = [
156
+ "strapi",
157
+ "cloud",
158
+ "cli"
159
+ ];
160
+ var homepage = "https://strapi.io";
161
+ var bugs = {
162
+ url: "https://github.com/strapi/strapi/issues"
163
+ };
164
+ var repository = {
165
+ type: "git",
166
+ url: "git://github.com/strapi/strapi.git"
167
+ };
168
+ var license = "SEE LICENSE IN LICENSE";
169
+ var author = {
170
+ name: "Strapi Solutions SAS",
171
+ email: "hi@strapi.io",
172
+ url: "https://strapi.io"
173
+ };
174
+ var maintainers = [
175
+ {
176
+ name: "Strapi Solutions SAS",
177
+ email: "hi@strapi.io",
178
+ url: "https://strapi.io"
179
+ }
180
+ ];
181
+ var main = "./dist/index.js";
182
+ var module = "./dist/index.mjs";
183
+ var source = "./src/index.ts";
184
+ var types = "./dist/src/index.d.ts";
185
+ var bin = "./bin/index.js";
186
+ var files = [
187
+ "./dist",
188
+ "./bin"
189
+ ];
190
+ var scripts = {
191
+ build: "run -T npm-run-all clean --parallel build:code build:types",
192
+ "build:code": "run -T rollup -c",
193
+ "build:types": "run -T tsc -p tsconfig.build.json --emitDeclarationOnly",
194
+ clean: "run -T rimraf ./dist",
195
+ lint: "run -T eslint .",
196
+ "test:unit": "run -T jest",
197
+ watch: "run -T rollup -c -w"
198
+ };
199
+ var dependencies = {
200
+ "@strapi/utils": "5.9.0",
201
+ axios: "1.7.4",
202
+ boxen: "5.1.2",
203
+ chalk: "4.1.2",
204
+ "cli-progress": "3.12.0",
205
+ commander: "8.3.0",
206
+ eventsource: "2.0.2",
207
+ "fast-safe-stringify": "2.1.1",
208
+ "fs-extra": "11.2.0",
209
+ inquirer: "8.2.5",
210
+ jsonwebtoken: "9.0.0",
211
+ "jwks-rsa": "3.1.0",
212
+ lodash: "4.17.21",
213
+ minimatch: "9.0.3",
214
+ open: "8.4.0",
215
+ ora: "5.4.1",
216
+ "pkg-up": "3.1.0",
217
+ tar: "6.2.1",
218
+ "xdg-app-paths": "8.3.0",
219
+ yup: "0.32.9"
220
+ };
221
+ var devDependencies = {
222
+ "@types/cli-progress": "3.11.5",
223
+ "@types/eventsource": "1.1.15",
224
+ "@types/lodash": "^4.14.191",
225
+ "eslint-config-custom": "5.9.0",
226
+ tsconfig: "5.9.0"
227
+ };
228
+ var engines = {
229
+ node: ">=18.0.0 <=22.x.x",
230
+ npm: ">=6.0.0"
231
+ };
232
+ var packageJson = {
233
+ name: name,
234
+ version: version,
235
+ description: description,
236
+ keywords: keywords,
237
+ homepage: homepage,
238
+ bugs: bugs,
239
+ repository: repository,
240
+ license: license,
241
+ author: author,
242
+ maintainers: maintainers,
243
+ main: main,
244
+ module: module,
245
+ source: source,
246
+ types: types,
247
+ bin: bin,
248
+ files: files,
249
+ scripts: scripts,
250
+ dependencies: dependencies,
251
+ devDependencies: devDependencies,
252
+ engines: engines
253
+ };
254
+
255
+ const VERSION = 'v1';
256
+ async function cloudApiFactory({ logger }, token) {
257
+ const localConfig = await getLocalConfig$1();
258
+ const customHeaders = {
259
+ 'x-device-id': localConfig.deviceId,
260
+ 'x-app-version': packageJson.version,
261
+ 'x-os-name': os.type(),
262
+ 'x-os-version': os.version(),
263
+ 'x-language': Intl.DateTimeFormat().resolvedOptions().locale,
264
+ 'x-node-version': process.versions.node
265
+ };
266
+ const axiosCloudAPI = axios.create({
267
+ baseURL: `${apiConfig.apiBaseUrl}/${VERSION}`,
268
+ headers: {
269
+ 'Content-Type': 'application/json',
270
+ ...customHeaders
271
+ }
272
+ });
273
+ if (token) {
274
+ axiosCloudAPI.defaults.headers.Authorization = `Bearer ${token}`;
275
+ }
276
+ return {
277
+ deploy ({ filePath, project }, { onUploadProgress }) {
278
+ return axiosCloudAPI.post(`/deploy/${project.name}`, {
279
+ file: fse__default.createReadStream(filePath),
280
+ targetEnvironment: project.targetEnvironment
281
+ }, {
282
+ headers: {
283
+ 'Content-Type': 'multipart/form-data'
284
+ },
285
+ onUploadProgress
286
+ });
287
+ },
288
+ async createProject ({ name, nodeVersion, region, plan }) {
289
+ const response = await axiosCloudAPI.post('/project', {
290
+ projectName: name,
291
+ region,
292
+ nodeVersion,
293
+ plan
294
+ });
295
+ return {
296
+ data: {
297
+ id: response.data.id,
298
+ name: response.data.name,
299
+ nodeVersion: response.data.nodeVersion,
300
+ region: response.data.region
301
+ },
302
+ status: response.status
303
+ };
304
+ },
305
+ getUserInfo () {
306
+ return axiosCloudAPI.get('/user');
307
+ },
308
+ async config () {
309
+ try {
310
+ const response = await axiosCloudAPI.get('/config');
311
+ if (response.status !== 200) {
312
+ throw new Error('Error fetching cloud CLI config from the server.');
313
+ }
314
+ return response;
315
+ } catch (error) {
316
+ logger.debug("🥲 Oops! Couldn't retrieve the cloud CLI config from the server. Please try again.");
317
+ throw error;
318
+ }
319
+ },
320
+ async listProjects () {
321
+ try {
322
+ const response = await axiosCloudAPI.get('/projects');
323
+ if (response.status !== 200) {
324
+ throw new Error('Error fetching cloud projects from the server.');
325
+ }
326
+ return response;
327
+ } catch (error) {
328
+ logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
329
+ throw error;
330
+ }
331
+ },
332
+ async listLinkProjects () {
333
+ try {
334
+ const response = await axiosCloudAPI.get('/projects-linkable');
335
+ if (response.status !== 200) {
336
+ throw new Error('Error fetching cloud projects from the server.');
337
+ }
338
+ return response;
339
+ } catch (error) {
340
+ logger.debug("🥲 Oops! Couldn't retrieve your project's list from the server. Please try again.");
341
+ throw error;
342
+ }
343
+ },
344
+ async listEnvironments ({ name }) {
345
+ try {
346
+ const response = await axiosCloudAPI.get(`/projects/${name}/environments`);
347
+ if (response.status !== 200) {
348
+ throw new Error('Error fetching cloud environments from the server.');
349
+ }
350
+ return response;
351
+ } catch (error) {
352
+ logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
353
+ throw error;
354
+ }
355
+ },
356
+ async listLinkEnvironments ({ name }) {
357
+ try {
358
+ const response = await axiosCloudAPI.get(`/projects/${name}/environments-linkable`);
359
+ if (response.status !== 200) {
360
+ throw new Error('Error fetching cloud environments from the server.');
361
+ }
362
+ return response;
363
+ } catch (error) {
364
+ logger.debug("🥲 Oops! Couldn't retrieve your project's environments from the server. Please try again.");
365
+ throw error;
366
+ }
367
+ },
368
+ async getProject ({ name }) {
369
+ try {
370
+ const response = await axiosCloudAPI.get(`/projects/${name}`);
371
+ if (response.status !== 200) {
372
+ throw new Error("Error fetching project's details.");
373
+ }
374
+ return response;
375
+ } catch (error) {
376
+ logger.debug("🥲 Oops! There was a problem retrieving your project's details. Please try again.");
377
+ throw error;
378
+ }
379
+ },
380
+ track (event, payload = {}) {
381
+ return axiosCloudAPI.post('/track', {
382
+ event,
383
+ payload
384
+ });
385
+ }
386
+ };
387
+ }
388
+
389
+ const LOCAL_SAVE_FILENAME = '.strapi-cloud.json';
390
+ const getFilePath = (directoryPath)=>path__default.join(directoryPath || process.cwd(), LOCAL_SAVE_FILENAME);
391
+ async function save(data, { directoryPath } = {}) {
392
+ const pathToFile = getFilePath(directoryPath);
393
+ // Ensure the directory exists and creates it if not
394
+ await fse__default.ensureDir(path__default.dirname(pathToFile));
395
+ await fse__default.writeJson(pathToFile, data, {
396
+ encoding: 'utf8'
397
+ });
398
+ }
399
+ async function retrieve({ directoryPath } = {}) {
400
+ const pathToFile = getFilePath(directoryPath);
401
+ const pathExists = await fse__default.pathExists(pathToFile);
402
+ if (!pathExists) {
403
+ return {};
404
+ }
405
+ return fse__default.readJSON(pathToFile, {
406
+ encoding: 'utf8'
407
+ });
408
+ }
409
+ async function patch(patchData, { directoryPath } = {}) {
410
+ const pathToFile = getFilePath(directoryPath);
411
+ const existingData = await retrieve({
412
+ directoryPath
413
+ });
414
+ if (!existingData) {
415
+ throw new Error('No configuration data found to patch.');
416
+ }
417
+ const newData = merge(existingData, patchData);
418
+ await fse__default.writeJson(pathToFile, newData, {
419
+ encoding: 'utf8'
420
+ });
421
+ }
422
+ async function deleteConfig({ directoryPath } = {}) {
423
+ const pathToFile = getFilePath(directoryPath);
424
+ const pathExists = await fse__default.pathExists(pathToFile);
425
+ if (pathExists) {
426
+ await fse__default.remove(pathToFile);
427
+ }
428
+ }
429
+
430
+ var strapiInfoSave = /*#__PURE__*/Object.freeze({
431
+ __proto__: null,
432
+ LOCAL_SAVE_FILENAME: LOCAL_SAVE_FILENAME,
433
+ deleteConfig: deleteConfig,
434
+ patch: patch,
435
+ retrieve: retrieve,
436
+ save: save
437
+ });
438
+
439
+ let cliConfig;
440
+ async function tokenServiceFactory({ logger }) {
441
+ const cloudApiService = await cloudApiFactory({
442
+ logger
443
+ });
444
+ async function saveToken(str) {
445
+ const appConfig = await getLocalConfig$1();
446
+ if (!appConfig) {
447
+ logger.error('There was a problem saving your token. Please try again.');
448
+ return;
449
+ }
450
+ appConfig.token = str;
451
+ try {
452
+ await saveLocalConfig(appConfig);
453
+ } catch (e) {
454
+ logger.debug(e);
455
+ logger.error('There was a problem saving your token. Please try again.');
456
+ }
457
+ }
458
+ async function retrieveToken() {
459
+ const appConfig = await getLocalConfig$1();
460
+ if (appConfig.token) {
461
+ // check if token is still valid
462
+ if (await isTokenValid(appConfig.token)) {
463
+ return appConfig.token;
464
+ }
465
+ }
466
+ return undefined;
467
+ }
468
+ async function validateToken(idToken, jwksUrl) {
469
+ const client = jwksClient({
470
+ jwksUri: jwksUrl
471
+ });
472
+ // Get the Key from the JWKS using the token header's Key ID (kid)
473
+ const getKey = (header, callback)=>{
474
+ client.getSigningKey(header.kid, (e, key)=>{
475
+ if (e) {
476
+ callback(e);
477
+ } else if (key) {
478
+ const publicKey = 'publicKey' in key ? key.publicKey : key.rsaPublicKey;
479
+ callback(null, publicKey);
480
+ } else {
481
+ callback(new Error('Key not found'));
482
+ }
483
+ });
484
+ };
485
+ const decodedToken = jwt.decode(idToken, {
486
+ complete: true
487
+ });
488
+ if (!decodedToken) {
489
+ if (typeof idToken === 'undefined' || idToken === '') {
490
+ logger.warn('You need to be logged in to use this feature. Please log in and try again.');
491
+ } else {
492
+ logger.error('There seems to be a problem with your login information. Please try logging in again.');
493
+ }
494
+ return Promise.reject(new Error('Invalid token'));
495
+ }
496
+ // Verify the JWT token signature using the JWKS Key
497
+ return new Promise((resolve, reject)=>{
498
+ jwt.verify(idToken, getKey, (err)=>{
499
+ if (err) {
500
+ reject(err);
501
+ }
502
+ if (decodedToken.payload.exp < Math.floor(Date.now() / 1000)) {
503
+ reject(new Error('Token is expired'));
504
+ }
505
+ resolve();
506
+ });
507
+ });
508
+ }
509
+ async function isTokenValid(token) {
510
+ try {
511
+ const config = await cloudApiService.config();
512
+ cliConfig = config.data;
513
+ if (token) {
514
+ await validateToken(token, cliConfig.jwksUrl);
515
+ return true;
516
+ }
517
+ return false;
518
+ } catch (e) {
519
+ logger.debug(e);
520
+ return false;
521
+ }
522
+ }
523
+ async function eraseToken() {
524
+ const appConfig = await getLocalConfig$1();
525
+ if (!appConfig) {
526
+ return;
527
+ }
528
+ delete appConfig.token;
529
+ try {
530
+ await saveLocalConfig(appConfig);
531
+ } catch (e) {
532
+ logger.debug(e);
533
+ logger.error('There was an issue removing your login information. Please try logging out again.');
534
+ throw e;
535
+ }
536
+ }
537
+ async function getValidToken(ctx, loginAction) {
538
+ let token = await retrieveToken();
539
+ while(!token || !await isTokenValid(token)){
540
+ logger.log(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.");
541
+ if (!await loginAction(ctx)) return null;
542
+ token = await retrieveToken();
543
+ }
544
+ return token;
545
+ }
546
+ return {
547
+ saveToken,
548
+ retrieveToken,
549
+ validateToken,
550
+ isTokenValid,
551
+ eraseToken,
552
+ getValidToken
553
+ };
554
+ }
555
+
556
+ const stringifyArg = (arg)=>{
557
+ return typeof arg === 'object' ? stringify(arg) : arg;
558
+ };
559
+ const createLogger = (options = {})=>{
560
+ const { silent = false, debug = false, timestamp = true } = options;
561
+ const state = {
562
+ errors: 0,
563
+ warning: 0
564
+ };
565
+ return {
566
+ get warnings () {
567
+ return state.warning;
568
+ },
569
+ get errors () {
570
+ return state.errors;
571
+ },
572
+ async debug (...args) {
573
+ if (silent || !debug) {
574
+ return;
575
+ }
576
+ console.log(chalk.cyan(`[DEBUG]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
577
+ },
578
+ info (...args) {
579
+ if (silent) {
580
+ return;
581
+ }
582
+ console.info(chalk.blue(`[INFO]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
583
+ },
584
+ log (...args) {
585
+ if (silent) {
586
+ return;
587
+ }
588
+ console.info(chalk.blue(`${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
589
+ },
590
+ success (...args) {
591
+ if (silent) {
592
+ return;
593
+ }
594
+ console.info(chalk.green(`[SUCCESS]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
595
+ },
596
+ warn (...args) {
597
+ state.warning += 1;
598
+ if (silent) {
599
+ return;
600
+ }
601
+ console.warn(chalk.yellow(`[WARN]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
602
+ },
603
+ error (...args) {
604
+ state.errors += 1;
605
+ if (silent) {
606
+ return;
607
+ }
608
+ console.error(chalk.red(`[ERROR]${timestamp ? `\t[${new Date().toISOString()}]` : ''}`), ...args.map(stringifyArg));
609
+ },
610
+ // @ts-expect-error – returning a subpart of ora is fine because the types tell us what is what.
611
+ spinner (text) {
612
+ if (silent) {
613
+ return {
614
+ succeed () {
615
+ return this;
616
+ },
617
+ fail () {
618
+ return this;
619
+ },
620
+ start () {
621
+ return this;
622
+ },
623
+ text: '',
624
+ isSpinning: false
625
+ };
626
+ }
627
+ return ora(text);
628
+ },
629
+ progressBar (totalSize, text) {
630
+ if (silent) {
631
+ return {
632
+ start () {
633
+ return this;
634
+ },
635
+ stop () {
636
+ return this;
637
+ },
638
+ update () {
639
+ return this;
640
+ }
641
+ };
642
+ }
643
+ const progressBar = new cliProgress.SingleBar({
644
+ format: `${text ? `${text} |` : ''}${chalk.green('{bar}')}| {percentage}%`,
645
+ barCompleteChar: '\u2588',
646
+ barIncompleteChar: '\u2591',
647
+ hideCursor: true,
648
+ forceRedraw: true
649
+ });
650
+ progressBar.start(totalSize, 0);
651
+ return progressBar;
652
+ }
653
+ };
654
+ };
655
+
656
+ var index = /*#__PURE__*/Object.freeze({
657
+ __proto__: null,
658
+ cloudApiFactory: cloudApiFactory,
659
+ createLogger: createLogger,
660
+ local: strapiInfoSave,
661
+ tokenServiceFactory: tokenServiceFactory
662
+ });
663
+
664
+ yup.object({
665
+ name: yup.string().required(),
666
+ exports: yup.lazy((value)=>yup.object(typeof value === 'object' ? Object.entries(value).reduce((acc, [key, value])=>{
667
+ if (typeof value === 'object') {
668
+ acc[key] = yup.object({
669
+ types: yup.string().optional(),
670
+ source: yup.string().required(),
671
+ module: yup.string().optional(),
672
+ import: yup.string().required(),
673
+ require: yup.string().required(),
674
+ default: yup.string().required()
675
+ }).noUnknown(true);
676
+ } else {
677
+ acc[key] = yup.string().matches(/^\.\/.*\.json$/).required();
678
+ }
679
+ return acc;
680
+ }, {}) : undefined).optional())
681
+ });
682
+ /**
683
+ * @description being a task to load the package.json starting from the current working directory
684
+ * using a shallow find for the package.json and `fs` to read the file. If no package.json is found,
685
+ * the process will throw with an appropriate error message.
686
+ */ const loadPkg = async ({ cwd, logger })=>{
687
+ const pkgPath = await pkgUp({
688
+ cwd
689
+ });
690
+ if (!pkgPath) {
691
+ throw new Error('Could not find a package.json in the current directory');
692
+ }
693
+ const buffer = await fse.readFile(pkgPath);
694
+ const pkg = JSON.parse(buffer.toString());
695
+ logger.debug('Loaded package.json:', os.EOL, pkg);
696
+ return pkg;
697
+ };
698
+
699
+ async function getProjectNameFromPackageJson(ctx) {
700
+ try {
701
+ const packageJson = await loadPkg(ctx);
702
+ return packageJson.name || 'my-strapi-project';
703
+ } catch (e) {
704
+ return 'my-strapi-project';
705
+ }
706
+ }
707
+
708
+ const trackEvent = async (ctx, cloudApiService, eventName, eventData)=>{
709
+ try {
710
+ await cloudApiService.track(eventName, eventData);
711
+ } catch (e) {
712
+ ctx.logger.debug(`Failed to track ${eventName}`, e);
713
+ }
714
+ };
715
+
716
+ const openModule$1 = import('open');
717
+ async function promptLogin(ctx) {
718
+ const response = await inquirer.prompt([
719
+ {
720
+ type: 'confirm',
721
+ name: 'login',
722
+ message: 'Would you like to login?'
723
+ }
724
+ ]);
725
+ if (response.login) {
726
+ const loginSuccessful = await loginAction(ctx);
727
+ return loginSuccessful;
728
+ }
729
+ return false;
730
+ }
731
+ async function loginAction(ctx) {
732
+ const { logger } = ctx;
733
+ const tokenService = await tokenServiceFactory(ctx);
734
+ const existingToken = await tokenService.retrieveToken();
735
+ const cloudApiService = await cloudApiFactory(ctx, existingToken || undefined);
736
+ if (existingToken) {
737
+ const isTokenValid = await tokenService.isTokenValid(existingToken);
738
+ if (isTokenValid) {
739
+ try {
740
+ const userInfo = await cloudApiService.getUserInfo();
741
+ const { email } = userInfo.data.data;
742
+ if (email) {
743
+ logger.log(`You are already logged into your account (${email}).`);
744
+ } else {
745
+ logger.log('You are already logged in.');
746
+ }
747
+ logger.log('To access your dashboard, please copy and paste the following URL into your web browser:');
748
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
749
+ return true;
750
+ } catch (e) {
751
+ logger.debug('Failed to fetch user info', e);
752
+ }
753
+ }
754
+ }
755
+ let cliConfig;
756
+ try {
757
+ logger.info('🔌 Connecting to the Strapi Cloud API...');
758
+ const config = await cloudApiService.config();
759
+ cliConfig = config.data;
760
+ } catch (e) {
761
+ logger.error('🥲 Oops! Something went wrong while logging you in. Please try again.');
762
+ logger.debug(e);
763
+ return false;
764
+ }
765
+ await trackEvent(ctx, cloudApiService, 'willLoginAttempt', {});
766
+ logger.debug('🔐 Creating device authentication request...', {
767
+ client_id: cliConfig.clientId,
768
+ scope: cliConfig.scope,
769
+ audience: cliConfig.audience
770
+ });
771
+ const deviceAuthResponse = await axios.post(cliConfig.deviceCodeAuthUrl, {
772
+ client_id: cliConfig.clientId,
773
+ scope: cliConfig.scope,
774
+ audience: cliConfig.audience
775
+ }).catch((e)=>{
776
+ logger.error('There was an issue with the authentication process. Please try again.');
777
+ if (e.message) {
778
+ logger.debug(e.message, e);
779
+ } else {
780
+ logger.debug(e);
781
+ }
782
+ });
783
+ openModule$1.then((open)=>{
784
+ open.default(deviceAuthResponse.data.verification_uri_complete).catch((e)=>{
785
+ logger.error('We encountered an issue opening the browser. Please try again later.');
786
+ logger.debug(e.message, e);
787
+ });
788
+ });
789
+ logger.log('If a browser tab does not open automatically, please follow the next steps:');
790
+ logger.log(`1. Open this url in your device: ${deviceAuthResponse.data.verification_uri_complete}`);
791
+ logger.log(`2. Enter the following code: ${deviceAuthResponse.data.user_code} and confirm to login.\n`);
792
+ const tokenPayload = {
793
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
794
+ device_code: deviceAuthResponse.data.device_code,
795
+ client_id: cliConfig.clientId
796
+ };
797
+ let isAuthenticated = false;
798
+ const authenticate = async ()=>{
799
+ const spinner = logger.spinner('Waiting for authentication');
800
+ spinner.start();
801
+ const spinnerFail = ()=>spinner.fail('Authentication failed!');
802
+ while(!isAuthenticated){
803
+ try {
804
+ const tokenResponse = await axios.post(cliConfig.tokenUrl, tokenPayload);
805
+ const authTokenData = tokenResponse.data;
806
+ if (tokenResponse.status === 200) {
807
+ // Token validation
808
+ try {
809
+ logger.debug('🔐 Validating token...');
810
+ await tokenService.validateToken(authTokenData.id_token, cliConfig.jwksUrl);
811
+ logger.debug('🔐 Token validation successful!');
812
+ } catch (e) {
813
+ logger.debug(e);
814
+ spinnerFail();
815
+ throw new Error('Unable to proceed: Token validation failed');
816
+ }
817
+ logger.debug('🔍 Fetching user information...');
818
+ const cloudApiServiceWithToken = await cloudApiFactory(ctx, authTokenData.access_token);
819
+ // Call to get user info to create the user in DB if not exists
820
+ await cloudApiServiceWithToken.getUserInfo();
821
+ logger.debug('🔍 User information fetched successfully!');
822
+ try {
823
+ logger.debug('📝 Saving login information...');
824
+ await tokenService.saveToken(authTokenData.access_token);
825
+ logger.debug('📝 Login information saved successfully!');
826
+ isAuthenticated = true;
827
+ } catch (e) {
828
+ logger.error('There was a problem saving your login information. Please try logging in again.');
829
+ logger.debug(e);
830
+ spinnerFail();
831
+ return false;
832
+ }
833
+ }
834
+ } catch (e) {
835
+ if (e.message === 'Unable to proceed: Token validation failed') {
836
+ logger.error('There seems to be a problem with your login information. Please try logging in again.');
837
+ spinnerFail();
838
+ await trackEvent(ctx, cloudApiService, 'didNotLogin', {
839
+ loginMethod: 'cli'
840
+ });
841
+ return false;
842
+ }
843
+ if (e.response?.data.error && ![
844
+ 'authorization_pending',
845
+ 'slow_down'
846
+ ].includes(e.response.data.error)) {
847
+ logger.debug(e);
848
+ spinnerFail();
849
+ await trackEvent(ctx, cloudApiService, 'didNotLogin', {
850
+ loginMethod: 'cli'
851
+ });
852
+ return false;
853
+ }
854
+ // Await interval before retrying
855
+ await new Promise((resolve)=>{
856
+ setTimeout(resolve, deviceAuthResponse.data.interval * 1000);
857
+ });
858
+ }
859
+ }
860
+ spinner.succeed('Authentication successful!');
861
+ logger.log('You are now logged into Strapi Cloud.');
862
+ logger.log('To access your dashboard, please copy and paste the following URL into your web browser:');
863
+ logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects`));
864
+ await trackEvent(ctx, cloudApiService, 'didLogin', {
865
+ loginMethod: 'cli'
866
+ });
867
+ };
868
+ await authenticate();
869
+ return isAuthenticated;
870
+ }
871
+
872
+ /**
873
+ * Apply default values to questions based on the provided mapper
874
+ * @param questionsMap - A partial object with keys matching the ProjectAnswers keys and values being the default value or a function to get the default value
875
+ */ function questionDefaultValuesMapper(questionsMap) {
876
+ return (questions)=>{
877
+ return questions.map((question)=>{
878
+ const questionName = question.name;
879
+ // If the question is part of the mapper, apply the default value
880
+ if (questionName in questionsMap) {
881
+ const questionDefault = questionsMap[questionName];
882
+ // If the default value is a function, call it with the question and get the default value
883
+ if (typeof questionDefault === 'function') {
884
+ return {
885
+ ...question,
886
+ default: questionDefault(question)
887
+ };
888
+ }
889
+ // else we consider it as a static value
890
+ return {
891
+ ...question,
892
+ default: questionDefault
893
+ };
894
+ }
895
+ // If the question is not part of the mapper, return the question as is
896
+ return question;
897
+ });
898
+ };
899
+ }
900
+ /**
901
+ * Get default values from questions
902
+ * @param questions - An array of questions for project creation
903
+ */ function getDefaultsFromQuestions(questions) {
904
+ return questions.reduce((acc, question)=>{
905
+ if (question.default && question.name) {
906
+ return {
907
+ ...acc,
908
+ [question.name]: question.default
909
+ };
910
+ }
911
+ return acc;
912
+ }, {});
913
+ }
914
+ /**
915
+ * Get the default node version based on the current node version if it is in the list of choices
916
+ * @param question - The question for the node version in project creation
917
+ */ function getProjectNodeVersionDefault(question) {
918
+ const currentNodeVersion = process.versions.node.split('.')[0];
919
+ // Node Version question is set up as a list, but the type of inquirer is dynamic and the question can change in the future (it comes from API)
920
+ if (question.type === 'list' && Array.isArray(question.choices)) {
921
+ const choice = question.choices.find((choice)=>choice.value === currentNodeVersion);
922
+ if (choice) {
923
+ return choice.value;
924
+ }
925
+ }
926
+ return question.default;
927
+ }
928
+
929
+ async function handleError(ctx, error) {
930
+ const { logger } = ctx;
931
+ logger.debug(error);
932
+ if (error instanceof AxiosError) {
933
+ const errorMessage = typeof error.response?.data === 'string' ? error.response.data : null;
934
+ switch(error.response?.status){
935
+ case 403:
936
+ logger.error(errorMessage || 'You do not have permission to create a project. Please contact support for assistance.');
937
+ return;
938
+ case 400:
939
+ logger.error(errorMessage || 'Invalid input. Please check your inputs and try again.');
940
+ return;
941
+ case 503:
942
+ logger.error('Strapi Cloud project creation is currently unavailable. Please try again later.');
943
+ return;
944
+ default:
945
+ if (errorMessage) {
946
+ logger.error(errorMessage);
947
+ return;
948
+ }
949
+ break;
950
+ }
951
+ }
952
+ logger.error('We encountered an issue while creating your project. Please try again in a moment. If the problem persists, contact support for assistance.');
953
+ }
954
+ async function createProject$1(ctx, cloudApi, projectInput) {
955
+ const { logger } = ctx;
956
+ const spinner = logger.spinner('Setting up your project...').start();
957
+ try {
958
+ const { data } = await cloudApi.createProject(projectInput);
959
+ await save({
960
+ project: data
961
+ });
962
+ spinner.succeed('Project created successfully!');
963
+ return data;
964
+ } catch (e) {
965
+ spinner.fail('An error occurred while creating the project on Strapi Cloud.');
966
+ throw e;
967
+ }
968
+ }
969
+ var action$6 = (async (ctx)=>{
970
+ const { logger } = ctx;
971
+ const { getValidToken, eraseToken } = await tokenServiceFactory(ctx);
972
+ const token = await getValidToken(ctx, promptLogin);
973
+ if (!token) {
974
+ return;
975
+ }
976
+ const cloudApi = await cloudApiFactory(ctx, token);
977
+ const { data: config } = await cloudApi.config();
978
+ const projectName = await getProjectNameFromPackageJson(ctx);
979
+ const defaultAnswersMapper = questionDefaultValuesMapper({
980
+ name: projectName,
981
+ nodeVersion: getProjectNodeVersionDefault
982
+ });
983
+ const questions = defaultAnswersMapper(config.projectCreation.questions);
984
+ const defaultValues = {
985
+ ...config.projectCreation.defaults,
986
+ ...getDefaultsFromQuestions(questions)
987
+ };
988
+ const projectAnswersDefaulted = defaults(defaultValues);
989
+ const projectAnswers = await inquirer.prompt(questions);
990
+ const projectInput = projectAnswersDefaulted(projectAnswers);
991
+ try {
992
+ return await createProject$1(ctx, cloudApi, projectInput);
993
+ } catch (e) {
994
+ if (e instanceof AxiosError && e.response?.status === 401) {
995
+ logger.warn('Oops! Your session has expired. Please log in again to retry.');
996
+ await eraseToken();
997
+ if (await promptLogin(ctx)) {
998
+ return await createProject$1(ctx, cloudApi, projectInput);
999
+ }
1000
+ } else {
1001
+ await handleError(ctx, e);
1002
+ }
1003
+ }
1004
+ });
1005
+
1006
+ function notificationServiceFactory({ logger }) {
1007
+ return (url, token, cliConfig)=>{
1008
+ const CONN_TIMEOUT = Number(cliConfig.notificationsConnectionTimeout);
1009
+ const es = new EventSource(url, {
1010
+ headers: {
1011
+ Authorization: `Bearer ${token}`
1012
+ }
1013
+ });
1014
+ let timeoutId;
1015
+ const resetTimeout = ()=>{
1016
+ clearTimeout(timeoutId);
1017
+ timeoutId = setTimeout(()=>{
1018
+ logger.log('We were unable to connect to the server at this time. This could be due to a temporary issue. Please try again in a moment.');
1019
+ es.close();
1020
+ }, CONN_TIMEOUT); // 5 minutes
1021
+ };
1022
+ es.onopen = resetTimeout;
1023
+ es.onmessage = (event)=>{
1024
+ resetTimeout();
1025
+ const data = JSON.parse(event.data);
1026
+ if (data.message) {
1027
+ logger.log(data.message);
1028
+ }
1029
+ // Close connection when a specific event is received
1030
+ if (data.event === 'deploymentFinished' || data.event === 'deploymentFailed') {
1031
+ es.close();
1032
+ }
1033
+ };
1034
+ };
1035
+ }
1036
+
1037
+ const buildLogsServiceFactory = ({ logger })=>{
1038
+ return async (url, token, cliConfig)=>{
1039
+ const CONN_TIMEOUT = Number(cliConfig.buildLogsConnectionTimeout);
1040
+ const MAX_RETRIES = Number(cliConfig.buildLogsMaxRetries);
1041
+ return new Promise((resolve, reject)=>{
1042
+ let timeoutId = null;
1043
+ let retries = 0;
1044
+ const connect = (url)=>{
1045
+ const spinner = logger.spinner('Connecting to server to get build logs');
1046
+ spinner.start();
1047
+ const es = new EventSource(`${url}`, {
1048
+ headers: {
1049
+ Authorization: `Bearer ${token}`
1050
+ }
1051
+ });
1052
+ const clearExistingTimeout = ()=>{
1053
+ if (timeoutId) {
1054
+ clearTimeout(timeoutId);
1055
+ }
1056
+ };
1057
+ const resetTimeout = ()=>{
1058
+ clearExistingTimeout();
1059
+ timeoutId = setTimeout(()=>{
1060
+ if (spinner.isSpinning) {
1061
+ spinner.fail('We were unable to connect to the server to get build logs at this time. This could be due to a temporary issue.');
1062
+ }
1063
+ es.close();
1064
+ reject(new Error('Connection timed out'));
1065
+ }, CONN_TIMEOUT);
1066
+ };
1067
+ es.onopen = resetTimeout;
1068
+ es.addEventListener('finished', (event)=>{
1069
+ const data = JSON.parse(event.data);
1070
+ logger.log(data.msg);
1071
+ es.close();
1072
+ clearExistingTimeout();
1073
+ resolve(null);
1074
+ });
1075
+ es.addEventListener('log', (event)=>{
1076
+ if (spinner.isSpinning) {
1077
+ spinner.succeed();
1078
+ }
1079
+ resetTimeout();
1080
+ const data = JSON.parse(event.data);
1081
+ logger.log(data.msg);
1082
+ });
1083
+ es.onerror = async ()=>{
1084
+ retries += 1;
1085
+ if (retries > MAX_RETRIES) {
1086
+ spinner.fail('We were unable to connect to the server to get build logs at this time.');
1087
+ es.close();
1088
+ clearExistingTimeout(); // Important to clear the event loop from remaining timeout - avoid to wait for nothing while the timeout is running
1089
+ reject(new Error('Max retries reached'));
1090
+ }
1091
+ };
1092
+ };
1093
+ connect(url);
1094
+ });
1095
+ };
1096
+ };
1097
+
1098
+ const boxenOptions = {
1099
+ padding: 1,
1100
+ margin: 1,
1101
+ align: 'center',
1102
+ borderColor: 'yellow',
1103
+ borderStyle: 'round'
1104
+ };
1105
+ const QUIT_OPTION$2 = 'Quit';
1106
+ async function promptForEnvironment(environments) {
1107
+ const choices = environments.map((env)=>({
1108
+ name: env,
1109
+ value: env
1110
+ }));
1111
+ const { selectedEnvironment } = await inquirer.prompt([
1112
+ {
1113
+ type: 'list',
1114
+ name: 'selectedEnvironment',
1115
+ message: 'Select the environment to deploy:',
1116
+ choices: [
1117
+ ...choices,
1118
+ {
1119
+ name: chalk.grey(`(${QUIT_OPTION$2})`),
1120
+ value: null
1121
+ }
1122
+ ]
1123
+ }
1124
+ ]);
1125
+ if (selectedEnvironment === null) {
1126
+ process.exit(1);
1127
+ }
1128
+ return selectedEnvironment;
1129
+ }
1130
+ async function upload(ctx, project, token, maxProjectFileSize) {
1131
+ const cloudApi = await cloudApiFactory(ctx, token);
1132
+ try {
1133
+ const storagePath = await getTmpStoragePath();
1134
+ const projectFolder = path__default.resolve(process.cwd());
1135
+ const packageJson = await loadPkg(ctx);
1136
+ if (!packageJson) {
1137
+ ctx.logger.error('Unable to deploy the project. Please make sure the package.json file is correctly formatted.');
1138
+ return;
1139
+ }
1140
+ ctx.logger.log('📦 Compressing project...');
1141
+ // hash packageJson.name to avoid conflicts
1142
+ const hashname = crypto.createHash('sha512').update(packageJson.name).digest('hex');
1143
+ const compressedFilename = `${hashname}.tar.gz`;
1144
+ try {
1145
+ ctx.logger.debug('Compression parameters\n', `Storage path: ${storagePath}\n`, `Project folder: ${projectFolder}\n`, `Compressed filename: ${compressedFilename}`);
1146
+ await compressFilesToTar(storagePath, projectFolder, compressedFilename);
1147
+ ctx.logger.log('📦 Project compressed successfully!');
1148
+ } catch (e) {
1149
+ ctx.logger.error('⚠️ Project compression failed. Try again later or check for large/incompatible files.');
1150
+ ctx.logger.debug(e);
1151
+ process.exit(1);
1152
+ }
1153
+ const tarFilePath = path__default.resolve(storagePath, compressedFilename);
1154
+ const fileStats = await fse__default.stat(tarFilePath);
1155
+ if (fileStats.size > maxProjectFileSize) {
1156
+ ctx.logger.log('Unable to proceed: Your project is too big to be transferred, please use a git repo instead.');
1157
+ try {
1158
+ await fse__default.remove(tarFilePath);
1159
+ } catch (e) {
1160
+ ctx.logger.log('Unable to remove file: ', tarFilePath);
1161
+ ctx.logger.debug(e);
1162
+ }
1163
+ return;
1164
+ }
1165
+ ctx.logger.info('🚀 Uploading project...');
1166
+ const progressBar = ctx.logger.progressBar(100, 'Upload Progress');
1167
+ try {
1168
+ const { data } = await cloudApi.deploy({
1169
+ filePath: tarFilePath,
1170
+ project
1171
+ }, {
1172
+ onUploadProgress (progressEvent) {
1173
+ const total = progressEvent.total || fileStats.size;
1174
+ const percentage = Math.round(progressEvent.loaded * 100 / total);
1175
+ progressBar.update(percentage);
1176
+ }
1177
+ });
1178
+ progressBar.update(100);
1179
+ progressBar.stop();
1180
+ ctx.logger.success('✨ Upload finished!');
1181
+ return data.build_id;
1182
+ } catch (e) {
1183
+ progressBar.stop();
1184
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1185
+ ctx.logger.debug(e);
1186
+ } finally{
1187
+ await fse__default.remove(tarFilePath);
1188
+ }
1189
+ process.exit(0);
1190
+ } catch (e) {
1191
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1192
+ ctx.logger.debug(e);
1193
+ process.exit(1);
1194
+ }
1195
+ }
1196
+ async function getProject(ctx) {
1197
+ const { project } = await retrieve();
1198
+ if (!project) {
1199
+ try {
1200
+ return await action$6(ctx);
1201
+ } catch (e) {
1202
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1203
+ ctx.logger.debug(e);
1204
+ process.exit(1);
1205
+ }
1206
+ }
1207
+ return project;
1208
+ }
1209
+ async function getConfig({ ctx, cloudApiService }) {
1210
+ try {
1211
+ const { data: cliConfig } = await cloudApiService.config();
1212
+ return cliConfig;
1213
+ } catch (e) {
1214
+ ctx.logger.debug('Failed to get cli config', e);
1215
+ return null;
1216
+ }
1217
+ }
1218
+ function validateEnvironment(ctx, environment, environments) {
1219
+ if (!environments.includes(environment)) {
1220
+ ctx.logger.error(`Environment ${environment} does not exist.`);
1221
+ process.exit(1);
1222
+ }
1223
+ }
1224
+ async function getTargetEnvironment(ctx, opts, project, environments) {
1225
+ if (opts.env) {
1226
+ validateEnvironment(ctx, opts.env, environments);
1227
+ return opts.env;
1228
+ }
1229
+ if (project.targetEnvironment) {
1230
+ return project.targetEnvironment;
1231
+ }
1232
+ if (environments.length > 1) {
1233
+ return promptForEnvironment(environments);
1234
+ }
1235
+ return environments[0];
1236
+ }
1237
+ function hasPendingOrLiveDeployment(environments, targetEnvironment) {
1238
+ const environment = environments.find((env)=>env.name === targetEnvironment);
1239
+ if (!environment) {
1240
+ throw new Error(`Environment details ${targetEnvironment} not found.`);
1241
+ }
1242
+ return environment.hasPendingDeployment || environment.hasLiveDeployment || false;
1243
+ }
1244
+ var action$5 = (async (ctx, opts)=>{
1245
+ const { getValidToken } = await tokenServiceFactory(ctx);
1246
+ const token = await getValidToken(ctx, promptLogin);
1247
+ if (!token) {
1248
+ return;
1249
+ }
1250
+ const project = await getProject(ctx);
1251
+ if (!project) {
1252
+ return;
1253
+ }
1254
+ const cloudApiService = await cloudApiFactory(ctx, token);
1255
+ let projectData;
1256
+ let environments;
1257
+ let environmentsDetails;
1258
+ try {
1259
+ const { data: { data, metadata } } = await cloudApiService.getProject({
1260
+ name: project.name
1261
+ });
1262
+ projectData = data;
1263
+ environments = projectData.environments;
1264
+ environmentsDetails = projectData.environmentsDetails;
1265
+ const isProjectSuspended = projectData.suspendedAt;
1266
+ if (isProjectSuspended) {
1267
+ ctx.logger.log('\n Oops! This project has been suspended. \n\n Please reactivate it from the dashboard to continue deploying: ');
1268
+ ctx.logger.log(chalk.underline(`${metadata.dashboardUrls.project}`));
1269
+ return;
1270
+ }
1271
+ } catch (e) {
1272
+ if (e instanceof AxiosError && e.response?.data) {
1273
+ if (e.response.status === 404) {
1274
+ ctx.logger.warn(`The project associated with this folder does not exist in Strapi Cloud. \nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command before deploying.`);
1275
+ } else {
1276
+ ctx.logger.error(e.response.data);
1277
+ }
1278
+ } else {
1279
+ ctx.logger.error("An error occurred while retrieving the project's information. Please try again later.");
1280
+ }
1281
+ ctx.logger.debug(e);
1282
+ return;
1283
+ }
1284
+ await trackEvent(ctx, cloudApiService, 'willDeployWithCLI', {
1285
+ projectInternalName: project.name
1286
+ });
1287
+ const notificationService = notificationServiceFactory(ctx);
1288
+ const buildLogsService = buildLogsServiceFactory(ctx);
1289
+ const cliConfig = await getConfig({
1290
+ ctx,
1291
+ cloudApiService
1292
+ });
1293
+ if (!cliConfig) {
1294
+ ctx.logger.error('An error occurred while retrieving data from Strapi Cloud. Please check your network or try again later.');
1295
+ return;
1296
+ }
1297
+ let maxSize = parseInt(cliConfig.maxProjectFileSize, 10);
1298
+ if (Number.isNaN(maxSize)) {
1299
+ ctx.logger.debug('An error occurred while parsing the maxProjectFileSize. Using default value.');
1300
+ maxSize = 100000000;
1301
+ }
1302
+ project.targetEnvironment = await getTargetEnvironment(ctx, opts, project, environments);
1303
+ if (!opts.force) {
1304
+ const shouldDisplayWarning = hasPendingOrLiveDeployment(environmentsDetails, project.targetEnvironment);
1305
+ if (shouldDisplayWarning) {
1306
+ ctx.logger.log(boxen(cliConfig.projectDeployment.confirmationText, boxenOptions));
1307
+ const { confirm } = await inquirer.prompt([
1308
+ {
1309
+ type: 'confirm',
1310
+ name: 'confirm',
1311
+ message: `Do you want to proceed with deployment to ${chalk.cyan(projectData.displayName)} on ${chalk.cyan(project.targetEnvironment)} environment?`
1312
+ }
1313
+ ]);
1314
+ if (!confirm) {
1315
+ process.exit(1);
1316
+ }
1317
+ }
1318
+ }
1319
+ const buildId = await upload(ctx, project, token, maxSize);
1320
+ if (!buildId) {
1321
+ return;
1322
+ }
1323
+ try {
1324
+ ctx.logger.log(`🚀 Deploying project to ${chalk.cyan(project.targetEnvironment ?? `production`)} environment...`);
1325
+ notificationService(`${apiConfig.apiBaseUrl}/notifications`, token, cliConfig);
1326
+ await buildLogsService(`${apiConfig.apiBaseUrl}/v1/logs/${buildId}`, token, cliConfig);
1327
+ ctx.logger.log('Visit the following URL for deployment logs. Your deployment will be available here shortly.');
1328
+ ctx.logger.log(chalk.underline(`${apiConfig.dashboardBaseUrl}/projects/${project.name}/deployments`));
1329
+ } catch (e) {
1330
+ ctx.logger.debug(e);
1331
+ if (e instanceof Error) {
1332
+ ctx.logger.error(e.message);
1333
+ } else {
1334
+ ctx.logger.error('An error occurred while deploying the project. Please try again later.');
1335
+ }
1336
+ }
1337
+ });
1338
+
1339
+ // TODO: Remove duplicated code by extracting to a shared package
1340
+ const assertCwdContainsStrapiProject = (name)=>{
1341
+ const logErrorAndExit = ()=>{
1342
+ console.log(`You need to run ${chalk.yellow(`strapi ${name}`)} in a Strapi project. Make sure you are in the right directory.`);
1343
+ process.exit(1);
1344
+ };
1345
+ try {
1346
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1347
+ const pkgJSON = require(`${process.cwd()}/package.json`);
1348
+ if (!has('dependencies.@strapi/strapi', pkgJSON) && !has('devDependencies.@strapi/strapi', pkgJSON)) {
1349
+ logErrorAndExit();
1350
+ }
1351
+ } catch (err) {
1352
+ logErrorAndExit();
1353
+ }
1354
+ };
1355
+ const runAction = (name, action)=>(...args)=>{
1356
+ assertCwdContainsStrapiProject(name);
1357
+ Promise.resolve().then(()=>{
1358
+ return action(...args);
1359
+ }).catch((error)=>{
1360
+ console.error(error);
1361
+ process.exit(1);
1362
+ });
1363
+ };
1364
+
1365
+ /**
1366
+ * `$ deploy project to the cloud`
1367
+ */ const command$7 = ({ ctx })=>{
1368
+ return createCommand('cloud:deploy').alias('deploy').description('Deploy a Strapi Cloud project').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").option('-f, --force', 'Skip confirmation to deploy').option('-e, --env <name>', 'Specify the environment to deploy').action((opts)=>runAction('deploy', action$5)(ctx, opts));
1369
+ };
1370
+
1371
+ var deployProject = {
1372
+ name: 'deploy-project',
1373
+ description: 'Deploy a Strapi Cloud project',
1374
+ action: action$5,
1375
+ command: command$7
1376
+ };
1377
+
1378
+ async function getLocalConfig(ctx) {
1379
+ try {
1380
+ return await retrieve();
1381
+ } catch (e) {
1382
+ ctx.logger.debug('Failed to get project config', e);
1383
+ ctx.logger.error('An error occurred while retrieving config data from your local project.');
1384
+ return null;
1385
+ }
1386
+ }
1387
+ async function getLocalProject(ctx) {
1388
+ const localConfig = await getLocalConfig(ctx);
1389
+ if (!localConfig || !localConfig.project) {
1390
+ ctx.logger.warn(`\nWe couldn't find a valid local project config.\nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command.`);
1391
+ process.exit(1);
1392
+ }
1393
+ return localConfig.project;
1394
+ }
1395
+
1396
+ const QUIT_OPTION$1 = 'Quit';
1397
+ async function promptForRelink(ctx, cloudApiService, existingConfig) {
1398
+ if (existingConfig && existingConfig.project) {
1399
+ const { shouldRelink } = await inquirer.prompt([
1400
+ {
1401
+ type: 'confirm',
1402
+ name: 'shouldRelink',
1403
+ message: `A project named ${chalk.cyan(existingConfig.project.displayName ? existingConfig.project.displayName : existingConfig.project.name)} is already linked to this local folder. Do you want to update the link?`,
1404
+ default: false
1405
+ }
1406
+ ]);
1407
+ if (!shouldRelink) {
1408
+ await trackEvent(ctx, cloudApiService, 'didNotLinkProject', {
1409
+ currentProjectName: existingConfig.project?.name
1410
+ });
1411
+ return false;
1412
+ }
1413
+ }
1414
+ return true;
1415
+ }
1416
+ async function getProjectsList(ctx, cloudApiService, existingConfig) {
1417
+ const spinner = ctx.logger.spinner('Fetching your projects...\n').start();
1418
+ try {
1419
+ const { data: { data: projectList } } = await cloudApiService.listLinkProjects();
1420
+ spinner.succeed();
1421
+ if (!Array.isArray(projectList)) {
1422
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud.");
1423
+ return null;
1424
+ }
1425
+ const projects = projectList.filter((project)=>!(project.isMaintainer || project.name === existingConfig?.project?.name)).map((project)=>{
1426
+ return {
1427
+ name: project.displayName,
1428
+ value: {
1429
+ name: project.name,
1430
+ displayName: project.displayName
1431
+ }
1432
+ };
1433
+ });
1434
+ if (projects.length === 0) {
1435
+ ctx.logger.log("We couldn't find any projects available for linking in Strapi Cloud.");
1436
+ return null;
1437
+ }
1438
+ return projects;
1439
+ } catch (e) {
1440
+ spinner.fail('An error occurred while fetching your projects from Strapi Cloud.');
1441
+ ctx.logger.debug('Failed to list projects', e);
1442
+ return null;
1443
+ }
1444
+ }
1445
+ async function getUserSelection(ctx, projects) {
1446
+ const { logger } = ctx;
1447
+ try {
1448
+ const answer = await inquirer.prompt([
1449
+ {
1450
+ type: 'list',
1451
+ name: 'linkProject',
1452
+ message: 'Which project do you want to link?',
1453
+ choices: [
1454
+ ...projects,
1455
+ {
1456
+ name: chalk.grey(`(${QUIT_OPTION$1})`),
1457
+ value: null
1458
+ }
1459
+ ]
1460
+ }
1461
+ ]);
1462
+ if (!answer.linkProject) {
1463
+ return null;
1464
+ }
1465
+ return answer;
1466
+ } catch (e) {
1467
+ logger.debug('Failed to get user input', e);
1468
+ logger.error('An error occurred while trying to get your input.');
1469
+ return null;
1470
+ }
1471
+ }
1472
+ var action$4 = (async (ctx)=>{
1473
+ const { getValidToken } = await tokenServiceFactory(ctx);
1474
+ const token = await getValidToken(ctx, promptLogin);
1475
+ const { logger } = ctx;
1476
+ if (!token) {
1477
+ return;
1478
+ }
1479
+ const cloudApiService = await cloudApiFactory(ctx, token);
1480
+ const existingConfig = await getLocalConfig(ctx);
1481
+ const shouldRelink = await promptForRelink(ctx, cloudApiService, existingConfig);
1482
+ if (!shouldRelink) {
1483
+ return;
1484
+ }
1485
+ await trackEvent(ctx, cloudApiService, 'willLinkProject', {});
1486
+ const projects = await getProjectsList(ctx, cloudApiService, existingConfig);
1487
+ if (!projects) {
1488
+ return;
1489
+ }
1490
+ const answer = await getUserSelection(ctx, projects);
1491
+ if (!answer) {
1492
+ return;
1493
+ }
1494
+ try {
1495
+ const { confirmAction } = await inquirer.prompt([
1496
+ {
1497
+ type: 'confirm',
1498
+ name: 'confirmAction',
1499
+ message: 'Warning: Once linked, deploying from CLI will replace the existing project and its data. Confirm to proceed:',
1500
+ default: false
1501
+ }
1502
+ ]);
1503
+ if (!confirmAction) {
1504
+ await trackEvent(ctx, cloudApiService, 'didNotLinkProject', {
1505
+ cancelledProjectName: answer.linkProject.name,
1506
+ currentProjectName: existingConfig ? existingConfig.project?.name : null
1507
+ });
1508
+ return;
1509
+ }
1510
+ await save({
1511
+ project: answer.linkProject
1512
+ });
1513
+ logger.log(` You have successfully linked your project to ${chalk.cyan(answer.linkProject.displayName)}. You are now able to deploy your project.`);
1514
+ await trackEvent(ctx, cloudApiService, 'didLinkProject', {
1515
+ projectInternalName: answer.linkProject
1516
+ });
1517
+ } catch (e) {
1518
+ logger.debug('Failed to link project', e);
1519
+ logger.error('An error occurred while linking the project.');
1520
+ await trackEvent(ctx, cloudApiService, 'didNotLinkProject', {
1521
+ projectInternalName: answer.linkProject
1522
+ });
1523
+ }
1524
+ });
1525
+
1526
+ /**
1527
+ * `$ link local directory to project of the cloud`
1528
+ */ const command$6 = ({ command, ctx })=>{
1529
+ command.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));
1530
+ };
1531
+
1532
+ var link = {
1533
+ name: 'link-project',
1534
+ description: 'Link a local directory to a Strapi Cloud project',
1535
+ action: action$4,
1536
+ command: command$6
1537
+ };
1538
+
1539
+ /**
1540
+ * `$ cloud device flow login`
1541
+ */ const command$5 = ({ ctx })=>{
1542
+ return createCommand('cloud:login').alias('login').description('Strapi Cloud Login').addHelpText('after', '\nAfter running this command, you will be prompted to enter your authentication information.').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('login', loginAction)(ctx));
1543
+ };
1544
+
1545
+ var login = {
1546
+ name: 'login',
1547
+ description: 'Strapi Cloud Login',
1548
+ action: loginAction,
1549
+ command: command$5
1550
+ };
1551
+
1552
+ const openModule = import('open');
1553
+ var action$3 = (async (ctx)=>{
1554
+ const { logger } = ctx;
1555
+ const { retrieveToken, eraseToken } = await tokenServiceFactory(ctx);
1556
+ const token = await retrieveToken();
1557
+ if (!token) {
1558
+ logger.log("You're already logged out.");
1559
+ return;
1560
+ }
1561
+ const cloudApiService = await cloudApiFactory(ctx, token);
1562
+ const config = await cloudApiService.config();
1563
+ const cliConfig = config.data;
1564
+ try {
1565
+ await eraseToken();
1566
+ openModule.then((open)=>{
1567
+ open.default(`${cliConfig.baseUrl}/oidc/logout?client_id=${encodeURIComponent(cliConfig.clientId)}&logout_hint=${encodeURIComponent(token)}
1568
+ `).catch((e)=>{
1569
+ // Failing to open the logout URL is not a critical error, so we just log it
1570
+ logger.debug(e.message, e);
1571
+ });
1572
+ });
1573
+ logger.log('🔌 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.');
1574
+ } catch (e) {
1575
+ logger.error('🥲 Oops! Something went wrong while logging you out. Please try again.');
1576
+ logger.debug(e);
1577
+ }
1578
+ await trackEvent(ctx, cloudApiService, 'didLogout', {
1579
+ loginMethod: 'cli'
1580
+ });
1581
+ });
1582
+
1583
+ /**
1584
+ * `$ cloud device flow logout`
1585
+ */ const command$4 = ({ ctx })=>{
1586
+ return createCommand('cloud:logout').alias('logout').description('Strapi Cloud Logout').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('logout', action$3)(ctx));
1587
+ };
1588
+
1589
+ var logout = {
1590
+ name: 'logout',
1591
+ description: 'Strapi Cloud Logout',
1592
+ action: action$3,
1593
+ command: command$4
1594
+ };
1595
+
1596
+ /**
1597
+ * `$ create project in Strapi cloud`
1598
+ */ const command$3 = ({ ctx })=>{
1599
+ return createCommand('cloud:create-project').description('Create a Strapi Cloud project').option('-d, --debug', 'Enable debugging mode with verbose logs').option('-s, --silent', "Don't log anything").action(()=>runAction('cloud:create-project', action$6)(ctx));
1600
+ };
1601
+
1602
+ var createProject = {
1603
+ name: 'create-project',
1604
+ description: 'Create a new project',
1605
+ action: action$6,
1606
+ command: command$3
1607
+ };
1608
+
1609
+ var action$2 = (async (ctx)=>{
1610
+ const { getValidToken } = await tokenServiceFactory(ctx);
1611
+ const token = await getValidToken(ctx, promptLogin);
1612
+ const { logger } = ctx;
1613
+ if (!token) {
1614
+ return;
1615
+ }
1616
+ const cloudApiService = await cloudApiFactory(ctx, token);
1617
+ const spinner = logger.spinner('Fetching your projects...').start();
1618
+ try {
1619
+ const { data: { data: projectList } } = await cloudApiService.listProjects();
1620
+ spinner.succeed();
1621
+ logger.log(projectList);
1622
+ } catch (e) {
1623
+ ctx.logger.debug('Failed to list projects', e);
1624
+ spinner.fail('An error occurred while fetching your projects from Strapi Cloud.');
1625
+ }
1626
+ });
1627
+
1628
+ /**
1629
+ * `$ list project from the cloud`
1630
+ */ const command$2 = ({ command, ctx })=>{
1631
+ command.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));
1632
+ };
1633
+
1634
+ var listProjects = {
1635
+ name: 'list-projects',
1636
+ description: 'List Strapi Cloud projects',
1637
+ action: action$2,
1638
+ command: command$2
1639
+ };
1640
+
1641
+ var action$1 = (async (ctx)=>{
1642
+ const { getValidToken } = await tokenServiceFactory(ctx);
1643
+ const token = await getValidToken(ctx, promptLogin);
1644
+ const { logger } = ctx;
1645
+ if (!token) {
1646
+ return;
1647
+ }
1648
+ const project = await getLocalProject(ctx);
1649
+ if (!project) {
1650
+ ctx.logger.debug(`No valid local project configuration was found.`);
1651
+ return;
1652
+ }
1653
+ const cloudApiService = await cloudApiFactory(ctx, token);
1654
+ const spinner = logger.spinner('Fetching environments...').start();
1655
+ await trackEvent(ctx, cloudApiService, 'willListEnvironment', {
1656
+ projectInternalName: project.name
1657
+ });
1658
+ try {
1659
+ const { data: { data: environmentsList } } = await cloudApiService.listEnvironments({
1660
+ name: project.name
1661
+ });
1662
+ spinner.succeed();
1663
+ logger.log(environmentsList);
1664
+ await trackEvent(ctx, cloudApiService, 'didListEnvironment', {
1665
+ projectInternalName: project.name
1666
+ });
1667
+ } catch (e) {
1668
+ if (e.response && e.response.status === 404) {
1669
+ spinner.succeed();
1670
+ logger.warn(`\nThe project associated with this folder does not exist in Strapi Cloud. \nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command`);
1671
+ } else {
1672
+ spinner.fail('An error occurred while fetching environments data from Strapi Cloud.');
1673
+ logger.debug('Failed to list environments', e);
1674
+ }
1675
+ await trackEvent(ctx, cloudApiService, 'didNotListEnvironment', {
1676
+ projectInternalName: project.name
1677
+ });
1678
+ }
1679
+ });
1680
+
1681
+ function defineCloudNamespace(command, ctx) {
1682
+ const cloud = command.command('cloud').description('Manage Strapi Cloud projects');
1683
+ // Define cloud namespace aliases:
1684
+ cloud.command('environments').description('Alias for cloud environment list').action(()=>runAction('list', action$1)(ctx));
1685
+ return cloud;
1686
+ }
1687
+
1688
+ let environmentCmd = null;
1689
+ const initializeEnvironmentCommand = (command, ctx)=>{
1690
+ if (!environmentCmd) {
1691
+ const cloud = defineCloudNamespace(command, ctx);
1692
+ environmentCmd = cloud.command('environment').description('Manage environments');
1693
+ }
1694
+ return environmentCmd;
1695
+ };
1696
+
1697
+ const command$1 = ({ command, ctx })=>{
1698
+ const environmentCmd = initializeEnvironmentCommand(command, ctx);
1699
+ environmentCmd.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));
1700
+ };
1701
+
1702
+ var listEnvironments = {
1703
+ name: 'list-environments',
1704
+ description: 'List Strapi Cloud environments',
1705
+ action: action$1,
1706
+ command: command$1
1707
+ };
1708
+
1709
+ const QUIT_OPTION = 'Quit';
1710
+ var action = (async (ctx)=>{
1711
+ const { getValidToken } = await tokenServiceFactory(ctx);
1712
+ const token = await getValidToken(ctx, promptLogin);
1713
+ const { logger } = ctx;
1714
+ if (!token) {
1715
+ return;
1716
+ }
1717
+ const project = await getLocalProject(ctx);
1718
+ if (!project) {
1719
+ logger.debug(`No valid local project configuration was found.`);
1720
+ return;
1721
+ }
1722
+ const cloudApiService = await cloudApiFactory(ctx, token);
1723
+ const environments = await getEnvironmentsList(ctx, cloudApiService, project);
1724
+ if (!environments) {
1725
+ logger.debug(`Fetching environments failed.`);
1726
+ return;
1727
+ }
1728
+ if (environments.length === 0) {
1729
+ logger.log(`The only available environment is already linked. You can add a new one from your project settings on the Strapi Cloud dashboard.`);
1730
+ return;
1731
+ }
1732
+ const answer = await promptUserForEnvironment(ctx, environments);
1733
+ if (!answer) {
1734
+ return;
1735
+ }
1736
+ await trackEvent(ctx, cloudApiService, 'willLinkEnvironment', {
1737
+ projectName: project.name,
1738
+ environmentName: answer.targetEnvironment
1739
+ });
1740
+ try {
1741
+ await patch({
1742
+ project: {
1743
+ targetEnvironment: answer.targetEnvironment
1744
+ }
1745
+ });
1746
+ } catch (e) {
1747
+ await trackEvent(ctx, cloudApiService, 'didNotLinkEnvironment', {
1748
+ projectName: project.name,
1749
+ environmentName: answer.targetEnvironment
1750
+ });
1751
+ logger.debug('Failed to link environment', e);
1752
+ logger.error('Failed to link the environment. If this issue persists, try re-linking your project or contact support.');
1753
+ process.exit(1);
1754
+ }
1755
+ logger.log(` You have successfully linked your project to ${chalk.cyan(answer.targetEnvironment)}, on ${chalk.cyan(project.displayName)}. You are now able to deploy your project.`);
1756
+ await trackEvent(ctx, cloudApiService, 'didLinkEnvironment', {
1757
+ projectName: project.name,
1758
+ environmentName: answer.targetEnvironment
1759
+ });
1760
+ });
1761
+ async function promptUserForEnvironment(ctx, environments) {
1762
+ const { logger } = ctx;
1763
+ try {
1764
+ const answer = await inquirer.prompt([
1765
+ {
1766
+ type: 'list',
1767
+ name: 'targetEnvironment',
1768
+ message: 'Which environment do you want to link?',
1769
+ choices: [
1770
+ ...environments,
1771
+ {
1772
+ name: chalk.grey(`(${QUIT_OPTION})`),
1773
+ value: null
1774
+ }
1775
+ ]
1776
+ }
1777
+ ]);
1778
+ if (!answer.targetEnvironment) {
1779
+ return null;
1780
+ }
1781
+ return answer;
1782
+ } catch (e) {
1783
+ logger.debug('Failed to get user input', e);
1784
+ logger.error('An error occurred while trying to get your environment selection.');
1785
+ return null;
1786
+ }
1787
+ }
1788
+ async function getEnvironmentsList(ctx, cloudApiService, project) {
1789
+ const spinner = ctx.logger.spinner('Fetching environments...\n').start();
1790
+ try {
1791
+ const { data: { data: environmentsList } } = await cloudApiService.listLinkEnvironments({
1792
+ name: project.name
1793
+ });
1794
+ if (!Array.isArray(environmentsList) || environmentsList.length === 0) {
1795
+ throw new Error('Environments not found in server response');
1796
+ }
1797
+ spinner.succeed();
1798
+ return environmentsList.filter((environment)=>environment.name !== project.targetEnvironment);
1799
+ } catch (e) {
1800
+ if (e.response && e.response.status === 404) {
1801
+ spinner.succeed();
1802
+ ctx.logger.warn(`\nThe project associated with this folder does not exist in Strapi Cloud. \nPlease link your local project to an existing Strapi Cloud project using the ${chalk.cyan('link')} command.`);
1803
+ } else {
1804
+ spinner.fail('An error occurred while fetching environments data from Strapi Cloud.');
1805
+ ctx.logger.debug('Failed to list environments', e);
1806
+ }
1807
+ }
1808
+ }
1809
+
1810
+ const command = ({ command, ctx })=>{
1811
+ const environmentCmd = initializeEnvironmentCommand(command, ctx);
1812
+ environmentCmd.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));
1813
+ };
1814
+
1815
+ var linkEnvironment = {
1816
+ name: 'link-environment',
1817
+ description: 'Link Strapi Cloud environment to a local project',
1818
+ action,
1819
+ command
1820
+ };
1821
+
1822
+ const cli = {
1823
+ deployProject,
1824
+ link,
1825
+ login,
1826
+ logout,
1827
+ createProject,
1828
+ linkEnvironment,
1829
+ listProjects,
1830
+ listEnvironments
1831
+ };
1832
+ const cloudCommands = [
1833
+ deployProject,
1834
+ link,
1835
+ login,
1836
+ logout,
1837
+ linkEnvironment,
1838
+ listProjects,
1839
+ listEnvironments
1840
+ ];
1841
+ async function initCloudCLIConfig() {
1842
+ const localConfig = await getLocalConfig$1();
1843
+ if (!localConfig.deviceId) {
1844
+ localConfig.deviceId = crypto$1.randomUUID();
1845
+ }
1846
+ await saveLocalConfig(localConfig);
1847
+ }
1848
+ async function buildStrapiCloudCommands({ command, ctx, argv }) {
1849
+ await initCloudCLIConfig();
1850
+ // Load all commands
1851
+ for (const cloudCommand of cloudCommands){
1852
+ try {
1853
+ // Add this command to the Commander command object
1854
+ const subCommand = await cloudCommand.command({
1855
+ command,
1856
+ ctx,
1857
+ argv
1858
+ });
1859
+ if (subCommand) {
1860
+ command.addCommand(subCommand);
1861
+ }
1862
+ } catch (e) {
1863
+ console.error(`Failed to load command ${cloudCommand.name}`, e);
1864
+ }
1865
+ }
1866
+ }
1867
+
1868
+ export { cli as a, buildStrapiCloudCommands as b, createLogger as c, index as i };
1869
+ //# sourceMappingURL=index-xAvJT3VT.mjs.map