@agility/cli
Version:
Agility CLI for working with your content. (Public Beta)
718 lines • 32.4 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileOperations = void 0;
var fs = __importStar(require("fs"));
var Https = __importStar(require("https"));
var path = __importStar(require("path"));
var os = require('os');
var state_1 = require("./state");
os.tmpDir = os.tmpdir;
var fileOperations = /** @class */ (function () {
function fileOperations(guid, locale) {
this._rootPath = state_1.state.rootPath;
this._guid = guid;
this._isGuidLevel = locale === undefined || locale === null || locale === "";
this._locale = locale !== null && locale !== void 0 ? locale : "";
this._legacyFolders = state_1.state.legacyFolders;
// Keep paths relative instead of resolving to absolute paths
// This prevents files from being written to /Users/ directories
this._resolvedRootPath = state_1.state.rootPath;
// Calculate paths based on legacy mode
if (state_1.state.legacyFolders) {
// Legacy mode: flat structure
this._basePath = this._resolvedRootPath;
this._mappingsPath = path.join(this._resolvedRootPath, 'mappings');
this._instanceLogDir = path.join(this._resolvedRootPath, 'logs');
}
else {
// Normal mode: nested structure
this._basePath = this._isGuidLevel ? path.join(this._resolvedRootPath, this._guid) : path.join(this._resolvedRootPath, this._guid, this._locale);
this._mappingsPath = path.join(this._resolvedRootPath, this._guid, 'mappings');
this._instanceLogDir = path.join(this._basePath, 'logs');
}
this._currentLogFilePath = path.join(this._instanceLogDir, 'instancelog.txt');
}
Object.defineProperty(fileOperations.prototype, "instancePath", {
// Public getters for path access
get: function () {
return this._basePath;
},
enumerable: false,
configurable: true
});
Object.defineProperty(fileOperations.prototype, "mappingsPath", {
get: function () {
return this._mappingsPath;
},
enumerable: false,
configurable: true
});
Object.defineProperty(fileOperations.prototype, "isLegacyMode", {
get: function () {
return this._legacyFolders;
},
enumerable: false,
configurable: true
});
Object.defineProperty(fileOperations.prototype, "resolvedRootPath", {
get: function () {
return this._resolvedRootPath;
},
enumerable: false,
configurable: true
});
Object.defineProperty(fileOperations.prototype, "guid", {
// Public getters for instance configuration
get: function () {
return this._guid;
},
enumerable: false,
configurable: true
});
Object.defineProperty(fileOperations.prototype, "locale", {
get: function () {
return this._locale;
},
enumerable: false,
configurable: true
});
/**
* Strip ANSI color codes from text for clean log files
* Matches ANSI escape sequences like [33m, [3m, [23m, [39m, etc.
* Also cleans up JSON formatting for better readability
*/
fileOperations.prototype.stripAnsiCodes = function (text) {
// eslint-disable-next-line no-control-regex
var cleaned = text.replace(/\x1b\[[0-9;]*m/g, '');
// Clean up JSON formatting: replace \n with actual newlines for better readability
cleaned = cleaned.replace(/\\n/g, '\n');
// Remove unnecessary escaped quotes in JSON context
cleaned = cleaned.replace(/\\"/g, '"');
return cleaned;
};
fileOperations.prototype.exportFiles = function (folder, fileIdentifier, extractedObject, baseFolder) {
var effectiveBase;
if (baseFolder) {
// If baseFolder is provided, use it directly.
// It's assumed to be the correct base, whether absolute or relative.
effectiveBase = baseFolder;
}
else {
// If no baseFolder is provided, check if the 'folder' argument itself is absolute.
if (path.isAbsolute(folder)) {
// If 'folder' is absolute, it defines the complete path up to its own level.
// So, the effectiveBase is empty string, and 'folder' will be joined from root.
effectiveBase = "";
}
else {
// If 'folder' is relative, use the base path (instance-specific path) as the base
effectiveBase = this._basePath;
}
}
// Create the full directory path using path.join for OS-independent path construction
var directoryForFile = path.join(effectiveBase, folder);
// Ensure the directory structure exists
if (!fs.existsSync(directoryForFile)) {
fs.mkdirSync(directoryForFile, { recursive: true });
}
var fileName = path.join(directoryForFile, "".concat(fileIdentifier, ".json"));
fs.writeFileSync(fileName, JSON.stringify(extractedObject));
};
fileOperations.prototype.appendFiles = function (folder, fileIdentifier, extractedObject) {
var folderPath = path.join(this._basePath, folder);
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
var fileName = path.join(folderPath, "".concat(fileIdentifier, ".json"));
fs.appendFileSync(fileName, JSON.stringify(extractedObject));
};
fileOperations.prototype.createLogFile = function (folder, fileIdentifier, baseFolder) {
if (baseFolder === undefined || baseFolder === '') {
baseFolder = this._basePath;
}
if (!fs.existsSync("".concat(baseFolder))) {
fs.mkdirSync("".concat(baseFolder));
}
if (!fs.existsSync("".concat(baseFolder, "/").concat(folder))) {
fs.mkdirSync("".concat(baseFolder, "/").concat(folder));
}
var fileName = "".concat(baseFolder, "/").concat(folder, "/").concat(fileIdentifier, ".txt");
fs.closeSync(fs.openSync(fileName, 'w'));
};
fileOperations.prototype.appendLogFile = function (data) {
if (!fs.existsSync(this._instanceLogDir)) {
fs.mkdirSync(this._instanceLogDir, { recursive: true });
}
// Strip ANSI color codes before writing to file
var cleanData = this.stripAnsiCodes(data);
fs.appendFileSync(this._currentLogFilePath, cleanData);
};
fileOperations.prototype.createFolder = function (folder) {
try {
var fullPath = void 0;
if (path.isAbsolute(folder)) {
fullPath = folder;
}
else {
// Use the base path (instance-specific path) instead of resolved root path
// This ensures folders are created in the correct nested structure
fullPath = path.join(this._basePath, folder);
}
// Normalize the path and split into segments
var normalizedPath = path.normalize(fullPath);
var segments = normalizedPath.split(path.sep);
// Start from the root and create each directory
var currentPath = '';
for (var _i = 0, segments_1 = segments; _i < segments_1.length; _i++) {
var segment = segments_1[_i];
currentPath = path.join(currentPath, segment);
// Skip empty segments
if (!segment)
continue;
try {
if (!fs.existsSync(currentPath)) {
fs.mkdirSync(currentPath);
}
}
catch (err) {
console.error("Error creating directory ".concat(currentPath, ":"), err);
return false;
}
}
// Verify the final directory exists
if (fs.existsSync(normalizedPath)) {
return true;
}
else {
return false;
}
}
catch (error) {
console.error('Error in createFolder:', error);
return false;
}
};
fileOperations.prototype.createBaseFolder = function (folder) {
if (folder === undefined || folder === '') {
folder = this._basePath;
}
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder);
}
};
fileOperations.prototype.checkBaseFolderExists = function (folder) {
if (!fs.existsSync(folder)) {
return false;
}
return true;
};
fileOperations.prototype.getFolderContents = function (folder) {
return fs.readdirSync(folder);
};
fileOperations.prototype.downloadFile = function (url, targetFile) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Promise(function (resolve, reject) {
// Ensure the target directory exists
var targetDir = path.dirname(targetFile);
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
}
Https.get(url, function (response) {
var _a;
var code = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 0;
if (code >= 400) {
return reject(new Error(response.statusMessage));
}
if (code > 300 && code < 400 && !!response.headers.location) {
return resolve(_this.downloadFile(response.headers.location, targetFile));
}
var fileWriter = fs
.createWriteStream(targetFile)
.on('finish', function () {
resolve({});
})
.on('error', function (err) {
reject(err);
});
response.pipe(fileWriter);
}).on('error', function (error) {
console.error("Error downloading from ".concat(url, ":"), error);
reject(error);
});
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
fileOperations.prototype.createFile = function (filename, content) {
fs.writeFileSync(filename, content);
};
fileOperations.prototype.saveFile = function (filename, content) {
fs.writeFileSync(filename, content);
};
fileOperations.prototype.saveFileToPath = function (filename, content, filePath) {
fs.writeFileSync(path.join(filePath, filename), content);
};
fileOperations.prototype.readFile = function (fileName) {
var file = fs.readFileSync(fileName, "utf-8");
return file;
};
fileOperations.prototype.createReadStream = function (fileName) {
return fs.createReadStream(fileName);
};
fileOperations.prototype.checkFileExists = function (filePath) {
try {
fs.accessSync(filePath, fs.constants.F_OK);
return true;
}
catch (err) {
return false;
}
};
fileOperations.prototype.deleteFile = function (fileName) {
fs.unlinkSync(fileName);
};
// Mapping file operations
fileOperations.prototype.getMappingFilePath = function (sourceGuid, targetGuid, locale) {
// Store mappings centrally in /agility-files/mappings/ instead of per-instance
return path.join(this._rootPath, 'mappings', "".concat(sourceGuid, "-").concat(targetGuid), locale !== null && locale !== void 0 ? locale : '');
};
fileOperations.prototype.getMappingFile = function (type, sourceGuid, targetGuid, locale) {
var centralMappingsPath = path.join(this._rootPath, 'mappings', "".concat(sourceGuid, "-").concat(targetGuid), locale !== null && locale !== void 0 ? locale : '', type);
if (fs.existsSync(centralMappingsPath)) {
var fullPath = path.join(centralMappingsPath, 'mappings.json');
if (!fs.existsSync(fullPath)) {
//initialize empty mappings file if it doesn't exist
fs.writeFileSync(fullPath, "[]");
}
var data = fs.readFileSync(fullPath, 'utf8');
var jsonData = JSON.parse(data);
return jsonData;
}
else {
return [];
}
};
fileOperations.prototype.saveMappingFile = function (mappingData, type, sourceGuid, targetGuid, locale) {
var mappingRootPath = this.getMappingFilePath(sourceGuid, targetGuid, locale);
var centralMappingsPath = path.join(mappingRootPath, type);
var mappingFilePath = path.join(centralMappingsPath, "mappings.json");
if (!fs.existsSync(centralMappingsPath)) {
fs.mkdirSync(centralMappingsPath, { recursive: true });
}
// This will overwrite the existing mappings.json file.
fs.writeFileSync(mappingFilePath, JSON.stringify(mappingData, null, 2));
};
/**
* Get reverse mapping file path for fallback lookups
* For B→A sync: when A→B mapping file exists, use it by flipping the source/target GUIDs
*/
fileOperations.prototype.getReverseMappingFilePath = function (sourceGuid, targetGuid, locale) {
var localeToUse = locale || this._locale;
var centralMappingsPath = path.join(this._rootPath, 'mappings');
return path.join(centralMappingsPath, "".concat(targetGuid, "-to-").concat(sourceGuid, "-").concat(localeToUse, ".json"));
};
// saveMappingFile(sourceGuid: string, targetGuid: string, mappingData: any, locale?: string): void {
// const localeToUse = locale || this._locale;
// // Ensure centralized mappings directory exists
// const centralMappingsPath = path.join(this._rootPath, 'mappings');
// if (!fs.existsSync(centralMappingsPath)) {
// fs.mkdirSync(centralMappingsPath, { recursive: true });
// }
// // Add locale to mapping data for consistency
// const mappingDataWithLocale = {
// ...mappingData,
// locale: localeToUse
// };
// const mappingFilePath = this.getMappingFilePath(sourceGuid, targetGuid, localeToUse);
// this.createFile(mappingFilePath, JSON.stringify(mappingDataWithLocale, null, 2));
// // TODO: PERSISTENCE INTEGRATION POINT
// // This is where we would integrate with external persistence services
// // for scenarios where mappings need to survive beyond ephemeral agents:
// //
// // Examples:
// // - Upload to cloud storage (AWS S3, Azure Blob, etc.)
// // - Save to database (MongoDB, PostgreSQL, etc.)
// // - Sync to external API/service
// // - Store in shared network drive
// //
// // Implementation example:
// // await this.persistMappingExternally(sourceGuid, targetGuid, mappingDataWithLocale, localeToUse);
// }
fileOperations.prototype.loadMappingFile = function (sourceGuid, targetGuid, locale) {
var localeToUse = locale || this._locale;
// First try to load direct mapping file (A→B)
var mappingFilePath = this.getMappingFilePath(sourceGuid, targetGuid, localeToUse);
if (this.checkFileExists(mappingFilePath)) {
try {
var content = this.readFile(mappingFilePath);
var mappingData = JSON.parse(content);
console.log("[FileOps] Loaded direct mapping file: ".concat(sourceGuid, "\u2192").concat(targetGuid));
return mappingData;
}
catch (error) {
console.error("Error loading mapping file ".concat(mappingFilePath, ":"), error);
}
}
// Try to load reverse mapping file (B→A) for fallback
var reverseMappingFilePath = this.getReverseMappingFilePath(sourceGuid, targetGuid, localeToUse);
if (this.checkFileExists(reverseMappingFilePath)) {
try {
var content = this.readFile(reverseMappingFilePath);
var reverseMappingData = JSON.parse(content);
console.log("[FileOps] Loaded reverse mapping file: ".concat(targetGuid, "\u2192").concat(sourceGuid, " (for ").concat(sourceGuid, "\u2192").concat(targetGuid, " sync)"));
return reverseMappingData;
}
catch (error) {
console.error("Error loading reverse mapping file ".concat(reverseMappingFilePath, ":"), error);
}
}
return null;
};
fileOperations.prototype.clearMappingFile = function (sourceGuid, targetGuid, locale) {
var localeToUse = locale || this._locale;
// Clear direct mapping file
var mappingFilePath = this.getMappingFilePath(sourceGuid, targetGuid, localeToUse);
if (this.checkFileExists(mappingFilePath)) {
this.deleteFile(mappingFilePath);
}
};
// Data folder path utilities
fileOperations.prototype.getDataFolderPath = function (folderName) {
if (folderName) {
return path.join(this._basePath, folderName);
}
return this._basePath;
};
fileOperations.prototype.getFolderPath = function (folderName) {
if (folderName) {
return path.join(this._basePath, folderName);
}
return this._basePath;
};
fileOperations.prototype.getFilePath = function (folderName, fileName) {
if (folderName && fileName) {
return path.join(this._basePath, folderName, fileName);
}
else if (folderName) {
return path.join(this._basePath, folderName);
}
else if (fileName) {
return path.join(this._basePath, fileName);
}
return this._basePath;
};
fileOperations.prototype.getDataFilePath = function (folderName, fileName) {
if (folderName && fileName) {
return path.join(this._basePath, folderName, fileName);
}
else if (folderName) {
return path.join(this._basePath, folderName);
}
else if (fileName) {
return path.join(this._basePath, fileName);
}
return this._basePath;
};
fileOperations.prototype.getNestedSitemapPath = function () {
return path.join(this._basePath, 'nestedsitemap', 'website.json');
};
// Path utilities
fileOperations.prototype.resolveFilePath = function (relativePath) {
if (path.isAbsolute(relativePath)) {
return relativePath;
}
return path.resolve(this._basePath, relativePath);
};
// JSON file utilities - centralized JSON parsing
fileOperations.prototype.readJsonFile = function (relativePath) {
try {
var fullPath = this.getDataFolderPath(relativePath);
if (!fs.existsSync(fullPath)) {
return null;
}
var content = fs.readFileSync(fullPath, 'utf8');
return JSON.parse(content);
}
catch (error) {
console.warn("[FileOps] Error reading JSON file ".concat(relativePath, ": ").concat(error.message));
return null;
}
};
fileOperations.prototype.readJsonFileAbsolute = function (absolutePath) {
try {
var content = fs.readFileSync(absolutePath, 'utf8');
return JSON.parse(content);
}
catch (error) {
return null;
// console.warn(`[FileOps] Error reading JSON file ${absolutePath}: ${error.message}`);
}
};
fileOperations.prototype.readJsonFilesFromFolder = function (folderName, fileExtension) {
if (fileExtension === void 0) { fileExtension = '.json'; }
try {
var folderPath = this.getDataFolderPath(folderName);
if (!fs.existsSync(folderPath)) {
return [];
}
var files = fs.readdirSync(folderPath).filter(function (file) { return file.endsWith(fileExtension); });
var results = [];
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
var file = files_1[_i];
try {
var content = fs.readFileSync(path.join(folderPath, file), 'utf8');
var parsed = JSON.parse(content);
results.push(parsed);
}
catch (error) {
console.warn("[FileOps] Error parsing JSON file ".concat(file, ": ").concat(error.message));
}
}
return results;
}
catch (error) {
console.warn("[FileOps] Error reading folder ".concat(folderName, ": ").concat(error.message));
return [];
}
};
fileOperations.prototype.listFilesInFolder = function (folderName, fileExtension) {
try {
var folderPath = this.getDataFolderPath(folderName);
if (!fs.existsSync(folderPath)) {
return [];
}
var files = fs.readdirSync(folderPath);
if (fileExtension) {
files = files.filter(function (file) { return file.endsWith(fileExtension); });
}
return files;
}
catch (error) {
console.warn("[FileOps] Error listing files in ".concat(folderName, ": ").concat(error.message));
return [];
}
};
fileOperations.prototype.readTempFile = function (fileName) {
var appName = 'mgmt-cli-code';
var tmpFolder = os.tmpDir();
var tmpDir = "".concat(tmpFolder, "/").concat(appName);
var fileData = this.readFile("".concat(tmpDir, "/").concat(fileName));
return fileData;
};
fileOperations.prototype.createTempFile = function (fileName, content) {
var _this = this;
var appName = 'mgmt-cli-code';
var tmpFolder = os.tmpDir();
var tmpDir = "".concat(tmpFolder, "/").concat(appName);
fs.access(tmpDir, function (error) {
if (error) {
fs.mkdirSync(tmpDir);
_this.createFile("".concat(tmpDir, "/").concat(fileName), content);
}
else {
_this.createFile("".concat(tmpDir, "/").concat(fileName), content);
}
});
return tmpDir;
};
fileOperations.prototype.renameFile = function (oldFile, newFile) {
fs.renameSync(oldFile, newFile);
};
fileOperations.prototype.readDirectory = function (folderName, baseFolder) {
var _this = this;
if (baseFolder === undefined || baseFolder === '') {
baseFolder = this._basePath;
}
var directory = "".concat(baseFolder, "/").concat(folderName);
var files = [];
fs.readdirSync(directory).forEach(function (file) {
var readFile = _this.readFile("".concat(directory, "/").concat(file));
files.push(readFile);
});
return files;
};
fileOperations.prototype.folderExists = function (folderName, baseFolder) {
if (baseFolder === undefined || baseFolder === '') {
baseFolder = this._basePath;
}
var directory = "".concat(baseFolder, "/").concat(folderName);
if (fs.existsSync(directory)) {
return true;
}
else {
return false;
}
};
fileOperations.prototype.codeFileExists = function () {
var appName = 'mgmt-cli-code';
var tmpFolder = os.tmpDir();
var tmpDir = "".concat(tmpFolder, "/").concat(appName, "/code.json");
if (fs.existsSync(tmpDir)) {
return true;
}
else {
return false;
}
};
fileOperations.prototype.deleteCodeFile = function () {
var appName = 'mgmt-cli-code';
var tmpFolder = os.tmpDir();
var tmpDir = "".concat(tmpFolder, "/").concat(appName, "/code.json");
if (fs.existsSync(tmpDir)) {
fs.rmSync(tmpDir);
console.log('Logged out successfully');
return true;
}
else {
return false;
}
};
fileOperations.prototype.fileExists = function (path) {
if (fs.existsSync(path)) {
return true;
}
return false;
};
fileOperations.prototype.cleanup = function (path) {
var _this = this;
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file) {
var curPath = "".concat(path, "/").concat(file);
if (fs.lstatSync(curPath).isDirectory()) {
_this.cleanup(curPath);
}
else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
fileOperations.prototype.cliFolderExists = function () {
if (fs.existsSync(this._basePath)) {
return true;
}
else {
return false;
}
};
fileOperations.prototype.finalizeLogFile = function (operationType) {
var now = new Date();
// Create semantic filename like "2025-may-12-at-10-15-32-am.txt"
var months = [
'january', 'february', 'march', 'april', 'may', 'june',
'july', 'august', 'september', 'october', 'november', 'december'
];
var year = now.getFullYear();
var month = months[now.getMonth()];
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var ampm = hour >= 12 ? 'pm' : 'am';
var hour12 = hour % 12 || 12;
var pad = function (num) { return String(num).padStart(2, '0'); };
var semanticTimestamp = "".concat(year, "-").concat(month, "-").concat(pad(day), "-at-").concat(pad(hour12), "-").concat(pad(minute), "-").concat(pad(second), "-").concat(ampm);
if (!fs.existsSync(this._currentLogFilePath)) {
// If the initial log file doesn't exist, there's nothing to rename.
// This might happen if no logging occurred.
// We can either create an empty one to signify the operation or just return an expected path.
// For now, let's log a message and return the expected path if it were created.
// console.warn(`\nLog file ${this._currentLogFilePath} not found. Cannot finalize.`);
var newLogFileName_1 = "".concat(operationType, "-").concat(semanticTimestamp, ".txt");
return path.join(this._instanceLogDir, newLogFileName_1);
}
var newLogFileName = "".concat(operationType, "-").concat(semanticTimestamp, ".txt");
var newLogFilePath = path.join(this._instanceLogDir, newLogFileName);
try {
// Ensure the directory exists (it should, if appendLogFile was called)
if (!fs.existsSync(this._instanceLogDir)) {
fs.mkdirSync(this._instanceLogDir, { recursive: true });
}
fs.renameSync(this._currentLogFilePath, newLogFilePath);
return newLogFilePath;
}
catch (error) {
console.error("Error renaming log file from ".concat(this._currentLogFilePath, " to ").concat(newLogFilePath, ":"), error);
// Fallback: return the original path or throw, depending on desired error handling
return this._currentLogFilePath; // Or throw error;
}
};
return fileOperations;
}());
exports.fileOperations = fileOperations;
//# sourceMappingURL=fileOperations.js.map