@contentstack/cli-variants 1.0.0 → 1.1.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.
Files changed (45) hide show
  1. package/lib/export/attributes.js +2 -1
  2. package/lib/export/audiences.js +2 -1
  3. package/lib/export/events.js +2 -1
  4. package/lib/export/experiences.js +3 -2
  5. package/lib/export/projects.js +2 -1
  6. package/lib/export/variant-entries.js +1 -1
  7. package/lib/import/attribute.js +2 -1
  8. package/lib/import/audiences.js +2 -1
  9. package/lib/import/events.js +2 -1
  10. package/lib/import/experiences.js +3 -2
  11. package/lib/import/project.js +3 -2
  12. package/lib/import/variant-entries.js +15 -9
  13. package/lib/messages/index.js +1 -1
  14. package/lib/types/personalization-api-adapter.d.ts +1 -1
  15. package/lib/types/variant-api-adapter.d.ts +3 -2
  16. package/lib/types/variant-entry.d.ts +0 -1
  17. package/lib/utils/attributes-helper.js +2 -2
  18. package/lib/utils/error-helper.js +6 -6
  19. package/lib/utils/logger.js +5 -4
  20. package/lib/utils/personalization-api-adapter.d.ts +2 -1
  21. package/lib/utils/personalization-api-adapter.js +54 -26
  22. package/lib/utils/variant-api-adapter.d.ts +5 -4
  23. package/lib/utils/variant-api-adapter.js +28 -10
  24. package/package.json +2 -2
  25. package/src/export/attributes.ts +6 -2
  26. package/src/export/audiences.ts +2 -1
  27. package/src/export/events.ts +2 -1
  28. package/src/export/experiences.ts +3 -2
  29. package/src/export/projects.ts +2 -1
  30. package/src/export/variant-entries.ts +1 -2
  31. package/src/import/attribute.ts +2 -2
  32. package/src/import/audiences.ts +2 -2
  33. package/src/import/events.ts +2 -2
  34. package/src/import/experiences.ts +3 -3
  35. package/src/import/project.ts +4 -4
  36. package/src/import/variant-entries.ts +22 -12
  37. package/src/messages/index.ts +1 -1
  38. package/src/types/personalization-api-adapter.ts +1 -1
  39. package/src/types/variant-api-adapter.ts +3 -1
  40. package/src/types/variant-entry.ts +0 -1
  41. package/src/utils/attributes-helper.ts +2 -2
  42. package/src/utils/error-helper.ts +6 -6
  43. package/src/utils/logger.ts +5 -4
  44. package/src/utils/personalization-api-adapter.ts +45 -22
  45. package/src/utils/variant-api-adapter.ts +19 -5
