@contentstack/cli-variants 0.0.1-alpha

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 (124) hide show
  1. package/lib/export/attributes.d.ts +15 -0
  2. package/lib/export/attributes.js +62 -0
  3. package/lib/export/audiences.d.ts +15 -0
  4. package/lib/export/audiences.js +63 -0
  5. package/lib/export/events.d.ts +15 -0
  6. package/lib/export/events.js +63 -0
  7. package/lib/export/experiences.d.ts +9 -0
  8. package/lib/export/experiences.js +99 -0
  9. package/lib/export/index.d.ts +9 -0
  10. package/lib/export/index.js +21 -0
  11. package/lib/export/projects.d.ts +9 -0
  12. package/lib/export/projects.js +73 -0
  13. package/lib/export/variant-entries.d.ts +18 -0
  14. package/lib/export/variant-entries.js +109 -0
  15. package/lib/import/attribute.d.ts +17 -0
  16. package/lib/import/attribute.js +64 -0
  17. package/lib/import/audiences.d.ts +19 -0
  18. package/lib/import/audiences.js +71 -0
  19. package/lib/import/events.d.ts +17 -0
  20. package/lib/import/events.js +62 -0
  21. package/lib/import/experiences.d.ts +46 -0
  22. package/lib/import/experiences.js +214 -0
  23. package/lib/import/index.d.ts +14 -0
  24. package/lib/import/index.js +21 -0
  25. package/lib/import/project.d.ts +13 -0
  26. package/lib/import/project.js +74 -0
  27. package/lib/import/variant-entries.d.ts +98 -0
  28. package/lib/import/variant-entries.js +407 -0
  29. package/lib/index.d.ts +5 -0
  30. package/lib/index.js +21 -0
  31. package/lib/messages/index.d.ts +35 -0
  32. package/lib/messages/index.js +55 -0
  33. package/lib/types/adapter-helper.d.ts +8 -0
  34. package/lib/types/adapter-helper.js +2 -0
  35. package/lib/types/content-types.d.ts +19 -0
  36. package/lib/types/content-types.js +2 -0
  37. package/lib/types/export-config.d.ts +264 -0
  38. package/lib/types/export-config.js +2 -0
  39. package/lib/types/import-config.d.ts +92 -0
  40. package/lib/types/import-config.js +2 -0
  41. package/lib/types/index.d.ts +8 -0
  42. package/lib/types/index.js +24 -0
  43. package/lib/types/personalization-api-adapter.d.ts +152 -0
  44. package/lib/types/personalization-api-adapter.js +2 -0
  45. package/lib/types/utils.d.ts +7 -0
  46. package/lib/types/utils.js +2 -0
  47. package/lib/types/variant-api-adapter.d.ts +49 -0
  48. package/lib/types/variant-api-adapter.js +2 -0
  49. package/lib/types/variant-entry.d.ts +47 -0
  50. package/lib/types/variant-entry.js +2 -0
  51. package/lib/utils/adapter-helper.d.ts +30 -0
  52. package/lib/utils/adapter-helper.js +95 -0
  53. package/lib/utils/attributes-helper.d.ts +7 -0
  54. package/lib/utils/attributes-helper.js +37 -0
  55. package/lib/utils/audiences-helper.d.ts +8 -0
  56. package/lib/utils/audiences-helper.js +49 -0
  57. package/lib/utils/error-helper.d.ts +6 -0
  58. package/lib/utils/error-helper.js +27 -0
  59. package/lib/utils/events-helper.d.ts +8 -0
  60. package/lib/utils/events-helper.js +27 -0
  61. package/lib/utils/helper.d.ts +4 -0
  62. package/lib/utils/helper.js +51 -0
  63. package/lib/utils/index.d.ts +9 -0
  64. package/lib/utils/index.js +25 -0
  65. package/lib/utils/logger.d.ts +3 -0
  66. package/lib/utils/logger.js +175 -0
  67. package/lib/utils/personalization-api-adapter.d.ts +73 -0
  68. package/lib/utils/personalization-api-adapter.js +184 -0
  69. package/lib/utils/variant-api-adapter.d.ts +79 -0
  70. package/lib/utils/variant-api-adapter.js +263 -0
  71. package/package.json +38 -0
  72. package/src/export/attributes.ts +55 -0
  73. package/src/export/audiences.ts +57 -0
  74. package/src/export/events.ts +57 -0
  75. package/src/export/experiences.ts +80 -0
  76. package/src/export/index.ts +11 -0
  77. package/src/export/projects.ts +45 -0
  78. package/src/export/variant-entries.ts +88 -0
  79. package/src/import/attribute.ts +60 -0
  80. package/src/import/audiences.ts +69 -0
  81. package/src/import/events.ts +58 -0
  82. package/src/import/experiences.ts +224 -0
  83. package/src/import/index.ts +16 -0
  84. package/src/import/project.ts +71 -0
  85. package/src/import/variant-entries.ts +483 -0
  86. package/src/index.ts +5 -0
  87. package/src/messages/index.ts +63 -0
  88. package/src/types/adapter-helper.ts +10 -0
  89. package/src/types/content-types.ts +41 -0
  90. package/src/types/export-config.ts +292 -0
  91. package/src/types/import-config.ts +95 -0
  92. package/src/types/index.ts +8 -0
  93. package/src/types/personalization-api-adapter.ts +197 -0
  94. package/src/types/utils.ts +8 -0
  95. package/src/types/variant-api-adapter.ts +56 -0
  96. package/src/types/variant-entry.ts +61 -0
  97. package/src/utils/adapter-helper.ts +79 -0
  98. package/src/utils/attributes-helper.ts +31 -0
  99. package/src/utils/audiences-helper.ts +50 -0
  100. package/src/utils/error-helper.ts +26 -0
  101. package/src/utils/events-helper.ts +26 -0
  102. package/src/utils/helper.ts +34 -0
  103. package/src/utils/index.ts +9 -0
  104. package/src/utils/logger.ts +160 -0
  105. package/src/utils/personalization-api-adapter.ts +188 -0
  106. package/src/utils/variant-api-adapter.ts +326 -0
  107. package/test/unit/export/variant-entries.test.ts +80 -0
  108. package/test/unit/import/variant-entries.test.ts +200 -0
  109. package/test/unit/mock/contents/content_types/CT-1.json +7 -0
  110. package/test/unit/mock/contents/entries/CT-1/en-us/variants/E-1/9b0da6xd7et72y-6gv7he23.json +12 -0
  111. package/test/unit/mock/contents/entries/CT-1/en-us/variants/E-1/index.json +3 -0
  112. package/test/unit/mock/contents/entries/CT-1/en-us/variants/E-2/9b0da6xd7et72y-6gv7he23.json +12 -0
  113. package/test/unit/mock/contents/entries/CT-1/en-us/variants/E-2/index.json +3 -0
  114. package/test/unit/mock/contents/mapper/assets/uid-mapping.json +6 -0
  115. package/test/unit/mock/contents/mapper/assets/url-mapping.json +6 -0
  116. package/test/unit/mock/contents/mapper/entries/data-for-variant-entry.json +6 -0
  117. package/test/unit/mock/contents/mapper/entries/empty-data/data-for-variant-entry.json +1 -0
  118. package/test/unit/mock/contents/mapper/entries/uid-mapping.json +6 -0
  119. package/test/unit/mock/contents/mapper/marketplace_apps/uid-mapping.json +3 -0
  120. package/test/unit/mock/contents/mapper/personalization/experiences/variants-uid-mapping.json +5 -0
  121. package/test/unit/mock/contents/mapper/taxonomies/terms/success.json +1 -0
  122. package/test/unit/mock/export-config.json +48 -0
  123. package/test/unit/mock/import-config.json +63 -0
  124. package/tsconfig.json +19 -0
