-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathexport-config-handler.ts
More file actions
146 lines (125 loc) · 5.47 KB
/
export-config-handler.ts
File metadata and controls
146 lines (125 loc) · 5.47 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
import merge from 'merge';
import * as path from 'path';
import { configHandler, isAuthenticated, cliux, sanitizePath, log } from '@contentstack/cli-utilities';
import defaultConfig from '../config';
import { readFile } from './file-helper';
import { askExportDir, askAPIKey } from './interactive';
import login from './basic-login';
import { filter, includes } from 'lodash';
import { ExportConfig } from '../types';
const setupConfig = async (exportCmdFlags: any): Promise<ExportConfig> => {
// Set progress supported module FIRST, before any log calls
// This ensures the logger respects the showConsoleLogs setting correctly
configHandler.set('log.progressSupportedModule', 'export');
let config = merge({}, defaultConfig);
// Track authentication method
let authenticationMethod = 'unknown';
log.debug('Setting up export configuration');
// setup the config
if (exportCmdFlags['config']) {
log.debug('Loading external configuration file...', { configFile: exportCmdFlags['config'] });
const externalConfig = await readFile(exportCmdFlags['config']);
config = merge.recursive(config, externalConfig);
}
config.exportDir = sanitizePath(
exportCmdFlags['data'] || exportCmdFlags['data-dir'] || config.data || (await askExportDir()),
);
const pattern = /[*$%#<>{}!&?]/g;
if (pattern.test(config.exportDir)) {
cliux.print(`\nPlease enter a directory path without any special characters: (*,&,{,},[,],$,%,<,>,?,!)`, {
color: 'yellow',
});
config.exportDir = sanitizePath(await askExportDir());
}
config.exportDir = config.exportDir.replace(/['"]/g, '');
config.exportDir = path.resolve(config.exportDir);
//Note to support the old key
config.data = config.exportDir;
const managementTokenAlias = exportCmdFlags['management-token-alias'] || exportCmdFlags['alias'];
if (managementTokenAlias) {
log.debug('Using management token alias', { alias: managementTokenAlias });
const { token, apiKey } = configHandler.get(`tokens.${managementTokenAlias}`) || {};
config.management_token = token;
config.apiKey = apiKey;
authenticationMethod = 'Management Token';
if (!config.management_token) {
log.debug('Management token not found for alias!', { alias: managementTokenAlias });
throw new Error(`No management token found on given alias ${managementTokenAlias}`);
}
log.debug('Management token configuration successful');
}
if (!config.management_token) {
if (!isAuthenticated()) {
log.debug('User not authenticated, checking for basic auth credentials');
if (config.username && config.password) {
log.debug('Using basic authentication with username/password');
await login(config);
authenticationMethod = 'Basic Auth';
log.debug('Basic authentication successful');
} else {
log.debug('No authentication method available');
throw new Error('Please login or provide an alias for the management token');
}
} else {
// Check if user is authenticated via OAuth
const isOAuthUser = configHandler.get('authorisationType') === 'OAUTH' || false;
if (isOAuthUser) {
authenticationMethod = 'OAuth';
log.debug('User authenticated via OAuth');
} else {
authenticationMethod = 'Basic Auth';
log.debug('User authenticated via auth token');
}
config.apiKey =
exportCmdFlags['stack-uid'] || exportCmdFlags['stack-api-key'] || config.source_stack || (await askAPIKey());
if (typeof config.apiKey !== 'string') {
log.debug('Invalid API key received!', { apiKey: config.apiKey });
throw new Error('Invalid API key received');
}
}
}
// Note support old config
config.source_stack = config.apiKey;
config.forceStopMarketplaceAppsPrompt = exportCmdFlags.yes;
config.auth_token = configHandler.get('authtoken'); // TBD handle auth token in httpClient & sdk
config.isAuthenticated = isAuthenticated();
if (exportCmdFlags['branch-alias']) {
config.branchAlias = exportCmdFlags['branch-alias'];
}
if (exportCmdFlags['branch']) {
config.branchName = exportCmdFlags['branch'];
}
if (exportCmdFlags['module']) {
config.moduleName = exportCmdFlags['module'];
config.singleModuleExport = true;
}
if (exportCmdFlags['secured-assets']) {
config.securedAssets = true;
}
if (Array.isArray(exportCmdFlags['content-types']) && exportCmdFlags['content-types'].length > 0) {
config.contentTypes = exportCmdFlags['content-types'];
}
if (Array.isArray(config.filteredModules) && config.filteredModules.length > 0) {
config.modules.types = filter(defaultConfig.modules.types, (module) => includes(config.filteredModules, module));
}
// Handle query flag - can be inline JSON or file path
if (exportCmdFlags['query']) {
try {
const queryInput = exportCmdFlags['query'];
// Check if it's a file path (contains .json extension or path separators)
if (queryInput.includes('.json') || queryInput.includes('/') || queryInput.includes('\\')) {
// Try to read as file path
config.query = await readFile(queryInput);
} else {
config.query = JSON.parse(queryInput);
}
} catch (error) {
throw new Error(`Invalid query format: ${error.message}`);
}
}
// Add authentication details to config for context tracking
config.authenticationMethod = authenticationMethod;
log.debug('Export configuration setup completed.', { ...config });
return config;
};
export default setupConfig;