UNPKG

@sap/generator-adaptation-project

Version:

Adaptation project allows you to create an app variant for an existing SAP Fiori elements-based or SAPUI5 freestyle application, without changing the original application.

971 lines (970 loc) 87.8 kB
"use strict"; 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 (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const fs = require("fs"); const path = __importStar(require("path")); const path_1 = require("path"); const uuid_1 = require("uuid"); const adp_cf_1 = require("@sap/adp-cf"); const yeoman_ui_types_1 = require("@sap-devx/yeoman-ui-types"); const adp_abap_1 = require("@sap/adp-abap"); const adp_tooling_1 = require("@sap-ux/adp-tooling"); const adp_common_1 = require("@sap/adp-common"); const AdaptationProjectGeneratorBase_1 = __importDefault(require("../common/generator/AdaptationProjectGeneratorBase")); const AppIdentifier_1 = __importDefault(require("../app/services/AppIdentifier")); const store_1 = require("@sap-ux/store"); const axios_1 = require("axios"); const types_1 = require("../common/types"); const file_system_1 = require("../common/utils/file-system"); const validator_1 = require("../common/questions/validator"); const project_input_validator_1 = require("@sap-ux/project-input-validator"); class AdaptationProjectGenerator extends AdaptationProjectGeneratorBase_1.default { constructor(args, opts) { super(args, opts, adp_common_1.GeneratorTypes.CREATION); this.STANDALONE_APPROUTER = "Standalone Approuter"; this.APPROUTER = "approuter"; this.BUSINESS_SERVICE = "businessService"; this.BASE_APP = "baseApp"; this.MANAGED_APPROUTER = "Approuter Managed by SAP Cloud Platform"; this.RESOURCE_BUNDLE_TEXT = "\n\n# This is the resource bundle for "; this.TRANSLARION_UUID_TEXT = "\n#__ldi.translation.uuid="; this.PROPERTIES_TEXT = ".properties"; this.mainI18nPath = "i18n/i18n.properties"; this.isInYeomanUIContext = false; this.isErrorPresent = false; this.isCFEnv = false; this.targetEnvironment = "ABAP"; this.showSolutionNamePrompt = false; this.approuter = null; this.baseAppOnChoiceError = null; this.cachedServiceName = null; this.apps = []; this.ui5VersionDetected = true; this.hasSystemAuthentication = false; this.extensibilitySubGenerator = undefined; this.isLoginSuccessfull = false; this.toolsId = (0, uuid_1.v4)(); this.isRunningInBAS = opts.isRunningInBAS || adp_common_1.EnvironmentUtils.isRunningInBAS(); if (args.length === 1) { try { this.jsonInput = JSON.parse(args[0]); return; } catch (error) { // do nothing, could be another parameter that is not parsable as json } } this.applicationValidator = new AppIdentifier_1.default(); this.localDestinationService = new adp_abap_1.LocalDestinationService(); this.writeContent = {}; this.fdcService = new adp_cf_1.FDCService(); this.isMtaYamlFound = adp_cf_1.YamlUtils.isMtaProject(process.cwd()); this.vscode = opts.vscode; this.isApplicationSupported = opts.isApplicationSupported || false; this.shouldCreateExtProject = opts.shouldCreateExtProject || false; this.flexUISystem = opts.flexUISystem || undefined; this.isCloudProject = opts.isCloudProject || undefined; this.isExtensionInstalled = opts.isExtensionInstalled || adp_common_1.VSCodeUtils.isExtensionInstalled("SAP.adp-ve-bas-ext"); this.isCFEnv = false; this.isCfInstalled = false; this._setPrompts(); } /** * Public API for implementing user interaction with generator */ prompting() { var _a, _b; return __awaiter(this, void 0, void 0, function* () { if (!this.isInYeomanUIContext && !this.jsonInput) { this.logger.error(adp_common_1.Messages.DO_NOT_USE_CONSOLE_GENERATOR); process.exit(1); } this.layer = this._getLayer(); this.isInternalUsage = adp_common_1.EnvironmentUtils.isInternalUsage(); this.endpointsManager = yield adp_common_1.EndpointsManager.getInstance(); this.providerManager = new adp_abap_1.AbapProvider(this.endpointsManager); this.manifestManager = new adp_abap_1.ManifestManager(this.providerManager); this.appsManager = new adp_abap_1.ApplicationManager(this.providerManager, !this.isInternalUsage); this.abapService = new adp_abap_1.AbapService(this.providerManager, !this.isInternalUsage); adp_common_1.UI5VersionsUtils.setInternalState(this.isInternalUsage); yield adp_common_1.UI5VersionsUtils.getPublicVersions(); if (this.jsonInput) { return; } if (this.isRunningInBAS) { this.isCfInstalled = yield this.fdcService.isCfInstalled(); this.logger.log(`Extension 'SAP.adp-ve-bas-ext' installed: ${this.isExtensionInstalled}`); if (this.isExtensionInstalled) { this.targetEnvAnswer = yield this.prompt(this._getTargetEnvPrompt()); this.logger.log(`Environment: ${this.targetEnvAnswer.targetEnv}`); this.targetEnvironment = this.targetEnvAnswer.targetEnv; this.isCFEnv = this.targetEnvironment === adp_common_1.Messages.CLOUD_FOUNDRY; const labels = this._getUIPageLabels(); this.prompts.splice(1, 1, labels); } else { this.targetEnvAnswer = { targetEnv: adp_common_1.Messages.ABAP }; } } else { // In VSCODE scenario we are not prompting for environment. this.targetEnvAnswer = { targetEnv: adp_common_1.Messages.ABAP }; } if (!this.isCFEnv) { this.answers = yield this.prompt(yield this._getConfigurationPrompts()); if (typeof this.answers.application === "string") { const id = this.answers.application; this.answers.application = { id }; } this.logger.log(`Application supported: ${this.isApplicationSupported}`); this.logger.log(`System: ${this.answers.system}`); this.logger.log(`Application: ${JSON.stringify(this.answers.application, null, 2)}`); const basicInformation = yield this.prompt(this._getBasicInformationPrompts()); this.logger.log(`Basic information: ${JSON.stringify(basicInformation)}`); Object.assign(this.answers, basicInformation); this.shouldCreateExtProject = this._allowExtensionProject() && this.answers.confirmPrompt; } else { this.isCFLoggedIn = yield this.fdcService.isLoggedIn(); this._setCFLoginPageDescription(this.isCFLoggedIn); yield this.prompt(yield this._getLoginPrompts()); const cfConfig = this.fdcService.getConfig(); this.logger.log(`Project organization information: ${JSON.stringify(cfConfig.org, null, 2)}`); this.logger.log(`Project space information: ${JSON.stringify(cfConfig.space, null, 2)}`); this.logger.log(`Project apiUrl information: ${JSON.stringify(cfConfig.url, null, 2)}`); this.cfOrganization = (_a = cfConfig === null || cfConfig === void 0 ? void 0 : cfConfig.org) === null || _a === void 0 ? void 0 : _a.name; this.cfSpace = (_b = cfConfig === null || cfConfig === void 0 ? void 0 : cfConfig.space) === null || _b === void 0 ? void 0 : _b.name; this.cfApiUrl = cfConfig.url; if (!this.isMtaYamlFound) { this.projectPathAnswers = yield this.prompt(this._promptUserForProjectPath()); this.projectPathAnswers.projectLocation = fs.realpathSync(this.projectPathAnswers.projectLocation, "utf-8"); this.cfProjectDestinationPath = this.destinationRoot(this.projectPathAnswers.projectLocation); this.logger.log(`Project path information: ${JSON.stringify(this.projectPathAnswers, null, 2)}`); } else { this.cfProjectDestinationPath = this.destinationRoot(process.cwd()); adp_cf_1.YamlUtils.loadYamlContent(path.join(this.cfProjectDestinationPath, "mta.yaml")); this.logger.log(`Project path information: ${this.cfProjectDestinationPath}`); } this.basicInfoAnswers = yield this.prompt(this._getBasicInformationPrompts(this.isCFLoggedIn, this.isCFEnv, this.cfProjectDestinationPath)); this.logger.log(`Basic information: ${JSON.stringify(this.basicInfoAnswers, null, 2)}`); this.appSourceAnswers = yield this.prompt(yield this._getApplicationSourcesPrompts(this.cfProjectDestinationPath)); this.logger.log(`App source information: ${JSON.stringify(this.appSourceAnswers, null, 2)}`); } }); } writing() { return __awaiter(this, void 0, void 0, function* () { if (this.jsonInput) { yield this._generateProjectArtifactsFromJson(); return; } if (this.shouldCreateExtProject && !this.isCFEnv) { yield this._generateExtensionProject(); return; } switch (this.targetEnvironment) { case adp_common_1.Messages.CLOUD_FOUNDRY: { if (!this.appSourceAnswers.baseApp) { // !!! This should be fixed when we can skip the redirect action return this.isInYeomanUIContext ? this.appWizard.showError(adp_common_1.Messages.LOGGED_OUT_ERROR, yeoman_ui_types_1.MessageType.notification) : this.logger.log(adp_common_1.Messages.LOGGED_OUT_ERROR); } yield this._generateAdpProjectArtifactsCF(); break; } case adp_common_1.Messages.ABAP: { try { yield this._generateAdpProjectArtifactsABAP(); } catch (e) { this.isErrorPresent = true; this.logger.error(e); this.fs.delete(path.join(this.answers.targetFolder, this.answers.projectName)); this.appWizard.showError(e.message, yeoman_ui_types_1.MessageType.notification); } break; } default: { break; } } }); } _generateProjectArtifactsFromJson() { return __awaiter(this, void 0, void 0, function* () { try { yield this._initializeAnswersFromJson(); yield this._generateAdpProjectArtifactsABAP(); (0, file_system_1.writeResult)(this.jsonInput.id, path.join(this.answers.targetFolder, this.answers.projectName)); } catch (error) { (0, file_system_1.writeResult)(this.jsonInput.id, `Failure: ${error === null || error === void 0 ? void 0 : error.message}`); throw error; } }); } _initializeAnswersFromJson() { return __awaiter(this, void 0, void 0, function* () { const { targetFolder = "/home/user/projects", system, client, username, password, application: baseAppName, projectName = (0, file_system_1.findUniqueDirName)(targetFolder, `${baseAppName}.variant`), namespace = this._generateValidNamespace(projectName, this.isInternalUsage), applicationTitle, applicationComponentHierarchy = "" } = this.jsonInput; const projectNameValidationResult = yield (0, validator_1.validateProjectName)(projectName, targetFolder, this.isInternalUsage, false); if (typeof projectNameValidationResult === "string") { throw new Error(projectNameValidationResult); } const namespaceValidationResult = yield (0, validator_1.validateNamespace)(namespace, projectName, this.isInternalUsage); if (typeof namespaceValidationResult === "string") { throw new Error(namespaceValidationResult); } const systems = this.endpointsManager.getEndpointNames(); const systemFound = systems.some((currentSystem) => currentSystem === system); if (!systemFound) { throw new Error(`System not found or not supported: ${system}`); } yield this.abapService.connectToSystem(system, username, password, client); this.isCloudProject = yield this.abapService.isAbapCloud(); const apps = yield this.appsManager.loadApps(this.isCloudProject); const application = apps.find((currentApp) => currentApp.id === baseAppName); if (!application) { throw new Error(`Application not found or not supported: ${baseAppName}`); } this.answers = { targetFolder, system, client, username, password, projectName, namespace, application, applicationTitle: applicationTitle || `${application.title} (variant)`, applicationComponentHierarchy }; }); } _generateExtensionProject() { return __awaiter(this, void 0, void 0, function* () { try { if (!this.answers.application) { throw new Error("Application parameters are missing."); } const destinationInfo = this.endpointsManager.getDestinationInfoByName(this.answers.system); if (!destinationInfo) { throw new Error("Destination info is missing."); } const data = { username: this.answers.username, password: this.answers.password, destination: { name: destinationInfo.Name, basUsage: destinationInfo.WebIDEUsage, host: destinationInfo.Host, sapClient: destinationInfo["sap-client"] }, applicationNS: this.answers.namespace, applicationName: this.answers.projectName, userUI5Ver: this._getTrimmedUI5Version(this.answers.ui5version), BSPUrl: this.answers.application.bspUrl, namespace: this.answers.application.id }; this.composeWith(this.extensibilitySubGenerator, { arguments: [JSON.stringify(data)], appWizard: this.appWizard }); this.logger.log(`'@bas-dev/generator-extensibility-sub' was called.`); } catch (e) { this.logger.log(`Creating Extension Project failed!`); this.logger.error(e.message); this.appWizard.showError(e.message, yeoman_ui_types_1.MessageType.notification); } }); } _resolveNodeModuleGenerator() { const nodePath = process.env["NODE_PATH"]; const nodePaths = nodePath.split(":"); if (this.extensibilitySubGenerator) { return true; } for (let i = 0; i < nodePaths.length; i++) { try { this.extensibilitySubGenerator = require.resolve((0, path_1.resolve)(nodePaths[i], "@bas-dev/generator-extensibility-sub/generators/app")); } catch (e) { // We don't care if there's an error while resolving the module // Continue with the next node_module path } if (this.extensibilitySubGenerator !== undefined) { this.logger.log(`'@bas-dev/generator-extensibility-sub' generator found for path: ${nodePaths[i]}.`); break; } } if (this.extensibilitySubGenerator === undefined) { this.logger.log(`'@bas-dev/generator-extensibility-sub' generator was not found for paths: ${JSON.stringify(nodePaths)}.`); return "Extensibility Project generator plugin was not found in your dev space, and is required for this action. To proceed, please install the <SAPUI5 Layout Editor & Extensibility> extension."; } return true; } _connectToAbapProviderIfNeeded() { return __awaiter(this, void 0, void 0, function* () { if (!this.providerManager.isConnected()) { yield this.providerManager.setProvider(this.answers.system, this.answers.client, this.answers.username, this.answers.password); } }); } _generateAdpProjectArtifactsABAP() { return __awaiter(this, void 0, void 0, function* () { let systemAuthDetails; if (!this.isRunningInBAS && this.localDestinationService.shouldGetLocalSystemAuthDetails()) { systemAuthDetails = yield this.localDestinationService.getSystemAuthDetails(this.answers.system); } else { systemAuthDetails = { url: this.answers.system, client: this.answers.client, password: this.answers.password, username: this.answers.username }; } const config = yield this._getTemplateModel(systemAuthDetails); // @ts-ignore yield (0, adp_tooling_1.generate)(path.join(this.answers.targetFolder, this.answers.projectName), config, this.fs); }); } _getManifestContent(applicationId, ui5SystemVersion) { return __awaiter(this, void 0, void 0, function* () { if (!this.manifest) { yield this._connectToAbapProviderIfNeeded(); this.manifest = yield this.manifestManager.getManifest(applicationId); } const appType = adp_common_1.AppUtils.getApplicationType(this.manifest); const content = []; const appInfo = { title: this.answers.applicationTitle, id: applicationId, type: appType }; const i18nModels = this._getI18NModels(this.manifest, appInfo); if (i18nModels) { i18nModels.forEach((i18nModel) => { if (i18nModel.key !== "i18n" && i18nModel.path !== this.mainI18nPath && i18nModel.content) { this.fs.write(path.join(this.answers.targetFolder, this.answers.projectName + "/webapp/" + i18nModel.path), i18nModel.content); } content.push(this._createDescriptorChangeForResourceModel(i18nModel.key, i18nModel.path, appType, ui5SystemVersion)); }); } //Adding version, fioriID, registrationID For Internal Applications if (this.isInternalUsage) { content.push({ changeType: "appdescr_fiori_setRegistrationIds", content: { registrationIds: [this.answers.fioriId] } }); content.push({ changeType: "appdescr_app_setAch", content: { ach: this.answers.applicationComponentHierarchy.toUpperCase() } }); } if (adp_common_1.UI5VersionsUtils.shouldSetMinUI5Version()) { const ui5MinVersion = { changeType: "appdescr_ui5_setMinUI5Version", content: { minUI5Version: this._getMinUI5VersionForManifest() } }; content.push(ui5MinVersion); } return content; }); } _getMinUI5VersionForManifest() { var _a; return ((_a = adp_common_1.UI5VersionsUtils.getSystemVersion()) === null || _a === void 0 ? void 0 : _a.indexOf("snapshot")) === -1 ? adp_common_1.UI5VersionsUtils.getSystemVersion() : adp_common_1.UI5VersionsUtils.getLatestPublicVersion(); } _getSupportForUI5Yaml() { const packageJSON = (0, file_system_1.getPackageJSONInfo)(this.logger); return { id: packageJSON.name, version: packageJSON.version, toolsId: this.toolsId }; } _generateAdpProjectArtifactsCF() { return __awaiter(this, void 0, void 0, function* () { const projectPath = this._getProjectPath(); const ui5version = yield adp_common_1.UI5VersionsUtils.getUI5Version(); yield adp_cf_1.YamlUtils.adjustMtaYaml(projectPath, this.basicInfoAnswers.projectName, this.appSourceAnswers.approuter, this.appSourceAnswers.businessSolutionName, this.appSourceAnswers.businessService); let businessSolutionName = null; if (this.appSourceAnswers.approuter === this.MANAGED_APPROUTER || this.approuter === this.MANAGED_APPROUTER) { businessSolutionName = this.appSourceAnswers["businessSolutionName"] ? this.appSourceAnswers["businessSolutionName"] : adp_cf_1.YamlUtils.getSAPCloudService(); } let i18nGuid = adp_common_1.Messages.I18N_KEY_GUIDELINES_MESSAGE; if (this._isInternalMode()) { i18nGuid += this.RESOURCE_BUNDLE_TEXT + this.basicInfoAnswers.applicationTitle + this.TRANSLARION_UUID_TEXT + this._generateGuid() + "\n\n"; } const folder = path.join(projectPath, this.basicInfoAnswers.projectName); const cfParams = this._getCFParameters(); this.writeContent.meta = Object.assign({ i18nGuid: i18nGuid, appHostId: this.appSourceAnswers.baseApp.appHostId, appName: this.appSourceAnswers.baseApp.appName, appVersion: this.appSourceAnswers.baseApp.appVersion, appId: this.appSourceAnswers.baseApp.appId, module: this.basicInfoAnswers.projectName, moduleTitle: this.basicInfoAnswers.applicationTitle, appVariantId: this.basicInfoAnswers.namespace, projectName: adp_cf_1.YamlUtils.getProjectName(), projectPath: projectPath, addSecurity: this.appSourceAnswers.addSecurity, addStandaloneApprouter: this.appSourceAnswers.approuter === this.STANDALONE_APPROUTER || this.approuter === this.STANDALONE_APPROUTER, sapCloudService: businessSolutionName, xsSecurityProjectName: adp_cf_1.YamlUtils.getProjectNameForXsSecurity(), folder }, cfParams); const manifest = this.fdcService.getManifestByBaseAppId(this.appSourceAnswers.baseApp.appId); const appdescrTpl = { content: [] }; const appType = adp_common_1.AppUtils.getApplicationType(manifest); const appInfo = { title: this.basicInfoAnswers.applicationTitle, id: this.appSourceAnswers.baseApp.appId, type: appType }; const i18nModels = this._getI18NModels(manifest, appInfo); if (i18nModels) { i18nModels.forEach((i18nModel) => { if (i18nModel.key !== "i18n" && i18nModel.path !== this.mainI18nPath && i18nModel.content) { this.fs.write(this.destinationPath(path.join(this.writeContent.meta.folder, "webapp", i18nModel.path)), i18nModel.content); } appdescrTpl.content.push(this._createDescriptorChangeForResourceModel(i18nModel.key, i18nModel.path, appType, ui5version)); }); } appdescrTpl.reference = this.writeContent.meta.appId; appdescrTpl.id = this.writeContent.meta.appVariantId; appdescrTpl.namespace = "apps/" + this.writeContent.meta.appId + "/appVariants/" + this.writeContent.meta.appVariantId + "/"; appdescrTpl.content.push({ changeType: "appdescr_ui5_setMinUI5Version", content: { minUI5Version: ui5version } }); appdescrTpl.layer = this._getLayer(); this.fs.copyTpl(this.templatePath("../../../templates/cf/package.json"), this.destinationPath(path.join(this.writeContent.meta.folder, "package.json")), this.writeContent.meta); this.fs.writeJSON(this.destinationPath(path.join(this.writeContent.meta.folder, "webapp", "manifest.appdescr_variant")), appdescrTpl); this.fs.copyTpl(this.templatePath("../../../templates/cf/ui5.yaml"), this.destinationPath(path.join(this.writeContent.meta.folder, "ui5.yaml")), this.writeContent.meta); this.fs.writeJSON(this.destinationPath(path.join(this.writeContent.meta.folder, "/.adp/config.json")), this._getConfigJsonCF(appType, this.writeContent.meta.appVariantId, ui5version)); if (this.writeContent.meta.addStandaloneApprouter) { this.fs.copyTpl(this.templatePath("../../../templates/cf/approuter/package.json"), this.destinationPath(path.join(this.writeContent.meta.projectPath, `${this.writeContent.meta.projectName}-approuter/package.json`)), this.writeContent.meta); this.fs.copyTpl(this.templatePath("../../../templates/cf/approuter/xs-app.json"), this.destinationPath(path.join(this.writeContent.meta.projectPath, `${this.writeContent.meta.projectName}-approuter/xs-app.json`)), this.writeContent.meta); } if (!this.fs.exists(path.join(this.writeContent.meta.projectPath, "xs-security.json"))) { this.fs.copyTpl(this.templatePath("../../../templates/cf/xs-security.json"), this.destinationPath(path.join(this.writeContent.meta.projectPath, "xs-security.json")), { projectName: adp_cf_1.YamlUtils.getProjectNameForXsSecurity() }); } this.fs.copyTpl(this.templatePath("../../../templates/cf/i18n/i18n.properties"), this.destinationPath(path.join(this.writeContent.meta.folder, "webapp/i18n/i18n.properties")), this.writeContent.meta); this.fs.copy(this.templatePath("../../../templates/cf/_gitignore"), this.destinationPath(path.join(this.writeContent.meta.folder, ".gitignore"))); }); } _getI18NModels(manifest, appInfo) { var _a; const i18nModels = []; try { Object.keys((_a = manifest["sap.ui5"]) === null || _a === void 0 ? void 0 : _a.models).forEach((modelObjectKey) => { const ui5Model = manifest["sap.ui5"].models[modelObjectKey]; if (ui5Model.type === "sap.ui.model.resource.ResourceModel") { const i18nContent = this._getI18NContent(ui5Model, modelObjectKey, appInfo.title); const resourceModelPath = this._extractResourceModelPath(ui5Model, modelObjectKey, appInfo.id); if (resourceModelPath) { i18nModels.push({ key: modelObjectKey, path: resourceModelPath, content: i18nContent }); } } }); return i18nModels; } catch (e) { throw new Error("Manifest parsing error: Check manifest/i18n for missing properties"); } } _getI18NContent(ui5Model, modelObjectKey, appTitle) { let i18nContent; if (this.isCFEnv) { if (ui5Model.uri) { if (modelObjectKey !== "i18n") { i18nContent = adp_common_1.Messages.I18N_KEY_GUIDELINES_MESSAGE; } } } else { i18nContent = adp_common_1.Messages.I18N_KEY_GUIDELINES_MESSAGE; } if (i18nContent && this.isInternalUsage) { i18nContent += this.RESOURCE_BUNDLE_TEXT + appTitle + this.TRANSLARION_UUID_TEXT + this._generateGuid(); } return i18nContent; } _extractResourceModelPath(ui5Model, modelObjectKey, appId) { let resourceModelPath; if (ui5Model.uri) { resourceModelPath = ui5Model.uri; } else if (ui5Model.settings) { const bundleName = ui5Model.settings.bundleName; if ((bundleName === null || bundleName === void 0 ? void 0 : bundleName.indexOf(appId)) === 0) { //remove the namespace and you are left with the ResourceModel path. const fileLocation = bundleName.slice(appId.length, bundleName.length); // Transform the dot notation of the namespace to a uri. resourceModelPath = fileLocation.replace(/\./g, "/").substring(1, fileLocation.length) + this.PROPERTIES_TEXT; } else { // The model is located outside the application. // We still need to enhance the model as they are (probably) used inside the app. // Take the original model name as filename and put it into the i18n folder. resourceModelPath = "i18n/" + modelObjectKey + this.PROPERTIES_TEXT; } } return resourceModelPath; } install() { return __awaiter(this, void 0, void 0, function* () { if (this.isErrorPresent || this.shouldCreateExtProject) { return; } const projectPath = this.isCFEnv ? path.join(this.writeContent.meta.projectPath, this.writeContent.meta.module) : path.join(this.answers.targetFolder, this.answers.projectName); try { yield (0, file_system_1.installDependencies)(projectPath); } catch (error) { this.appWizard.showError(error.message, yeoman_ui_types_1.MessageType.notification); } }); } end() { return __awaiter(this, void 0, void 0, function* () { if (this.isErrorPresent || this.isCFEnv || this.jsonInput || this.shouldCreateExtProject) { return; } try { const projectPath = { fsPath: path.join(this.answers.targetFolder, this.answers.projectName) }; this.vscode.commands.executeCommand("sap.ux.application.info", projectPath); } catch (e) { this.appWizard.showError(e.message, yeoman_ui_types_1.MessageType.notification); } }); } _generateGuid() { return (this._generate4Chars() + this._generate4Chars() + "-" + this._generate4Chars() + "-" + this._generate4Chars() + "-" + this._generate4Chars() + "-" + this._generate4Chars() + this._generate4Chars() + this._generate4Chars()); } _determineInitialPrompt() { if (this.isExtensionInstalled) { return { name: adp_common_1.Messages.TARGET_ENV, description: "" }; } return { name: adp_common_1.Messages.CONFIGURATION_STEP, description: adp_common_1.Messages.CONFIGURATION_STEP }; } _determineSecondPrompt() { if (this.isExtensionInstalled) { return { name: adp_common_1.Messages.CONFIGURATION_STEP, description: adp_common_1.Messages.CONFIGURATION_STEP }; } return { name: adp_common_1.Messages.BASIC_INFORMATION_STEP, description: adp_common_1.Messages.BASIC_INFORMATION_STEP_DESCRIPTION }; } _setPrompts() { this.setPromptsCallback = (fn) => { //setPromptsCallback gets called only in Yeoman UI. Thus we can use it to know the running context. this.isInYeomanUIContext = true; if (this.prompts) { this.prompts.setCallback(fn); } }; this.prompts = new yeoman_ui_types_1.Prompts([this._determineInitialPrompt(), this._determineSecondPrompt()]); } _getUIPageLabels() { let prompts; if (!this.isCFEnv) { prompts = [ { name: adp_common_1.Messages.CONFIGURATION_STEP, description: adp_common_1.Messages.CONFIGURATION_STEP }, { name: adp_common_1.Messages.BASIC_INFORMATION_STEP, description: adp_common_1.Messages.BASIC_INFORMATION_STEP_DESCRIPTION } ]; } else { prompts = [ { name: adp_common_1.Messages.LOGIN_CF, description: adp_common_1.Messages.PROVIDE_CREDENTIALS }, { name: adp_common_1.Messages.PROJECT_PATH, description: adp_common_1.Messages.PROVIDE_PATH }, { name: adp_common_1.Messages.BASIC_INFORMATION_STEP, description: adp_common_1.Messages.BASIC_INFORMATION_STEP_DESCRIPTION }, { name: adp_common_1.Messages.APP_DETAILS, description: adp_common_1.Messages.SETUP_APP } ]; } return prompts; } _setCFLoginPageDescription(isLoggedIn) { const pageLabel = { name: adp_common_1.Messages.LOGIN_CF, description: isLoggedIn ? "" : adp_common_1.Messages.PROVIDE_CREDENTIALS }; this.prompts.splice(1, 1, [pageLabel]); } _getTemplateModel(systemAuthDetails) { var _a; return __awaiter(this, void 0, void 0, function* () { let i18description = adp_common_1.Messages.I18N_KEY_GUIDELINES_MESSAGE; const ui5version = this.isCloudProject ? adp_common_1.UI5VersionsUtils.getLatestPublicVersion() : adp_common_1.UI5VersionsUtils.getVersionToBeUsed(this.answers.ui5version); const ui5SystemVersion = adp_common_1.UI5VersionsUtils.getFormattedVersion(ui5version); const enableTypeScript = this.answers.enableTypeScript; if (this.isInternalUsage) { i18description += this.RESOURCE_BUNDLE_TEXT + this.answers.applicationTitle + this.TRANSLARION_UUID_TEXT + this._generateGuid() + "\n\n"; } const app = { id: this.answers.namespace, reference: this.answers.application.id, layer: this._getLayer(), title: this.answers.applicationTitle, content: yield this._getManifestContent(this.answers.application.id, ui5SystemVersion), i18nDescription: i18description }; const target = Object.assign({ client: this.isRunningInBAS ? (_a = this.answers) === null || _a === void 0 ? void 0 : _a.client : systemAuthDetails === null || systemAuthDetails === void 0 ? void 0 : systemAuthDetails.client }, (this.isRunningInBAS ? { destination: this.answers.system } : { url: systemAuthDetails === null || systemAuthDetails === void 0 ? void 0 : systemAuthDetails.url })); if (!this.isRunningInBAS && this.isCloudProject && (systemAuthDetails === null || systemAuthDetails === void 0 ? void 0 : systemAuthDetails.authenticationType) === store_1.AuthenticationType.ReentranceTicket) { target["authenticationType"] = store_1.AuthenticationType.ReentranceTicket; } if (this.isCloudProject) { yield this.abapService.connectToSystem(this.answers.system, this.answers.username, this.answers.password, this.answers.client); const systemInfo = yield this.abapService.getSystemInfo(); Object.assign(app, { bspName: this.answers.application.bspName, languages: systemInfo.activeLanguages }); } return { app, target, ui5: { minVersion: ui5version.split(" ")[0], version: adp_common_1.UI5VersionsUtils.getFormattedVersion(ui5version), frameworkUrl: adp_common_1.UI5VersionsUtils.getOfficialBaseUI5VersionUrl(ui5version) }, package: { name: this.answers.projectName }, customConfig: { adp: { environment: this.isCloudProject ? "C" : "P", support: this._getSupportForUI5Yaml() } }, options: { fioriTools: true, enableTypeScript } }; }); } _getConfigJsonCF(appType, componentName, ui5version) { return { "componentname": componentName, "appvariant": this.basicInfoAnswers.projectName, "layer": this._getLayer(), "isOVPApp": adp_common_1.AppUtils.isOVPApp(appType), "isFioriElement": adp_common_1.AppUtils.isFioriElementsApp(appType), "environment": "CF", "ui5Version": ui5version, "cfApiUrl": this.cfApiUrl, "cfSpace": this.cfSpace, "cfOrganization": this.cfOrganization }; } _createDescriptorChangeForResourceModel(sModelId, sPath, appType, ui5Version) { const fallbackLocaleSupported = adp_common_1.UI5VersionsUtils.isFeatureSupportedVersion("1.84.0", ui5Version); if (appType === adp_common_1.ApplicationType.FREE_STYLE && fallbackLocaleSupported) { return { changeType: "appdescr_ui5_addNewModelEnhanceWith", content: { modelId: sModelId, bundleUrl: sPath, supportedLocales: [""], fallbackLocale: "" } }; } return { changeType: "appdescr_ui5_addNewModelEnhanceWith", content: { "modelId": sModelId }, texts: { "i18n": sPath } }; } _getTrimmedUI5Version(version) { const regex = /\b\d+\.\d+\.\d+\b/g; const includesText = version.includes("(system version)") || version.includes("latest"); let trimmedVersion; try { if (includesText) { trimmedVersion = version.match(regex)[0]; } } catch (e) { return version; } return trimmedVersion !== null && trimmedVersion !== void 0 ? trimmedVersion : version; } _getProjectPath() { return this.isMtaYamlFound ? process.cwd() : this.projectPathAnswers.projectLocation; } _generate4Chars() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } _isInternalMode() { return this.isInternalUsage; } _getLayer() { return this._isInternalMode() ? "VENDOR" /* FlexLayer.VENDOR */ : "CUSTOMER_BASE" /* FlexLayer.CUSTOMER_BASE */; } _getTargetEnvPrompt() { return [ { type: types_1.PromptType.LIST, name: "targetEnv", message: adp_common_1.Messages.SELECT_ENV, choices: () => this._getEnvironments(), default: () => { var _a; return (_a = this._getEnvironments()[0]) === null || _a === void 0 ? void 0 : _a.name; }, guiOptions: { mandatory: true, hint: adp_common_1.Messages.TARGET_ENV_TOOLTIP }, validate: (value) => (0, validator_1.validateEnvironment)(value, adp_common_1.Messages.TARGET_ENV, this.fdcService) } ]; } _getEnvironments() { const choices = [{ name: adp_common_1.Messages.ABAP, value: adp_common_1.Messages.ABAP }]; if (this.isCfInstalled) { choices.push({ name: "Cloud Foundry", value: adp_common_1.Messages.CLOUD_FOUNDRY }); } else { this.appWizard.showInformation(adp_common_1.Messages.CLOUD_FOUNDRY_NOT_INSTALLED, yeoman_ui_types_1.MessageType.prompt); console.log(adp_common_1.Messages.CLOUD_FOUNDRY_NOT_INSTALLED); } return choices; } // prettier-ignore _getBasicInformationPrompts(isLoggedIn = false, isCFEnv = false, destinationPath = this.destinationPath()) { return [ this._getProjectNamePrompt(this.isInternalUsage, destinationPath, isCFEnv, isLoggedIn), this._getApplicationTitlePrompt(isCFEnv, isLoggedIn), this._getNamespacePrompt(this.isInternalUsage, isCFEnv, isLoggedIn), ...(!isCFEnv ? [ this._getTargetFolderPrompt(), this._getUi5VersionPrompt(), this._getCurrentUI5VersionPrompt(), this._getVersionInfoPrompt(), this._getEnableTypeScriptPrompt(), ] : []) ]; } _getProjectNamePrompt(isInternalMode, destinationPath, isCfMode, isLoggedIn) { return { type: types_1.PromptType.INPUT, name: "projectName", message: () => { if (isInternalMode) { return isCfMode ? adp_common_1.Messages.PROJECT_NAME_CF_INTERNAL_PROMPT_LABEL : adp_common_1.Messages.PROJECT_NAME_INTERNAL_PROMPT_LABEL; } else { return isCfMode ? adp_common_1.Messages.PROJECT_NAME_CF_EXTERNAL_PROMPT_LABEL : adp_common_1.Messages.PROJECT_NAME_EXTERNAL_PROMPT_LABEL; } }, default: (answers) => __awaiter(this, void 0, void 0, function* () { return (0, file_system_1.findUniqueDirName)(answers.targetFolder || destinationPath, "app.variant"); }), guiOptions: { mandatory: true, hint: adp_common_1.Messages.PROJECT_NAME_TOOLTIP(isInternalMode, isCfMode), breadcrumb: "Project Name" }, validate: (value, answers) => { return (0, validator_1.validateProjectName)(value, answers.targetFolder || destinationPath, isInternalMode, isCfMode); }, when: () => { return this._isVisible(isCfMode, isLoggedIn); }, store: false }; } _getApplicationTitlePrompt(isCfMode, isLoggedIn) { return { type: types_1.PromptType.INPUT, name: "applicationTitle", message: adp_common_1.Messages.APPLICATION_TITLE_PROMPT_LABEL, default: () => adp_common_1.Messages.APPLICATION_TITLE_DEFAULT_VALUE, guiOptions: { mandatory: true, hint: adp_common_1.Messages.APPLICATION_TITLE_TOOLTIP, breadcrumb: adp_common_1.Messages.APPLICATION_TITLE_PROMPT_LABEL }, validate: (value) => (0, validator_1.validateEmptyInput)(value, adp_common_1.Messages.APPLICATION_TITLE_PROMPT_LABEL), when: () => { return this._isVisible(isCfMode, isLoggedIn); }, store: false }; } _getNamespacePrompt(isInternalMode, isCfMode, isLoggedIn) { const namespacePrompt = { type: types_1.PromptType.INPUT, name: "namespace", message: adp_common_1.Messages.NAMESPACE_PROMPT_LABEL, guiOptions: { applyDefaultWhenDirty: true }, default: (answers) => { return this._generateValidNamespace(answers.projectName, isInternalMode); }, when: () => { return this._isVisible(isCfMode, isLoggedIn); }, store: false }; if (isInternalMode && (!isCfMode || (isCfMode && isLoggedIn))) { namespacePrompt.guiOptions.type = types_1.PromptGuiOptionsType.LABEL; namespacePrompt.when = (answers) => { return !!answers.projectName; }; } else { namespacePrompt.guiOptions.mandatory = true; namespacePrompt.guiOptions.breadcrumb = adp_common_1.Messages.NAMESPACE_PROMPT_LABEL; namespacePrompt.validate = (value, answers) => (0, validator_1.validateNamespace)(value, answers.projectName, isInternalMode); } return namespacePrompt; } _getEnableTypeScriptPrompt() { return { type: types_1.PromptType.CONFIRM, name: "enableTypeScript", message: "Enable TypeScript", default: false, guiOptions: { breadcrumb: true }, when: () => this.isApplicationSupported && !this.answers.confirmPrompt }; } _isVisible(isCfMode, isLoggedIn) { return !isCfMode || (isCfMode && isLoggedIn); } _generateValidNamespace(projectName, isInternalMode) { return isInternalMode ? projectName : "customer." + projectName; } _getConfigurationPrompts() { return __awaiter(this, void 0, void 0, function* () { return [ yield this._getSystemPrompt(), this._getSystemClientPrompt(), this._getUsernamePrompt(), this._getPasswordPrompt(), this._getOnPemiseProjectTypeLabelPrompt(), this._getCloudProjectTypeLabelPrompt(), this._getNotFlexAndNotDeployableSystemLabelPrompt(), this._getNotFlexEnabledSystemLabelPrompt(), this._getNotDeployableSystemLabelPrompt(), this._getApplicationPrompt(), this._getAdpOverAdpInfoPrompt(), this._getAdpOverAdpPartialSupportInfoPrompt(), this._getApplicationInfoPrompt(), this._getApplicationV4InfoPrompt(), this._getFioriIdPrompt(), this._getACHprompt(), this.getApplicationInfoErrorPrompt(), this.getConfirmExtProjCreationPrompt() ]; }); } _getUsernamePrompt() { return { type: types_1.PromptType.INPUT, name: "username", message: adp_common_1.Messages.USERNAME_PROMPT_LABEL, validate: (value) => __awaiter(this, void 0, void 0, function* () { if (!value) { return adp_common_1.Messages.INPUT_CANNOT_BE_EMPTY_ERROR(adp_common_1.Messages.USERNAME); } return true; }), when: (answers) => { if (answers.system) { return this.hasSystemAuthentication; } else { return false; } }, guiOptions: { mandatory: true }, store: false }; } _getPasswordPrompt() { return { type: types_1.PromptType.PASSWORD, guiType: "login", name: "password", message: adp_common_1.Messages.PASSWORD_PROMPT_LABEL, mask: "*", validate: (value, answers) => __awaiter(this, void 0, void 0, function* () { if (!value) { return adp_common_1.Messages.INPUT_CANNOT_BE_EMPTY_ERROR(adp_common_1.Messages.PASSWORD); } //answers.password not set yet, use "value" instead try { yield this.abapService.connectToSystem(answers.system, answers.client, answers.username, value); yield this._getSystemData(); if (this.isInternalUsage && this.isCloudProject) { return adp_common_1.Messages.ERROR_CLOUD_SYSTEM_FOR_INTERNAL_USERS; } yield this._validateSystemVersion(answers.system); this.isLoginSuccessfull = true; return true; } catch (e) { this.flexUISystem = undefined;