@@ -0,0 +1,30 @@
1
+ import { HttpClientOptions } from '@contentstack/cli-utilities';
2
+ import messages, { $t } from '../messages';
3
+ import { APIConfig, AdapterHelperInterface } from '../types';
4
+ export declare class AdapterHelper<C, ApiClient> implements AdapterHelperInterface<C, ApiClient> {
5
+ readonly adapterConfig: APIConfig;
6
+ readonly config: C;
7
+ readonly $t: typeof $t;
8
+ readonly apiClient: ApiClient;
9
+ readonly cmaAPIClient?: ApiClient;
10
+ readonly messages: typeof messages;
11
+ constructor(adapterConfig: APIConfig, options?: HttpClientOptions);
12
+ /**
13
+ * The function constructs a query string from a given object by encoding its key-value pairs.
14
+ * @param query - It looks like you have a function `constructQuery` that takes a query object as a
15
+ * parameter. The function loops through the keys in the query object and constructs a query string
16
+ * based on the key-value pairs.
17
+ * @returns The `constructQuery` function returns a string that represents the query parameters
18
+ * constructed from the input `query` object. If the `query` object is empty (has no keys), the
19
+ * function does not return anything (void).
20
+ */
21
+ constructQuery(query: Record<string, any>): string | void;
22
+ /**
23
+ * The `delay` function in TypeScript returns a Promise that resolves after a specified number of
24
+ * milliseconds.
25
+ * @param {number} ms - The `ms` parameter represents the number of milliseconds for which the delay
26
+ * should occur before the `Promise` is resolved.
27
+ * @returns A Promise that resolves after the specified delay in milliseconds.
28
+ */
29
+ delay(ms: number): Promise<void>;
30
+ }
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.AdapterHelper = void 0;
30
+ const pick_1 = __importDefault(require("lodash/pick"));
31
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
32
+ const messages_1 = __importStar(require("../messages"));
33
+ class AdapterHelper {
34
+ constructor(adapterConfig, options) {
35
+ this.adapterConfig = adapterConfig;
36
+ this.$t = messages_1.$t;
37
+ this.messages = messages_1.default;
38
+ this.config = adapterConfig.config;
39
+ delete this.adapterConfig.config;
40
+ const pickConfig = [
41
+ 'url',
42
+ 'auth',
43
+ 'method',
44
+ 'baseURL',
45
+ 'headers',
46
+ 'adapter',
47
+ 'httpAgent',
48
+ 'httpsAgent',
49
+ 'responseType',
50
+ ];
51
+ this.apiClient = new cli_utilities_1.HttpClient((0, pick_1.default)(adapterConfig, pickConfig), options);
52
+ if (adapterConfig.cmaConfig) {
53
+ this.cmaAPIClient = new cli_utilities_1.HttpClient((0, pick_1.default)(adapterConfig.cmaConfig, pickConfig), options);
54
+ }
55
+ }
56
+ /**
57
+ * The function constructs a query string from a given object by encoding its key-value pairs.
58
+ * @param query - It looks like you have a function `constructQuery` that takes a query object as a
59
+ * parameter. The function loops through the keys in the query object and constructs a query string
60
+ * based on the key-value pairs.
61
+ * @returns The `constructQuery` function returns a string that represents the query parameters
62
+ * constructed from the input `query` object. If the `query` object is empty (has no keys), the
63
+ * function does not return anything (void).
64
+ */
65
+ constructQuery(query) {
66
+ if (Object.keys(query).length) {
67
+ let queryParam = '';
68
+ for (const key in query) {
69
+ if (Object.prototype.hasOwnProperty.call(query, key)) {
70
+ const element = query[key];
71
+ switch (typeof element) {
72
+ case 'boolean':
73
+ queryParam = queryParam.concat(key);
74
+ break;
75
+ default:
76
+ queryParam = queryParam.concat(`&${key}=${encodeURIComponent(element)}`);
77
+ break;
78
+ }
79
+ }
80
+ }
81
+ return queryParam;
82
+ }
83
+ }
84
+ /**
85
+ * The `delay` function in TypeScript returns a Promise that resolves after a specified number of
86
+ * milliseconds.
87
+ * @param {number} ms - The `ms` parameter represents the number of milliseconds for which the delay
88
+ * should occur before the `Promise` is resolved.
89
+ * @returns A Promise that resolves after the specified delay in milliseconds.
90
+ */
91
+ delay(ms) {
92
+ return new Promise((resolve) => setTimeout(resolve, ms <= 0 ? 0 : ms));
93
+ }
94
+ }
95
+ exports.AdapterHelper = AdapterHelper;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * function to either modify the UID or eliminate it if the attribute is not created in the target project
3
+ * @param attributeRules
4
+ * @param attributesUid - {attributesUid} attributes mapper data in format {<old-uid>: <new-uid>}
5
+ * @returns
6
+ */
7
+ export declare const lookUpAttributes: (attributeRules: Record<string, any>[], attributesUid: Record<string, string>) => Record<string, any>[];
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lookUpAttributes = void 0;
4
+ /**
5
+ * function to either modify the UID or eliminate it if the attribute is not created in the target project
6
+ * @param attributeRules
7
+ * @param attributesUid - {attributesUid} attributes mapper data in format {<old-uid>: <new-uid>}
8
+ * @returns
9
+ */
10
+ const lookUpAttributes = (attributeRules, attributesUid) => {
11
+ var _a;
12
+ for (let index = 0; index < (attributeRules === null || attributeRules === void 0 ? void 0 : attributeRules.length); index++) {
13
+ const rule = attributeRules[index];
14
+ if (rule['__type'] === 'Rule') {
15
+ // Check if attribute reference exists in attributesUid
16
+ const attributeRef = (_a = rule.attribute) === null || _a === void 0 ? void 0 : _a.ref;
17
+ const attributeType = rule.attribute['__type'];
18
+ // check if type is UserAttributeReference
19
+ if (attributeType === 'UserAttributeReference') {
20
+ if (attributeRef && attributesUid.hasOwnProperty(attributeRef) && attributesUid[attributeRef]) {
21
+ rule.attribute.ref = attributesUid[attributeRef];
22
+ }
23
+ else {
24
+ // Remove the rule if the attribute reference is not found
25
+ attributeRules.splice(index, 1);
26
+ --index;
27
+ }
28
+ }
29
+ }
30
+ else if (rule['__type'] === 'RuleCombination' && Array.isArray(rule.rules)) {
31
+ // Recursively look up attributes in nested rule combinations
32
+ (0, exports.lookUpAttributes)(rule.rules, attributesUid);
33
+ }
34
+ }
35
+ return attributeRules;
36
+ };
37
+ exports.lookUpAttributes = lookUpAttributes;
@@ -0,0 +1,8 @@
1
+ import { CreateExperienceInput } from '../types';
2
+ /**
3
+ * function to either modify the UID or eliminate it if the audience is not created in the target project
4
+ * @param experience - experience object
5
+ * @param audiencesUid - {audiencesUid} audiences mapper data in format {<old-uid>: <new-uid>}
6
+ * @returns
7
+ */
8
+ export declare const lookUpAudiences: (experience: CreateExperienceInput, audiencesUid: Record<string, string>) => CreateExperienceInput;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lookUpAudiences = void 0;
4
+ /**
5
+ * function for substituting an old audience UID with a new one or deleting the audience information if it does not exist
6
+ * @param audiences - {audiences} list of audience
7
+ * @param audiencesUid - {audiencesUid} audiences mapper data in format {<old-uid>: <new-uid>}
8
+ */
9
+ function updateAudiences(audiences, audiencesUid) {
10
+ for (let audienceIndex = audiences.length - 1; audienceIndex >= 0; audienceIndex--) {
11
+ const audienceUid = audiences[audienceIndex];
12
+ if (audiencesUid.hasOwnProperty(audienceUid) && audiencesUid[audienceUid]) {
13
+ audiences[audienceIndex] = audiencesUid[audienceUid];
14
+ }
15
+ else {
16
+ audiences.splice(audienceIndex, 1);
17
+ }
18
+ }
19
+ }
20
+ /**
21
+ * function to either modify the UID or eliminate it if the audience is not created in the target project
22
+ * @param experience - experience object
23
+ * @param audiencesUid - {audiencesUid} audiences mapper data in format {<old-uid>: <new-uid>}
24
+ * @returns
25
+ */
26
+ const lookUpAudiences = (experience, audiencesUid) => {
27
+ var _a, _b, _c, _d, _e, _f;
28
+ // Update experience variations
29
+ if ((_a = experience === null || experience === void 0 ? void 0 : experience.variations) === null || _a === void 0 ? void 0 : _a.length) {
30
+ for (let index = experience.variations.length - 1; index >= 0; index--) {
31
+ const expVariations = experience.variations[index];
32
+ if (expVariations['__type'] === 'AudienceBasedVariation' && ((_b = expVariations === null || expVariations === void 0 ? void 0 : expVariations.audiences) === null || _b === void 0 ? void 0 : _b.length)) {
33
+ updateAudiences(expVariations.audiences, audiencesUid);
34
+ if (!expVariations.audiences.length) {
35
+ experience.variations.splice(index, 1);
36
+ }
37
+ }
38
+ }
39
+ }
40
+ // Update targeting audiences
41
+ if (((_c = experience === null || experience === void 0 ? void 0 : experience.targeting) === null || _c === void 0 ? void 0 : _c.hasOwnProperty('audience')) && ((_f = (_e = (_d = experience === null || experience === void 0 ? void 0 : experience.targeting) === null || _d === void 0 ? void 0 : _d.audience) === null || _e === void 0 ? void 0 : _e.audiences) === null || _f === void 0 ? void 0 : _f.length)) {
42
+ updateAudiences(experience.targeting.audience.audiences, audiencesUid);
43
+ if (!experience.targeting.audience.audiences.length) {
44
+ experience.targeting = {};
45
+ }
46
+ }
47
+ return experience;
48
+ };
49
+ exports.lookUpAudiences = lookUpAudiences;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Formats the errors into a single string.
3
+ * @param errors - The errors to be formatted.
4
+ * @returns The formatted errors as a string.
5
+ */
6
+ export declare function formatErrors(errors: any): string;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatErrors = formatErrors;
4
+ /**
5
+ * Formats the errors into a single string.
6
+ * @param errors - The errors to be formatted.
7
+ * @returns The formatted errors as a string.
8
+ */
9
+ function formatErrors(errors) {
10
+ const errorMessages = [];
11
+ for (const errorKey in errors) {
12
+ const errorValue = errors[errorKey];
13
+ if (Array.isArray(errorValue)) {
14
+ errorMessages.push(...errorValue.map((error) => formatError(error)));
15
+ }
16
+ else {
17
+ errorMessages.push(formatError(errorValue));
18
+ }
19
+ }
20
+ return errorMessages.join(' ');
21
+ }
22
+ function formatError(error) {
23
+ if (typeof error === 'object') {
24
+ return Object.values(error).join(' ');
25
+ }
26
+ return String(error);
27
+ }
@@ -0,0 +1,8 @@
1
+ import { CreateExperienceInput } from '../types';
2
+ /**
3
+ * function to either modify the UID or eliminate it if the event is not created in the target project
4
+ * @param experience - experience object
5
+ * @param eventsUid - {eventsUid} events mapper data in format {<old-uid>: <new-uid>}
6
+ * @returns
7
+ */
8
+ export declare const lookUpEvents: (experience: CreateExperienceInput, eventsUid: Record<string, string>) => CreateExperienceInput;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lookUpEvents = void 0;
4
+ /**
5
+ * function to either modify the UID or eliminate it if the event is not created in the target project
6
+ * @param experience - experience object
7
+ * @param eventsUid - {eventsUid} events mapper data in format {<old-uid>: <new-uid>}
8
+ * @returns
9
+ */
10
+ const lookUpEvents = (experience, eventsUid) => {
11
+ var _a, _b;
12
+ // Update events uid in experience metrics
13
+ if ((_a = experience === null || experience === void 0 ? void 0 : experience.metrics) === null || _a === void 0 ? void 0 : _a.length) {
14
+ for (let metricIndex = ((_b = experience === null || experience === void 0 ? void 0 : experience.metrics) === null || _b === void 0 ? void 0 : _b.length) - 1; metricIndex >= 0; metricIndex--) {
15
+ const metric = experience === null || experience === void 0 ? void 0 : experience.metrics[metricIndex];
16
+ const eventUid = metric.event;
17
+ if (eventsUid.hasOwnProperty(eventUid) && eventsUid[eventUid]) {
18
+ experience.metrics[metricIndex].event = eventsUid[eventUid];
19
+ }
20
+ else {
21
+ experience === null || experience === void 0 ? void 0 : experience.metrics.splice(metricIndex, 1);
22
+ }
23
+ }
24
+ }
25
+ return experience;
26
+ };
27
+ exports.lookUpEvents = lookUpEvents;
@@ -0,0 +1,4 @@
1
+ import { FsUtility } from '@contentstack/cli-utilities';
2
+ export declare const formatError: (error: any) => any;
3
+ export declare const fsUtil: FsUtility;
4
+ export declare const askProjectName: (defaultValue: unknown) => Promise<string>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.askProjectName = exports.fsUtil = exports.formatError = void 0;
13
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
14
+ const formatError = function (error) {
15
+ try {
16
+ if (typeof error === 'string') {
17
+ error = JSON.parse(error);
18
+ }
19
+ else {
20
+ error = JSON.parse(error.message);
21
+ }
22
+ }
23
+ catch (e) { }
24
+ let message = error.errorMessage || error.error_message || error.message || error;
25
+ if (error.errors && Object.keys(error.errors).length > 0) {
26
+ Object.keys(error.errors).forEach((e) => {
27
+ let entity = e;
28
+ if (e === 'authorization')
29
+ entity = 'Management Token';
30
+ if (e === 'api_key')
31
+ entity = 'Stack API key';
32
+ if (e === 'uid')
33
+ entity = 'Content Type';
34
+ if (e === 'access_token')
35
+ entity = 'Delivery Token';
36
+ message += ' ' + [entity, error.errors[e]].join(' ');
37
+ });
38
+ }
39
+ return message;
40
+ };
41
+ exports.formatError = formatError;
42
+ exports.fsUtil = new cli_utilities_1.FsUtility();
43
+ const askProjectName = (defaultValue) => __awaiter(void 0, void 0, void 0, function* () {
44
+ return yield cli_utilities_1.cliux.inquire({
45
+ type: 'input',
46
+ name: 'name',
47
+ default: defaultValue,
48
+ message: 'Enter the project name:',
49
+ });
50
+ });
51
+ exports.askProjectName = askProjectName;
@@ -0,0 +1,9 @@
1
+ export * from './adapter-helper';
2
+ export * from './variant-api-adapter';
3
+ export * from './personalization-api-adapter';
4
+ export * from './logger';
5
+ export * from './helper';
6
+ export * from './attributes-helper';
7
+ export * from './audiences-helper';
8
+ export * from './events-helper';
9
+ export * from './error-helper';
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./adapter-helper"), exports);
18
+ __exportStar(require("./variant-api-adapter"), exports);
19
+ __exportStar(require("./personalization-api-adapter"), exports);
20
+ __exportStar(require("./logger"), exports);
21
+ __exportStar(require("./helper"), exports);
22
+ __exportStar(require("./attributes-helper"), exports);
23
+ __exportStar(require("./audiences-helper"), exports);
24
+ __exportStar(require("./events-helper"), exports);
25
+ __exportStar(require("./error-helper"), exports);
@@ -0,0 +1,3 @@
1
+ import { ExportConfig, ImportConfig } from '../types';
2
+ export declare const log: (config: ExportConfig | ImportConfig, message: any, type: "info" | "error" | "success") => void;
3
+ export declare const unlinkFileLogger: () => void;
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.unlinkFileLogger = exports.log = void 0;
30
+ const winston = __importStar(require("winston"));
31
+ const path = __importStar(require("path"));
32
+ const mkdirp_1 = __importDefault(require("mkdirp"));
33
+ const cli_utilities_1 = require("@contentstack/cli-utilities");
34
+ const slice = Array.prototype.slice;
35
+ const ansiRegexPattern = [
36
+ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
37
+ '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))',
38
+ ].join('|');
39
+ function returnString(args) {
40
+ let returnStr = '';
41
+ if (args && args.length) {
42
+ returnStr = args
43
+ .map(function (item) {
44
+ if (item && typeof item === 'object') {
45
+ try {
46
+ return JSON.stringify(item).replace(/authtoken\":\d"blt................/g, 'authtoken":"blt....');
47
+ }
48
+ catch (error) { }
49
+ return item;
50
+ }
51
+ return item;
52
+ })
53
+ .join(' ')
54
+ .trim();
55
+ }
56
+ returnStr = returnStr.replace(new RegExp(ansiRegexPattern, 'g'), '').trim();
57
+ return returnStr;
58
+ }
59
+ const myCustomLevels = {
60
+ levels: {
61
+ warn: 1,
62
+ info: 2,
63
+ debug: 3,
64
+ },
65
+ colors: {
66
+ //colors aren't being used anywhere as of now, we're using chalk to add colors while logging
67
+ info: 'blue',
68
+ debug: 'green',
69
+ warn: 'yellow',
70
+ error: 'red',
71
+ },
72
+ };
73
+ let logger;
74
+ let errorLogger;
75
+ let successTransport;
76
+ let errorTransport;
77
+ function init(_logPath) {
78
+ if (!logger || !errorLogger) {
79
+ const logsDir = path.resolve((0, cli_utilities_1.sanitizePath)(_logPath), 'logs', 'export');
80
+ // Create dir if doesn't already exist
81
+ mkdirp_1.default.sync(logsDir);
82
+ successTransport = {
83
+ filename: path.join((0, cli_utilities_1.sanitizePath)(logsDir), 'success.log'),
84
+ maxFiles: 20,
85
+ maxsize: 1000000,
86
+ tailable: true,
87
+ level: 'info',
88
+ };
89
+ errorTransport = {
90
+ filename: path.join((0, cli_utilities_1.sanitizePath)(logsDir), 'error.log'),
91
+ maxFiles: 20,
92
+ maxsize: 1000000,
93
+ tailable: true,
94
+ level: 'error',
95
+ };
96
+ logger = winston.createLogger({
97
+ transports: [
98
+ new winston.transports.File(successTransport),
99
+ new winston.transports.Console({ format: winston.format.simple() }),
100
+ ],
101
+ levels: myCustomLevels.levels,
102
+ });
103
+ errorLogger = winston.createLogger({
104
+ transports: [
105
+ new winston.transports.File(errorTransport),
106
+ new winston.transports.Console({
107
+ level: 'error',
108
+ format: winston.format.combine(winston.format.colorize({ all: true, colors: { error: 'red' } }), winston.format.simple()),
109
+ }),
110
+ ],
111
+ levels: { error: 0 },
112
+ });
113
+ }
114
+ return {
115
+ log: function (message) {
116
+ const args = slice.call(arguments);
117
+ const logString = returnString(args);
118
+ if (logString) {
119
+ logger.log('info', logString);
120
+ }
121
+ },
122
+ warn: function () {
123
+ const args = slice.call(arguments);
124
+ const logString = returnString(args);
125
+ if (logString) {
126
+ logger.log('warn', logString);
127
+ }
128
+ },
129
+ error: function (message) {
130
+ const args = slice.call(arguments);
131
+ const logString = returnString(args);
132
+ if (logString) {
133
+ errorLogger.log('error', logString);
134
+ }
135
+ },
136
+ debug: function () {
137
+ const args = slice.call(arguments);
138
+ const logString = returnString(args);
139
+ if (logString) {
140
+ logger.log('debug', logString);
141
+ }
142
+ },
143
+ };
144
+ }
145
+ const log = (config, message, type) => {
146
+ const logsPath = config.data;
147
+ // ignoring the type argument, as we are not using it to create a logfile anymore
148
+ if (type !== 'error') {
149
+ // removed type argument from init method
150
+ init(logsPath).log(message);
151
+ }
152
+ else {
153
+ init(logsPath).error(message);
154
+ }
155
+ };
156
+ exports.log = log;
157
+ const unlinkFileLogger = () => {
158
+ if (logger) {
159
+ const transports = logger.transports;
160
+ transports.forEach((transport) => {
161
+ if (transport.name === 'file') {
162
+ logger.remove(transport);
163
+ }
164
+ });
165
+ }
166
+ if (errorLogger) {
167
+ const transports = errorLogger.transports;
168
+ transports.forEach((transport) => {
169
+ if (transport.name === 'file') {
170
+ errorLogger.remove(transport);
171
+ }
172
+ });
173
+ }
174
+ };
175
+ exports.unlinkFileLogger = unlinkFileLogger;
@@ -0,0 +1,73 @@
1
+ import { AdapterHelper } from './adapter-helper';
2
+ import { HttpClient } from '@contentstack/cli-utilities';
3
+ import { ProjectStruct, Personalization, GetProjectsParams, CreateProjectInput, CreateAttributeInput, APIConfig, GetVariantGroupInput, EventStruct, AudienceStruct, AttributeStruct, CreateAudienceInput, CreateEventInput, CreateExperienceInput, ExperienceStruct, UpdateExperienceInput, CMSExperienceStruct, VariantAPIRes, APIResponse, VariantGroupStruct, VariantGroup } from '../types';
4
+ export declare class PersonalizationAdapter<T> extends AdapterHelper<T, HttpClient> implements Personalization<T> {
5
+ constructor(options: APIConfig);
6
+ projects(options: GetProjectsParams): Promise<ProjectStruct[]>;
7
+ /**
8
+ * This TypeScript function creates a project by making an asynchronous API call to retrieve project
9
+ * data.
10
+ * @param {CreateProjectInput} input - The `input` parameter in the `createProject` function likely
11
+ * represents the data needed to create a new project. It could include details such as the project
12
+ * name, description, owner, deadline, or any other relevant information required to set up a new
13
+ * project.
14
+ * @returns The `createProject` function is returning a Promise that resolves to either a
15
+ * `ProjectStruct` object or `void`.
16
+ */
17
+ createProject(project: CreateProjectInput): Promise<ProjectStruct>;
18
+ /**
19
+ * The function `createAttribute` asynchronously retrieves attribute data from an API endpoint.
20
+ * @param {CreateAttributeInput} input - The `input` parameter in the `createAttribute` function is
21
+ * of type `CreateAttributeInput`. This parameter likely contains the necessary data or information
22
+ * needed to create a new attribute.
23
+ * @returns The `createAttribute` function is returning the data obtained from a GET request to the
24
+ * `/attributes` endpoint using the `apiClient` with the input provided. The data returned is of type
25
+ * `ProjectStruct`.
26
+ */
27
+ createAttribute(attribute: CreateAttributeInput): Promise<AttributeStruct>;
28
+ getExperiences(): Promise<ExperienceStruct[]>;
29
+ getExperience(experienceUid: string): Promise<ExperienceStruct | void>;
30
+ getVariantGroup(input: GetVariantGroupInput): Promise<VariantGroupStruct | void>;
31
+ updateVariantGroup(input: VariantGroup): Promise<VariantGroup | void>;
32
+ getEvents(): Promise<EventStruct[] | void>;
33
+ createEvents(event: CreateEventInput): Promise<void | EventStruct>;
34
+ getAudiences(): Promise<AudienceStruct[] | void>;
35
+ getAttributes(): Promise<AttributeStruct[] | void>;
36
+ /**
37
+ * @param {CreateAudienceInput} audience - The `audience` parameter in the `createAudience` function is
38
+ * of type `CreateAudienceInput`. This parameter likely contains the necessary data or information
39
+ * needed to create a new audience.
40
+ * @returns The `createAudience` function is returning the data obtained from a GET request to the
41
+ * `/audiences` endpoint using the `apiClient` with the input provided. The data returned is of type
42
+ * `AudienceStruct`.
43
+ */
44
+ createAudience(audience: CreateAudienceInput): Promise<void | AudienceStruct>;
45
+ /**
46
+ * @param {CreateExperienceInput} experience - The `experience` parameter in the `createExperience` function is
47
+ * of type `CreateExperienceInput`. This parameter likely contains the necessary data or information
48
+ * needed to create a new audience.
49
+ * @returns The `createExperience` function is returning the data obtained from a GET request to the
50
+ * `/experiences` endpoint using the `apiClient` with the input provided. The data returned is of type
51
+ * `ExperienceStruct`.
52
+ */
53
+ createExperience(experience: CreateExperienceInput): Promise<void | ExperienceStruct>;
54
+ /**
55
+ * @param {UpdateExperienceInput} experience - The `experience` parameter in the `updateCTsInExperience` function is
56
+ * of type `UpdateExperienceInput`. This parameter likely contains the necessary data or information
57
+ * needed to attach CT in new created experience.
58
+ */
59
+ updateCTsInExperience(experience: UpdateExperienceInput, experienceUid: string): Promise<void | CMSExperienceStruct>;
60
+ /**
61
+ * @param {UpdateExperienceInput} experienceUid - The `experienceUid` parameter in the `getCTsFromExperience` function is
62
+ * of type `string`. This parameter likely contains the necessary data or information
63
+ * needed to fetch CT details related to experience.
64
+ */
65
+ getCTsFromExperience(experienceUid: string): Promise<void | CMSExperienceStruct>;
66
+ /**
67
+ * Handles the API response for variant requests.
68
+ * @param res - The API response object.
69
+ * @returns The variant API response data.
70
+ * @throws If the API response status is not within the success range, an error message is thrown.
71
+ */
72
+ handleVariantAPIRes(res: APIResponse): VariantAPIRes;
73
+ }