@@ -21,7 +21,7 @@ class ExportAttributes extends utils_1.PersonalizationAdapter {
21
21
  super({
22
22
  config: exportConfig,
23
23
  baseURL: exportConfig.modules.personalize.baseURL[exportConfig.region.name],
24
- headers: { authtoken: exportConfig.auth_token, 'X-Project-Uid': exportConfig.project_id },
24
+ headers: { 'X-Project-Uid': exportConfig.project_id },
25
25
  });
26
26
  this.exportConfig = exportConfig;
27
27
  this.personalizeConfig = exportConfig.modules.personalize;
@@ -34,6 +34,7 @@ class ExportAttributes extends utils_1.PersonalizationAdapter {
34
34
  var _a;
35
35
  try {
36
36
  (0, utils_1.log)(this.exportConfig, 'Starting attributes export', 'info');
37
+ yield this.init();
37
38
  yield utils_1.fsUtil.makeDirectory(this.attributesFolderPath);
38
39
  this.attributes = (yield this.getAttributes());
39
40
  if (!((_a = this.attributes) === null || _a === void 0 ? void 0 : _a.length)) {
@@ -20,7 +20,7 @@ class ExportAudiences extends utils_1.PersonalizationAdapter {
20
20
  super({
21
21
  config: exportConfig,
22
22
  baseURL: exportConfig.modules.personalize.baseURL[exportConfig.region.name],
23
- headers: { authtoken: exportConfig.auth_token, 'X-Project-Uid': exportConfig.project_id },
23
+ headers: { 'X-Project-Uid': exportConfig.project_id },
24
24
  });
25
25
  this.exportConfig = exportConfig;
26
26
  this.personalizeConfig = exportConfig.modules.personalize;
@@ -33,6 +33,7 @@ class ExportAudiences extends utils_1.PersonalizationAdapter {
33
33
  var _a;
34
34
  try {
35
35
  (0, utils_1.log)(this.exportConfig, 'Starting audiences export', 'info');
36
+ yield this.init();
36
37
  yield utils_1.fsUtil.makeDirectory(this.audiencesFolderPath);
37
38
  this.audiences = (yield this.getAudiences());
38
39
  if (!((_a = this.audiences) === null || _a === void 0 ? void 0 : _a.length)) {
@@ -20,7 +20,7 @@ class ExportEvents extends utils_1.PersonalizationAdapter {
20
20
  super({
21
21
  config: exportConfig,
22
22
  baseURL: exportConfig.modules.personalize.baseURL[exportConfig.region.name],
23
- headers: { authtoken: exportConfig.auth_token, 'X-Project-Uid': exportConfig.project_id },
23
+ headers: { 'X-Project-Uid': exportConfig.project_id },
24
24
  });
25
25
  this.exportConfig = exportConfig;
26
26
  this.personalizeConfig = exportConfig.modules.personalize;
@@ -33,6 +33,7 @@ class ExportEvents extends utils_1.PersonalizationAdapter {
33
33
  var _a;
34
34
  try {
35
35
  (0, utils_1.log)(this.exportConfig, 'Starting events export', 'info');
36
+ yield this.init();
36
37
  yield utils_1.fsUtil.makeDirectory(this.eventsFolderPath);
37
38
  this.events = (yield this.getEvents());
38
39
  if (!((_a = this.events) === null || _a === void 0 ? void 0 : _a.length)) {
@@ -40,10 +40,10 @@ class ExportExperiences extends utils_1.PersonalizationAdapter {
40
40
  super({
41
41
  config: exportConfig,
42
42
  baseURL: exportConfig.modules.personalize.baseURL[exportConfig.region.name],
43
- headers: { authtoken: exportConfig.auth_token, 'X-Project-Uid': exportConfig.project_id },
43
+ headers: { 'X-Project-Uid': exportConfig.project_id },
44
44
  cmaConfig: {
45
45
  baseURL: exportConfig.region.cma + `/v3`,
46
- headers: { authtoken: exportConfig.auth_token, api_key: exportConfig.apiKey },
46
+ headers: { api_key: exportConfig.apiKey },
47
47
  },
48
48
  });
49
49
  this.exportConfig = exportConfig;
@@ -58,6 +58,7 @@ class ExportExperiences extends utils_1.PersonalizationAdapter {
58
58
  // loop through experiences and get content types attached to it
59
59
  // write experiences in to a file
60
60
  (0, utils_1.log)(this.exportConfig, 'Starting experiences export', 'info');
61
+ yield this.init();
61
62
  yield utils_1.fsUtil.makeDirectory(this.experiencesFolderPath);
62
63
  yield utils_1.fsUtil.makeDirectory(path.resolve((0, cli_utilities_1.sanitizePath)(this.experiencesFolderPath), 'versions'));
63
64
  const experiences = (yield this.getExperiences()) || [];
@@ -40,7 +40,7 @@ class ExportProjects extends utils_1.PersonalizationAdapter {
40
40
  super({
41
41
  config: exportConfig,
42
42
  baseURL: exportConfig.modules.personalize.baseURL[exportConfig.region.name],
43
- headers: { authtoken: exportConfig.auth_token, organization_uid: exportConfig.org_uid },
43
+ headers: { organization_uid: exportConfig.org_uid },
44
44
  });
45
45
  this.exportConfig = exportConfig;
46
46
  this.personalizeConfig = exportConfig.modules.personalize;
@@ -51,6 +51,7 @@ class ExportProjects extends utils_1.PersonalizationAdapter {
51
51
  var _a;
52
52
  try {
53
53
  (0, utils_1.log)(this.exportConfig, 'Starting projects export', 'info');
54
+ yield this.init();
54
55
  yield utils_1.fsUtil.makeDirectory(this.projectFolderPath);
55
56
  const project = yield this.projects({ connectedStackApiKey: this.exportConfig.apiKey });
56
57
  if (!project || (project === null || project === void 0 ? void 0 : project.length) < 1) {
@@ -47,7 +47,6 @@ class VariantEntries extends variant_api_adapter_1.default {
47
47
  headers: {
48
48
  api_key: config.apiKey,
49
49
  branch: config.branchName,
50
- authtoken: config.auth_token,
51
50
  organization_uid: config.org_uid,
52
51
  'X-Project-Uid': config.project_id,
53
52
  },
@@ -65,6 +64,7 @@ class VariantEntries extends variant_api_adapter_1.default {
65
64
  return __awaiter(this, void 0, void 0, function* () {
66
65
  const variantEntry = this.config.modules.variantEntry;
67
66
  const { entries, locale, contentTypeUid: content_type_uid } = options;
67
+ yield this.variantInstance.init();
68
68
  for (let index = 0; index < entries.length; index++) {
69
69
  const entry = entries[index];
70
70
  const variantEntryBasePath = (0, path_1.join)((0, cli_utilities_1.sanitizePath)(this.entriesDirPath), (0, cli_utilities_1.sanitizePath)(content_type_uid), (0, cli_utilities_1.sanitizePath)(locale), (0, cli_utilities_1.sanitizePath)(variantEntry.dirName), (0, cli_utilities_1.sanitizePath)(entry.uid));
@@ -18,7 +18,7 @@ class Attribute extends utils_1.PersonalizationAdapter {
18
18
  const conf = {
19
19
  config,
20
20
  baseURL: config.modules.personalize.baseURL[config.region.name],
21
- headers: { 'X-Project-Uid': config.modules.personalize.project_id, authtoken: config.auth_token },
21
+ headers: { 'X-Project-Uid': config.modules.personalize.project_id },
22
22
  };
23
23
  super(Object.assign(config, conf));
24
24
  this.config = config;
@@ -37,6 +37,7 @@ class Attribute extends utils_1.PersonalizationAdapter {
37
37
  return __awaiter(this, void 0, void 0, function* () {
38
38
  var _a;
39
39
  this.log(this.config, this.$t(this.messages.IMPORT_MSG, { module: 'Attributes' }), 'info');
40
+ yield this.init();
40
41
  yield utils_1.fsUtil.makeDirectory(this.attrMapperDirPath);
41
42
  const { dirName, fileName } = this.attributeConfig;
42
43
  const attributesPath = (0, path_1.resolve)((0, cli_utilities_1.sanitizePath)(this.config.data), (0, cli_utilities_1.sanitizePath)(this.personalizeConfig.dirName), (0, cli_utilities_1.sanitizePath)(dirName), (0, cli_utilities_1.sanitizePath)(fileName));
@@ -18,7 +18,7 @@ class Audiences extends utils_1.PersonalizationAdapter {
18
18
  const conf = {
19
19
  config,
20
20
  baseURL: config.modules.personalize.baseURL[config.region.name],
21
- headers: { 'X-Project-Uid': config.modules.personalize.project_id, authtoken: config.auth_token },
21
+ headers: { 'X-Project-Uid': config.modules.personalize.project_id },
22
22
  };
23
23
  super(Object.assign(config, conf));
24
24
  this.config = config;
@@ -39,6 +39,7 @@ class Audiences extends utils_1.PersonalizationAdapter {
39
39
  return __awaiter(this, void 0, void 0, function* () {
40
40
  var _a, _b;
41
41
  this.log(this.config, this.$t(this.messages.IMPORT_MSG, { module: 'Audiences' }), 'info');
42
+ yield this.init();
42
43
  yield utils_1.fsUtil.makeDirectory(this.audienceMapperDirPath);
43
44
  const { dirName, fileName } = this.audienceConfig;
44
45
  const audiencesPath = (0, path_1.resolve)((0, cli_utilities_1.sanitizePath)(this.config.data), (0, cli_utilities_1.sanitizePath)(this.personalizeConfig.dirName), (0, cli_utilities_1.sanitizePath)(dirName), (0, cli_utilities_1.sanitizePath)(fileName));
@@ -18,7 +18,7 @@ class Events extends utils_1.PersonalizationAdapter {
18
18
  const conf = {
19
19
  config,
20
20
  baseURL: config.modules.personalize.baseURL[config.region.name],
21
- headers: { 'X-Project-Uid': config.modules.personalize.project_id, authtoken: config.auth_token },
21
+ headers: { 'X-Project-Uid': config.modules.personalize.project_id },
22
22
  };
23
23
  super(Object.assign(config, conf));
24
24
  this.config = config;
@@ -37,6 +37,7 @@ class Events extends utils_1.PersonalizationAdapter {
37
37
  return __awaiter(this, void 0, void 0, function* () {
38
38
  var _a;
39
39
  this.log(this.config, this.$t(this.messages.IMPORT_MSG, { module: 'Events' }), 'info');
40
+ yield this.init();
40
41
  yield utils_1.fsUtil.makeDirectory(this.eventMapperDirPath);
41
42
  const { dirName, fileName } = this.eventsConfig;
42
43
  const eventsPath = (0, path_1.resolve)((0, cli_utilities_1.sanitizePath)(this.config.data), (0, cli_utilities_1.sanitizePath)(this.personalizeConfig.dirName), (0, cli_utilities_1.sanitizePath)(dirName), (0, cli_utilities_1.sanitizePath)(fileName));
@@ -35,10 +35,10 @@ class Experiences extends utils_1.PersonalizationAdapter {
35
35
  const conf = {
36
36
  config,
37
37
  baseURL: config.modules.personalize.baseURL[config.region.name],
38
- headers: { 'X-Project-Uid': config.modules.personalize.project_id, authtoken: config.auth_token },
38
+ headers: { 'X-Project-Uid': config.modules.personalize.project_id },
39
39
  cmaConfig: {
40
40
  baseURL: config.region.cma + `/v3`,
41
- headers: { authtoken: config.auth_token, api_key: config.apiKey },
41
+ headers: { api_key: config.apiKey },
42
42
  },
43
43
  };
44
44
  super(Object.assign(config, conf));
@@ -80,6 +80,7 @@ class Experiences extends utils_1.PersonalizationAdapter {
80
80
  return __awaiter(this, void 0, void 0, function* () {
81
81
  var _a;
82
82
  this.log(this.config, this.$t(this.messages.IMPORT_MSG, { module: 'Experiences' }), 'info');
83
+ yield this.init();
83
84
  yield utils_1.fsUtil.makeDirectory(this.expMapperDirPath);
84
85
  if ((0, fs_1.existsSync)(this.experiencesPath)) {
85
86
  try {
@@ -18,7 +18,7 @@ class Project extends utils_1.PersonalizationAdapter {
18
18
  const conf = {
19
19
  config,
20
20
  baseURL: config.modules.personalize.baseURL[config.region.name],
21
- headers: { organization_uid: config.org_uid, authtoken: config.auth_token },
21
+ headers: { organization_uid: config.org_uid },
22
22
  };
23
23
  super(Object.assign(config, conf));
24
24
  this.config = config;
@@ -41,6 +41,7 @@ class Project extends utils_1.PersonalizationAdapter {
41
41
  this.log(this.config, 'No project found!', 'info');
42
42
  return;
43
43
  }
44
+ yield this.init();
44
45
  for (const project of projects) {
45
46
  const createProject = (newName) => __awaiter(this, void 0, void 0, function* () {
46
47
  return yield this.createProject({
@@ -48,7 +49,7 @@ class Project extends utils_1.PersonalizationAdapter {
48
49
  description: project.description,
49
50
  connectedStackApiKey: this.config.apiKey,
50
51
  }).catch((error) => __awaiter(this, void 0, void 0, function* () {
51
- if (error === 'personalization.PROJECTS.DUPLICATE_NAME' || error === 'personalize.PROJECTS.DUPLICATE_NAME') {
52
+ if (error.includes('personalization.PROJECTS.DUPLICATE_NAME') || error.includes('personalize.PROJECTS.DUPLICATE_NAME')) {
52
53
  const projectName = yield (0, utils_1.askProjectName)('Copy Of ' + (newName || project.name));
53
54
  return yield createProject(projectName);
54
55
  }
@@ -56,7 +56,6 @@ class VariantEntries extends variant_api_adapter_1.default {
56
56
  headers: {
57
57
  api_key: config.apiKey,
58
58
  branch: config.branchName,
59
- authtoken: config.auth_token,
60
59
  organization_uid: config.org_uid,
61
60
  'X-Project-Uid': config.modules.personalize.project_id,
62
61
  },
@@ -114,6 +113,8 @@ class VariantEntries extends variant_api_adapter_1.default {
114
113
  this.assetUidMapper = (utils_1.fsUtil.readFile(assetUidMapperPath, true) || {});
115
114
  this.assetUrlMapper = (utils_1.fsUtil.readFile(assetUrlMapperPath, true) || {});
116
115
  this.environments = (utils_1.fsUtil.readFile(envPath, true) || {});
116
+ // set the token
117
+ yield this.variantInstance.init();
117
118
  for (const entriesForVariant of entriesForVariants) {
118
119
  yield this.importVariantEntries(entriesForVariant);
119
120
  }
@@ -291,7 +292,7 @@ class VariantEntries extends variant_api_adapter_1.default {
291
292
  * @param variantEntry - The entry variant to update.
292
293
  */
293
294
  updateFileFields(variantEntry) {
294
- var _a;
295
+ var _a, _b;
295
296
  const setValue = (currentObj, keys) => {
296
297
  if (!currentObj || keys.length === 0)
297
298
  return;
@@ -304,7 +305,14 @@ class VariantEntries extends variant_api_adapter_1.default {
304
305
  else if (currentObj && typeof currentObj === 'object') {
305
306
  if (firstKey in currentObj) {
306
307
  if (keys.length === 1) {
307
- currentObj[firstKey] = { uid: currentObj[firstKey], filename: 'dummy.jpeg' };
308
+ // Check if the current property is already an object with uid and filename
309
+ const existingValue = currentObj[firstKey];
310
+ if (existingValue && typeof existingValue === 'object' && existingValue.uid) {
311
+ currentObj[firstKey] = { uid: existingValue.uid, filename: 'dummy.jpeg' };
312
+ }
313
+ else {
314
+ currentObj[firstKey] = { uid: currentObj[firstKey], filename: 'dummy.jpeg' };
315
+ }
308
316
  }
309
317
  else {
310
318
  setValue(currentObj[firstKey], restKeys);
@@ -312,10 +320,8 @@ class VariantEntries extends variant_api_adapter_1.default {
312
320
  }
313
321
  }
314
322
  };
315
- const pathsToUpdate = (_a = variantEntry === null || variantEntry === void 0 ? void 0 : variantEntry._metadata) === null || _a === void 0 ? void 0 : _a.references.filter((ref) => ref._content_type_uid === 'sys_assets').map((ref) => ref.path);
316
- if (pathsToUpdate) {
317
- pathsToUpdate.forEach((path) => setValue(variantEntry, path.split('.')));
318
- }
323
+ const pathsToUpdate = ((_b = (_a = variantEntry === null || variantEntry === void 0 ? void 0 : variantEntry._metadata) === null || _a === void 0 ? void 0 : _a.references) === null || _b === void 0 ? void 0 : _b.filter((ref) => ref._content_type_uid === 'sys_assets').map((ref) => ref.path)) || [];
324
+ pathsToUpdate.forEach((path) => setValue(variantEntry, path.split('.')));
319
325
  }
320
326
  /**
321
327
  * Publishes variant entries in batch for a given entry UID and content type.
@@ -328,6 +334,7 @@ class VariantEntries extends variant_api_adapter_1.default {
328
334
  return __awaiter(this, void 0, void 0, function* () {
329
335
  var _a;
330
336
  const allPromise = [];
337
+ (0, utils_1.log)(this.config, `Publishing variant entries for entry uid '${entryUid}' of Content Type '${content_type}'`, 'info');
331
338
  for (let [, variantEntry] of (0, entries_1.default)(batch)) {
332
339
  const variantEntryUID = variantEntry.uid;
333
340
  const oldVariantUid = variantEntry._variant._uid || '';
@@ -359,11 +366,9 @@ class VariantEntries extends variant_api_adapter_1.default {
359
366
  entry: {
360
367
  environments,
361
368
  locales,
362
- publish_with_base_entry: false,
363
369
  variants: [{ uid: newVariantUid, version: 1 }],
364
370
  },
365
371
  locale: variantEntry.locale,
366
- version: 1,
367
372
  };
368
373
  const promise = this.variantInstance.publishVariantEntry(publishReq, {
369
374
  entry_uid: entryUid,
@@ -377,6 +382,7 @@ class VariantEntries extends variant_api_adapter_1.default {
377
382
  allPromise.push(promise);
378
383
  }
379
384
  yield Promise.allSettled(allPromise);
385
+ (0, utils_1.log)(this.config, `Published variant entries for entry uid '${entryUid}' of Content Type '${content_type}'`, 'info');
380
386
  });
381
387
  }
382
388
  /**
@@ -27,7 +27,7 @@ const expImportMsg = {
27
27
  UPDATING_CT_IN_EXP: 'Updating content types in experiences...',
28
28
  UPDATED_CT_IN_EXP: 'Successfully updated content types in experiences!',
29
29
  VALIDATE_VARIANT_AND_VARIANT_GRP: 'Validating variant group and variants creation...',
30
- PERSONALIZE_JOB_FAILURE: 'Something went wrong with personalize background job! Failed to fetch some variant & variant groups',
30
+ PERSONALIZE_JOB_FAILURE: 'Something went wrong! Failed to fetch some variant and variant groups.',
31
31
  };
32
32
  const messages = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, errors), commonMsg), migrationMsg), variantEntry), expImportMsg);
33
33
  /**
@@ -160,6 +160,6 @@ export interface Personalization<T> extends AdapterHelperInterface<T, HttpClient
160
160
  createExperience(experience: CreateExperienceInput): Promise<ExperienceStruct | void>;
161
161
  getCTsFromExperience(experienceUid: string): Promise<CMSExperienceStruct | void>;
162
162
  updateCTsInExperience(experience: UpdateExperienceInput, experienceUid: string): Promise<CMSExperienceStruct | void>;
163
- handleVariantAPIRes(res: any): VariantAPIRes;
163
+ handleVariantAPIRes(res: any): Promise<VariantAPIRes>;
164
164
  }
165
165
  export {};
@@ -35,6 +35,7 @@ export type VariantOptions = VariantsOption & {
35
35
  variant_uid: string;
36
36
  };
37
37
  export interface VariantInterface<T, ApiClient> extends AdapterHelperInterface<T, ApiClient> {
38
+ init(): Promise<void>;
38
39
  variantEntry(options: VariantOptions): Promise<{
39
40
  entry: Record<string, any>;
40
41
  }>;
@@ -42,8 +43,8 @@ export interface VariantInterface<T, ApiClient> extends AdapterHelperInterface<T
42
43
  entries?: Record<string, any>[] | unknown[];
43
44
  } | void>;
44
45
  createVariantEntry(input: CreateVariantEntryDto, options: CreateVariantEntryOptions, apiParams: Record<string, any>): Promise<VariantEntryStruct | string | void>;
45
- handleVariantAPIRes(res: APIResponse): VariantEntryStruct | {
46
+ handleVariantAPIRes(res: APIResponse): Promise<VariantEntryStruct | {
46
47
  entries: VariantEntryStruct[];
47
48
  count: number;
48
- } | string;
49
+ } | string>;
49
50
  }
@@ -36,7 +36,6 @@ export type PublishVariantEntryDto = {
36
36
  entry: {
37
37
  environments: string[];
38
38
  locales: string[];
39
- publish_with_base_entry: boolean;
40
39
  variants: {
41
40
  uid: string;
42
41
  version?: number;
@@ -15,8 +15,8 @@ const lookUpAttributes = (attributeRules, attributesUid) => {
15
15
  // Check if attribute reference exists in attributesUid
16
16
  const attributeRef = (_a = rule.attribute) === null || _a === void 0 ? void 0 : _a.ref;
17
17
  const attributeType = rule.attribute['__type'];
18
- // check if type is UserAttributeReference
19
- if (attributeType === 'UserAttributeReference') {
18
+ // check if type is CustomAttributeReference
19
+ if (attributeType === 'CustomAttributeReference') {
20
20
  if (attributeRef && attributesUid.hasOwnProperty(attributeRef) && attributesUid[attributeRef]) {
21
21
  rule.attribute.ref = attributesUid[attributeRef];
22
22
  }
@@ -11,17 +11,17 @@ function formatErrors(errors) {
11
11
  for (const errorKey in errors) {
12
12
  const errorValue = errors[errorKey];
13
13
  if (Array.isArray(errorValue)) {
14
- errorMessages.push(...errorValue.map((error) => formatError(error)));
14
+ errorMessages.push(...errorValue.map((error) => formatError(errorKey, error)));
15
15
  }
16
16
  else {
17
- errorMessages.push(formatError(errorValue));
17
+ errorMessages.push(formatError(errorKey, errorValue));
18
18
  }
19
19
  }
20
20
  return errorMessages.join(' ');
21
21
  }
22
- function formatError(error) {
23
- if (typeof error === 'object') {
24
- return Object.values(error).join(' ');
22
+ function formatError(errorKey, error) {
23
+ if (typeof error === 'object' && error !== null) {
24
+ return `${errorKey}: ${Object.values(error).join(' ')}`;
25
25
  }
26
- return error;
26
+ return `${errorKey}: ${error}`;
27
27
  }
@@ -74,9 +74,9 @@ let logger;
74
74
  let errorLogger;
75
75
  let successTransport;
76
76
  let errorTransport;
77
- function init(_logPath) {
77
+ function init(_logPath, module) {
78
78
  if (!logger || !errorLogger) {
79
- const logsDir = path.resolve((0, cli_utilities_1.sanitizePath)(_logPath), 'logs', 'export');
79
+ const logsDir = path.resolve((0, cli_utilities_1.sanitizePath)(_logPath), 'logs', (0, cli_utilities_1.sanitizePath)(module));
80
80
  // Create dir if doesn't already exist
81
81
  mkdirp_1.default.sync(logsDir);
82
82
  successTransport = {
@@ -145,12 +145,13 @@ function init(_logPath) {
145
145
  const log = (config, message, type) => {
146
146
  const logsPath = config.data;
147
147
  // ignoring the type argument, as we are not using it to create a logfile anymore
148
+ const module = config['backupDir'] ? 'import' : 'export';
148
149
  if (type !== 'error') {
149
150
  // removed type argument from init method
150
- init(logsPath).log(message);
151
+ init(logsPath, module).log(message);
151
152
  }
152
153
  else {
153
- init(logsPath).error(message);
154
+ init(logsPath, module).error(message);
154
155
  }
155
156
  };
156
157
  exports.log = log;
@@ -3,6 +3,7 @@ import { HttpClient } from '@contentstack/cli-utilities';
3
3
  import { ProjectStruct, Personalization, GetProjectsParams, CreateProjectInput, CreateAttributeInput, APIConfig, GetVariantGroupInput, EventStruct, AudienceStruct, AttributeStruct, CreateAudienceInput, CreateEventInput, CreateExperienceInput, ExperienceStruct, UpdateExperienceInput, CMSExperienceStruct, VariantAPIRes, APIResponse, VariantGroupStruct, VariantGroup, CreateExperienceVersionInput } from '../types';
4
4
  export declare class PersonalizationAdapter<T> extends AdapterHelper<T, HttpClient> implements Personalization<T> {
5
5
  constructor(options: APIConfig);
6
+ init(): Promise<void>;
6
7
  projects(options: GetProjectsParams): Promise<ProjectStruct[]>;
7
8
  /**
8
9
  * This TypeScript function creates a project by making an asynchronous API call to retrieve project
@@ -72,5 +73,5 @@ export declare class PersonalizationAdapter<T> extends AdapterHelper<T, HttpClie
72
73
  * @returns The variant API response data.
73
74
  * @throws If the API response status is not within the success range, an error message is thrown.
74
75
  */
75
- handleVariantAPIRes(res: APIResponse): VariantAPIRes;
76
+ handleVariantAPIRes(res: APIResponse): Promise<VariantAPIRes>;
76
77
  }
@@ -22,16 +22,37 @@ var __rest = (this && this.__rest) || function (s, e) {
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.PersonalizationAdapter = void 0;
24
24
  const adapter_helper_1 = require("./adapter-helper");
25
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
25
26
  const error_helper_1 = require("./error-helper");
26
27
  class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
27
28
  constructor(options) {
28
29
  super(options);
29
30
  }
31
+ init() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ var _a, _b;
34
+ yield cli_utilities_1.authenticationHandler.getAuthDetails();
35
+ const token = cli_utilities_1.authenticationHandler.accessToken;
36
+ if (cli_utilities_1.authenticationHandler.isOauthEnabled) {
37
+ this.apiClient.headers({ authorization: token });
38
+ if (this.adapterConfig.cmaConfig) {
39
+ (_a = this.cmaAPIClient) === null || _a === void 0 ? void 0 : _a.headers({ authorization: token });
40
+ }
41
+ }
42
+ else {
43
+ this.apiClient.headers({ authtoken: token });
44
+ if (this.adapterConfig.cmaConfig) {
45
+ (_b = this.cmaAPIClient) === null || _b === void 0 ? void 0 : _b.headers({ authtoken: token });
46
+ }
47
+ }
48
+ });
49
+ }
30
50
  projects(options) {
31
51
  return __awaiter(this, void 0, void 0, function* () {
52
+ yield this.init();
32
53
  const getProjectEndPoint = `/projects?connectedStackApiKey=${options.connectedStackApiKey}`;
33
54
  const data = yield this.apiClient.get(getProjectEndPoint);
34
- return this.handleVariantAPIRes(data);
55
+ return (yield this.handleVariantAPIRes(data));
35
56
  });
36
57
  }
37
58
  /**
@@ -47,7 +68,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
47
68
  createProject(project) {
48
69
  return __awaiter(this, void 0, void 0, function* () {
49
70
  const data = yield this.apiClient.post('/projects', project);
50
- return this.handleVariantAPIRes(data);
71
+ return (yield this.handleVariantAPIRes(data));
51
72
  });
52
73
  }
53
74
  /**
@@ -62,35 +83,35 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
62
83
  createAttribute(attribute) {
63
84
  return __awaiter(this, void 0, void 0, function* () {
64
85
  const data = yield this.apiClient.post('/attributes', attribute);
65
- return this.handleVariantAPIRes(data);
86
+ return (yield this.handleVariantAPIRes(data));
66
87
  });
67
88
  }
68
89
  getExperiences() {
69
90
  return __awaiter(this, void 0, void 0, function* () {
70
91
  const getExperiencesEndPoint = `/experiences`;
71
92
  const data = yield this.apiClient.get(getExperiencesEndPoint);
72
- return this.handleVariantAPIRes(data);
93
+ return (yield this.handleVariantAPIRes(data));
73
94
  });
74
95
  }
75
96
  getExperience(experienceUid) {
76
97
  return __awaiter(this, void 0, void 0, function* () {
77
98
  const getExperiencesEndPoint = `/experiences/${experienceUid}`;
78
99
  const data = yield this.apiClient.get(getExperiencesEndPoint);
79
- return this.handleVariantAPIRes(data);
100
+ return (yield this.handleVariantAPIRes(data));
80
101
  });
81
102
  }
82
103
  getExperienceVersions(experienceUid) {
83
104
  return __awaiter(this, void 0, void 0, function* () {
84
105
  const getExperiencesVersionsEndPoint = `/experiences/${experienceUid}/versions`;
85
106
  const data = yield this.apiClient.get(getExperiencesVersionsEndPoint);
86
- return this.handleVariantAPIRes(data);
107
+ return (yield this.handleVariantAPIRes(data));
87
108
  });
88
109
  }
89
110
  createExperienceVersion(experienceUid, input) {
90
111
  return __awaiter(this, void 0, void 0, function* () {
91
112
  const createExperiencesVersionsEndPoint = `/experiences/${experienceUid}/versions`;
92
113
  const data = yield this.apiClient.post(createExperiencesVersionsEndPoint, input);
93
- return this.handleVariantAPIRes(data);
114
+ return (yield this.handleVariantAPIRes(data));
94
115
  });
95
116
  }
96
117
  updateExperienceVersion(experienceUid, versionId, input) {
@@ -104,7 +125,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
104
125
  }
105
126
  const updateExperiencesVersionsEndPoint = `/experiences/${experienceUid}/versions/${versionId}`;
106
127
  const data = yield this.apiClient.put(updateExperiencesVersionsEndPoint, input);
107
- return this.handleVariantAPIRes(data);
128
+ return (yield this.handleVariantAPIRes(data));
108
129
  });
109
130
  }
110
131
  getVariantGroup(input) {
@@ -114,7 +135,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
114
135
  const data = yield this.cmaAPIClient
115
136
  .queryParams({ experience_uid: input.experienceUid })
116
137
  .get(getVariantGroupEndPoint);
117
- return this.handleVariantAPIRes(data);
138
+ return (yield this.handleVariantAPIRes(data));
118
139
  }
119
140
  });
120
141
  }
@@ -123,32 +144,32 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
123
144
  if (this.cmaAPIClient) {
124
145
  const updateVariantGroupEndPoint = `/variant_groups/${input.uid}`;
125
146
  const data = yield this.cmaAPIClient.put(updateVariantGroupEndPoint, input);
126
- return this.handleVariantAPIRes(data);
147
+ return (yield this.handleVariantAPIRes(data));
127
148
  }
128
149
  });
129
150
  }
130
151
  getEvents() {
131
152
  return __awaiter(this, void 0, void 0, function* () {
132
153
  const data = yield this.apiClient.get('/events');
133
- return this.handleVariantAPIRes(data);
154
+ return (yield this.handleVariantAPIRes(data));
134
155
  });
135
156
  }
136
157
  createEvents(event) {
137
158
  return __awaiter(this, void 0, void 0, function* () {
138
159
  const data = yield this.apiClient.post('/events', event);
139
- return this.handleVariantAPIRes(data);
160
+ return (yield this.handleVariantAPIRes(data));
140
161
  });
141
162
  }
142
163
  getAudiences() {
143
164
  return __awaiter(this, void 0, void 0, function* () {
144
165
  const data = yield this.apiClient.get('/audiences');
145
- return this.handleVariantAPIRes(data);
166
+ return (yield this.handleVariantAPIRes(data));
146
167
  });
147
168
  }
148
169
  getAttributes() {
149
170
  return __awaiter(this, void 0, void 0, function* () {
150
171
  const data = yield this.apiClient.get('/attributes');
151
- return this.handleVariantAPIRes(data);
172
+ return (yield this.handleVariantAPIRes(data));
152
173
  });
153
174
  }
154
175
  /**
@@ -162,7 +183,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
162
183
  createAudience(audience) {
163
184
  return __awaiter(this, void 0, void 0, function* () {
164
185
  const data = yield this.apiClient.post('/audiences', audience);
165
- return this.handleVariantAPIRes(data);
186
+ return (yield this.handleVariantAPIRes(data));
166
187
  });
167
188
  }
168
189
  /**
@@ -176,7 +197,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
176
197
  createExperience(experience) {
177
198
  return __awaiter(this, void 0, void 0, function* () {
178
199
  const data = yield this.apiClient.post('/experiences', experience);
179
- return this.handleVariantAPIRes(data);
200
+ return (yield this.handleVariantAPIRes(data));
180
201
  });
181
202
  }
182
203
  /**
@@ -188,7 +209,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
188
209
  return __awaiter(this, void 0, void 0, function* () {
189
210
  const updateCTInExpEndPoint = `/experiences/${experienceUid}/cms-integration/variant-group`;
190
211
  const data = yield this.apiClient.post(updateCTInExpEndPoint, experience);
191
- return this.handleVariantAPIRes(data);
212
+ return (yield this.handleVariantAPIRes(data));
192
213
  });
193
214
  }
194
215
  /**
@@ -200,7 +221,7 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
200
221
  return __awaiter(this, void 0, void 0, function* () {
201
222
  const getCTFromExpEndPoint = `/experiences/${experienceUid}/cms-integration/variant-group`;
202
223
  const data = yield this.apiClient.get(getCTFromExpEndPoint);
203
- return this.handleVariantAPIRes(data);
224
+ return (yield this.handleVariantAPIRes(data));
204
225
  });
205
226
  }
206
227
  /**
@@ -210,14 +231,21 @@ class PersonalizationAdapter extends adapter_helper_1.AdapterHelper {
210
231
  * @throws If the API response status is not within the success range, an error message is thrown.
211
232
  */
212
233
  handleVariantAPIRes(res) {
213
- const { status, data } = res;
214
- if (status >= 200 && status < 300) {
215
- return data;
216
- }
217
- const errorMsg = (data === null || data === void 0 ? void 0 : data.errors)
218
- ? (0, error_helper_1.formatErrors)(data.errors)
219
- : (data === null || data === void 0 ? void 0 : data.error) || (data === null || data === void 0 ? void 0 : data.error_message) || (data === null || data === void 0 ? void 0 : data.message) || 'Something went wrong while processing variant entries request!';
220
- throw errorMsg;
234
+ return __awaiter(this, void 0, void 0, function* () {
235
+ const { status, data } = res;
236
+ if (status >= 200 && status < 300) {
237
+ return data;
238
+ }
239
+ // Refresh the access token if it has expired
240
+ yield cli_utilities_1.authenticationHandler.refreshAccessToken(res);
241
+ const errorMsg = (data === null || data === void 0 ? void 0 : data.errors)
242
+ ? (0, error_helper_1.formatErrors)(data.errors)
243
+ : (data === null || data === void 0 ? void 0 : data.error) ||
244
+ (data === null || data === void 0 ? void 0 : data.error_message) ||
245
+ (data === null || data === void 0 ? void 0 : data.message) ||
246
+ 'Something went wrong while processing variant entries request!';
247
+ throw errorMsg;
248
+ });
221
249
  }
222
250
  }
223
251
  exports.PersonalizationAdapter = PersonalizationAdapter;