@magentrix-corp/magentrix-cli 1.2.0 → 1.2.1
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.
- package/actions/publish.js +75 -6
- package/actions/pull.js +423 -333
- package/actions/setup.js +62 -15
- package/package.json +1 -1
- package/utils/cli/helpers/ensureApiKey.js +28 -22
- package/utils/cli/helpers/ensureInstanceUrl.js +35 -27
- package/utils/cli/writeRecords.js +13 -2
- package/utils/config.js +76 -0
- package/utils/magentrix/api/auth.js +45 -6
- package/utils/updateFileBase.js +4 -0
package/actions/pull.js
CHANGED
|
@@ -7,12 +7,12 @@ import { ProgressTracker } from "../utils/progress.js";
|
|
|
7
7
|
import { createLogger, Logger } from "../utils/logger.js";
|
|
8
8
|
import { EXPORT_ROOT, TYPE_DIR_MAP } from "../vars/global.js";
|
|
9
9
|
import { mapRecordToFile, writeRecords } from "../utils/cli/writeRecords.js";
|
|
10
|
-
import { updateBase, removeFromBase } from "../utils/updateFileBase.js";
|
|
10
|
+
import { updateBase, removeFromBase, removeFromBaseBulk } from "../utils/updateFileBase.js";
|
|
11
11
|
import { compareAllFilesAndLogStatus, promptConflictResolution, showCurrentConflicts } from "../utils/cli/helpers/compare.js";
|
|
12
12
|
import path from "path";
|
|
13
13
|
import { compareLocalAndRemote } from "../utils/compare.js";
|
|
14
14
|
import chalk from 'chalk';
|
|
15
|
-
import { getFileTag } from "../utils/filetag.js";
|
|
15
|
+
import { getFileTag, setFileTag } from "../utils/filetag.js";
|
|
16
16
|
import { downloadAssetsZip, listAssets } from "../utils/magentrix/api/assets.js";
|
|
17
17
|
import { downloadAssets, walkAssets } from "../utils/downloadAssets.js";
|
|
18
18
|
import { v4 as uuidv4 } from 'uuid';
|
|
@@ -72,380 +72,470 @@ export const pull = async () => {
|
|
|
72
72
|
const instanceChanged = lastInstanceUrl && lastInstanceUrl !== instanceUrl;
|
|
73
73
|
|
|
74
74
|
if (instanceChanged) {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
75
|
+
progress.stopSpinner();
|
|
76
|
+
progress.render();
|
|
77
|
+
console.log(chalk.yellow.bold(`\n⚠️ INSTANCE CHANGE DETECTED`));
|
|
78
|
+
console.log(chalk.yellow(`Previous instance: ${chalk.cyan(lastInstanceUrl)}`));
|
|
79
|
+
console.log(chalk.yellow(`New instance: ${chalk.cyan(instanceUrl)}`));
|
|
80
|
+
console.log();
|
|
81
|
+
console.log(chalk.red.bold(`⚠️ WARNING: This will DELETE your existing ${chalk.white(EXPORT_ROOT + '/')} directory!`));
|
|
82
|
+
console.log(chalk.gray(`This is necessary to prevent mixing files from different instances.`));
|
|
83
|
+
console.log();
|
|
84
|
+
|
|
85
|
+
const confirm = readlineSync.question(
|
|
86
|
+
chalk.yellow(`Type ${chalk.white.bold('yes')} to continue and delete ${EXPORT_ROOT}/, or ${chalk.white.bold('no')} to cancel: `)
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
if (confirm.trim().toLowerCase() !== 'yes') {
|
|
90
|
+
console.log(chalk.red('\n❌ Pull cancelled. No files were deleted.'));
|
|
91
|
+
console.log(chalk.gray(`Tip: To pull from ${chalk.cyan(lastInstanceUrl)}, switch back to those credentials.`));
|
|
92
|
+
process.exit(0);
|
|
93
|
+
}
|
|
88
94
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
95
|
+
console.log(chalk.yellow(`\n🗑️ Removing existing ${EXPORT_ROOT}/ directory...`));
|
|
96
|
+
if (fs.existsSync(EXPORT_ROOT)) {
|
|
97
|
+
fs.rmSync(EXPORT_ROOT, { recursive: true, force: true });
|
|
98
|
+
}
|
|
99
|
+
// Clear the base.json cache as well since it's from a different instance
|
|
100
|
+
fs.writeFileSync('.magentrix/base.json', JSON.stringify({}));
|
|
101
|
+
config.save('cachedFiles', {}, { filename: 'fileCache.json' });
|
|
102
|
+
config.save('trackedFileTags', {}, { filename: 'fileIdIndex.json' });
|
|
103
|
+
console.log(chalk.green(`✓ Removed ${EXPORT_ROOT}/ directory\n`));
|
|
104
|
+
|
|
105
|
+
progress.start(); // Restart progress tracker
|
|
106
|
+
progress.startStep('check');
|
|
93
107
|
}
|
|
94
108
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
109
|
+
// Save the current instance URL for future comparisons
|
|
110
|
+
config.save('lastInstanceUrl', instanceUrl, { global: false, filename: 'config.json' });
|
|
111
|
+
progress.completeStep('check', instanceChanged ? '✓ Instance reset' : '✓ Instance verified');
|
|
112
|
+
|
|
113
|
+
// Step 3: Prepare queries for both ActiveClass and ActivePage
|
|
114
|
+
const queries = [
|
|
115
|
+
{
|
|
116
|
+
name: "ActiveClass",
|
|
117
|
+
query: "SELECT Id,Body,Name,CreatedOn,Description,ModifiedOn,Type FROM ActiveClass",
|
|
118
|
+
contentField: "Body",
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
name: "ActivePage",
|
|
122
|
+
query: "SELECT Id,Content,Name,CreatedOn,Description,ModifiedOn,Type FROM ActivePage",
|
|
123
|
+
contentField: "Content",
|
|
124
|
+
}
|
|
125
|
+
];
|
|
126
|
+
|
|
127
|
+
// Step 3: Load existing base.json to detect deletions
|
|
128
|
+
progress.startStep('load');
|
|
129
|
+
const hits = await config.searchObject({}, { filename: "base.json", global: false });
|
|
130
|
+
const cachedResults = hits?.[0]?.value || {};
|
|
131
|
+
const cachedAssets = Object.values(cachedResults).filter(c =>
|
|
132
|
+
c.type === 'File' || c.type === 'Folder'
|
|
133
|
+
);
|
|
134
|
+
progress.completeStep('load', `✓ Loaded ${Object.keys(cachedResults).length} cached entries`);
|
|
135
|
+
|
|
136
|
+
// Step 4a: Download code entities (ActiveClass and ActivePage)
|
|
137
|
+
progress.startStep('download-code');
|
|
138
|
+
|
|
139
|
+
let activeClassResult, activePageResult;
|
|
140
|
+
const codeDownloadErrors = [];
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
logger.info('Starting code entity downloads');
|
|
144
|
+
const meqlResults = await Promise.all(
|
|
145
|
+
queries.map(q => meqlQuery(instanceUrl, token.value, q.query))
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
[activeClassResult, activePageResult] = meqlResults;
|
|
149
|
+
const totalCodeEntities = activeClassResult.Records.length + activePageResult.Records.length;
|
|
150
|
+
|
|
151
|
+
logger.info(`Downloaded ${totalCodeEntities} code entities`, {
|
|
152
|
+
activeClass: activeClassResult.Records.length,
|
|
153
|
+
activePage: activePageResult.Records.length
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
progress.updateProgress('download-code', totalCodeEntities, totalCodeEntities, `Downloaded ${totalCodeEntities} code entities`);
|
|
157
|
+
progress.completeStep('download-code', `✓ Downloaded ${totalCodeEntities} code entities`);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
logger.error('Error downloading code entities', error);
|
|
160
|
+
codeDownloadErrors.push({ stage: 'code-download', error: error.message });
|
|
161
|
+
progress.failStep('download-code', error.message);
|
|
162
|
+
|
|
163
|
+
// Show error preview
|
|
164
|
+
progress.stopSpinner();
|
|
165
|
+
console.log('');
|
|
166
|
+
console.log(chalk.red.bold('❌ Code Download Error:'));
|
|
167
|
+
console.log(chalk.red(` ${error.message.substring(0, 200)}`));
|
|
168
|
+
console.log(chalk.cyan(`\n 📄 Full details in log file`));
|
|
169
|
+
console.log('');
|
|
170
|
+
|
|
171
|
+
// Initialize empty data structures
|
|
172
|
+
if (!activeClassResult) activeClassResult = { Records: [] };
|
|
173
|
+
if (!activePageResult) activePageResult = { Records: [] };
|
|
174
|
+
|
|
175
|
+
// Restart progress for next step
|
|
176
|
+
progress.start();
|
|
177
|
+
progress.startStep('download-assets');
|
|
98
178
|
}
|
|
99
|
-
// Clear the base.json cache as well since it's from a different instance
|
|
100
|
-
fs.writeFileSync('.magentrix/base.json', JSON.stringify({}));
|
|
101
|
-
config.save('cachedFiles', {}, { filename: 'fileCache.json' });
|
|
102
|
-
config.save('trackedFileTags', {}, { filename: 'fileIdIndex.json' });
|
|
103
|
-
console.log(chalk.green(`✓ Removed ${EXPORT_ROOT}/ directory\n`));
|
|
104
179
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
// Save the current instance URL for future comparisons
|
|
110
|
-
config.save('lastInstanceUrl', instanceUrl, { global: false, filename: 'config.json' });
|
|
111
|
-
progress.completeStep('check', instanceChanged ? '✓ Instance reset' : '✓ Instance verified');
|
|
112
|
-
|
|
113
|
-
// Step 3: Prepare queries for both ActiveClass and ActivePage
|
|
114
|
-
const queries = [
|
|
115
|
-
{
|
|
116
|
-
name: "ActiveClass",
|
|
117
|
-
query: "SELECT Id,Body,Name,CreatedOn,Description,ModifiedOn,Type FROM ActiveClass",
|
|
118
|
-
contentField: "Body",
|
|
119
|
-
},
|
|
120
|
-
{
|
|
121
|
-
name: "ActivePage",
|
|
122
|
-
query: "SELECT Id,Content,Name,CreatedOn,Description,ModifiedOn,Type FROM ActivePage",
|
|
123
|
-
contentField: "Content",
|
|
180
|
+
// Step 4b: Download static assets
|
|
181
|
+
if (!codeDownloadErrors.length) {
|
|
182
|
+
progress.startStep('download-assets');
|
|
124
183
|
}
|
|
125
|
-
];
|
|
126
|
-
|
|
127
|
-
// Step 3: Load existing base.json to detect deletions
|
|
128
|
-
progress.startStep('load');
|
|
129
|
-
const hits = await config.searchObject({}, { filename: "base.json", global: false });
|
|
130
|
-
const cachedResults = hits?.[0]?.value || {};
|
|
131
|
-
const cachedAssets = Object.values(cachedResults).filter(c =>
|
|
132
|
-
c.type === 'File' || c.type === 'Folder'
|
|
133
|
-
);
|
|
134
|
-
progress.completeStep('load', `✓ Loaded ${Object.keys(cachedResults).length} cached entries`);
|
|
135
|
-
|
|
136
|
-
// Step 4a: Download code entities (ActiveClass and ActivePage)
|
|
137
|
-
progress.startStep('download-code');
|
|
138
|
-
|
|
139
|
-
let activeClassResult, activePageResult;
|
|
140
|
-
const codeDownloadErrors = [];
|
|
141
|
-
|
|
142
|
-
try {
|
|
143
|
-
logger.info('Starting code entity downloads');
|
|
144
|
-
const meqlResults = await Promise.all(
|
|
145
|
-
queries.map(q => meqlQuery(instanceUrl, token.value, q.query))
|
|
146
|
-
);
|
|
147
|
-
|
|
148
|
-
[activeClassResult, activePageResult] = meqlResults;
|
|
149
|
-
const totalCodeEntities = activeClassResult.Records.length + activePageResult.Records.length;
|
|
150
|
-
|
|
151
|
-
logger.info(`Downloaded ${totalCodeEntities} code entities`, {
|
|
152
|
-
activeClass: activeClassResult.Records.length,
|
|
153
|
-
activePage: activePageResult.Records.length
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
progress.updateProgress('download-code', totalCodeEntities, totalCodeEntities, `Downloaded ${totalCodeEntities} code entities`);
|
|
157
|
-
progress.completeStep('download-code', `✓ Downloaded ${totalCodeEntities} code entities`);
|
|
158
|
-
} catch (error) {
|
|
159
|
-
logger.error('Error downloading code entities', error);
|
|
160
|
-
codeDownloadErrors.push({ stage: 'code-download', error: error.message });
|
|
161
|
-
progress.failStep('download-code', error.message);
|
|
162
184
|
|
|
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
|
-
progress.
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
logger.info(`Downloaded ${assets.tree.length} asset folders`);
|
|
195
|
-
progress.completeStep('download-assets', `✓ Downloaded ${assets.tree.length} asset folders`);
|
|
196
|
-
} catch (error) {
|
|
197
|
-
logger.error('Error downloading static assets', error);
|
|
198
|
-
assetDownloadErrors.push({ stage: 'asset-download', error: error.message });
|
|
199
|
-
progress.failStep('download-assets', error.message);
|
|
200
|
-
|
|
201
|
-
// Show error preview
|
|
202
|
-
progress.stopSpinner();
|
|
203
|
-
console.log('');
|
|
204
|
-
console.log(chalk.red.bold('❌ Asset Download Error:'));
|
|
205
|
-
console.log(chalk.red(` ${error.message.substring(0, 200)}`));
|
|
206
|
-
console.log(chalk.cyan(`\n 📄 Full details in log file`));
|
|
207
|
-
console.log('');
|
|
208
|
-
|
|
209
|
-
// Initialize empty data structure
|
|
210
|
-
if (!assets) assets = { tree: [] };
|
|
185
|
+
let assets;
|
|
186
|
+
const assetDownloadErrors = [];
|
|
187
|
+
|
|
188
|
+
try {
|
|
189
|
+
logger.info('Starting static asset downloads');
|
|
190
|
+
assets = await downloadAssets(instanceUrl, token.value, null, (current, total, message) => {
|
|
191
|
+
progress.updateProgress('download-assets', current, total, message);
|
|
192
|
+
}, logger);
|
|
193
|
+
|
|
194
|
+
logger.info(`Downloaded ${assets.tree.length} asset folders`);
|
|
195
|
+
progress.completeStep('download-assets', `✓ Downloaded ${assets.tree.length} asset folders`);
|
|
196
|
+
} catch (error) {
|
|
197
|
+
logger.error('Error downloading static assets', error);
|
|
198
|
+
assetDownloadErrors.push({ stage: 'asset-download', error: error.message });
|
|
199
|
+
progress.failStep('download-assets', error.message);
|
|
200
|
+
|
|
201
|
+
// Show error preview
|
|
202
|
+
progress.stopSpinner();
|
|
203
|
+
console.log('');
|
|
204
|
+
console.log(chalk.red.bold('❌ Asset Download Error:'));
|
|
205
|
+
console.log(chalk.red(` ${error.message.substring(0, 200)}`));
|
|
206
|
+
console.log(chalk.cyan(`\n 📄 Full details in log file`));
|
|
207
|
+
console.log('');
|
|
208
|
+
|
|
209
|
+
// Initialize empty data structure
|
|
210
|
+
if (!assets) assets = { tree: [] };
|
|
211
|
+
|
|
212
|
+
// Restart progress for next step
|
|
213
|
+
progress.start();
|
|
214
|
+
}
|
|
211
215
|
|
|
212
|
-
//
|
|
213
|
-
|
|
214
|
-
|
|
216
|
+
// Check if we have any data to continue with
|
|
217
|
+
if (!activeClassResult?.Records?.length && !activePageResult?.Records?.length && !assets?.tree?.length) {
|
|
218
|
+
throw new Error('Download failed completely. No data available to continue.');
|
|
219
|
+
}
|
|
215
220
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
221
|
+
// Step 5: Process files and detect changes
|
|
222
|
+
progress.startStep('process');
|
|
223
|
+
const { allRecords, issues, deletionLogs, processingErrors } = await (async () => {
|
|
224
|
+
let processedCount = 0;
|
|
225
|
+
const totalToProcess = cachedAssets.length + (activeClassResult.Records.length + activePageResult.Records.length);
|
|
226
|
+
const processingErrors = [];
|
|
227
|
+
|
|
228
|
+
// Collect all server asset paths
|
|
229
|
+
const serverAssetPaths = new Set();
|
|
230
|
+
const collectServerPaths = (records) => {
|
|
231
|
+
try {
|
|
232
|
+
for (const record of records) {
|
|
233
|
+
const fullPath = path.join(EXPORT_ROOT, record?.Path);
|
|
234
|
+
serverAssetPaths.add(path.normalize(fullPath));
|
|
235
|
+
|
|
236
|
+
if (record?.Type === 'Folder' && record?.Children?.length > 0) {
|
|
237
|
+
collectServerPaths(record.Children);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
} catch (err) {
|
|
241
|
+
processingErrors.push({ stage: 'collect-paths', error: err.message });
|
|
242
|
+
logger.error('Error collecting server paths', err);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
collectServerPaths(assets.tree);
|
|
246
|
+
progress.updateProgress('process', ++processedCount, totalToProcess, 'Collecting server paths');
|
|
247
|
+
|
|
248
|
+
// Detect and delete assets that were on server before but are now gone
|
|
249
|
+
const assetsToDelete = [];
|
|
250
|
+
for (const cached of cachedAssets) {
|
|
251
|
+
const cachedPath = path.normalize(cached.lastKnownActualPath || cached.filePath || cached.lastKnownPath);
|
|
252
|
+
|
|
253
|
+
// If this asset was in base.json but not returned from server, it was deleted
|
|
254
|
+
if (!serverAssetPaths.has(cachedPath)) {
|
|
255
|
+
assetsToDelete.push(cachedPath);
|
|
256
|
+
}
|
|
220
257
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
258
|
+
processedCount++;
|
|
259
|
+
if (processedCount % 50 === 0) {
|
|
260
|
+
progress.updateProgress('process', processedCount, totalToProcess, `Checking assets...`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
progress.updateProgress('process', processedCount, totalToProcess, `Found ${assetsToDelete.length} assets to delete`);
|
|
264
|
+
|
|
265
|
+
// Count total assets (for progress tracking)
|
|
266
|
+
// Note: We don't update base.json for assets here because:
|
|
267
|
+
// 1. Assets are already downloaded and written to disk
|
|
268
|
+
// 2. Their base will be updated during the "Writing files" stage if modified
|
|
269
|
+
// 3. Updating base.json thousands of times here is extremely slow
|
|
270
|
+
logger.info('Counting assets in tree');
|
|
271
|
+
let assetCount = 0;
|
|
272
|
+
const countAssets = (records) => {
|
|
232
273
|
for (const record of records) {
|
|
233
|
-
|
|
234
|
-
serverAssetPaths.add(path.normalize(fullPath));
|
|
235
|
-
|
|
274
|
+
assetCount++;
|
|
236
275
|
if (record?.Type === 'Folder' && record?.Children?.length > 0) {
|
|
237
|
-
|
|
276
|
+
countAssets(record.Children);
|
|
238
277
|
}
|
|
239
278
|
}
|
|
240
|
-
} catch (err) {
|
|
241
|
-
processingErrors.push({ stage: 'collect-paths', error: err.message });
|
|
242
|
-
logger.error('Error collecting server paths', err);
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
collectServerPaths(assets.tree);
|
|
246
|
-
progress.updateProgress('process', ++processedCount, totalToProcess, 'Collecting server paths');
|
|
247
|
-
|
|
248
|
-
// Detect and delete assets that were on server before but are now gone
|
|
249
|
-
const assetsToDelete = [];
|
|
250
|
-
for (const cached of cachedAssets) {
|
|
251
|
-
const cachedPath = path.normalize(cached.lastKnownActualPath || cached.filePath || cached.lastKnownPath);
|
|
252
|
-
|
|
253
|
-
// If this asset was in base.json but not returned from server, it was deleted
|
|
254
|
-
if (!serverAssetPaths.has(cachedPath)) {
|
|
255
|
-
assetsToDelete.push(cachedPath);
|
|
256
279
|
}
|
|
257
280
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
281
|
+
countAssets(assets.tree);
|
|
282
|
+
logger.info(`Counted ${assetCount} total assets`);
|
|
283
|
+
processedCount += assetCount;
|
|
284
|
+
progress.updateProgress('process', processedCount, totalToProcess, `Processed ${assetCount} assets`);
|
|
285
|
+
|
|
286
|
+
// Handle code entity (ActiveClass, ActivePage) deletions
|
|
287
|
+
const activeClassRecords = (activeClassResult.Records || []).map(record => {
|
|
288
|
+
record.Content = record.Body;
|
|
289
|
+
delete record.Body;
|
|
290
|
+
return record;
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
const activePageRecords = (activePageResult.Records || []);
|
|
294
|
+
const allRecords = [...activeClassRecords, ...activePageRecords].map(mapRecordToFile);
|
|
295
|
+
|
|
296
|
+
// Get all server record IDs
|
|
297
|
+
const serverRecordIds = new Set([
|
|
298
|
+
...activeClassRecords.map(r => r.Id),
|
|
299
|
+
...activePageRecords.map(r => r.Id)
|
|
300
|
+
]);
|
|
301
|
+
|
|
302
|
+
// Find code entities in base.json that are no longer on server
|
|
303
|
+
const cachedCodeEntities = Object.values(cachedResults).filter(c =>
|
|
304
|
+
c.type !== 'File' && c.type !== 'Folder' && c.recordId
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
const codeEntitiesToDelete = [];
|
|
308
|
+
for (const cached of cachedCodeEntities) {
|
|
309
|
+
// If this code entity was in base.json but not returned from server, it was deleted
|
|
310
|
+
if (!serverRecordIds.has(cached.recordId)) {
|
|
311
|
+
codeEntitiesToDelete.push(cached);
|
|
312
|
+
}
|
|
261
313
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
314
|
+
|
|
315
|
+
// Delete local files/folders that were deleted on server
|
|
316
|
+
logger.info(`Starting deletion of ${assetsToDelete.length} assets`);
|
|
317
|
+
const deletionLogs = [];
|
|
318
|
+
for (const assetPath of assetsToDelete) {
|
|
319
|
+
try {
|
|
320
|
+
if (fs.existsSync(assetPath)) {
|
|
321
|
+
const stats = fs.statSync(assetPath);
|
|
322
|
+
if (stats.isDirectory()) {
|
|
323
|
+
fs.rmSync(assetPath, { recursive: true, force: true });
|
|
324
|
+
deletionLogs.push({ type: 'folder', path: assetPath });
|
|
325
|
+
logger.info('Deleted folder', { path: assetPath });
|
|
326
|
+
} else {
|
|
327
|
+
fs.unlinkSync(assetPath);
|
|
328
|
+
deletionLogs.push({ type: 'file', path: assetPath });
|
|
329
|
+
logger.info('Deleted file', { path: assetPath });
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
} catch (err) {
|
|
333
|
+
deletionLogs.push({ type: 'error', path: assetPath, error: err.message });
|
|
334
|
+
logger.error(`Failed to delete asset: ${assetPath}`, err);
|
|
277
335
|
}
|
|
278
336
|
}
|
|
279
|
-
}
|
|
280
337
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
// Handle code entity (ActiveClass, ActivePage) deletions
|
|
287
|
-
const activeClassRecords = (activeClassResult.Records || []).map(record => {
|
|
288
|
-
record.Content = record.Body;
|
|
289
|
-
delete record.Body;
|
|
290
|
-
return record;
|
|
291
|
-
});
|
|
292
|
-
|
|
293
|
-
const activePageRecords = (activePageResult.Records || []);
|
|
294
|
-
const allRecords = [...activeClassRecords, ...activePageRecords].map(mapRecordToFile);
|
|
295
|
-
|
|
296
|
-
// Get all server record IDs
|
|
297
|
-
const serverRecordIds = new Set([
|
|
298
|
-
...activeClassRecords.map(r => r.Id),
|
|
299
|
-
...activePageRecords.map(r => r.Id)
|
|
300
|
-
]);
|
|
301
|
-
|
|
302
|
-
// Find code entities in base.json that are no longer on server
|
|
303
|
-
const cachedCodeEntities = Object.values(cachedResults).filter(c =>
|
|
304
|
-
c.type !== 'File' && c.type !== 'Folder' && c.recordId
|
|
305
|
-
);
|
|
338
|
+
// Bulk remove from base.json
|
|
339
|
+
const assetPathsToRemove = deletionLogs
|
|
340
|
+
.filter(l => l.type === 'file' || l.type === 'folder')
|
|
341
|
+
.map(l => l.path);
|
|
306
342
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
// If this code entity was in base.json but not returned from server, it was deleted
|
|
310
|
-
if (!serverRecordIds.has(cached.recordId)) {
|
|
311
|
-
codeEntitiesToDelete.push(cached);
|
|
343
|
+
if (assetPathsToRemove.length > 0) {
|
|
344
|
+
removeFromBaseBulk(assetPathsToRemove);
|
|
312
345
|
}
|
|
313
|
-
}
|
|
314
346
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
deletionLogs.push({ type: 'folder', path: assetPath });
|
|
325
|
-
logger.info('Deleted folder', { path: assetPath });
|
|
326
|
-
} else {
|
|
327
|
-
fs.unlinkSync(assetPath);
|
|
328
|
-
deletionLogs.push({ type: 'file', path: assetPath });
|
|
329
|
-
logger.info('Deleted file', { path: assetPath });
|
|
347
|
+
// Delete local code entity files that were deleted on server
|
|
348
|
+
logger.info(`Starting deletion of ${codeEntitiesToDelete.length} code entities`);
|
|
349
|
+
for (const entity of codeEntitiesToDelete) {
|
|
350
|
+
const entityPath = entity.filePath || entity.lastKnownPath;
|
|
351
|
+
try {
|
|
352
|
+
if (entityPath && fs.existsSync(entityPath)) {
|
|
353
|
+
fs.unlinkSync(entityPath);
|
|
354
|
+
deletionLogs.push({ type: 'entity', path: entityPath, entityType: entity.type });
|
|
355
|
+
logger.info('Deleted code entity', { path: entityPath, type: entity.type });
|
|
330
356
|
}
|
|
357
|
+
} catch (err) {
|
|
358
|
+
deletionLogs.push({ type: 'error', path: entityPath, error: err.message });
|
|
359
|
+
logger.error(`Failed to delete code entity: ${entityPath}`, err);
|
|
331
360
|
}
|
|
332
|
-
// Remove from base.json
|
|
333
|
-
removeFromBase(assetPath);
|
|
334
|
-
} catch (err) {
|
|
335
|
-
deletionLogs.push({ type: 'error', path: assetPath, error: err.message });
|
|
336
|
-
logger.error(`Failed to delete asset: ${assetPath}`, err);
|
|
337
361
|
}
|
|
338
|
-
}
|
|
339
362
|
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
logger.error(`Failed to delete code entity: ${entityPath}`, err);
|
|
363
|
+
// Bulk remove code entities from base.json
|
|
364
|
+
const entityIdsToRemove = deletionLogs
|
|
365
|
+
.filter(l => l.type === 'entity')
|
|
366
|
+
.map(l => {
|
|
367
|
+
// Find the entity object that corresponds to this path to get the ID
|
|
368
|
+
const entity = codeEntitiesToDelete.find(e =>
|
|
369
|
+
(e.filePath === l.path || e.lastKnownPath === l.path)
|
|
370
|
+
);
|
|
371
|
+
return entity ? entity.recordId : null;
|
|
372
|
+
})
|
|
373
|
+
.filter(id => id !== null);
|
|
374
|
+
|
|
375
|
+
if (entityIdsToRemove.length > 0) {
|
|
376
|
+
removeFromBaseBulk(entityIdsToRemove);
|
|
355
377
|
}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
logger.warning('Record has error', { record: record.Name || record.relativePath });
|
|
368
|
-
processingErrors.push({
|
|
369
|
-
stage: 'record-error',
|
|
370
|
-
file: record.Name || record.relativePath,
|
|
371
|
-
error: 'Record contains error flag'
|
|
372
|
-
});
|
|
373
|
-
continue;
|
|
378
|
+
logger.info(`Completed deletions - ${deletionLogs.length} items deleted`);
|
|
379
|
+
progress.updateProgress('process', processedCount, totalToProcess, `Deleted ${deletionLogs.length} items`);
|
|
380
|
+
|
|
381
|
+
// Compare files and detect conflicts
|
|
382
|
+
logger.info(`Starting file comparison for ${allRecords.length} records`);
|
|
383
|
+
// --- Fix for Bug 1: Rename Tracking ---
|
|
384
|
+
// Build a map of RecordId -> LocalPath from cached results
|
|
385
|
+
const localPathMap = new Map();
|
|
386
|
+
Object.values(cachedResults).forEach(entry => {
|
|
387
|
+
if (entry.recordId && (entry.filePath || entry.lastKnownPath)) {
|
|
388
|
+
localPathMap.set(entry.recordId, entry.filePath || entry.lastKnownPath);
|
|
374
389
|
}
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// Check for renames before comparison
|
|
393
|
+
for (const record of allRecords) {
|
|
394
|
+
if (localPathMap.has(record.Id)) {
|
|
395
|
+
const oldPath = localPathMap.get(record.Id);
|
|
396
|
+
const newPath = path.join(EXPORT_ROOT, record.relativePath);
|
|
397
|
+
|
|
398
|
+
// Normalize paths for comparison
|
|
399
|
+
let normalizedOld = path.normalize(path.resolve(oldPath));
|
|
400
|
+
const normalizedNew = path.normalize(path.resolve(newPath));
|
|
401
|
+
|
|
402
|
+
// Fix for path resolution: base.json might store paths relative to CWD or EXPORT_ROOT
|
|
403
|
+
// If direct resolution fails, try prepending EXPORT_ROOT
|
|
404
|
+
if (!fs.existsSync(normalizedOld)) {
|
|
405
|
+
const withRoot = path.normalize(path.resolve(EXPORT_ROOT, oldPath));
|
|
406
|
+
if (fs.existsSync(withRoot)) {
|
|
407
|
+
normalizedOld = withRoot;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
375
410
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
411
|
+
if (normalizedOld !== normalizedNew && fs.existsSync(normalizedOld)) {
|
|
412
|
+
try {
|
|
413
|
+
logger.info(`Detected rename: ${path.relative(EXPORT_ROOT, oldPath)} -> ${record.relativePath}`);
|
|
414
|
+
|
|
415
|
+
// Ensure target directory exists
|
|
416
|
+
fs.mkdirSync(path.dirname(normalizedNew), { recursive: true });
|
|
417
|
+
|
|
418
|
+
// Rename file
|
|
419
|
+
fs.renameSync(normalizedOld, normalizedNew);
|
|
420
|
+
|
|
421
|
+
// Update fileIdIndex.json to point to the new path
|
|
422
|
+
// This must be done BEFORE writeRecords runs, otherwise findFileByTag
|
|
423
|
+
// will return the old path and writeRecords will recreate the old file
|
|
424
|
+
await setFileTag(normalizedNew, record.Id);
|
|
425
|
+
|
|
426
|
+
// Update base.json immediately to reflect new path
|
|
427
|
+
// We use the existing record data but update the path
|
|
428
|
+
updateBase(record.relativePath, record, normalizedNew);
|
|
429
|
+
|
|
430
|
+
// Remove old path from deletion logs if it was marked for deletion
|
|
431
|
+
// (It might have been marked if the old filename wasn't in the server response)
|
|
432
|
+
const deletionIndex = deletionLogs.findIndex(l => path.normalize(l.path) === normalizedOld);
|
|
433
|
+
if (deletionIndex !== -1) {
|
|
434
|
+
deletionLogs.splice(deletionIndex, 1);
|
|
435
|
+
logger.info(`Cancelled deletion of renamed file: ${path.relative(EXPORT_ROOT, oldPath)}`);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
console.log(chalk.cyan(` ↻ Renamed: ${path.relative(EXPORT_ROOT, oldPath)} -> ${record.relativePath}`));
|
|
439
|
+
} catch (err) {
|
|
440
|
+
logger.error(`Failed to rename file: ${oldPath} -> ${newPath}`, err);
|
|
441
|
+
processingErrors.push({
|
|
442
|
+
stage: 'rename',
|
|
443
|
+
file: record.relativePath,
|
|
444
|
+
error: `Rename failed: ${err.message}`
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
379
448
|
}
|
|
449
|
+
}
|
|
450
|
+
// --- End Fix for Bug 1 ---
|
|
451
|
+
|
|
452
|
+
const issues = [];
|
|
453
|
+
for (let i = 0; i < allRecords.length; i++) {
|
|
454
|
+
const record = allRecords[i];
|
|
455
|
+
try {
|
|
456
|
+
if (record?.error) {
|
|
457
|
+
logger.warning('Record has error', { record: record.Name || record.relativePath });
|
|
458
|
+
processingErrors.push({
|
|
459
|
+
stage: 'record-error',
|
|
460
|
+
file: record.Name || record.relativePath,
|
|
461
|
+
error: 'Record contains error flag'
|
|
462
|
+
});
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// Log every 50th file to track progress
|
|
467
|
+
if (i % 50 === 0) {
|
|
468
|
+
logger.info(`Comparing file ${i + 1}/${allRecords.length}: ${record.relativePath}`);
|
|
469
|
+
}
|
|
380
470
|
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
471
|
+
const status = compareLocalAndRemote(
|
|
472
|
+
path.join(EXPORT_ROOT, record.relativePath),
|
|
473
|
+
{ ...record, content: record.Content }
|
|
474
|
+
);
|
|
385
475
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
476
|
+
// Missing files will just be written
|
|
477
|
+
if (!['in_sync', 'missing'].includes(status.status)) {
|
|
478
|
+
issues.push({ relativePath: record.relativePath, status: status.status });
|
|
479
|
+
logger.info('Conflict detected', { file: record.relativePath, status: status.status });
|
|
480
|
+
}
|
|
481
|
+
} catch (err) {
|
|
482
|
+
processingErrors.push({
|
|
483
|
+
stage: 'compare-files',
|
|
484
|
+
file: record?.relativePath || record?.Name,
|
|
485
|
+
error: err.message
|
|
486
|
+
});
|
|
487
|
+
logger.error(`Error comparing file ${record?.relativePath}`, err);
|
|
390
488
|
}
|
|
391
|
-
} catch (err) {
|
|
392
|
-
processingErrors.push({
|
|
393
|
-
stage: 'compare-files',
|
|
394
|
-
file: record?.relativePath || record?.Name,
|
|
395
|
-
error: err.message
|
|
396
|
-
});
|
|
397
|
-
logger.error(`Error comparing file ${record?.relativePath}`, err);
|
|
398
|
-
}
|
|
399
489
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
490
|
+
processedCount++;
|
|
491
|
+
if (processedCount % 10 === 0 || i === allRecords.length - 1) {
|
|
492
|
+
progress.updateProgress('process', processedCount, totalToProcess, `Comparing files...`);
|
|
493
|
+
}
|
|
403
494
|
}
|
|
404
|
-
|
|
405
|
-
logger.info(`Completed file comparison - found ${issues.length} conflicts`);
|
|
495
|
+
logger.info(`Completed file comparison - found ${issues.length} conflicts`);
|
|
406
496
|
|
|
407
|
-
|
|
408
|
-
|
|
497
|
+
return { allRecords, issues, deletionLogs, processingErrors };
|
|
498
|
+
})();
|
|
409
499
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
500
|
+
// Show completion message with error count if any
|
|
501
|
+
if (processingErrors.length > 0) {
|
|
502
|
+
progress.completeStep('process', `⚠ Processed ${allRecords.length} records with ${processingErrors.length} errors`);
|
|
503
|
+
} else {
|
|
504
|
+
progress.completeStep('process', `✓ Processed ${allRecords.length} records, ${deletionLogs.length} deletions`);
|
|
505
|
+
}
|
|
416
506
|
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
507
|
+
// Note: Error preview will be shown in final summary, not here to avoid UI glitches
|
|
508
|
+
// Pause progress display for deletion logs and conflict resolution
|
|
509
|
+
progress.stopSpinner();
|
|
510
|
+
|
|
511
|
+
// Display deletion logs
|
|
512
|
+
for (const log of deletionLogs) {
|
|
513
|
+
if (log.type === 'folder') {
|
|
514
|
+
console.log(chalk.gray(` 🗑️ Removed deleted folder: ${path.relative(process.cwd(), log.path)}`));
|
|
515
|
+
} else if (log.type === 'file') {
|
|
516
|
+
console.log(chalk.gray(` 🗑️ Removed deleted file: ${path.relative(process.cwd(), log.path)}`));
|
|
517
|
+
} else if (log.type === 'entity') {
|
|
518
|
+
console.log(chalk.gray(` 🗑️ Removed deleted ${log.entityType}: ${path.relative(process.cwd(), log.path)}`));
|
|
519
|
+
} else if (log.type === 'error') {
|
|
520
|
+
console.warn(chalk.yellow(` ⚠️ Could not delete ${log.path}: ${log.error}`));
|
|
521
|
+
}
|
|
431
522
|
}
|
|
432
|
-
}
|
|
433
523
|
|
|
434
|
-
|
|
524
|
+
let resolutionMethod = 'skip';
|
|
435
525
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
526
|
+
// Check for conflicts
|
|
527
|
+
progress.startStep('conflicts');
|
|
528
|
+
if (issues.length > 0) {
|
|
529
|
+
progress.stopSpinner();
|
|
530
|
+
resolutionMethod = await promptConflictResolution(issues);
|
|
531
|
+
progress.startSpinner();
|
|
532
|
+
}
|
|
533
|
+
progress.completeStep('conflicts', issues.length > 0 ? `✓ Resolved ${issues.length} conflicts` : '✓ No conflicts');
|
|
444
534
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
535
|
+
// Step 6: Write all ActiveClass and ActivePage records
|
|
536
|
+
progress.startStep('write');
|
|
537
|
+
await writeRecords(allRecords, resolutionMethod, progress, logger);
|
|
538
|
+
progress.completeStep('write', `✓ Wrote ${allRecords.length} files`);
|
|
449
539
|
|
|
450
540
|
// Step 7: Finish progress tracker
|
|
451
541
|
logger.info('Pull completed successfully');
|