UNPKG

@sap/generator-fiori

Version:

Create an SAPUI5 application using SAP Fiori elements or a freestyle approach

1 lines 37.3 kB
"use strict";exports.id=3688,exports.ids=[3688],exports.modules={15034(e,a,i){i.d(a,{sm:()=>ae,WJ:()=>x,jn:()=>MtaConfig,ns:()=>generateAppConfig,vJ:()=>generateBaseConfig,m8:()=>generateCAPConfig,dF:()=>useAbapDirectServiceBinding});var n=i(76760),s=i(57975),r=i(73024),o=i(87827),d=i(76178),p=i(1083),c=i(7083),u=i(2307),l=i(68801);const m=JSON.parse('{"debug":{"logError":"{{method}} error found: {{ error }}","mtaLoaded":"MTA {{ type }} loaded. The size is: {{ size }}.","ui5YamlDoesNotExist":"The `ui5.yaml` file does not exist in the project. Create one. Returned error: {{- error }}","capMtaCreated":"CAP MTA configuration created.","capMtaUpdated":"CAP MTA configuration updated.","capGenerationCompleted":"CAP generation completed.","mtaCreated":"The MTA configuration has been created: {{- mtaPath}}.","mtaSaved":"The MTA configuration has been saved.","mtaSavedFailed":"Saving the MTA configuration failed with the error: {{- error }}.","addingRouter":"Adding {{routerType}} app router...","addMissingModules":"Adding missing modules to MTA configuration...","cleanupModules":"Cleanup modules.","creatingMta":"Creating MTA using {{- cdsParams }}...","html5AppAdded":"HTML5 application added to MTA configuration: {{- appName}}","html5AlreadyExists":"HTML5 application {{- appName}} already exists in the MTA configuration.","addXsuaaService":"Adding XSUAA service to MTA configuration.","mtaReadWithPrefix":"Read `mta.yaml` with prefix {{- prefix }}.","errorReadingMta":"An error occurred when reading the `mta.yaml` file: {{- error }}. Please check the file.","unableToReadPackageJson":"Unable to read the `package.json` file: {{- error }}.","processHTML5App":"Processing HTML5 app: {{- appName }}."},"error":{"unableToLoadMTA":"Unable to load the `mta.yaml` configuration: {{- mtaDir }}. Returned error: {{- error }}.","updatingMTAExtensionFailed":"Unable to add the MTA extension configuration to the file: {{mtaExtFilePath}}.","cannotFindBinary":"Cannot find the \\"{{bin}}\\" executable. Please add it to the path or use \\"npm i -g {{- pkg}}\\" to install it.","mtaExtensionFailed":"Unable to create or update the MTA extension file for the API Hub Enterprise destination configuration: {{error}}.","serviceKeyFailed":"Failed to fetch the service key.","missingMtaParameters":"Missing required parameters, MTA Path, MTA ID, or the Router type is missing.","invalidMtaIdWithChars":"The MTA ID can only contain letters, numbers, dashes, periods, and underscores.","invalidMtaId":"The MTA ID must start with a letter or underscore and be less than 128 characters.","missingABAPServiceBindingDetails":"Missing ABAP service details for direct service binding.","mtaFolderAlreadyExists":"A folder with same name already exists in the target directory.","mtaAlreadyExists":"An `mta.yaml` file already exists in the target directory.","cannotUpdateRouterXSApp":"Unable to update the router `xs-app.json` welcome location.","targetFolderDoesNotExist":"The target folder does not exist: {{targetFolder}}. Check the folder has the correct permissions.","doesNotContainACapApp":"The target folder does not contain a Node.js CAP project. Please ensure the folder contains a Node.js CAP project.","errorInstallingNodeModules":"An error occurred when installing node modules. Please check the logs.","errorGeneratingMtaYaml":"An error occurred when creating the mta.yaml file. For more information, check the logs.","noUI5AppFound":"No SAPUI5 application found. Please ensure the manifest.json file contains a valid \'sap.app.id\'.","mtaFileNotReady":"The `mta.yaml` file in \'{{- mtaPath}}\' was not ready within the allowed time. Please check the file system and retry."},"info":{"existingMTAExtensionNotFound":"Cannot find a valid existing MTA extension file. A new one will be created. Error: {{- error}}.","existingDestinationNotFound":"A destination service resource cannot be found in the `mta.yaml` file. An MTA extension destination instance cannot be added.","mtaExtensionCreated":"Created file: {{mtaExtFile}} to extend the MTA module: {{appMtaId}} with the destination configuration.","mtaExtensionUpdated":"Updated file: {{mtaExtFile}} with the module destination configuration."}}'),h="cf-deploy-config-writer",g=l.createInstance();function t(e,a){return g.t(e,a)}(async function initI18n(){await g.init({resources:{en:{[h]:m}},lng:"en",fallbackLng:"en",defaultNS:h,ns:[h],showSupportNotice:!1})})().catch(()=>{});const f="welcomeFile",y="build-result",w="build-parameters",v="managed:xsuaa",A="managed:app-front",M="html5-apps-repo:app-host",P="srv-api",x="fiori-default-srv-api",b="NONE",T="Generated by Fiori Tools",S="router",R="cds",C="@sap/cds-dk",I="@sap/cds",N="0.0.1",D="^5.0.5",E="rimraf",F="mbt",$="^1.2.49",H=/^(5750|6338)$/.test(i.j)?null:["add","mta"],j={Name:P,Type:"HTTP",URL:"~{srv-api/srv-url}",ProxyType:"Internet",Authentication:"NoAuthentication","HTML5.DynamicDestination":!0,"HTML5.ForwardAuthToken":!0},k={Name:"ui5",Type:"HTTP",URL:u.e_.SAPUI5_CDN,ProxyType:"Internet",Authentication:"NoAuthentication"},U={name:"ui5",url:u.e_.SAPUI5_CDN},L={name:P,url:"~{srv-api/srv-url}",forwardAuthToken:!0},_={init_data:{instance:{existing_destinations_policy:"update",destinations:[{Name:"ui5",Type:"HTTP",URL:u.e_.SAPUI5_CDN,ProxyType:"Internet",Authentication:"NoAuthentication"}]}}},q={group:"destinations",properties:{forwardAuthToken:!1,name:"ui5",url:u.e_.SAPUI5_CDN}},B={HTML5Runtime_enabled:!0,version:"1.0.0",..._},O={name:P,properties:{"srv-url":"${default-url}"}},J={builder:"custom","build-result":"dist",commands:["npm install","npm run build:cf"],"supported-platforms":[]},Y="npm run build:cf",X="ui5 build preload --clean-dest --config ui5-deploy.yaml --include-task=generateCachebusterInfo",z="rimraf resources mta_archives && mbt build",undeployMTAScript=e=>`cf undeploy ${e} --delete-services --delete-service-keys --delete-service-brokers`,cannotFindBinary=(e,a)=>t("error.cannotFindBinary",{bin:e,pkg:a}),G=cannotFindBinary(R,C),V=cannotFindBinary("mta","mta"),W=128,K=100;var Z;!function(e){e.Existing="org.cloudfoundry.existing-service",e.Managed="org.cloudfoundry.managed-service"}(Z||(Z={}));const Q="standard",ee="managed",te="appFront";var ae;!function(e){e.apiHub="API_HUB",e.apiHubEnterprise="API_HUB_ENTERPRISE"}(ae||(ae={}));var ie=i(29473),ne=i(85263),se=i(28470),re=i(73136);function readManifest(e,a){return a.readJSON(e)}function getTemplatePath(e){return(0,n.join)((0,n.dirname)((0,re.fileURLToPath)(require("node:url").pathToFileURL(__filename).href)),"../templates",e)}function toMtaModuleName(e){return e.replaceAll(/[`~!@#$%^&*£()|+=?;:'",.<>]/gi,"")}async function getDestinationProperties(e,a={}){let i,n=!1;if((0,d.isAppStudio)()&&e){const s=await async function getBTPDestinations(e={}){return e.list??=await(0,d.listDestinations)({stripS4HCApiHosts:!0}),e.list}(a);s[e]&&(n=(0,d.isFullUrlDestination)(s[e]),i=s[e].Authentication)}return{destinationIsFullUrl:n,destinationAuthentication:i}}function addXSSecurityConfig({mtaPath:e,mtaId:a},i,s=!0){i.copyTpl(getTemplatePath(`common/${c.o3.XSSecurityJson}`),(0,n.join)(e,c.o3.XSSecurityJson),{id:a.slice(0,K),addTenant:s})}async function generateSupportingConfig(e,a,i=!0){e.mtaId&&!a.exists((0,n.join)(e.mtaPath,"package.json"))&&function addRootPackage({mtaPath:e,mtaId:a},i){i.copyTpl(getTemplatePath(c.o3.Package),(0,n.join)(e,c.o3.Package),{mtaId:a})}(e,a),e.mtaId&&!a.exists((0,n.join)(e.mtaPath,c.o3.XSSecurityJson))&&addXSSecurityConfig(e,a,i),a.exists((0,n.join)(e.mtaPath,".gitignore"))||function addGitIgnore(e,a){a.copyTpl(getTemplatePath("gitignore.tmpl"),(0,n.join)(e,c.o3.DotGitIgnore),{})}(e.mtaPath,a)}async function updateRootPackage({mtaId:e,rootPath:a},i){if(fileExists(i,(0,n.join)(a,c.o3.Package))){await async function alignCdsVersions(e,a){const i=(0,n.join)(e,c.o3.Package),s=a.readJSON(i)??{},r=(0,ne.coerce)(s?.devDependencies?.[C]),o=s?.dependencies?.[I];!r&&o&&await(0,c.u1)(e,C,o,a)}(a,i),await(0,c.u1)(a,E,D,i),await(0,c.u1)(a,"mbt",$,i);let r=[];i?.exists((0,n.join)(a,c.o3.MtaExtYaml))&&(r=["-e",c.o3.MtaExtYaml]);for(const n of[{name:"undeploy",run:undeployMTAScript(e)},{name:"build",run:`${z} --mtar archive`},{name:"deploy",run:(s=r,`cf deploy mta_archives/archive.mtar ${s.length>0?`${s.join(" ")} `:""}--retries 1`)}])await(0,c.Hg)(a,n.name,n.run,i)}var s}function fileExists(e,a){return e.exists(a)}function renderTemplateToDisk(e,a,i){const n=(0,r.readFileSync)(getTemplatePath(e),"utf-8");(0,r.writeFileSync)(a,(0,ie.render)(n,i))}class MtaConfig{mta;apps=new Map;modules=new Map;resources=new Map;log;mtaDir;dirty=!1;mtaId;static async newInstance(e,a){return new MtaConfig(e,a).init()}constructor(e,a){this.mta=new o.dx(e,!1),this.log=a,this.mtaDir=e}async init(){try{await this.loadMTAResources(),await this.loadMTAModules(),this.mtaId=await(this.mta?.getMtaID())}catch(e){this.log?.error(t("error.unableToLoadMTA",{error:e,mtaDir:this.mtaDir}))}return this}targetExists(e,a){return e&&-1!==e.findIndex(e=>!0===e.parameters?.["content-target"]&&this.resources.get(a)?.name===e.name)}async loadMTAResources(){(await this.mta.getResources()||[]).forEach(e=>{e.parameters?.service&&("html5-apps-repo"===e.parameters?.service?this.resources.set("app-host"===e.parameters["service-plan"]?M:"html5-apps-repo:app-runtime",e):"xsuaa"===e.parameters?.service?this.resources.set(v,e):"app-front"===e.parameters?.service?this.resources.set(A,e):e.type===Z.Existing?this.resources.set(e.name,e):this.resources.set(e.parameters.service,e))}),this.log?.debug(t("debug.mtaLoaded",{type:"resources",size:this.resources.size}))}async loadMTAModules(){(await(this.mta?.getModules())||[]).forEach(e=>{e.type&&("html5"===e.type?this.apps.set(e.name,e):this.targetExists(e.requires??[],"destination")?this.modules.set("com.sap.application.content:destination",e):this.targetExists(e.requires??[],M)?this.modules.set("com.sap.application.content:resource",e):this.targetExists(e.requires??[],A)?this.modules.set("com.sap.application.content:appfront",e):this.modules.set(e.type,e))}),this.log?.debug(t("debug.mtaLoaded",{type:"modules",size:this.modules.size}))}async addAppContent(){this.resources.has(M)||await this.addHtml5Host();const e=this.resources.get(M)?.name;if(e){const a={name:`${this.prefix?.slice(0,K)}-app-content`,type:"com.sap.application.content",path:".",requires:[{name:e,parameters:{"content-target":!0}}],"build-parameters":{"build-result":"resources",requires:[]}};await(this.mta?.addModule(a)),this.modules.set("com.sap.application.content:resource",a),this.dirty=!0}}async addUaa(){const e={name:`${this.prefix?.slice(0,K)}-uaa`,type:"org.cloudfoundry.managed-service",parameters:{service:"xsuaa","service-plan":"application",path:"./xs-security.json","service-name":`${this.prefix?.slice(0,K)}-xsuaa-service`,config:{xsappname:`${this.prefix?.slice(0,K)}-\${space-guid}`,"tenant-mode":"dedicated"}}};await(this.mta?.addResource(e)),this.resources.set("xsuaa",e),this.dirty=!0}async addHtml5Runtime(){const e={name:`${this.prefix?.slice(0,K)}-html5-repo-runtime`,type:"org.cloudfoundry.managed-service",parameters:{"service-plan":"app-runtime",service:"html5-apps-repo"}};await(this.mta?.addResource(e)),this.resources.set("html5-apps-repo:app-runtime",e),this.dirty=!0}async updateServiceName(e,a){const i=this.resources.get(a);i&&!i.parameters?.["service-name"]&&(i.parameters={...i.parameters??{},"service-name":`${this.prefix?.slice(0,K)}-${e}-service`},await(this.mta?.updateResource(i)),this.resources.set(a,i),this.dirty=!0)}getServiceInstanceName(e){const a=this.resources.get(e),i=a?.parameters?.["service-name"];return i||a?.name}async addAppFrontResource(){const e={name:`${this.prefix?.slice(0,94)}-app-front`,type:"org.cloudfoundry.managed-service",parameters:{service:"app-front","service-name":`${this.prefix?.slice(0,96)}-app-front-service`,"service-plan":"developer"}};await(this.mta?.addResource(e)),this.resources.set(A,e),this.dirty=!0}async addHtml5Host(){const e={name:`${this.prefix?.slice(0,K)}-repo-host`,type:"org.cloudfoundry.managed-service",parameters:{"service-name":`${this.prefix?.slice(0,K)}-html5-service`,"service-plan":"app-host",service:"html5-apps-repo"}};await(this.mta?.addResource(e)),this.resources.set(M,e),this.dirty=!0}async addDestinationResource(e=!1){const a=`${this.prefix?.slice(0,K)}-destination-service`,i={name:a,type:"org.cloudfoundry.managed-service",parameters:{service:"destination","service-name":a,"service-plan":"lite",config:{...B,HTML5Runtime_enabled:e}}};await(this.mta?.addResource(i)),this.resources.set("destination",i),this.dirty=!0}async updateDestinationResource(e=!1){const a=this.resources.get("destination");a&&(a.parameters={...a.parameters??{},config:{...a.parameters?.config??{},HTML5Runtime_enabled:e}},a.parameters?.config?.init_data?.instance?.destinations||(a.parameters.config={...a.parameters.config,..._}),a.parameters?.config?.init_data?.instance?.destinations?.some(e=>e.Name===k.Name)||a.parameters.config.init_data.instance.destinations.push(k),await(this.mta?.updateResource(a)),this.resources.set("destination",a),this.dirty=!0)}async updateServerModule(e,a=v,i=!0){const n=this.resources.get(a),s=this.modules.get(e);s&&(i&&!s.provides?.some(e=>e.name===P)&&(s.provides=[...s.provides??[],O]),n&&!s.requires?.some(e=>e.name===n.name)&&(s.requires=[...s.requires??[],{name:n.name}]),await(this.mta?.updateModule(s)),this.modules.set(e,s),this.dirty=!0)}async addManagedUAAWithSecurity(){this.log?.debug(t("debug.addXsuaaService"));const e={name:`${this.prefix?.slice(0,K)}-uaa`,type:"org.cloudfoundry.managed-service",parameters:{path:"./xs-security.json",service:"xsuaa","service-name":`${this.prefix?.slice(0,K)}-xsuaa-service`,"service-plan":"application",...this.modules.has("nodejs")&&this.modules.has("com.sap.application.content:appfront")?{config:{xsappname:`${this.prefix?.slice(0,K)}-\${org}-\${space}`,"tenant-mode":"dedicated"}}:{}}};await(this.mta?.addResource(e)),this.resources.set(v,e),this.dirty=!0}isODataDestination(e){return(0,d.isGenericODataDestination)(e)||(0,d.isAbapEnvironmentOnBtp)(e)}async cleanupMissingResources(){this.log?.debug(t("debug.addMissingModules")),this.modules.has("com.sap.application.content:appfront")||(this.modules.has("com.sap.application.content:resource")||await this.addAppContent(),this.resources.get("destination")?await this.updateDestinationResource(this.modules.has("com.sap.application.content:destination")):await this.addDestinationResource(this.modules.has("com.sap.application.content:destination")))}async cleanupModules(){this.log?.debug(t("debug.cleanupModules"));for(const e of[this.modules.get("com.sap.application.content:destination"),this.modules.get("approuter.nodejs")].filter(e=>void 0!==e)){const a=this.resources.get("destination")?.name??`${this.prefix?.slice(0,K)}-destination-service`;-1===e?.requires?.findIndex(e=>e.name===a)&&("approuter.nodejs"===e.type&&e.requires.push({name:a,...q}),"com.sap.application.content"===e.type&&e.requires.push({name:a,parameters:{"content-target":!0}}),await(this.mta?.updateModule(e)),this.dirty=!0)}}get prefix(){return this.mtaId}get standaloneRouterPath(){return this.modules.get("approuter.nodejs")?.path}get cloudServiceName(){let e;return this.modules.forEach(a=>{const i=a.parameters?.content?.instance?.destinations??[];"com.sap.application.content"===a.type&&i.length&&i.some(a=>(e=a["sap.cloud.service"],!!e))}),e}hasAppFrontendRouter(){return this.modules.has("com.sap.application.content:appfront")}async getParameters(){return this.mta.getParameters()}async getBuildParameters(){return this.mta.getBuildParameters()}async updateParameters(e){await(this.mta?.updateParameters(e)),this.dirty=!0}async updateBuildParams(e){await(this.mta?.updateBuildParameters(e)),this.dirty=!0}async addApp(e,a){const i=this.getAppContentModule();let n=!1;if(i){i[w]=i[w]??{},i[w][y]=i[w]?.[y]??"resources",i[w].requires=i[w].requires??[];const a=`${e}.zip`;-1!==i[w].requires?.findIndex(e=>e.artifacts?.includes?.(a))?(this.log?.debug(t("debug.html5AlreadyExists",{appName:e})),n=!0):i[w].requires.push({name:e.slice(0,W),artifacts:[a],"target-path":`${i[w][y]}/`.replace(/\/{2,}/g,"/")}),await(this.mta?.updateModule(i)),this.dirty=!0}if(!n&&!this.apps.get(e)){const i={name:e.slice(0,W),type:"html5",path:a,"build-parameters":J};await(this.mta?.addModule(i)),this.apps.set(e,i),this.dirty=!0,this.log?.debug(t("debug.html5AppAdded",{appName:e}))}await this.syncHtml5Apps(),await this.addMtaDeployParameters()}async syncHtml5Apps(){for(const[e,a]of this.apps.entries())if("html5"===a.type&&a.path&&a["build-parameters"]){this.log?.debug(t("debug.processHTML5App",{appName:e}));try{const e=JSON.parse((0,r.readFileSync)((0,n.join)(this.mtaDir,a.path,c.o3.Package),"utf8"));e&&(0,c.ws)(e,"@sap/ux-ui5-tooling")&&(a["build-parameters"].commands=["npm install","npm run build:cf"],await(this.mta?.updateModule(a)),this.dirty=!0)}catch(e){this.log?.debug(t("debug.unableToReadPackageJson",{error:e}))}}}async addConnectivityResource(){const e="connectivity",a=Z.Managed,i=`${this.prefix?.slice(0,K)}-connectivity`,n=this.modules.get("approuter.nodejs");n&&-1===n.requires?.findIndex(e=>e.name===i)&&(n.requires.push({name:i}),await(this.mta?.updateModule(n)));const s={name:i,type:a,parameters:{service:e,"service-plan":"lite"}};this.resources.has(e)||(await(this.mta?.addResource(s)),this.resources.set(e,s)),this.dirty=!0}async addRouterType({routerType:e,addMissingModules:a=!0}={}){e===Q&&await this.addStandaloneRouter(!0),e===ee&&await this.addManagedAppRouter(),e===te&&await this.addAppFrontAppRouter(),e!==te&&(a&&await this.cleanupMissingResources(),await this.cleanupModules()),await this.addMtaDeployParameters()}async addRoutingModules({isManagedApp:e=!1,isAppFrontApp:a=!1,addMissingModules:i=!0}={}){e&&await this.addManagedAppRouter(),a&&await this.addAppFrontAppRouter(),i&&await this.cleanupMissingResources(),await this.cleanupModules()}async addAbapService(e,a){const i=`${this.prefix?.slice(0,24)}-abap-${e.slice(0,20)}`,n=this.modules.get("approuter.nodejs");n&&-1===n.requires?.findIndex(e=>e.name===i)&&(n.requires.push({name:i}),await(this.mta?.updateModule(n)));const s={name:i,type:Z.Existing,parameters:{"service-name":e,protocol:["ODataV2"],service:a,"service-plan":"16_abap_64_db"}};this.resources.has(i)||(await(this.mta?.addResource(s)),this.resources.set(i,s)),this.dirty=!0}get isABAPServiceFound(){let e=!1;const a=Array.from(this.resources.keys());for(const i of a)if(i.includes(`${this.prefix}-abap-`)){e=!0;break}return e}async addStandaloneRouter(e=!1){this.log?.debug(t("debug.addingRouter",{routerType:Q})),this.resources.has("xsuaa")||await this.addUaa(),this.resources.has("html5-apps-repo:app-runtime")||await this.addHtml5Runtime(),this.resources.has("destination")||await this.addDestinationResource();const a=this.resources.get("html5-apps-repo:app-runtime")?.name,i=this.resources.get("xsuaa")?.name,n=this.resources.get("destination")?.name;if(n&&i&&a){const s={name:`${this.prefix?.slice(0,K)}-router`,type:"approuter.nodejs",path:e?`${S}`:`cf/${S}`,parameters:{"disk-quota":"256M",memory:"256M"},requires:[{name:a},{name:i},{name:n,group:"destinations",properties:{name:"ui5",url:"https://ui5.sap.com",forwardAuthToken:!1}}]};await(this.mta?.addModule(s)),this.modules.set("approuter.nodejs",s),this.dirty=!0}}hasManagedXsuaaResource(){return this.resources.has(v)}hasResource(e){return this.resources.has(e)}async addMtaExtensionConfig(e,a,i){let s=this.resources.get("destination")?.name;s||(this.log?.info(t("info.existingDestinationNotFound")),s=`${this.prefix?.slice(0,K)}-destination-service`);const o=this.mtaId,d=(0,n.join)(this.mta.mtaDirPath,c.o3.MtaExtYaml);let u;try{const e=(0,r.readFileSync)(d,"utf-8");u=await p.Jz.newInstance(e)}catch(e){this.log?.info(t("info.existingMTAExtensionNotFound",{error:e.message}))}if(u){const n=u.getSequence({path:"resources"}).items.findIndex(e=>e.get("name")===s);if(n>-1){const s={Authentication:"NoAuthentication",Name:e,ProxyType:"Internet",Type:"HTTP",URL:a,[`URL.headers.${i.key}`]:i.value};u.appendTo({path:`resources.${n}.parameters.config.init_data.instance.destinations`,value:s}),(0,r.writeFileSync)(d,u.toString()),this.log?.info(t("info.mtaExtensionUpdated",{mtaExtFile:c.o3.MtaExtYaml}))}else this.log?.error(t("error.updatingMTAExtensionFailed",{mtaExtFilePath:d}))}else{const n={appMtaId:o,mtaExtensionId:`${o}-ext`,destinationName:e,destinationUrl:a,headerKey:i.key,headerValue:i.value,destinationServiceName:s,mtaVersion:"1.0.0"};renderTemplateToDisk(`app/${c.o3.MtaExtYaml}`,d,n),this.log?.info(t("info.mtaExtensionCreated",{appMtaId:o,mtaExtFile:c.o3.MtaExtYaml}))}}async addDestinationToAppRouter(e){this.hasAppFrontendRouter()?await this.appendAppfrontCAPDestination(e):await this.appendInstanceBasedDestination(e)}async appendAppfrontCAPDestination(e){const a=this.modules.get("com.sap.application.content:appfront");if(a){const i=e===x?P:e;if(!a.parameters?.config?.destinations?.some(e=>e.Name===i)){const e={...L,name:i};a.parameters?.config?.destinations.push(e),await(this.mta?.updateModule(a))}}}async appendInstanceBasedDestination(e){const a=this.resources.get("destination"),i=e===x?P:e;if(a){a.requires?.some(e=>e.name===P)||(a.requires=[...a.requires??[],{name:P}]);e===P&&a.parameters?.config?.init_data?.instance?.destinations?.some(e=>e.Name===P)||a.parameters?.config?.init_data?.instance?.destinations?.some(e=>e.Name===i)||a.parameters?.config?.init_data?.instance?.destinations?.push({...j,Name:i}),await(this.mta?.updateResource(a)),this.resources.set("destination",a),await this.updateServerModule(this.modules.has("nodejs")?"nodejs":"java"),this.dirty=!0}}async save(){return this.dirty&&await(this.mta?.save()),this.dirty}async addAppFrontAppRouter(){if(this.resources.has(v)||await this.addManagedUAAWithSecurity(),await this.updateServiceName("xsuaa",v),this.resources.has(A)||await this.addAppFrontResource(),!this.modules.has("com.sap.application.content:appfront")){this.log?.debug(t("debug.addingRouter",{routerType:te}));const e=this.resources.get(A)?.name;if(e){const a={name:`${this.prefix?.slice(0,K)}-app-content`,type:"com.sap.application.content",path:".",requires:[{name:e,parameters:{"content-target":!0}}],parameters:{config:{destinations:[U]}}};this.modules.has("nodejs")&&a.requires?.push({name:P}),await(this.mta?.addModule(a)),this.modules.set("com.sap.application.content:appfront",a),this.dirty=!0}}await this.updateServerModule("com.sap.application.content:appfront",v,!1),await this.updateServerModule("nodejs",v,!1)}async addManagedAppRouter(){if(this.resources.has("destination")||await this.addDestinationResource(!0),this.resources.has(v)||await this.addManagedUAAWithSecurity(),this.resources.has(M)||await this.addHtml5Host(),!this.modules.has("com.sap.application.content:destination")){this.log?.debug(t("debug.addingRouter",{routerType:ee}));const e=this.resources.get("destination")?.name,a=this.resources.get(M)?.name,i=this.resources.get(v)?.name;if(e&&a&&i){await this.updateServiceName("html5",M),await this.updateServiceName("xsuaa",v);const n=this.getServiceInstanceName(M),s=this.getServiceInstanceName(v),r={name:`${this.prefix?.slice(0,K)}-destination-content`,type:"com.sap.application.content",requires:[{name:e,parameters:{"content-target":!0}},{name:a,parameters:{"service-key":{name:`${a}-key`}}},{name:i,parameters:{"service-key":{name:`${i}-key`}}}],parameters:{content:{instance:{destinations:[{Name:`${this.prefix?.slice(0,K)}_html_repo_host`,ServiceInstanceName:n,ServiceKeyName:`${a}-key`,"sap.cloud.service":`${this.prefix?.slice(0,K)}`},{Authentication:"OAuth2UserTokenExchange",Name:`${this.prefix?.slice(0,K)}_uaa`,ServiceInstanceName:s,ServiceKeyName:`${i}-key`,"sap.cloud.service":`${this.prefix?.slice(0,K)}`}],existing_destinations_policy:"update"}}},"build-parameters":{"no-source":!0}};await(this.mta?.addModule(r)),this.modules.set("com.sap.application.content:destination",r),this.dirty=!0}}}getExposedDestinations(e=!1){const a=[],i=this.resources.get("destination");i&&(i.parameters?.config?.init_data?.instance?.destinations?.forEach(i=>(!e||this.isODataDestination(i))&&a.push(i.Name)),i.parameters?.config?.init_data?.subaccount?.destinations?.forEach(i=>(!e||this.isODataDestination(i))&&a.push(i.Name)));const n=this.modules.get("com.sap.application.content:destination");return n&&n.parameters?.content?.instance?.destinations?.map(i=>(!e||this.isODataDestination(i))&&a.push(i.Name)),a}getFormattedPrefix(e){return(0,s.format)(e,this.prefix).replace(/[^\w-]/g,"_")}getAppContentModule(){return this.modules.get("com.sap.application.content:resource")??this.modules.get("com.sap.application.content:appfront")}async addMtaBuildParameters(){const e=await this.getBuildParameters()??{};e["before-all"]??=[],e["before-all"].push({builder:"custom",commands:["npm install"]}),await this.updateBuildParams(e)}async addMtaDeployParameters(){let e=await this.getParameters();e={...e??{}},e.deploy_mode="html5-repo",e["enable-parallel-deployments"]=!0,await this.updateParameters(e)}}async function useAbapDirectServiceBinding(e,a,i="",s){try{let r;if(a){const a=await(0,c.ez)(e);a&&(r=(0,n.dirname)(a.mtaPath))}else i&&(r=(0,n.dirname)(i));if(r){return(await MtaConfig.newInstance(r,s)).isABAPServiceFound}return!1}catch(e){return s?.debug(t("debug.logError",{error:e,method:"useAbapDirectServiceBinding"})),!1}}async function waitForMtaFile(e,a={}){const{maxWaitMs:i=5e3,pollIntervalMs:s=100}=a,d=(0,n.join)(e,c.o3.MtaYaml),p=Date.now()+i;for(;Date.now()<p;){if((0,r.existsSync)(d))try{const a=new o.dx(e,!1);if(await a.getMtaID())return}catch{}await new Promise(e=>setTimeout(e,s))}throw new Error(t("error.mtaFileNotReady",{mtaPath:e}))}var oe=i(19563);class LoggerHelper{static _logger=new oe.ToolsLogger({logPrefix:"@sap-ux/cf-deploy-config-writer"});static get logger(){return LoggerHelper._logger}static set logger(e){LoggerHelper._logger=e}}var de=i(44425),pe=i(14501);async function getMtaConfig(e){try{await waitForMtaFile(e)}catch{return void LoggerHelper.logger?.debug(t("debug.mtaReadWithPrefix",{prefix:void 0}))}const a=await MtaConfig.newInstance(e,LoggerHelper.logger);return LoggerHelper.logger?.debug(t("debug.mtaReadWithPrefix",{prefix:a?.prefix})),a}function createMTA(e){const a=`${e.mtaId.slice(0,W)}`;e.mtaId=a,renderTemplateToDisk(`app/${c.o3.MtaYaml}`,(0,n.join)(e.mtaPath,c.o3.MtaYaml),{id:a,mtaDescription:e.mtaDescription??T,mtaVersion:e.mtaVersion??N}),LoggerHelper.logger?.debug(t("debug.mtaCreated",{mtaPath:e.mtaPath}))}function doesMTABinaryExist(){if(!(0,de.sync)("mta"))throw new Error(V)}function validateMtaConfig(e){if(doesMTABinaryExist(),!e.routerType||!e.mtaId||!e.mtaPath)throw new Error(t("error.missingMtaParameters"));if(e.mtaId.length>W||!/^[a-zA-Z_]/.test(e.mtaId))throw new Error(t("error.invalidMtaId"));if(!/^[\w\-.]*$/.test(e.mtaId))throw new Error(t("error.invalidMtaIdWithChars"));if(function validateVersion(e){const a=(0,ne.coerce)(e);if(e&&!a||a&&!(0,ne.satisfies)(a,`>=${N}`))throw new Error("Invalid MTA version specified. Please use version 0.0.1 or higher.");return!0}(e.mtaVersion),e.abapServiceProvider&&(!e.abapServiceProvider.abapService||!e.abapServiceProvider.abapServiceName))throw new Error(t("error.missingABAPServiceBindingDetails"));!function setMtaDefaults(e){e.mtaPath=e.mtaPath.replace(/\/$/,""),e.addConnectivityService??=!1,e.mtaId=toMtaModuleName(e.mtaId)}(e)}async function addRoutingConfig(e,a){const i=await getMtaConfig(e.mtaPath);i&&(e.routerType===Q?await async function addStandaloneRouter(e,a,i){await a.addStandaloneRouter(!0),e.addConnectivityService&&await a.addConnectivityResource();const{abapServiceName:s,abapService:r}=e.abapServiceProvider??{};if(s&&r&&await a.addAbapService(s,r),i.copyTpl(getTemplatePath("router/package.json"),(0,n.join)(e.mtaPath,`${S}/${c.o3.Package}`)),s){let a;try{const e=await(0,pe.apiGetInstanceCredentials)(s);a=e?.credentials}catch{LoggerHelper.logger?.error(t("error.serviceKeyFailed"))}const r=a?.endpoints?Object.keys(a.endpoints):[""],o=a?a["sap.cloud.service"]:"";i.copyTpl(getTemplatePath("router/xs-app-abapservice.json"),(0,n.join)(e.mtaPath,`${S}/${c.o3.XSAppJson}`),{servicekeyService:o,servicekeyEndpoint:r[0]})}else i.copyTpl(getTemplatePath("router/xs-app-server.json"),(0,n.join)(e.mtaPath,`${S}/${c.o3.XSAppJson}`))}(e,i,a):await i.addRouterType({routerType:e.routerType,addMissingModules:!1}),await i.save(),LoggerHelper.logger?.debug(t("debug.capMtaUpdated")))}async function generateCAPMTA(e,a){if(e.routerType===te)await async function createCAPMTAAppFrontend(e,a){renderTemplateToDisk(`frontend/${c.o3.MtaYaml}`,(0,n.join)(e.mtaPath,c.o3.MtaYaml),{id:`${e.mtaId.slice(0,W)}`,mtaDescription:e.mtaDescription??T,mtaVersion:e.mtaVersion??N}),addXSSecurityConfig(e,a,!1),LoggerHelper.logger?.debug(t("debug.mtaCreated",{mtaPath:e.mtaPath}))}(e,a);else{const a=[...H,...["xsuaa","destination","html5-repo"]];LoggerHelper.logger?.debug(t("debug.creatingMta",{cdsParams:a.toString()})),await async function runCommand(e,a,i,n){const s=new se.qo;try{await s.run(a,i,{cwd:e})}catch(e){const a=e instanceof Error?e.message:String(e);throw new Error(`${n}: ${a}`)}}(e.mtaPath,R,a,t("error.errorGeneratingMtaYaml")),LoggerHelper.logger?.debug(t("debug.capMtaCreated"))}}var ce=i(64812),ue=i(90718);async function generateAppConfig(e,a,i){return a??=(0,ue.v)((0,ce.v)()),i&&(LoggerHelper.logger=i),doesMTABinaryExist(),await async function generateDeployConfig(e,a){LoggerHelper?.logger?.debug(`Generate HTML5 app deployment configuration with: \n ${JSON.stringify(e)}`);const i=await async function getUpdatedConfig(e,a){const i=e.lcapMode??!1,{rootPath:s,isCap:r,mtaId:o,mtaPath:d,hasRoot:p,capRoot:l}=await async function getProjectProperties(e){let a,i,s,r=!1;const o=await(0,c.ez)(e.appPath);o&&(i=(0,n.dirname)(o.mtaPath),s=await async function getMtaId(e){return(await getMtaConfig(e))?.prefix}(i));const d=o?.hasRoot??!1,p=await(0,c.JR)(e.appPath)??void 0;p?(!function doesCDSBinaryExist(){if(!(0,de.sync)(R))throw new Error(G)}(),r=!0,a=p):a=i??e.appPath;return{rootPath:a,isCap:r,mtaId:s,mtaPath:i,hasRoot:d,capRoot:p}}(e),{serviceHost:m,destination:h,firstServicePathSegmentUI5Config:g}=await async function processUI5Config(e,a){let i,n,s;try{const r=(await(0,c.Pd)(e,c.o3.Ui5Yaml,a)).findCustomMiddleware(u.bx);1===r?.configuration?.backend?.length&&(i=r?.configuration?.backend[0].destination,n=r?.configuration?.backend[0].url,s=r?.configuration?.backend[0].path)}catch(e){LoggerHelper.logger?.debug(t("debug.ui5YamlDoesNotExist",{error:e.message}))}return{destination:i,serviceHost:n,firstServicePathSegmentUI5Config:s}}(e.appPath,a),{servicePath:f,firstServicePathSegment:y,appId:w}=await async function processManifest(e,a){const i=await(0,c.vv)(e),s=readManifest((0,n.join)(i,c.o3.Manifest),a),r=s?.["sap.app"]?.id?function mta_config_toMtaModuleName(e){return toMtaModuleName(e).slice(0,W)}(s["sap.app"].id):void 0,o=s?.["sap.app"]?.dataSources?.mainService?.uri,d=o?.substring(0,o.indexOf("/",1));return{servicePath:o,firstServicePathSegment:d,appId:r}}(e.appPath,a);if(!w)throw new Error(t("error.noUI5AppFound"));const{destinationIsFullUrl:v,destinationAuthentication:A}=await getDestinationProperties(e.destinationName??h);!function enforceValidRouterConfig(e){const{addManagedAppRouter:a,addAppFrontendRouter:i}=e;a?e.addAppFrontendRouter=!1:i?e.addManagedAppRouter=!1:(e.addManagedAppRouter??=!0,e.addAppFrontendRouter??=!1)}(e);const M={appPath:e.appPath.replace(/\/$/,""),destinationName:e.destinationName??h,addManagedAppRouter:e.addManagedAppRouter,addAppFrontendRouter:e.addAppFrontendRouter,addMtaDestination:e.addMtaDestination??!1,cloudServiceName:e.cloudServiceName,lcapMode:!!r&&i,isMtaRoot:p??!1,serviceHost:e.serviceHost??m,rootPath:s.replace(/\/$/,""),destinationAuthentication:e.destinationAuthentication??A,isDestinationFullUrl:e.isDestinationFullUrl??v,apiHubConfig:e.apiHubConfig,firstServicePathSegment:g??y??"<apply-service-segment-path>",mtaId:o,mtaPath:d,isCap:r,servicePath:f,appId:w,capRoot:l};return M}(e,a);LoggerHelper?.logger?.debug(`Deployment configuration updated: \n ${JSON.stringify(i)}`),i.lcapMode||await async function generateMTAFile(e,a){e.mtaId||(e.isCap?await generateCAPMTA({...e,mtaPath:e.rootPath},a):createMTA({mtaId:e.appId,mtaPath:e.mtaPath??e.rootPath}),e.mtaId=e.appId,e.mtaPath=e.rootPath);await async function appendAppRouter(e,a){const i=await getMtaConfig(e.rootPath);if(i){await i.addRoutingModules({isManagedApp:e.addManagedAppRouter,isAppFrontApp:e.addAppFrontendRouter,addMissingModules:!e.addAppFrontendRouter});const s=e.appId,r=function toPosixPath(e){return(0,n.normalize)(e).split(/[\\/]/g).join(n.posix.sep)}((0,n.relative)(e.rootPath,e.appPath));await i.addApp(s,r??"."),(e.addMtaDestination&&e.isCap||e.destinationName===x)&&(e.destinationName=e.destinationName===x?P:e.destinationName,await i.addDestinationToAppRouter(e.destinationName),i.hasManagedXsuaaResource()||(e.destinationAuthentication=d.Authentication.NO_AUTHENTICATION)),function cleanupStandaloneRoutes({rootPath:e,appId:a},i,s){const r=i.standaloneRouterPath;if(r)try{const i=(0,n.join)(r,c.o3.XSAppJson),o=s.readJSON((0,n.join)(e,i));(o&&!o?.[f]||"/"===o?.[f])&&(o[f]=`/${a}`,s.writeJSON((0,n.join)(e,i),o))}catch(e){LoggerHelper.logger?.error(t("error.cannotUpdateRouterXSApp",{error:e}))}}(e,i,a),await async function saveMta(e,a){try{await a.save(),LoggerHelper.logger?.debug(t("debug.mtaSaved"))}catch(e){LoggerHelper.logger?.debug(t("debug.mtaSavedFailed",{error:e}))}if(e.apiHubConfig?.apiHubType===ae.apiHubEnterprise)try{await a.addMtaExtensionConfig(e.destinationName,e.serviceHost,{key:"ApiKey",value:e.apiHubConfig.apiHubKey})}catch(e){LoggerHelper.logger?.error(t("error.mtaExtensionFailed",{error:e}))}}(e,i),e.cloudServiceName=i.cloudServiceName,e.addAppFrontendRouter=i.hasAppFrontendRouter()}}(e,a),await generateSupportingConfig(e,a)}(i,a);await async function appendCloudFoundryConfigurations(e,a){const i=e.addAppFrontendRouter?"ias":"xsuaa",s={service:e.addAppFrontendRouter?"app-front":"html5-apps-repo-rt",authenticationType:i,addAppFrontendRoutes:e.addAppFrontendRouter??!1,...e.destinationName&&e.destinationName!==b?{destination:e.destinationName,servicePathSegment:`${e.firstServicePathSegment}${e.isDestinationFullUrl?"/.*":""}`,targetPath:`${e.isDestinationFullUrl?"":e.firstServicePathSegment}/$1`,authentication:e.destinationAuthentication===d.Authentication.NO_AUTHENTICATION?"none":i}:{}};a.copyTpl(getTemplatePath("app/xs-app-destination.json"),(0,n.join)(e.appPath,c.o3.XSAppJson),s),await async function generateUI5DeployConfig(e,a){const i=await(0,c.Pd)(e.appPath,c.o3.Ui5Yaml,a),s=!!i.findCustomMiddleware("ui5-tooling-transpile-task"),r=!!i.findCustomMiddleware("ui5-tooling-modules-task"),o=i.removeConfig("server"),d=await u.io.newInstance(o.toString());d.addComment({comment:" yaml-language-server: $schema=https://sap.github.io/ui5-tooling/schema/ui5.yaml.json",location:"beginning"}),d.setConfiguration({propertiesFileSourceEncoding:"UTF-8"}),d.addCloudFoundryDeployTask(e.appId,r,s),a.write((0,n.join)(e.appPath,c.o3.UI5DeployYaml),d.toString())}(e,a)}(i,a),await async function updateManifest(e,a){const i=await(0,c.vv)(e.appPath,a),s=readManifest((0,n.join)(i,c.o3.Manifest),a);if(s&&e.cloudServiceName){const r={...s["sap.cloud"],public:!0,service:e.cloudServiceName};a.extendJSON((0,n.join)(i,c.o3.Manifest),{"sap.cloud":r})}}(i,a),await async function updateHTML5AppPackage(e,a){let i=[];fileExists(a,(0,n.join)(e.appPath,c.o3.MtaExtYaml))&&(i=["-e",c.o3.MtaExtYaml]);await(0,c.Hg)(e.appPath,"build:cf",X,a),await async function addCommonPackageDependencies(e,a){await(0,c.u1)(e,"ui5-task-zipper","^3.4.x",a),await(0,c.u1)(e,"@ui5/cli","^4.0.33",a)}(e.appPath,a),e.isCap&&await(0,c.Hg)(e.appPath,"build",Y,a);e.mtaPath&&!e.isMtaRoot&&(await(0,c.Hg)(e.appPath,"build:mta",z,a),await(0,c.Hg)(e.appPath,"deploy",(s=i,"fiori cfDeploy"+(s.length>0?` ${s.join(" ")}`:"")),a),await(0,c.Hg)(e.appPath,"undeploy",undeployMTAScript(e.mtaId??e.appId),a),await(0,c.u1)(e.appPath,E,D,a),await(0,c.u1)(e.appPath,F,$,a));var s}(i,a),i.isMtaRoot&&await updateRootPackage({mtaId:i.mtaId??i.appId,rootPath:i.rootPath},a)}(e,a),a}async function generateBaseConfig(e,a,i){if(a??=(0,ue.v)((0,ce.v)()),i&&(LoggerHelper.logger=i),i?.debug(`Generate base configuration using: \n ${JSON.stringify(e)}`),validateMtaConfig(e),fileExists(a,(0,n.join)(e.mtaPath,e.mtaId)))throw new Error(t("error.mtaAlreadyExists"));return createMTA(e),await addRoutingConfig(e,a),await generateSupportingConfig(e,a),LoggerHelper.logger?.debug(`CF Config ${JSON.stringify(e,null,2)}`),a}async function generateCAPConfig(e,a,i){return a??=(0,ue.v)((0,ce.v)()),i&&(LoggerHelper.logger=i),i?.debug(`Generate CAP configuration using: \n ${JSON.stringify(e)}`),await async function validateConfig(e){if(validateMtaConfig(e),"CAPNodejs"!==await(0,c.il)(e.mtaPath))throw new Error(t("error.doesNotContainACapApp"));if(function isMTAFound(e){return(0,r.existsSync)((0,n.join)(e,c.o3.MtaYaml))}(e.mtaPath))throw new Error(t("error.mtaAlreadyExists"))}(e),await generateCAPMTA(e,a),await waitForMtaFile(e.mtaPath),await addRoutingConfig(e,a),await updateRootPackage({mtaId:e.mtaId,rootPath:e.mtaPath},a),LoggerHelper.logger?.debug(t("debug.capGenerationCompleted")),a}}};