@contentstack/cli-cm-export 1.5.8 → 1.6.1

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 (97) hide show
  1. package/README.md +2 -2
  2. package/lib/commands/cm/stacks/export.d.ts +10 -0
  3. package/lib/commands/cm/stacks/export.js +108 -0
  4. package/lib/config/index.d.ts +3 -0
  5. package/lib/config/index.js +393 -0
  6. package/lib/export/index.d.ts +1 -0
  7. package/lib/export/index.js +8 -0
  8. package/lib/export/module-exporter.d.ts +15 -0
  9. package/lib/export/module-exporter.js +93 -0
  10. package/lib/export/modules/assets.d.ts +54 -0
  11. package/lib/export/modules/assets.js +303 -0
  12. package/lib/export/modules/base-class.d.ts +48 -0
  13. package/lib/export/modules/base-class.js +117 -0
  14. package/lib/export/modules/index.d.ts +3 -0
  15. package/lib/export/modules/index.js +38 -0
  16. package/lib/export/modules/locales.d.ts +16 -0
  17. package/lib/export/modules/locales.js +68 -0
  18. package/lib/export/modules-js/assets.d.ts +43 -0
  19. package/lib/export/modules-js/assets.js +391 -0
  20. package/lib/export/modules-js/content-types.d.ts +21 -0
  21. package/lib/export/modules-js/content-types.js +75 -0
  22. package/lib/export/modules-js/custom-roles.d.ts +21 -0
  23. package/lib/export/modules-js/custom-roles.js +76 -0
  24. package/lib/export/modules-js/entries.d.ts +18 -0
  25. package/lib/export/modules-js/entries.js +141 -0
  26. package/lib/export/modules-js/environments.d.ts +16 -0
  27. package/lib/export/modules-js/environments.js +62 -0
  28. package/lib/export/modules-js/extensions.d.ts +18 -0
  29. package/lib/export/modules-js/extensions.js +57 -0
  30. package/lib/export/modules-js/global-fields.d.ts +22 -0
  31. package/lib/export/modules-js/global-fields.js +107 -0
  32. package/lib/export/modules-js/index.d.ts +1 -0
  33. package/lib/export/modules-js/index.js +33 -0
  34. package/lib/export/modules-js/labels.d.ts +14 -0
  35. package/lib/export/modules-js/labels.js +56 -0
  36. package/lib/export/modules-js/locales.d.ts +23 -0
  37. package/lib/export/modules-js/locales.js +67 -0
  38. package/lib/export/modules-js/marketplace-apps.d.ts +21 -0
  39. package/lib/export/modules-js/marketplace-apps.js +144 -0
  40. package/lib/export/modules-js/stack.d.ts +18 -0
  41. package/lib/export/modules-js/stack.js +91 -0
  42. package/lib/export/modules-js/webhooks.d.ts +18 -0
  43. package/lib/export/modules-js/webhooks.js +60 -0
  44. package/lib/export/modules-js/workflows.d.ts +16 -0
  45. package/lib/export/modules-js/workflows.js +89 -0
  46. package/lib/types/default-config.d.ts +158 -0
  47. package/lib/types/default-config.js +2 -0
  48. package/lib/types/export-config.d.ts +34 -0
  49. package/lib/types/export-config.js +2 -0
  50. package/lib/types/index.d.ts +45 -0
  51. package/lib/types/index.js +2 -0
  52. package/lib/utils/basic-login.d.ts +8 -0
  53. package/lib/utils/basic-login.js +45 -0
  54. package/lib/utils/common-helper.d.ts +11 -0
  55. package/lib/utils/common-helper.js +78 -0
  56. package/lib/utils/export-config-handler.d.ts +3 -0
  57. package/lib/utils/export-config-handler.js +72 -0
  58. package/lib/utils/file-helper.d.ts +14 -0
  59. package/lib/utils/file-helper.js +120 -0
  60. package/lib/utils/index.d.ts +10 -0
  61. package/lib/utils/index.js +21 -0
  62. package/lib/utils/interactive.d.ts +6 -0
  63. package/lib/utils/interactive.js +71 -0
  64. package/lib/utils/logger.d.ts +8 -0
  65. package/lib/utils/logger.js +154 -0
  66. package/lib/utils/marketplace-app-helper.d.ts +1 -0
  67. package/lib/utils/marketplace-app-helper.js +23 -0
  68. package/lib/utils/setup-branches.d.ts +3 -0
  69. package/lib/utils/setup-branches.js +49 -0
  70. package/lib/utils/setup-export-dir.d.ts +2 -0
  71. package/lib/utils/setup-export-dir.js +12 -0
  72. package/messages/index.json +1 -7
  73. package/oclif.manifest.json +1 -1
  74. package/package.json +37 -23
  75. package/src/app.js +0 -161
  76. package/src/commands/cm/stacks/export.js +0 -202
  77. package/src/config/default.js +0 -360
  78. package/src/lib/export/assets.js +0 -451
  79. package/src/lib/export/content-types.js +0 -90
  80. package/src/lib/export/custom-roles.js +0 -93
  81. package/src/lib/export/entries.js +0 -200
  82. package/src/lib/export/environments.js +0 -74
  83. package/src/lib/export/extensions.js +0 -69
  84. package/src/lib/export/global-fields.js +0 -122
  85. package/src/lib/export/labels.js +0 -69
  86. package/src/lib/export/locales.js +0 -72
  87. package/src/lib/export/marketplace-apps.js +0 -184
  88. package/src/lib/export/stack.js +0 -99
  89. package/src/lib/export/webhooks.js +0 -76
  90. package/src/lib/export/workflows.js +0 -110
  91. package/src/lib/util/export-flags.js +0 -193
  92. package/src/lib/util/helper.js +0 -113
  93. package/src/lib/util/index.js +0 -80
  94. package/src/lib/util/log.js +0 -158
  95. package/src/lib/util/login.js +0 -79
  96. package/src/lib/util/marketplace-app-helper.js +0 -24
  97. package/src/lib/util/setup-branches.js +0 -56
