UNPKG

@criticalmanufacturing/dev-i18n-transform

Version:
376 lines (375 loc) 21.2 kB
"use strict"; 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; return g = { next: verb(0), "throw": verb(1), "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 (_) 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 }; } }; exports.__esModule = true; //#region Imports var os = require("os"); var util_1 = require("../util"); var translation_1 = require("../model/translation"); var index_1 = require("../logger/index"); var fs = require("fs"); var beautify = require("js-beautify"); var argv = require("minimist")(process.argv); // Import config var config; if (argv["config"] === undefined || argv["config"] === null) { config = require("../i18n-import.config.json"); } else { config = require(argv["config"]); } //#endregion var StructuredQueryLanguageConverter = /** @class */ (function () { //#endregion //#region Constructor function StructuredQueryLanguageConverter() { this._util = new util_1.Util(); } //#endregion //#region Public Methods /** * Receiving a localized message, this method will find the file that will change and * insert the new localized message or replace the text if already exists. * Return the path of modified file * @param object (localized message) * @param key (package of config.packages.i18n) * @param originalFileName (OPTIONAL - name of file to be written) */ StructuredQueryLanguageConverter.prototype.writeToFile = function (object, key, originalFileName) { return __awaiter(this, void 0, void 0, function () { var literal, pack, fileName, localizedMessageText, cultureName, localizedMessageName, callWriteNewLocalizedMessageToFile, aux, localizedMessage, localizedMessageSections, firstLocalizedMessageSection, content, data, regexMainString, replaceMessage, messageToReplace, textToFile, outputText, outputText, err_1; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); literal = {}; pack = void 0; fileName = void 0; localizedMessageText = this.getLocalizedText(object); cultureName = this.getCultureName(object); localizedMessageName = this.getLocalizedName(object); if (originalFileName === undefined && key !== null) { fileName = this.getFileName(object); // "pack" equals to path in key on config.json pack = config.packages.i18n[key].path; fileName = pack + "/" + fileName + "." + cultureName + ".ts"; fileName = fileName.replace(/\\/gm, "/"); } else { fileName = originalFileName; } if (localizedMessageText == null) { index_1["default"].warn("Translation not found for " + object.localizedMessageName + " (language: " + cultureName + ")"); } else if (localizedMessageText != null && typeof localizedMessageText === "string" && localizedMessageText.length > 0) { this._util.setNestedPropertyByArray(literal, localizedMessageName.split("."), localizedMessageText, true); } callWriteNewLocalizedMessageToFile = function (data, firstLocalizedMessageSection, localizedMessageSections, fileName, localizedMessage, localizedMessageName, localizedMessageText) { _this.writeNewLocalizedMessageToFile(data, firstLocalizedMessageSection, localizedMessageSections, fileName, localizedMessage, localizedMessageName, localizedMessageText); }; if (!fs.existsSync(fileName)) return [3 /*break*/, 2]; aux = localizedMessageName.split("."); localizedMessage = void 0; localizedMessageSections = void 0; firstLocalizedMessageSection = void 0; if (aux.length === 1) { localizedMessage = aux[0]; firstLocalizedMessageSection = null; } else { localizedMessageSections = localizedMessageName.split(".").slice(0, -1); firstLocalizedMessageSection = localizedMessageSections[0]; localizedMessage = aux[aux.length - 1]; } return [4 /*yield*/, fs.readFileSync(fileName)]; case 1: content = _a.sent(); data = content.toString(); // Check if the file contains "export default {" if (data.includes("export default {")) { // If localized message already exists, locates it and replace its value if (data.match(localizedMessage)) { regexMainString = "PARAMETER\:\ .*,*"; regexMainString = regexMainString.replace("PARAMETER", localizedMessage); replaceMessage = new RegExp(regexMainString); messageToReplace = localizedMessage + ": \"" + localizedMessageText + "\","; textToFile = data.replace(replaceMessage, messageToReplace); fs.writeFileSync(fileName, Buffer.from(textToFile), { flag: "w" }); } // If the localized message doesn't exist else { callWriteNewLocalizedMessageToFile(data, firstLocalizedMessageSection, localizedMessageSections, fileName, localizedMessage, localizedMessageName, localizedMessageText); } } // If file doesn't have "export default" else { outputText = "export default " + data + ";"; outputText = beautify(outputText, { indent_size: 4 }); outputText += os.EOL; fs.writeFileSync(fileName, Buffer.from(outputText), { flag: "w" }); } return [3 /*break*/, 3]; case 2: outputText = "export default " + this.stringifyTS(literal) + ";"; outputText = beautify(outputText, { indent_size: 4 }); outputText += os.EOL; fs.writeFileSync(fileName, Buffer.from(outputText), { flag: "w+" }); _a.label = 3; case 3: return [2 /*return*/, fileName]; case 4: err_1 = _a.sent(); console.log(err_1); return [2 /*return*/, undefined]; case 5: return [2 /*return*/]; } }); }); }; //#endregion //#region Private Methods /** * Write the new localized message to file * @param data (data of file) * @param firstLocalizedMessageSection (first section in localized message name) * @param localizedMessageSections (sections in localized message name) * @param fileName (name of file) * @param localizedMessage (localized message) * @param localizedMessageName (name of localized message) * @param localizedMessageText (text of localized message) */ StructuredQueryLanguageConverter.prototype.writeNewLocalizedMessageToFile = function (data, firstLocalizedMessageSection, localizedMessageSections, fileName, localizedMessage, localizedMessageName, localizedMessageText) { return __awaiter(this, void 0, void 0, function () { var literal_1, ifLMDoesNotExist, ifLMAndSectionDoesNotExist, regexMainString, regEx, textToFile, text, index, regexMainString, regEx, regexString, regExpression, LMReplaced, LM, LMDoesNotExist, text, regEx, textToFile, text, regEx, textToFile, text, regEx, textToFile, text, regEx_1, textToFile, text; var _this = this; return __generator(this, function (_a) { try { literal_1 = {}; if (localizedMessageText != null && typeof localizedMessageText === "string" && localizedMessageText.length > 0) { this._util.setNestedPropertyByArray(literal_1, localizedMessageName.split("."), localizedMessageText, true); } ifLMDoesNotExist = function () { var output = _this.stringifyTS(literal_1); output = beautify(output, { indent_size: 4 }); return output; }; ifLMAndSectionDoesNotExist = function (LM) { var object = {}; _this._util.setNestedPropertyByArray(object, LM, localizedMessageText, true); var output = _this.stringifyTS(object); output = beautify(output, { indent_size: 4 }); return output; }; // Checks if the first section of localized message is different than null and file already contains it if (data.match(firstLocalizedMessageSection) && firstLocalizedMessageSection != null) { // If the last section already exists, put the new localized message in first line after declaration of last section if (data.match(localizedMessageSections[localizedMessageSections.length - 1])) { regexMainString = "PARAMETER\:\ {"; regexMainString = regexMainString.replace("PARAMETER", localizedMessageSections[localizedMessageSections.length - 1]); regEx = new RegExp(regexMainString); textToFile = localizedMessageSections[localizedMessageSections.length - 1] + ": {\n\t" + localizedMessage + ": \"" + localizedMessageText + "\","; text = beautify(data.replace(regEx, textToFile)); fs.writeFileSync(fileName, Buffer.from(text), { flag: "w" }); } // Locates the last section where occurs the match else { for (index = localizedMessageSections.length - 2; index >= 0; index--) { if (data.match(localizedMessageSections[index])) { regexMainString = "PARAMETER\:\ {"; regexMainString = regexMainString.replace("PARAMETER", localizedMessageSections[index]); regEx = new RegExp(regexMainString); regexString = ".*PARAMETER"; regexString = regexString.replace("PARAMETER", localizedMessageSections[index]); regExpression = new RegExp(regexString); LMReplaced = localizedMessageName.replace(regExpression, "" + localizedMessageSections[index]); LM = LMReplaced.split("."); LMDoesNotExist = ifLMAndSectionDoesNotExist(LM); LMDoesNotExist = LMDoesNotExist.slice(2, -3) + ","; text = beautify(data.replace(regEx, LMDoesNotExist)); fs.writeFileSync(fileName, Buffer.from(text), { flag: "w" }); break; } } } } // If data of file match "export default {}", replace "}" else if (data.match("export default {}")) { regEx = new RegExp(/}.*/g); textToFile = "\n\t" + ifLMDoesNotExist().slice(2, -1) + "};"; text = beautify(data.replace(regEx, textToFile)); fs.writeFileSync(fileName, Buffer.from(text), { flag: "w" }); } /* * If file looks like: "export default {" * }" */ else if (data.match("export default {\r\n}")) { regEx = "export default {\r\n}"; textToFile = "export default {\n\t" + ifLMDoesNotExist().slice(2, -1) + "}"; text = beautify(data.replace(regEx, textToFile)); fs.writeFileSync(fileName, Buffer.from(text), { flag: "w" }); } // Append in the end of file else { regEx = new RegExp(/,\r*\n};*/g); if (data.match(regEx)) { textToFile = ",\n\t" + ifLMDoesNotExist().slice(2, -1) + "};"; text = beautify(data.replace(regEx, textToFile)); fs.writeFileSync(fileName, Buffer.from(text), { flag: "w" }); } else { regEx_1 = new RegExp(/\r*\n};*/g); textToFile = ",\n\t" + ifLMDoesNotExist().slice(2, -1) + "};"; text = beautify(data.replace(regEx_1, textToFile)); fs.writeFileSync(fileName, Buffer.from(text), { flag: "w" }); } } } catch (err) { console.log(err); } return [2 /*return*/]; }); }); }; StructuredQueryLanguageConverter.prototype.isTemplateString = function (text) { return text.indexOf("${") >= 0; }; StructuredQueryLanguageConverter.prototype.stringifyTS = function (obj) { var _this = this; var arrOfKeyVal = [], objKeys = []; // Handle leafs if (obj instanceof translation_1.Translation) { if (obj.isLiteral === true) { return obj.text; } else { return this.isTemplateString(obj.text) ? "`" + obj.text + "`" : "\"" + obj.text + "\""; } } /*********CHECK FOR ARRAY**********/ else if (Array.isArray(obj)) { // Check for empty array if (obj.length === 0) return "[]"; else { var arrVal_1 = []; obj.forEach(function (el) { arrVal_1.push(_this.stringifyTS(el)); }); return "[" + arrVal_1 + "]"; } } /*********CHECK FOR OBJECT**********/ else if (obj instanceof Object) { // Get object keys objKeys = Object.keys(obj); // Set key output; objKeys.forEach(function (key) { var keyOut = "" + key; var keyValOut = obj[key]; // Skip functions and undefined properties if (keyValOut instanceof Function || typeof keyValOut === undefined) { arrOfKeyVal.push(""); } else if (typeof keyValOut === "string") { keyValOut = _this.isTemplateString(keyValOut) ? "`" + keyValOut + "`" : "\"" + keyValOut + "\""; arrOfKeyVal.push(keyOut + ": " + keyValOut); } else if (typeof keyValOut === "boolean" || typeof keyValOut === "number" || keyValOut === null) { arrOfKeyVal.push(keyOut + ": " + keyValOut); // Check for nested objects, call recursively until no more objects } else if (keyValOut instanceof Object) { arrOfKeyVal.push(keyOut + ": " + _this.stringifyTS(keyValOut)); } }); return "{" + arrOfKeyVal + "}"; } throw new Error("Not Implemented"); }; /** * Receiving a localized message, get the name of file to be changed * @param object (localized message) */ StructuredQueryLanguageConverter.prototype.getFileName = function (object) { var fileName; if (object.localizedMessageName != null) fileName = object.localizedMessageName.split("#")[0]; return fileName; }; /** * Receiving a localized message, get the name of localized message * @param object (localized message) */ StructuredQueryLanguageConverter.prototype.getLocalizedName = function (object) { var fileName; if (object.localizedMessageName != null) fileName = object.localizedMessageName.split("#")[1]; return fileName; }; /** * Receiving a localized message, get the name of culture * @param object (localized message) */ StructuredQueryLanguageConverter.prototype.getCultureName = function (object) { var cultureName; if (object.cultureName != null) cultureName = object.cultureName; return cultureName; }; /** * Receiving a localized message, get the text of localized message * @param object (localized message) */ StructuredQueryLanguageConverter.prototype.getLocalizedText = function (object) { var localizedText; if (object.localizedMessageText != null) localizedText = object.localizedMessageText; return localizedText; }; return StructuredQueryLanguageConverter; }()); exports.StructuredQueryLanguageConverter = StructuredQueryLanguageConverter;