@intlayer/chokidar
Version:
Uses chokidar to scan and build Intlayer declaration files into dictionaries based on Intlayer configuration.
91 lines (89 loc) • 4.02 kB
JavaScript
import { getFormatFromExtension } from "../utils/getFormatFromExtension.mjs";
import { transformJSFile } from "./transformJSFile.mjs";
import { detectFormatCommand } from "../detectFormatCommand.mjs";
import { getContentDeclarationFileTemplate } from "../getContentDeclarationFileTemplate/getContentDeclarationFileTemplate.mjs";
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { basename, extname, join } from "node:path";
import { getAppLogger, logger } from "@intlayer/config/logger";
import { existsSync } from "node:fs";
import { execSync } from "node:child_process";
//#region src/writeContentDeclaration/writeJSFile.ts
/**
* Updates a JavaScript/TypeScript file based on the provided JSON instructions.
* It targets a specific dictionary object within the file (identified by its 'key' property)
* and updates its 'content' entries. Currently, it focuses on modifying arguments
* of 't' (translation) function calls.
*/
const writeJSFile = async (filePath, dictionary, configuration, noMetadata) => {
const mergedDictionary = {
...configuration.dictionary,
...dictionary
};
const appLogger = getAppLogger(configuration);
if (!existsSync(filePath)) {
const format = getFormatFromExtension(extname(filePath));
appLogger("File does not exist, creating it", { isVerbose: true });
const template = await getContentDeclarationFileTemplate(mergedDictionary.key, format, Object.fromEntries(Object.entries({
id: noMetadata ? void 0 : mergedDictionary.id,
locale: noMetadata ? void 0 : mergedDictionary.locale,
filled: noMetadata ? void 0 : mergedDictionary.filled,
fill: noMetadata ? void 0 : mergedDictionary.fill,
description: noMetadata ? void 0 : mergedDictionary.description,
title: noMetadata ? void 0 : mergedDictionary.title,
tags: noMetadata ? void 0 : mergedDictionary.tags,
version: noMetadata ? void 0 : mergedDictionary.version,
priority: noMetadata ? void 0 : mergedDictionary.priority,
importMode: noMetadata ? void 0 : mergedDictionary.importMode
}).filter(([, value]) => value !== void 0)), noMetadata);
const tempDir = configuration.system?.tempDir;
if (tempDir) await mkdir(tempDir, { recursive: true });
const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;
const tempPath = tempDir ? join(tempDir, tempFileName) : `${filePath}.${tempFileName}`;
try {
await writeFile(tempPath, template, "utf-8");
await rename(tempPath, filePath);
} catch (error) {
try {
await rm(tempPath, { force: true });
} catch {}
throw error;
}
}
let fileContent = await readFile(filePath, "utf-8");
if (fileContent === "") {
const format = getFormatFromExtension(extname(filePath));
fileContent = await getContentDeclarationFileTemplate(mergedDictionary.key, format, {}, noMetadata);
}
const finalCode = await transformJSFile(fileContent, dictionary, dictionary.locale, noMetadata);
const tempDir = configuration.system?.tempDir;
if (tempDir) await mkdir(tempDir, { recursive: true });
const tempFileName = `${basename(filePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;
const tempPath = tempDir ? join(tempDir, tempFileName) : `${filePath}.${tempFileName}`;
try {
await writeFile(tempPath, finalCode, "utf-8");
await rename(tempPath, filePath);
logger(`Successfully updated ${filePath}`, {
level: "info",
isVerbose: true
});
} catch (error) {
try {
await rm(tempPath, { force: true });
} catch {}
const err = error;
logger(`Failed to write updated file: ${filePath}`, { level: "error" });
throw new Error(`Failed to write updated file ${filePath}: ${err.message}`);
}
const formatCommand = detectFormatCommand(configuration);
if (formatCommand) try {
execSync(formatCommand.replace("{{file}}", filePath), {
stdio: "inherit",
cwd: configuration.system.baseDir
});
} catch (error) {
console.error(error);
}
};
//#endregion
export { writeJSFile };
//# sourceMappingURL=writeJSFile.mjs.map