UNPKG

@crestron/ch5-shell-utilities-cli

Version:
593 lines (592 loc) 30.8 kB
"use strict"; // Copyright (C) 2021 to the present, Crestron Electronics, Inc. // All rights reserved. // No part of this software may be reproduced in any form, machine // or natural, without the express written consent of Crestron Electronics. // Use of this source code is subject to the terms of the Crestron Software License Agreement // under which you licensed this source code. var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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 (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.Ch5GeneratePageCli = void 0; var Ch5BaseClassForCli_1 = require("../Ch5BaseClassForCli"); var path = require('path'); var fs = require("fs"); var fsExtra = require("fs-extra"); var Ch5GeneratePageCli = /** @class */ (function (_super) { __extends(Ch5GeneratePageCli, _super); function Ch5GeneratePageCli(showOutputMessages) { if (showOutputMessages === void 0) { showOutputMessages = true; } var _this = _super.call(this, "generate-page") || this; _this.showOutputMessages = showOutputMessages; /* - "basePathForPages": "./app/project/components/pages/" - This indicates the path where the page will be generated. - "templatesPath": "./ch5-shell-utilities-cli/src/cli/generate-page/templates/" - This indicates the path where the templates can be found */ _this.MIN_LENGTH_OF_PAGE_NAME = 2; _this.MAX_LENGTH_OF_PAGE_NAME = 31; _this.outputResponse = {}; return _this; } /** * Initialize */ Ch5GeneratePageCli.prototype.initialize = function () { this.outputResponse = { result: false, errorMessage: "", warningMessage: "", data: { pageName: "", menuOption: "", fileName: "", folderPath: "" } }; }; /** * Method for generating page */ Ch5GeneratePageCli.prototype.run = function () { return __awaiter(this, void 0, void 0, function () { var e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, 4, 5]); this.checkVersionToExecute(); // Initialize this.initialize(); // Verify input params this.verifyInputParams(); // Ask details to developer based on input parameter validation return [4 /*yield*/, this.checkPromptQuestions()]; case 1: // Ask details to developer based on input parameter validation _a.sent(); // Update project-config first (so that if this fails, we don't worry about file deletion). Next Delete Files return [4 /*yield*/, this.processRequest()]; case 2: // Update project-config first (so that if this fails, we don't worry about file deletion). Next Delete Files _a.sent(); return [3 /*break*/, 5]; case 3: e_1 = _a.sent(); if (e_1 && this.utils.isValidInput(e_1.message)) { if (e_1.message.trim().toLowerCase() === 'error') { this.outputResponse.errorMessage = this.getText("ERRORS.SOMETHING_WENT_WRONG"); } else { this.outputResponse.errorMessage = e_1.message; } } else { this.outputResponse.errorMessage = this.getText("ERRORS.SOMETHING_WENT_WRONG"); this.logger.log(e_1); } return [3 /*break*/, 5]; case 4: // Clean up this.cleanUp(); return [7 /*endfinally*/]; case 5: // Show output response this.logOutput(); return [2 /*return*/, this.outputResponse.result]; // The return is required to validate in automation test case } }); }); }; /** * Verify input parameters */ Ch5GeneratePageCli.prototype.verifyInputParams = function () { var tabDisplayText = this.getText("ERRORS.TAB_DELIMITER"); if (this.utils.isValidInput(this.inputArguments["name"])) { var validationResponse = this.validatePageName(this.inputArguments["name"]); if (validationResponse === "") { this.outputResponse.data.pageName = this.inputArguments["name"]; } else { this.outputResponse.warningMessage += tabDisplayText + this.getText("ERRORS.PAGE_NAME_INVALID_ENTRY", validationResponse); } } if (this.utils.isValidInput(this.inputArguments["menu"])) { var validationResponse = this.validateMenuOption(this.inputArguments["menu"]); if (validationResponse === "") { this.outputResponse.data.menuOption = this.inputArguments["menu"]; } else { this.outputResponse.warningMessage += tabDisplayText + validationResponse + "\n"; } } if (this.utils.isValidInput(this.outputResponse.warningMessage)) { if (this.showOutputMessages === true) { this.logger.printWarning(this.getText("ERRORS.MESSAGE_TITLE", this.outputResponse.warningMessage)); } } }; /** * Check if there are questions to be prompted to the developer */ Ch5GeneratePageCli.prototype.checkPromptQuestions = function () { return __awaiter(this, void 0, void 0, function () { var pages, newPageNameToSet, questionsArray, response, questionsArray, response, originalInputName; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!!this.utils.isValidInput(this.outputResponse.data.pageName)) return [3 /*break*/, 2]; pages = this.projectConfig.getAllPages(); pages = pages.sort(this.utils.dynamicSort("asc", "pageName")); this.logger.log("pages", pages); newPageNameToSet = this.loopAndCheckPage(pages); questionsArray = [ { type: "text", name: "pageName", initial: newPageNameToSet, hint: "", message: this.getText("VALIDATIONS.GET_PAGE_NAME"), validate: function (compName) { var output = _this.validatePageName(compName); return output === "" ? true : output; } } ]; return [4 /*yield*/, this.getEnquirer.prompt(questionsArray)]; case 1: response = _a.sent(); if (!this.utils.isValidInput(response.pageName)) { throw new Error(this.getText("ERRORS.PAGE_NAME_EMPTY_IN_REQUEST")); } this.logger.log(" response.pageName: ", response.pageName); this.outputResponse.data.pageName = response.pageName; _a.label = 2; case 2: if (!!this.utils.isValidInput(this.outputResponse.data.menuOption)) return [3 /*break*/, 4]; questionsArray = [ { type: 'select', name: 'menuOption', message: this.getText("VALIDATIONS.GET_ADD_TO_MENU_MESSAGE"), choices: [ { message: this.getText("VALIDATIONS.GET_ADD_TO_MENU_YES"), hint: this.getText("VALIDATIONS.GET_ADD_TO_MENU_HINT_YES"), value: 'Y' }, { message: this.getText("VALIDATIONS.GET_ADD_TO_MENU_NO"), hint: this.getText("VALIDATIONS.GET_ADD_TO_MENU_HINT_NO"), value: 'N' } ], initial: 0 } ]; return [4 /*yield*/, this.getEnquirer.prompt(questionsArray)]; case 3: response = _a.sent(); if (!this.utils.isValidInput(response.menuOption)) { throw new Error(this.getText("ERRORS.ADD_TO_MENU_EMPTY_IN_REQUEST")); } this.logger.log(" response.menuOption: ", response.menuOption); this.outputResponse.data.menuOption = response.menuOption; _a.label = 4; case 4: originalInputName = this.namingHelper.convertMultipleSpacesToSingleSpace(this.outputResponse.data.pageName.trim().toLowerCase()); this.outputResponse.data.pageName = this.namingHelper.camelize(originalInputName); this.logger.log(" this.outputResponse.data.pageName: ", this.outputResponse.data.pageName); this.logger.log(" this.outputResponse.data.menuOption: ", this.outputResponse.data.menuOption); this.outputResponse.data.fileName = this.namingHelper.dasherize(originalInputName); this.logger.log(" this.outputResponse.data.fileName: ", this.outputResponse.data.fileName); if (!this.utils.isValidInput(this.outputResponse.data.pageName) && !this.utils.isValidInput(this.outputResponse.data.menuOption)) { throw new Error(this.getText("ERRORS.PROGRAM_STOPPED_OR_UNKNOWN_ERROR")); } else if (!this.utils.isValidInput(this.outputResponse.data.pageName)) { throw new Error(this.getText("ERRORS.PAGE_NAME_EMPTY_IN_REQUEST")); } else if (!this.utils.isValidInput(this.outputResponse.data.menuOption)) { throw new Error(this.getText("ERRORS.ADD_TO_MENU_EMPTY_IN_REQUEST")); } else if (!this.utils.isValidInput(this.outputResponse.data.fileName)) { throw new Error(this.getText("ERRORS.SOMETHING_WENT_WRONG")); } return [2 /*return*/]; } }); }); }; /** * Implement this component's main purpose */ Ch5GeneratePageCli.prototype.processRequest = function () { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.projectConfig.isPageExistInJSON(this.outputResponse.data.pageName)) return [3 /*break*/, 1]; throw new Error(this.getText("ERRORS.PAGE_EXISTS_IN_PROJECT_CONFIG_JSON")); case 1: return [4 /*yield*/, this.createFolder().then(function (folderPathResponseGenerated) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: this.logger.log(" Folder Path (generated): " + folderPathResponseGenerated); this.outputResponse.data.folderPath = folderPathResponseGenerated; if (!this.utils.isValidInput(this.outputResponse.data.folderPath)) return [3 /*break*/, 5]; return [4 /*yield*/, this.createNewFile("html", "html.template", "")]; case 1: _a.sent(); return [4 /*yield*/, this.createNewFile("js", "js.template", "")]; case 2: _a.sent(); return [4 /*yield*/, this.createNewFile("scss", "scss.template", "")]; case 3: _a.sent(); return [4 /*yield*/, this.createNewFile("json", "emulator.template", "-emulator")]; case 4: _a.sent(); this.projectConfig.savePageToJSON(this.createPageObject()); this.outputResponse.result = true; return [3 /*break*/, 6]; case 5: throw new Error(this.getText("ERRORS.ERROR_IN_FOLDER_PATH")); case 6: return [2 /*return*/]; } }); }); }).catch(function (err) { throw new Error(err); })]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; /** * Clean up */ Ch5GeneratePageCli.prototype.cleanUp = function () { // Nothing to cleanup for this process }; /** * Log Final Response Message */ Ch5GeneratePageCli.prototype.logOutput = function () { if (this.showOutputMessages === true) { if (this.outputResponse.result === false) { this.logger.printError(this.outputResponse.errorMessage); } else { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE", this.outputResponse.data.pageName, this.outputResponse.data.folderPath)); if (this.outputResponse.data.menuOption === "Y") { this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_NAVIGATION_ADDED")); } this.logger.printSuccess(this.getText("SUCCESS_MESSAGE_CONCLUSION")); } } }; /** * Create Folder for the Pages to be created */ Ch5GeneratePageCli.prototype.createFolder = function () { return __awaiter(this, void 0, void 0, function () { var isFolderCreated, fullPath, folderPath, folderPathSplit, i, previousPath, files, j, file, fileName; return __generator(this, function (_a) { isFolderCreated = false; fullPath = ""; folderPath = this.getConfigNode("basePathForPages") + this.outputResponse.data.fileName + "/"; folderPathSplit = folderPath.toString().split("/"); for (i = 0; i < folderPathSplit.length; i++) { this.logger.log(folderPathSplit[i]); if (folderPathSplit[i] && folderPathSplit[i].trim() !== "") { previousPath = fullPath; fullPath += folderPathSplit[i] + "/"; if (!fs.existsSync(fullPath)) { this.logger.log("Creating new folder " + folderPathSplit[i] + " inside the folder " + previousPath); fs.mkdirSync(fullPath, { recursive: true, }); isFolderCreated = true; } else { this.logger.log(fullPath + " exists !!!"); } } } // Check if Folder exists if (isFolderCreated === false) { files = fs.readdirSync(fullPath); if (files.length === 0) { // Check if folder is empty. return [2 /*return*/, fullPath]; } else { // listing all files using forEach for (j = 0; j < files.length; j++) { file = files[j]; // If a single file exists, do not continue the process of generating page // If not, ensure to send message that folder is not empty but still created new files this.logger.log(file); fileName = this.outputResponse.data.fileName; this.logger.log(fileName.toLowerCase() + ".html"); if (file.toLowerCase() === fileName.toLowerCase() + ".html" || file.toLowerCase() === fileName.toLowerCase() + ".scss" || file.toLowerCase() === fileName.toLowerCase() + ".js") { throw new Error(this.getText("ERRORS.HTML_FILE_EXISTS", fileName.toLowerCase() + ".html", fullPath)); } } return [2 /*return*/, fullPath]; } } else { return [2 /*return*/, fullPath]; } return [2 /*return*/]; }); }); }; /** * Create New File based on templates * @param {string} fileExtension - File extension - applicable values are .html, .js, .scss * @param {string} templateFile - Template file name */ Ch5GeneratePageCli.prototype.createNewFile = function (fileExtension, templateFile, fileNameSuffix) { return __awaiter(this, void 0, void 0, function () { var actualContent, completeFilePath; return __generator(this, function (_a) { if (templateFile !== "") { actualContent = fsExtra.readFileSync(path.join(__dirname, "templates", templateFile)); actualContent = this.utils.replaceAll(actualContent, "<%pageName%>", this.outputResponse.data.pageName); actualContent = this.utils.replaceAll(actualContent, "<%titlePageName%>", this.namingHelper.capitalizeEachWordWithSpaces(this.outputResponse.data.pageName)); actualContent = this.utils.replaceAll(actualContent, "<%stylePageName%>", this.namingHelper.dasherize(this.outputResponse.data.pageName)); actualContent = this.utils.replaceAll(actualContent, "<%copyrightYear%>", String(new Date().getFullYear())); actualContent = this.utils.replaceAll(actualContent, "<%fileName%>", this.outputResponse.data.fileName); completeFilePath = this.outputResponse.data.folderPath + this.outputResponse.data.fileName + fileNameSuffix + "." + fileExtension; fsExtra.writeFileSync(completeFilePath, actualContent); // Success case, the file was saved this.logger.log("File contents saved!"); } return [2 /*return*/]; }); }); }; /** * Creates the page object in project-config.json. * If the menuOrientation is horizontal, then iconPosition is set to bottom by default. * If the menuOrientation is vertical, then iconPosition is set to empty by default. * If the menuOrientation is none, then iconPosition and iconUrl are set to empty. */ Ch5GeneratePageCli.prototype.createPageObject = function () { var allowNavigation = this.utils.convertStringToBoolean(this.outputResponse.data.menuOption); var pageObject = { "pageName": this.outputResponse.data.pageName, "fullPath": this.outputResponse.data.folderPath, "fileName": this.outputResponse.data.fileName + '.html', "preloadPage": true, "cachePage": false, "standAloneView": !allowNavigation }; if (allowNavigation === true) { var projectConfigJSON = this.projectConfig.getJson(); if (projectConfigJSON.menuOrientation === 'horizontal') { pageObject.navigation = { "sequence": this.projectConfig.getHighestNavigationSequence() + 1, "label": this.outputResponse.data.pageName.toLowerCase(), "isI18nLabel": false, "iconClass": "fas fa-file-alt", "iconUrl": "", "iconPosition": "bottom" }; } else if (projectConfigJSON.menuOrientation === 'vertical') { pageObject.navigation = { "sequence": this.projectConfig.getHighestNavigationSequence() + 1, "label": this.outputResponse.data.pageName.toLowerCase(), "isI18nLabel": false, "iconClass": "fas fa-file-alt", "iconUrl": "", "iconPosition": "" }; } else { pageObject.navigation = { "sequence": this.projectConfig.getHighestNavigationSequence() + 1, "label": this.outputResponse.data.pageName.toLowerCase(), "isI18nLabel": false, "iconClass": "", "iconUrl": "", "iconPosition": "" }; } } pageObject.animation = { "transitionIn": "", "transitionOut": "", "transitionDuration": "1s", "transitionDelay": "0s" }; return pageObject; }; /** * Loop and check the next valid page to set * @param {*} pages */ Ch5GeneratePageCli.prototype.loopAndCheckPage = function (pages) { var pageFound = false; var newPageNameToSet = ""; var i = 1; do { newPageNameToSet = "Page" + i; pageFound = false; for (var j = 0; j < pages.length; j++) { if (pages[j].pageName.trim().toLowerCase() === newPageNameToSet.toString().toLowerCase()) { pageFound = true; break; } } i++; } while (pageFound === true); return newPageNameToSet; }; /** * Method to validate Page Name * @param {string} pageName */ Ch5GeneratePageCli.prototype.validatePageName = function (pageName) { this.logger.log("pageName to Validate", pageName); if (this.utils.isValidInput(pageName)) { pageName = String(pageName).trim(); if (pageName.length < this.MIN_LENGTH_OF_PAGE_NAME || pageName.length > this.MAX_LENGTH_OF_PAGE_NAME) { return this.getText("ERRORS.PAGE_NAME_LENGTH", String(this.MIN_LENGTH_OF_PAGE_NAME), String(this.MAX_LENGTH_OF_PAGE_NAME)); } else { var pageValidity = new RegExp(/^[a-zA-Z][a-zA-Z0-9-_ $]*$/).test(pageName); if (pageValidity === false) { return this.getText("ERRORS.PAGE_NAME_MANDATORY"); } else { var originalInputName = this.namingHelper.convertMultipleSpacesToSingleSpace(pageName.trim().toLowerCase()); originalInputName = this.namingHelper.camelize(originalInputName); this.logger.log(" originalInputName: " + originalInputName); if (this.projectConfig.isPageExistInJSON(originalInputName)) { return this.getText("ERRORS.PAGE_EXISTS_IN_PROJECT_CONFIG_JSON"); } else if (this.projectConfig.isWidgetExistInJSON(originalInputName)) { return this.getText("ERRORS.WIDGET_EXISTS_IN_PROJECT_CONFIG_JSON"); } else if (this.checkPageNameForDisallowedKeywords(originalInputName, "startsWith") === true) { return this.getText("ERRORS.PAGE_CANNOT_START_WITH", this.getInvalidPageStartWithValues()); } else if (this.checkPageNameForDisallowedKeywords(originalInputName, "equals") === true) { return this.getText("ERRORS.PAGE_DISALLOWED_KEYWORDS"); } else { return ""; } } } } else { return this.getText("ERRORS.PAGE_NAME_MANDATORY"); } }; /** * Gets the keywords that are not allowed for pages to start */ Ch5GeneratePageCli.prototype.getInvalidPageStartWithValues = function () { var output = ""; var templateNames = this.getConfigNode("templateNames"); for (var i = 0; i < templateNames.disallowed["startsWith"].length; i++) { output += "'" + templateNames.disallowed["startsWith"][i] + "', "; } output = output.trim(); return output.substr(0, output.length - 1); }; /** * Checks if the pageName has disallowed keywords * @param {*} pageName * @param {*} type */ Ch5GeneratePageCli.prototype.checkPageNameForDisallowedKeywords = function (pageName, type) { var templateNames = this.getConfigNode("templateNames"); if (type === "startsWith") { for (var i = 0; i < templateNames.disallowed[type].length; i++) { if (pageName.trim().toLowerCase().startsWith(templateNames.disallowed[type][i].trim().toLowerCase())) { return true; } } } else if (type === "equals") { for (var i = 0; i < templateNames.disallowed[type].length; i++) { if (pageName.trim().toLowerCase() === templateNames.disallowed[type][i].trim().toLowerCase()) { return true; } } } return false; }; /** * Validate Menu Option * @param {*} menuOption */ Ch5GeneratePageCli.prototype.validateMenuOption = function (menuOption) { this.logger.log("menuOption to Validate", menuOption); if (this.utils.isValidInput(menuOption)) { menuOption = String(menuOption).trim().toLowerCase(); if (menuOption === "y" || menuOption === "n") { return ""; } else { return this.getText("ERRORS.ADD_TO_MENU_INVALID_ENTRY"); } } else { return this.getText("ERRORS.ADD_TO_MENU_INVALID_ENTRY"); } }; return Ch5GeneratePageCli; }(Ch5BaseClassForCli_1.Ch5BaseClassForCli)); exports.Ch5GeneratePageCli = Ch5GeneratePageCli;