-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport-setup-asset-mappers.ts
More file actions
193 lines (169 loc) · 7.3 KB
/
import-setup-asset-mappers.ts
File metadata and controls
193 lines (169 loc) · 7.3 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
import { readdirSync, statSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { formatError, log } from '@contentstack/cli-utilities';
import { IMPORT_ASSETS_MAPPER_FILES, PROCESS_NAMES, PROCESS_STATUS } from '../constants/index';
import type { AssetManagementAPIConfig, ImportContext } from '../types/asset-management-api';
import type { AssetMapperImportSetupResult, RunAssetMapperImportSetupParams } from '../types/import-setup-asset-mapper';
import ImportAssets from '../import/assets';
import { AssetManagementAdapter } from '../utils/asset-management-api-adapter';
import { AssetManagementImportSetupAdapter } from './base';
const PROCESS = PROCESS_NAMES.AM_IMPORT_SETUP_ASSET_MAPPERS;
/**
* Builds identity uid/url and space-uid mapper files from an Asset Management export layout
* for spaces that already exist in the target org (reuse path).
*/
export default class ImportSetupAssetMappers extends AssetManagementImportSetupAdapter {
constructor(params: RunAssetMapperImportSetupParams) {
super(params);
}
private async fetchExistingSpaceUidsInOrg(apiConfig: AssetManagementAPIConfig): Promise<Set<string>> {
const adapter = new AssetManagementAdapter(apiConfig);
await adapter.init();
const { spaces } = await adapter.listSpaces();
const uids = new Set<string>();
for (const s of spaces) {
if (s.uid) {
uids.add(s.uid);
}
}
return uids;
}
private listExportedSpaceDirectories(spacesRootPath: string): { spaceDirs: string[]; readFailed: boolean } {
try {
const spaceDirs = readdirSync(spacesRootPath).filter((entry) => {
try {
return statSync(join(spacesRootPath, entry)).isDirectory() && entry.startsWith('am');
} catch {
return false;
}
});
return { spaceDirs, readFailed: false };
} catch {
log.info(`Could not read Asset Management spaces directory: ${spacesRootPath}`, this.params.context);
return { spaceDirs: [], readFailed: true };
}
}
async start(): Promise<AssetMapperImportSetupResult> {
const p = this.params;
const {
contentDir,
mapperBaseDir,
assetManagementUrl,
org_uid,
source_stack,
apiKey,
host,
context,
} = p;
const apiConcurrencyResolved = p.apiConcurrency ?? p.fetchConcurrency;
if (!assetManagementUrl) {
log.info(
'AM 2.0 export detected but assetManagementUrl is not configured in the region settings. Skipping AM 2.0 asset mapper setup.',
context,
);
return { kind: 'skipped', reason: 'missing_asset_management_url' };
}
if (!org_uid) {
log.error('Cannot run Asset Management import-setup: organization UID is missing.', context);
return { kind: 'skipped', reason: 'missing_organization_uid' };
}
const parentProgressManager = this.resolveParentProgress();
const spacesDirSegment = p.spacesDirName ?? 'spaces';
const spacesRootPath = resolve(contentDir, spacesDirSegment);
const mapperRoot = p.mapperRootDir ?? 'mapper';
const mapperAssetsMod = p.mapperAssetsModuleDir ?? 'assets';
const mapperDirPath = join(mapperBaseDir, mapperRoot, mapperAssetsMod);
const uidFile = p.mapperUidFileName ?? IMPORT_ASSETS_MAPPER_FILES.UID_MAPPING;
const urlFile = p.mapperUrlFileName ?? IMPORT_ASSETS_MAPPER_FILES.URL_MAPPING;
const spaceUidFile = p.mapperSpaceUidFileName ?? IMPORT_ASSETS_MAPPER_FILES.SPACE_UID_MAPPING;
const duplicateAssetMapperPath = join(mapperDirPath, IMPORT_ASSETS_MAPPER_FILES.DUPLICATE_ASSETS);
const apiConfig: AssetManagementAPIConfig = {
baseURL: assetManagementUrl,
headers: { organization_uid: org_uid },
context,
};
const importContext: ImportContext = {
spacesRootPath,
sourceApiKey: source_stack,
apiKey,
host,
org_uid,
context,
apiConcurrency: apiConcurrencyResolved,
spacesDirName: p.spacesDirName,
fieldsDir: p.fieldsDir,
assetTypesDir: p.assetTypesDir,
fieldsFileName: p.fieldsFileName,
assetTypesFileName: p.assetTypesFileName,
foldersFileName: p.foldersFileName,
assetsFileName: p.assetsFileName,
fieldsImportInvalidKeys: p.fieldsImportInvalidKeys,
assetTypesImportInvalidKeys: p.assetTypesImportInvalidKeys,
uploadAssetsConcurrency: p.uploadAssetsConcurrency,
importFoldersConcurrency: p.importFoldersConcurrency,
mapperRootDir: mapperRoot,
mapperAssetsModuleDir: mapperAssetsMod,
mapperUidFileName: uidFile,
mapperUrlFileName: urlFile,
mapperSpaceUidFileName: spaceUidFile,
};
try {
if (parentProgressManager) {
parentProgressManager.addProcess(PROCESS, 1);
parentProgressManager
.startProcess(PROCESS)
.updateStatus(PROCESS_STATUS[PROCESS].GENERATING, PROCESS);
}
const existingSpaceUids = await this.fetchExistingSpaceUidsInOrg(apiConfig);
const { spaceDirs, readFailed } = this.listExportedSpaceDirectories(spacesRootPath);
if (spaceDirs.length === 0 && !readFailed) {
log.info(
`No Asset Management space directories (am*) found under ${spacesDirSegment}/.`,
context,
);
}
const allUidMap: Record<string, string> = {};
const allUrlMap: Record<string, string> = {};
const spaceUidMap: Record<string, string> = {};
const assetsImporter = new ImportAssets(apiConfig, importContext);
for (const spaceUid of spaceDirs) {
const spaceDir = join(spacesRootPath, spaceUid);
if (existingSpaceUids.has(spaceUid)) {
const { uidMap, urlMap } = await assetsImporter.buildIdentityMappersFromExport(spaceDir);
Object.assign(allUidMap, uidMap);
Object.assign(allUrlMap, urlMap);
spaceUidMap[spaceUid] = spaceUid;
parentProgressManager?.tick(true, `Asset Management space reused: ${spaceUid}`, null, PROCESS);
log.info(
`Asset Management space "${spaceUid}" exists in org; identity asset mappers merged from export.`,
context,
);
} else {
log.info(
`Asset Management space "${spaceUid}" is not in the target org yet. Import assets first, then re-run import-setup to refresh mappers after upload.`,
context,
);
}
}
await mkdir(mapperDirPath, { recursive: true });
await writeFile(join(mapperDirPath, uidFile), JSON.stringify(allUidMap), 'utf8');
await writeFile(join(mapperDirPath, urlFile), JSON.stringify(allUrlMap), 'utf8');
await writeFile(join(mapperDirPath, spaceUidFile), JSON.stringify(spaceUidMap), 'utf8');
await writeFile(duplicateAssetMapperPath, JSON.stringify({}), 'utf8');
parentProgressManager?.completeProcess(PROCESS, true);
log.success(
'The required Asset Management setup files for assets have been generated successfully.',
context,
);
return { kind: 'success' };
} catch (error) {
parentProgressManager?.completeProcess(PROCESS, false);
log.error(`Error occurred while generating Asset Management asset mappers: ${formatError(error)}.`, context);
return {
kind: 'error',
errorMessage: (error as Error)?.message || 'Asset Management asset mapper generation failed',
};
}
}
}