@@ -1,451 +0,0 @@
1
- /*!
2
- * Contentstack Export
3
- * Copyright (c) 2019 Contentstack LLC
4
- * MIT Licensed
5
- */
6
-
7
- const mkdirp = require('mkdirp');
8
- const path = require('path');
9
- const fs = require('fs');
10
- const Promise = require('bluebird');
11
- const _ = require('lodash');
12
- const chalk = require('chalk');
13
- const progress = require('progress-stream');
14
- const { HttpClient, configHandler } = require('@contentstack/cli-utilities');
15
-
16
- const helper = require('../util/helper');
17
- const { addlogs } = require('../util/log');
18
-
19
- let config = require('../../config/default');
20
-
21
- module.exports = class ExportAssets {
22
- config;
23
- bLimit;
24
- vLimit;
25
- invalidKeys;
26
- folderJSONPath;
27
- folderData = [];
28
- assetsFolderPath;
29
- assetContents = {};
30
- httpClient = HttpClient.create();
31
- assetConfig = config.modules.assets;
32
-
33
- constructor(exportConfig, stackAPIClient) {
34
- this.stackAPIClient = stackAPIClient;
35
- this.config = _.merge(config, exportConfig);
36
- this.folderData = [];
37
- this.assetContents = {};
38
- this.assetDownloadRetry = {};
39
- this.assetDownloadRetryLimit = 3;
40
- this.invalidKeys = this.assetConfig.invalidKeys;
41
- this.bLimit = this.assetConfig.batchLimit || 15;
42
- this.vLimit = this.assetConfig.downloadLimit || this.config.fetchConcurrency || 3;
43
- }
44
-
45
- start() {
46
- const self = this;
47
- this.assetsFolderPath = path.resolve(this.config.data, this.config.branchName || '', this.assetConfig.dirName);
48
- this.assetContentsFile = path.resolve(this.assetsFolderPath, 'assets.json');
49
- this.folderJSONPath = path.resolve(this.assetsFolderPath, 'folders.json');
50
-
51
- addlogs(this.config, 'Starting assets export', 'success');
52
-
53
- // Create asset folder
54
- mkdirp.sync(this.assetsFolderPath);
55
-
56
- return new Promise((resolve, reject) => {
57
- // TBD: getting all the assets should have optimized
58
- return self
59
- .getAssetCount()
60
- .then((count) => {
61
- const assetBatches = [];
62
-
63
- if (typeof count !== 'number' || count === 0) {
64
- addlogs(self.config, 'No assets found', 'success');
65
- return resolve();
66
- }
67
- for (let i = 0; i <= count; i += self.bLimit) {
68
- assetBatches.push(i);
69
- }
70
-
71
- return Promise.map(
72
- assetBatches,
73
- (batch) => {
74
- return self
75
- .getAssetJSON(batch)
76
- .then((assetsJSON) => {
77
- return Promise.map(
78
- assetsJSON,
79
- (assetJSON) => {
80
- if (self.assetConfig.downloadVersionAssets) {
81
- return self
82
- .getVersionedAssetJSON(assetJSON.uid, assetJSON._version)
83
- .then(() => {
84
- self.assetContents[assetJSON.uid] = assetJSON;
85
- })
86
- .catch((error) => {
87
- addlogs(
88
- self.config,
89
- chalk.red('The following asset failed to download\n' + JSON.stringify(assetJSON)),
90
- );
91
- addlogs(self.config, error, 'error');
92
- });
93
- } else {
94
- return self
95
- .downloadAsset(assetJSON)
96
- .then(() => {
97
- self.assetContents[assetJSON.uid] = assetJSON;
98
- })
99
- .catch((err) => {
100
- addlogs(
101
- { errorCode: err && err.code, uid: assetJSON.uid },
102
- `Asset download failed - ${assetJSON.uid}`,
103
- 'error',
104
- );
105
- return err;
106
- });
107
- }
108
- },
109
- { concurrency: self.vLimit },
110
- )
111
- .then(() => {
112
- addlogs(self.config, 'Batch no ' + (batch + 1) + ' of assets is complete', 'success');
113
- // helper.writeFileSync(this.assetContentsFile, self.assetContents)
114
- })
115
- .catch((error) => {
116
- console.log('Error fetch/download the asset', error && error.message);
117
- addlogs(self.config, 'Asset batch ' + (batch + 1) + ' failed to download', 'error');
118
- addlogs(self.config, error, 'error');
119
- });
120
- })
121
- .catch((error) => {
122
- addlogs(self.config, error, 'error');
123
- reject(error);
124
- });
125
- },
126
- { concurrency: self.assetConfig.concurrencyLimit || 1 },
127
- )
128
- .then(() => {
129
- helper.writeFileSync(self.assetContentsFile, self.assetContents);
130
-
131
- return self
132
- .exportFolders()
133
- .then(() => {
134
- addlogs(self.config, chalk.green('Asset export completed successfully'), 'success');
135
- return resolve();
136
- })
137
- .catch((error) => {
138
- addlogs(self.config, error, 'success');
139
- reject(error);
140
- });
141
- })
142
- .catch((error) => {
143
- helper.writeFileSync(self.assetContentsFile, self.assetContents);
144
- addlogs(
145
- self.config,
146
- chalk.red('Asset export failed due to the following errors ' + JSON.stringify(error), 'error'),
147
- );
148
- addlogs(self.config, error, 'success');
149
- reject(error);
150
- });
151
- })
152
- .catch((error) => {
153
- addlogs(self.config, error, 'success');
154
- reject(error);
155
- });
156
- });
157
- }
158
-
159
- exportFolders() {
160
- const self = this;
161
- return new Promise((resolve, reject) => {
162
- return self
163
- .getAssetCount(true)
164
- .then((fCount) => {
165
- if (fCount === 0) {
166
- addlogs(self.config, 'No folders were found in the stack!', 'success');
167
- return resolve();
168
- }
169
-
170
- return self
171
- .getFolderJSON(0, fCount)
172
- .then(() => {
173
- // asset folders have been successfully exported
174
- addlogs(self.config, 'Asset-folders have been successfully exported!', 'success');
175
- return resolve();
176
- })
177
- .catch((error) => {
178
- addlogs(self.config, chalk.red('Error while exporting asset-folders!'), 'error');
179
- return reject(error);
180
- });
181
- })
182
- .catch((error) => {
183
- addlogs(self.config, error, 'error');
184
- // error while fetching asset folder count
185
- return reject(error);
186
- });
187
- });
188
- }
189
-
190
- getFolderJSON(skip, fCount) {
191
- const self = this;
192
- return new Promise((resolve, reject) => {
193
- if (typeof skip !== 'number') {
194
- skip = 0;
195
- }
196
-
197
- if (skip >= fCount) {
198
- helper.writeFileSync(self.folderJSONPath, self.folderData);
199
- return resolve();
200
- }
201
-
202
- const queryRequestObj = {
203
- skip,
204
- include_folders: true,
205
- query: { is_dir: true },
206
- };
207
-
208
- self.stackAPIClient
209
- .asset()
210
- .query(queryRequestObj)
211
- .find()
212
- .then((response) => {
213
- skip += 100;
214
- self.folderData.push(...response.items);
215
- return self.getFolderJSON(skip, fCount).then(resolve).catch(reject);
216
- })
217
- .catch((error) => reject(error));
218
- });
219
- }
220
-
221
- getAssetCount(folder) {
222
- const self = this;
223
- return new Promise((resolve, reject) => {
224
- if (folder && typeof folder === 'boolean') {
225
- const queryOptions = {
226
- skip: 99999990,
227
- include_count: true,
228
- include_folders: true,
229
- query: { is_dir: true },
230
- };
231
- self.stackAPIClient
232
- .asset()
233
- .query(queryOptions)
234
- .find()
235
- .then((asset) => {
236
- return resolve(asset.count);
237
- })
238
- .catch((error) => {
239
- addlogs(self.config, error, 'error');
240
- });
241
- } else {
242
- const queryOptions = { skip: 99999990, include_count: true };
243
- self.stackAPIClient
244
- .asset()
245
- .query(queryOptions)
246
- .find()
247
- .then(({ count }) => resolve(count))
248
- .catch((error) => {
249
- addlogs(self.config, error, 'error');
250
- reject(error);
251
- });
252
- }
253
- });
254
- }
255
-
256
- getAssetJSON(skip) {
257
- const self = this;
258
- return new Promise((resolve, reject) => {
259
- if (typeof skip !== 'number') {
260
- skip = 0;
261
- }
262
- const queryRequestObj = {
263
- skip: skip,
264
- limit: self.bLimit,
265
- include_publish_details: true,
266
- except: {
267
- BASE: self.invalidKeys,
268
- },
269
- };
270
-
271
- self.stackAPIClient
272
- .asset()
273
- .query(queryRequestObj)
274
- .find()
275
- .then(({ items }) => resolve(items))
276
- .catch((error) => {
277
- addlogs(self.config, error, 'error');
278
- return reject();
279
- });
280
- });
281
- }
282
-
283
- getVersionedAssetJSON(uid, version, bucket) {
284
- const self = this;
285
- const assetVersionInfo = bucket || [];
286
-
287
- return new Promise((resolve, reject) => {
288
- if (self.assetDownloadRetry[uid + version] > self.assetDownloadRetryLimit) {
289
- console.log('Reached max', self.assetDownloadRetry[uid + version]);
290
- return reject(new Error('Asset Max download retry limit exceeded! ' + uid));
291
- }
292
-
293
- if (version <= 0) {
294
- const assetVersionInfoFile = path.resolve(self.assetsFolderPath, uid, '_contentstack_' + uid + '.json');
295
- helper.writeFileSync(assetVersionInfoFile, assetVersionInfo);
296
- return resolve();
297
- }
298
- const queryrequestOption = {
299
- version: version,
300
- include_publish_details: true,
301
- except: {
302
- BASE: self.invalidKeys,
303
- },
304
- };
305
-
306
- self.stackAPIClient
307
- .asset(uid)
308
- .fetch(queryrequestOption)
309
- .then((versionedAssetJSONResponse) => {
310
- self
311
- .downloadAsset(versionedAssetJSONResponse)
312
- .then(() => {
313
- assetVersionInfo.splice(0, 0, versionedAssetJSONResponse);
314
- // Remove duplicates
315
- assetVersionInfo = _.uniqWith(assetVersionInfo, _.isEqual);
316
- self.getVersionedAssetJSON(uid, --version, assetVersionInfo).then(resolve).catch(reject);
317
- })
318
- .catch(reject);
319
- })
320
- .catch((error) => {
321
- addlogs(self.config, error, 'error');
322
- console.log('Error on fetch', error && error.message);
323
-
324
- if (error.status === 408) {
325
- console.log('retrying', uid);
326
- // retrying when timeout
327
- self.assetDownloadRetry[uid + version]
328
- ? ++self.assetDownloadRetry[uid + version]
329
- : (self.assetDownloadRetry[uid + version] = 1);
330
- return self.getVersionedAssetJSON(uid, version, assetVersionInfo).then(resolve).catch(reject);
331
- }
332
- reject(error);
333
- });
334
- });
335
- }
336
-
337
- downloadAsset(asset) {
338
- const self = this;
339
- return new Promise(async (resolve, reject) => {
340
- const assetFolderPath = path.resolve(self.assetsFolderPath, asset.uid);
341
- const assetFilePath = path.resolve(assetFolderPath, asset.filename);
342
-
343
- if (fs.existsSync(assetFilePath)) {
344
- addlogs(
345
- self.config,
346
- 'Skipping download of { title: ' + asset.filename + ', uid: ' + asset.uid + ' }, as they already exist',
347
- 'success',
348
- );
349
- return resolve();
350
- }
351
- self.assetStream = {
352
- url: self.config.securedAssets
353
- ? `${asset.url}?authtoken=${configHandler.get('authtoken')}`
354
- : asset.url,
355
- };
356
-
357
- mkdirp.sync(assetFolderPath);
358
- const assetFileStream = fs.createWriteStream(assetFilePath);
359
- self.assetStream.url = encodeURI(self.assetStream.url);
360
- self.httpClient
361
- .options({ responseType: 'stream' })
362
- .get(self.assetStream.url)
363
- .then(({ data: assetStreamRequest }) => {
364
- if (self.assetConfig.enableDownloadStatus) {
365
- const str = progress({
366
- time: 5000,
367
- length: assetStreamRequest.headers['content-length'],
368
- });
369
- str.on('progress', (progressData) => {
370
- console.log(`${asset.filename}: ${Math.round(progressData.percentage)}%`);
371
- });
372
- assetStreamRequest.pipe(str).pipe(assetFileStream);
373
- }
374
- assetStreamRequest.pipe(assetFileStream);
375
- })
376
- .catch((error) => {
377
- addlogs(self.config, error, 'error');
378
- reject(error);
379
- });
380
- assetFileStream
381
- .on('close', () => {
382
- addlogs(self.config, 'Downloaded ' + asset.filename + ': ' + asset.uid + ' successfully!', 'success');
383
- return resolve();
384
- })
385
- .on('error', (error) => {
386
- addlogs(self.config, error, 'error');
387
- reject(error);
388
- });
389
- });
390
- }
391
-
392
- getFolders() {
393
- const self = this;
394
- return new Promise((resolve, reject) => {
395
- return self
396
- .getAssetCount(true)
397
- .then((count) => {
398
- if (count === 0) {
399
- addlogs(self.config, 'No folders were found in the stack', 'success');
400
- return resolve();
401
- }
402
- return self
403
- .getFolderDetails(0, count)
404
- .then(() => {
405
- addlogs(self.config, chalk.green('Exported asset-folders successfully!'), 'success');
406
- return resolve();
407
- })
408
- .catch((error) => {
409
- addlogs(self.config, error, 'error');
410
- reject(error);
411
- });
412
- })
413
- .catch((error) => {
414
- addlogs(self.config, error, 'error');
415
- reject(error);
416
- });
417
- });
418
- }
419
-
420
- getFolderDetails(skip, tCount) {
421
- const self = this;
422
- return new Promise((resolve, reject) => {
423
- if (typeof skip !== 'number') {
424
- skip = 0;
425
- }
426
- if (skip > tCount) {
427
- helper.writeFileSync(self.folderJSONPath, self.folderContents);
428
- return resolve();
429
- }
430
- const queryRequestObj = {
431
- skip: skip,
432
- include_folders: true,
433
- query: { is_dir: true },
434
- };
435
- self.stackAPIClient
436
- .asset()
437
- .query(queryRequestObj)
438
- .find()
439
- .then((folderDetailsResponse) => {
440
- for (let i in folderDetailsResponse.items) {
441
- self.folderContents.push(folderDetailsResponse.items[i]);
442
- }
443
- skip += 100;
444
- return self.getFolderDetails(skip, tCount).then(resolve).catch(reject);
445
- })
446
- .catch((error) => {
447
- addlogs(self.config, error, 'error');
448
- });
449
- });
450
- }
451
- };
@@ -1,90 +0,0 @@
1
- const path = require('path');
2
- const fileHelper = require('../util/helper');
3
- const chalk = require('chalk');
4
- const { executeTask, formatError } = require('../util');
5
- const { addlogs } = require('../util/log');
6
-
7
- class ContentTypesExport {
8
- constructor(exportConfig, stackAPIClient) {
9
- this.stackAPIClient = stackAPIClient;
10
- this.exportConfig = exportConfig;
11
- this.contentTypesConfig = exportConfig.modules.content_types;
12
- this.qs = {
13
- include_count: true,
14
- asc: 'updated_at',
15
- limit: this.contentTypesConfig.limit,
16
- include_global_field_schema: true,
17
- };
18
- // If content type id is provided then use it as part of query
19
- if (Array.isArray(this.exportConfig.contentTypes) && this.exportConfig.length > 0) {
20
- this.qs.uid = { $in: this.exportConfig.contentTypes };
21
- }
22
- this.contentTypesPath = path.resolve(
23
- exportConfig.data,
24
- exportConfig.branchName || '',
25
- this.contentTypesConfig.dirName,
26
- );
27
- this.contentTypes = [];
28
- this.fetchConcurrency = this.contentTypesConfig.fetchConcurrency || this.exportConfig.fetchConcurrency;
29
- this.writeConcurrency = this.contentTypesConfig.writeConcurrency || this.exportConfig.writeConcurrency;
30
- }
31
-
32
- async start() {
33
- try {
34
- addlogs(this.exportConfig, 'Starting content type export', 'success');
35
- await fileHelper.makeDirectory(this.contentTypesPath);
36
- await this.getContentTypes();
37
- await this.writeContentTypes(this.contentTypes);
38
- addlogs(this.exportConfig, chalk.green('Content type(s) exported successfully'), 'success');
39
- } catch (error) {
40
- addlogs(this.exportConfig, chalk.red(`Failed to export content types ${formatError(error)}`), 'error');
41
- throw new Error('Failed to export content types');
42
- }
43
- }
44
-
45
- async getContentTypes(skip = 0) {
46
- if (skip) {
47
- this.qs.skip = skip;
48
- }
49
-
50
- const contentTypeSearchResponse = await this.stackAPIClient.contentType().query(this.qs).find();
51
- if (Array.isArray(contentTypeSearchResponse.items) && contentTypeSearchResponse.items.length > 0) {
52
- let updatedContentTypes = this.sanitizeAttribs(contentTypeSearchResponse.items);
53
- this.contentTypes.push(...updatedContentTypes);
54
-
55
- skip += this.contentTypesConfig.limit;
56
- if (skip > contentTypeSearchResponse.count) {
57
- return;
58
- }
59
- return await this.getContentTypes(skip);
60
- } else {
61
- console.log('No content types returned for the given query');
62
- }
63
- }
64
-
65
- sanitizeAttribs(contentTypes) {
66
- let updatedContentTypes = [];
67
- contentTypes.forEach((contentType) => {
68
- for (let key in contentType) {
69
- if (this.contentTypesConfig.validKeys.indexOf(key) === -1) {
70
- delete contentType[key];
71
- }
72
- }
73
- updatedContentTypes.push(contentType);
74
- });
75
- return updatedContentTypes;
76
- }
77
-
78
- async writeContentTypes(contentTypes) {
79
- function write(contentType) {
80
- return fileHelper.writeFile(
81
- path.join(this.contentTypesPath,
82
- `${contentType.uid === 'schema' ? 'schema|1' : contentType.uid}.json`),
83
- contentType);
84
- }
85
- await executeTask(contentTypes, write.bind(this), { concurrency: this.writeConcurrency });
86
- return fileHelper.writeFile(path.join(this.contentTypesPath, 'schema.json'), contentTypes);
87
- }
88
- }
89
-
90
- module.exports = ContentTypesExport;
@@ -1,93 +0,0 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const chalk = require('chalk');
5
- const mkdirp = require('mkdirp');
6
- const { merge } = require('lodash');
7
- const helper = require('../util/helper');
8
- const { addlogs } = require('../util/log');
9
- const { formatError } = require('../util');
10
- const config = require('../../config/default');
11
-
12
- module.exports = class ExportCustomRoles {
13
- roles = {};
14
- customRoles = {};
15
- EXISTING_ROLES = {
16
- Admin: 1,
17
- Developer: 1,
18
- 'Content Manager': 1,
19
- };
20
- rolesConfig = config.modules.customRoles;
21
-
22
- constructor(exportConfig, stackAPIClient) {
23
- this.config = merge(config, exportConfig);
24
- this.stackAPIClient = stackAPIClient;
25
- }
26
-
27
- async start() {
28
- const self = this;
29
-
30
- try {
31
- addlogs(this.config, 'Starting roles export', 'success');
32
- const rolesFolderPath = path.resolve(this.config.data, this.config.branchName || '', this.rolesConfig.dirName);
33
- mkdirp.sync(rolesFolderPath);
34
- const roles = await self.stackAPIClient.role().fetchAll({ include_rules: true, include_permissions: true });
35
- const customRoles = roles.items.filter((role) => !self.EXISTING_ROLES[role.name]);
36
- if (!customRoles.length) {
37
- addlogs(self.config, 'No custom roles were found in the Stack', 'success');
38
- return;
39
- }
40
- await self.getCustomRolesLocales(
41
- customRoles,
42
- path.join(rolesFolderPath, self.rolesConfig.customRolesLocalesFileName),
43
- self.stackAPIClient,
44
- self.config,
45
- );
46
- self.customRoles = {};
47
- customRoles.forEach((role) => {
48
- addlogs(self.config, role.name + ' role was exported successfully', 'success');
49
- self.customRoles[role.uid] = role;
50
- });
51
- helper.writeFileSync(path.join(rolesFolderPath, self.rolesConfig.fileName), self.customRoles);
52
- addlogs(self.config, chalk.green('All the custom roles have been exported successfully'), 'success');
53
- } catch (error) {
54
- if (error.statusCode === 401) {
55
- addlogs(
56
- self.config,
57
- chalk.red('You are not allowed to export roles, Unless you provide email and password in config'),
58
- 'error',
59
- );
60
- return;
61
- }
62
- addlogs(self.config, 'Error occurred in exporting roles. ' + error && error.message, 'error');
63
- addlogs(self.config, formatError(error), 'error');
64
- throw error;
65
- }
66
- }
67
-
68
- async getCustomRolesLocales(customRoles, customRolesLocalesFilepath, stackAPIClient, config) {
69
- const localesMap = {};
70
- for (const role of customRoles) {
71
- const rulesLocales = role.rules.find((rule) => rule.module === 'locale');
72
- if (rulesLocales.locales && rulesLocales.locales.length) {
73
- rulesLocales.locales.forEach((locale) => {
74
- localesMap[locale] = 1;
75
- });
76
- }
77
- }
78
- if (Object.keys(localesMap).length) {
79
- const locales = await stackAPIClient.locale().query({}).find();
80
- const sourceLocalesMap = {};
81
- for (const locale of locales.items) {
82
- sourceLocalesMap[locale.uid] = locale;
83
- }
84
- for (const locale in localesMap) {
85
- if(sourceLocalesMap[locale]!==undefined) {
86
- delete sourceLocalesMap[locale]['stackHeaders'];
87
- }
88
- localesMap[locale] = sourceLocalesMap[locale];
89
- }
90
- helper.writeFileSync(customRolesLocalesFilepath, localesMap);
91
- }
92
- }
93
- };