-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexperiences.ts
More file actions
221 lines (193 loc) · 9.88 KB
/
experiences.ts
File metadata and controls
221 lines (193 loc) · 9.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import * as path from 'path';
import { sanitizePath, log, handleAndLogError } from '@contentstack/cli-utilities';
import { PersonalizeConfig, ExportConfig, ExperienceStruct } from '../types';
import { fsUtil, PersonalizationAdapter } from '../utils';
import { PROCESS_NAMES, MODULE_CONTEXTS, EXPORT_PROCESS_STATUS } from '../utils/constants';
export default class ExportExperiences extends PersonalizationAdapter<ExportConfig> {
private experiencesFolderPath: string;
public exportConfig: ExportConfig;
public personalizeConfig: PersonalizeConfig;
constructor(exportConfig: ExportConfig) {
super({
config: exportConfig,
baseURL: exportConfig.modules.personalize.baseURL[exportConfig.region.name],
headers: { 'X-Project-Uid': exportConfig.project_id },
cmaConfig: {
baseURL: exportConfig.region.cma + `/v3`,
headers: {
api_key: exportConfig.apiKey,
...(exportConfig.branchName ? { branch: exportConfig.branchName } : {}),
},
},
});
this.exportConfig = exportConfig;
this.personalizeConfig = exportConfig.modules.personalize;
this.experiencesFolderPath = path.resolve(
sanitizePath(exportConfig.exportDir),
sanitizePath(this.personalizeConfig.dirName),
'experiences',
);
this.exportConfig.context.module = MODULE_CONTEXTS.EXPERIENCES;
}
async start() {
try {
log.debug('Starting experiences export process...', this.exportConfig.context);
log.info('Starting experiences export', this.exportConfig.context);
const { experiences } = await this.withLoadingSpinner(
'EXPERIENCES: Initializing export and fetching data...',
async () => {
log.debug('Initializing personalization adapter...', this.exportConfig.context);
await this.init();
log.debug('Personalization adapter initialized successfully', this.exportConfig.context);
log.debug(`Creating experiences directory at: ${this.experiencesFolderPath}`, this.exportConfig.context);
await fsUtil.makeDirectory(this.experiencesFolderPath);
log.debug('Experiences directory created successfully', this.exportConfig.context);
const versionsDirPath = path.resolve(sanitizePath(this.experiencesFolderPath), 'versions');
log.debug(`Creating versions directory at: ${versionsDirPath}`, this.exportConfig.context);
await fsUtil.makeDirectory(versionsDirPath);
log.debug('Versions directory created successfully', this.exportConfig.context);
log.debug('Fetching experiences from personalization API...', this.exportConfig.context);
const experiences: Array<ExperienceStruct> = (await this.getExperiences()) || [];
log.debug(`Fetched ${experiences?.length || 0} experiences`, this.exportConfig.context);
return { experiences };
},
);
if (!experiences || experiences?.length < 1) {
log.debug('No experiences found, completing export', this.exportConfig.context);
log.info('No experiences found for the given project.', this.exportConfig.context);
return;
}
let progress: any;
const processName = PROCESS_NAMES.EXPERIENCES;
if (this.parentProgressManager) {
progress = this.parentProgressManager;
this.progressManager = this.parentProgressManager;
progress.updateProcessTotal(processName, experiences.length);
} else {
// Create our own progress for standalone execution
progress = this.createSimpleProgress(PROCESS_NAMES.EXPERIENCES, experiences.length);
}
log.debug(`Processing ${experiences.length} experiences`, this.exportConfig.context);
progress.updateStatus(EXPORT_PROCESS_STATUS[PROCESS_NAMES.EXPERIENCES].EXPORTING, processName);
const experiencesFilePath = path.resolve(sanitizePath(this.experiencesFolderPath), 'experiences.json');
log.debug(`Writing experiences to: ${experiencesFilePath}`, this.exportConfig.context);
fsUtil.writeFile(experiencesFilePath, experiences);
const experienceToVariantsStrList: Array<string> = [];
const experienceToContentTypesMap: Record<string, string[]> = {};
log.debug(
`Processing ${experiences.length} experiences for variants and content types`,
this.exportConfig.context,
);
progress.updateStatus(EXPORT_PROCESS_STATUS[PROCESS_NAMES.EXPERIENCES].EXPORTING, processName);
for (let experienceIndex = 0; experienceIndex < experiences.length; experienceIndex++) {
const experience = experiences[experienceIndex];
try {
log.debug(
`Processing experience: ${experience.name} (${experience.uid}) - ${experienceIndex + 1}/${
experiences.length
}`,
this.exportConfig.context,
);
// create id mapper for experience to variants
let variants = experience?._cms?.variants ?? {};
// talisman-ignore-start
log.debug(
`Found ${Object.keys(variants).length} variants for experience: ${experience.name}`,
this.exportConfig.context,
);
// talisman-ignore-end
// talisman-ignore-start
Object.keys(variants).forEach((variantShortId: string) => {
const experienceToVariantsStr = `${experience.uid}-${variantShortId}-${variants[variantShortId]}`;
experienceToVariantsStrList.push(experienceToVariantsStr);
log.debug(`Added variant mapping: ${experienceToVariantsStr}`, this.exportConfig.context);
});
// talisman-ignore-end
// Fetch versions of experience
try {
log.debug(`Fetching versions for experience: ${experience.name}`, this.exportConfig.context);
const experienceVersions = (await this.getExperienceVersions(experience.uid)) || [];
log.debug(
`Fetched ${experienceVersions.length} versions for experience: ${experience.name}`,
this.exportConfig.context,
);
if (experienceVersions.length > 0) {
const versionsFilePath = path.resolve(
sanitizePath(this.experiencesFolderPath),
'versions',
`${experience.uid}.json`,
);
log.debug(`Writing experience versions to: ${versionsFilePath}`, this.exportConfig.context);
fsUtil.writeFile(versionsFilePath, experienceVersions);
} else {
log.debug(`No versions found for experience: ${experience.name}`, this.exportConfig.context);
log.info(`No versions found for experience '${experience.name}'`, this.exportConfig.context);
}
} catch (error: any) {
log.debug(
`Error occurred while fetching versions for experience: ${experience.name}`,
this.exportConfig.context,
);
handleAndLogError(
error,
{ ...this.exportConfig.context },
`Failed to fetch versions of experience ${experience.name}`,
);
}
// Fetch content types of experience
try {
log.debug(`Fetching variant group for experience: ${experience.name}`, this.exportConfig.context);
const { variant_groups: [variantGroup] = [] } =
(await this.getVariantGroup({ experienceUid: experience.uid })) || {};
if (variantGroup?.content_types?.length) {
log.debug(
`Found ${variantGroup.content_types.length} content types for experience: ${experience.name}`,
this.exportConfig.context,
);
experienceToContentTypesMap[experience.uid] = variantGroup.content_types;
} else {
log.debug(`No content types found for experience: ${experience.name}`, this.exportConfig.context);
}
} catch (error: any) {
log.debug(
`Error occurred while fetching content types for experience: ${experience.name}`,
this.exportConfig.context,
);
handleAndLogError(
error,
{ ...this.exportConfig.context },
`Failed to fetch content types of experience ${experience.name}`,
);
}
} catch (error: any) {
log.debug(`Error occurred while processing experience: ${experience.name}`, this.exportConfig.context);
handleAndLogError(error, { ...this.exportConfig.context }, `Failed to process experience ${experience.name}`);
}
}
progress.updateStatus(EXPORT_PROCESS_STATUS[PROCESS_NAMES.EXPERIENCES].EXPORTING, processName);
// Write final mapping files
const variantsIdsFilePath = path.resolve(
sanitizePath(this.experiencesFolderPath),
'experiences-variants-ids.json',
);
log.debug(`Writing experience variants mapping to: ${variantsIdsFilePath}`, this.exportConfig.context);
fsUtil.writeFile(variantsIdsFilePath, experienceToVariantsStrList);
const contentTypesFilePath = path.resolve(
sanitizePath(this.experiencesFolderPath),
'experiences-content-types.json',
);
log.debug(`Writing experience content types mapping to: ${contentTypesFilePath}`, this.exportConfig.context);
fsUtil.writeFile(contentTypesFilePath, experienceToContentTypesMap);
// Complete progress only if we're managing our own progress
if (!this.parentProgressManager) {
this.completeProgress(true);
}
log.debug('Experiences export completed successfully', this.exportConfig.context);
log.success('Experiences exported successfully!', this.exportConfig.context);
} catch (error: any) {
log.debug(`Error occurred during experiences export: ${error}`, this.exportConfig.context);
this.completeProgress(false, error?.message || 'Experiences export failed');
handleAndLogError(error, { ...this.exportConfig.context });
}
}
}