diff --git a/.changeset/slimy-toes-win.md b/.changeset/slimy-toes-win.md new file mode 100644 index 00000000000..ccff2cea134 --- /dev/null +++ b/.changeset/slimy-toes-win.md @@ -0,0 +1,8 @@ +--- +'@sap-ux/backend-proxy-middleware-cf': patch +'@sap-ux/preview-middleware': patch +'@sap-ux/generator-adp': patch +'@sap-ux/adp-tooling': patch +--- + +feat: Enable Adaptation Editor for CF projects diff --git a/packages/adp-tooling/src/base/helper.ts b/packages/adp-tooling/src/base/helper.ts index 56ed4e99249..6b839260112 100644 --- a/packages/adp-tooling/src/base/helper.ts +++ b/packages/adp-tooling/src/base/helper.ts @@ -1,12 +1,13 @@ import type { Editor } from 'mem-fs-editor'; +import type { ReaderCollection } from '@ui5/fs'; import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { join, isAbsolute, relative, basename, dirname } from 'node:path'; import type { UI5Config } from '@sap-ux/ui5-config'; import type { InboundContent, Inbound } from '@sap-ux/axios-extension'; -import { getWebappPath, FileName, readUi5Yaml, type ManifestNamespace } from '@sap-ux/project-access'; +import { getWebappPath, FileName, readUi5Yaml, type ManifestNamespace, type Manifest } from '@sap-ux/project-access'; -import type { DescriptorVariant, AdpPreviewConfig } from '../types'; +import type { DescriptorVariant, AdpPreviewConfig, UI5YamlCustomTaskConfiguration } from '../types'; /** * Get the app descriptor variant. @@ -86,6 +87,57 @@ export function extractAdpConfig(ui5Conf: UI5Config): AdpPreviewConfig | undefin return customMiddleware?.configuration?.adp; } +/** + * Extracts the CF build task from the UI5 configuration. + * + * @param {UI5Config} ui5Conf - The UI5 configuration. + * @returns {UI5YamlCustomTaskConfiguration} The CF build task. + */ +export function extractCfBuildTask(ui5Conf: UI5Config): UI5YamlCustomTaskConfiguration { + const buildTask = + ui5Conf.findCustomTask('app-variant-bundler-build')?.configuration; + + if (!buildTask) { + throw new Error('No CF ADP project found'); + } + + return buildTask; +} + +/** + * Read the manifest from the local dist folder. + * + * @param {string} useLocal - The path to the dist folder. + * @returns {Manifest} The manifest. + */ +export function readLocalManifest(useLocal: string): Manifest { + const distPath = join(process.cwd(), useLocal); + const manifestPath = join(distPath, 'manifest.json'); + return JSON.parse(readFileSync(manifestPath, 'utf-8')) as Manifest; +} + +/** + * Load and parse the app variant descriptor. + * + * @param {ReaderCollection} rootProject - The root project. + * @returns {Promise} The parsed descriptor variant. + */ +export async function loadAppVariant(rootProject: ReaderCollection): Promise { + const appVariant = await rootProject.byPath('/manifest.appdescr_variant'); + if (!appVariant) { + throw new Error('ADP configured but no manifest.appdescr_variant found.'); + } + try { + const content = await appVariant.getString(); + if (!content || content.trim() === '') { + throw new Error('ADP configured but manifest.appdescr_variant file is empty.'); + } + return JSON.parse(content) as DescriptorVariant; + } catch (e) { + throw new Error(`Failed to parse manifest.appdescr_variant: ${e.message}`); + } +} + /** * Convenience wrapper that reads the ui5.yaml and directly returns the ADP preview configuration. * Throws if the configuration cannot be found. diff --git a/packages/adp-tooling/src/cf/app/discovery.ts b/packages/adp-tooling/src/cf/app/discovery.ts index e1e82b602fe..f2e867c9137 100644 --- a/packages/adp-tooling/src/cf/app/discovery.ts +++ b/packages/adp-tooling/src/cf/app/discovery.ts @@ -1,8 +1,11 @@ +import type AdmZip from 'adm-zip'; + import type { ToolsLogger } from '@sap-ux/logger'; import { t } from '../../i18n'; +import { extractXSApp } from '../utils'; import { getFDCApps } from '../services/api'; -import type { CfConfig, CFApp, ServiceKeys } from '../../types'; +import type { CfConfig, CFApp, ServiceKeys, XsApp } from '../../types'; /** * Get the app host ids. @@ -25,6 +28,73 @@ export function getAppHostIds(serviceKeys: ServiceKeys[]): string[] { return [...new Set(appHostIds)]; } +/** + * Extracts the backend URL from service key credentials. Iterates through all endpoint keys to find the first endpoint with a URL. + * + * @param {ServiceKeys[]} serviceKeys - The credentials from service keys. + * @returns {string | undefined} The backend URL or undefined if not found. + */ +export function getBackendUrlFromServiceKeys(serviceKeys: ServiceKeys[]): string | undefined { + if (!serviceKeys || serviceKeys.length === 0) { + return undefined; + } + + const endpoints = serviceKeys[0]?.credentials?.endpoints as Record | undefined; + if (endpoints && typeof endpoints === 'object' && endpoints !== null) { + for (const key in endpoints) { + if (Object.hasOwn(endpoints, key)) { + const endpoint = endpoints[key] as { url?: string } | undefined; + if (endpoint && typeof endpoint === 'object' && endpoint.url && typeof endpoint.url === 'string') { + return endpoint.url; + } + } + } + } + + return undefined; +} + +/** + * Extracts OAuth paths from xs-app.json routes that have a source property. + * These paths should receive OAuth Bearer tokens in the middleware. + * + * @param {AdmZip.IZipEntry[]} zipEntries - The zip entries containing xs-app.json. + * @returns {string[]} Array of path patterns (from route.source) that have a source property. + */ +export function getOAuthPathsFromXsApp(zipEntries: AdmZip.IZipEntry[]): string[] { + const xsApp: XsApp | undefined = extractXSApp(zipEntries); + if (!xsApp?.routes) { + return []; + } + + const pathsSet = new Set(); + for (const route of xsApp.routes) { + if (route.service === 'html5-apps-repo-rt' || !route.source) { + continue; + } + + let path = route.source; + // Remove leading ^ and trailing $ + path = path.replace(/^\^/, '').replace(/\$$/, ''); + // Remove capture groups like (.*) or $1 + path = path.replace(/\([^)]*\)/g, ''); + // Remove regex quantifiers + path = path.replace(/\$\d+/g, ''); + // Clean up any remaining regex characters at the end + path = path.replace(/\/?\*$/, ''); + // Normalize multiple consecutive slashes to single slash + while (path.includes('//')) { + path = path.replaceAll('//', '/'); + } + + if (path) { + pathsSet.add(path); + } + } + + return Array.from(pathsSet); +} + /** * Discover apps from FDC API based on credentials. * diff --git a/packages/adp-tooling/src/cf/services/api.ts b/packages/adp-tooling/src/cf/services/api.ts index df93f5c943f..759bc4403dc 100644 --- a/packages/adp-tooling/src/cf/services/api.ts +++ b/packages/adp-tooling/src/cf/services/api.ts @@ -315,7 +315,10 @@ async function getServiceInstance(params: GetServiceInstanceParams): Promise} The service instance keys. */ -async function getOrCreateServiceKeys(serviceInstance: ServiceInstance, logger: ToolsLogger): Promise { +export async function getOrCreateServiceKeys( + serviceInstance: ServiceInstance, + logger: ToolsLogger +): Promise { const serviceInstanceName = serviceInstance.name; try { const credentials = await getServiceKeys(serviceInstance.guid); diff --git a/packages/adp-tooling/src/preview/adp-preview.ts b/packages/adp-tooling/src/preview/adp-preview.ts index 3aca81fc500..77a9ec7b4c7 100644 --- a/packages/adp-tooling/src/preview/adp-preview.ts +++ b/packages/adp-tooling/src/preview/adp-preview.ts @@ -129,10 +129,14 @@ export class AdpPreview { /** * Fetch all required configurations from the backend and initialize all configurations. * - * @param descriptorVariant descriptor variant from the project - * @returns the UI5 flex layer for which editing is enabled + * @param {DescriptorVariant} descriptorVariant - Descriptor variant from the project. + * @returns {Promise} The UI5 flex layer for which editing is enabled. */ async init(descriptorVariant: DescriptorVariant): Promise { + if (this.config.useLocal) { + return this.initLocal(descriptorVariant); + } + this.descriptorVariantId = descriptorVariant.id; this.provider = await createAbapServiceProvider( this.config.target, @@ -152,11 +156,27 @@ export class AdpPreview { return descriptorVariant.layer; } + /** + * Initialize the preview for a local CF ADP project. + * + * @param descriptorVariant descriptor variant from the project + * @returns the UI5 flex layer for which editing is enabled + */ + private async initLocal(descriptorVariant: DescriptorVariant): Promise { + this.descriptorVariantId = descriptorVariant.id; + this.isCloud = false; + this.routesHandler = new RoutesHandler(this.project, this.util, {} as AbapServiceProvider, this.logger); + return descriptorVariant.layer; + } + /** * Synchronize local changes with the backend. * The descriptor is refreshed only if the global flag is set to true. */ async sync(): Promise { + if (this.config.useLocal) { + return; + } if (!global.__SAP_UX_MANIFEST_SYNC_REQUIRED__ && this.mergedDescriptor) { return; } diff --git a/packages/adp-tooling/src/preview/routes-handler.ts b/packages/adp-tooling/src/preview/routes-handler.ts index 90840ed22c9..46d228e44bb 100644 --- a/packages/adp-tooling/src/preview/routes-handler.ts +++ b/packages/adp-tooling/src/preview/routes-handler.ts @@ -47,6 +47,11 @@ type ControllerInfo = { controllerName: string }; * @description Handles API Routes */ export default class RoutesHandler { + /** + * Whether this is running in local mode (CF ADP without backend). + */ + private readonly isLocalMode: boolean; + /** * Constructor taking project as input. * @@ -60,7 +65,9 @@ export default class RoutesHandler { private readonly util: MiddlewareUtils, private readonly provider: AbapServiceProvider, private readonly logger: ToolsLogger - ) {} + ) { + this.isLocalMode = !provider || typeof provider.getLayeredRepository !== 'function'; + } /** * Reads files from workspace by given search pattern. @@ -288,6 +295,16 @@ export default class RoutesHandler { try { const isRunningInBAS = isAppStudio(); + if (this.isLocalMode) { + // In local mode (CF ADP), skip ManifestService as it requires ABAP backend + const apiResponse: AnnotationDataSourceResponse = { + isRunningInBAS, + annotationDataSourceMap: {} + }; + this.sendFilesResponse(res, apiResponse); + return; + } + const manifestService = await this.getManifestService(); const dataSources = manifestService.getManifestDataSources(); const apiResponse: AnnotationDataSourceResponse = { diff --git a/packages/adp-tooling/src/types.ts b/packages/adp-tooling/src/types.ts index 4391e4079ac..73691157db9 100644 --- a/packages/adp-tooling/src/types.ts +++ b/packages/adp-tooling/src/types.ts @@ -39,6 +39,10 @@ export interface AdpPreviewConfig { * If set to true then certification validation errors are ignored. */ ignoreCertErrors?: boolean; + /** + * For CF ADP projects: when set to 'dist', serve resources from local dist instead of backend merge. + */ + useLocal?: string; } export interface OnpremApp { @@ -884,6 +888,8 @@ export interface UI5YamlCustomTaskConfiguration { space: string; html5RepoRuntime: string; sapCloudService: string; + serviceInstanceName: string; + serviceInstanceGuid: string; } export interface UI5YamlCustomTask { @@ -1039,6 +1045,18 @@ export interface CfAdpWriterConfig { approuter: AppRouterType; businessService: string; businessSolutionName?: string; + /** + * GUID of the business service instance. + */ + serviceInstanceGuid?: string; + /** + * Backend URL from service instance keys. + */ + backendUrl?: string; + /** + * OAuth paths extracted from xs-app.json routes that have a source property. + */ + oauthPaths?: string[]; }; project: { name: string; @@ -1068,6 +1086,9 @@ export interface CreateCfConfigParams { layer: FlexLayer; manifest: Manifest; html5RepoRuntimeGuid: string; + serviceInstanceGuid?: string; + backendUrl?: string; + oauthPaths?: string[]; projectPath: string; addStandaloneApprouter?: boolean; publicVersions: UI5Version; @@ -1137,7 +1158,6 @@ export interface CFApp { messages?: string[]; serviceInstanceGuid?: string; } - /** * CF services (application sources) prompts */ diff --git a/packages/adp-tooling/src/writer/cf.ts b/packages/adp-tooling/src/writer/cf.ts index c5b8055e9a4..11e1eb689ac 100644 --- a/packages/adp-tooling/src/writer/cf.ts +++ b/packages/adp-tooling/src/writer/cf.ts @@ -7,7 +7,7 @@ import { adjustMtaYaml } from '../cf'; import { getApplicationType } from '../source'; import { fillDescriptorContent } from './manifest'; import type { CfAdpWriterConfig, Content } from '../types'; -import { getCfVariant, writeCfTemplates, writeCfUI5Yaml, writeCfUI5BuildYaml } from './project-utils'; +import { getCfVariant, writeCfTemplates, writeCfUI5Yaml } from './project-utils'; import { getI18nDescription, getI18nModels, writeI18nModels } from './i18n'; /** @@ -54,7 +54,6 @@ export async function generateCf( await writeCfTemplates(basePath, variant, fullConfig, fs); await writeCfUI5Yaml(fullConfig.project.folder, fullConfig, fs); - await writeCfUI5BuildYaml(fullConfig.project.folder, fullConfig, fs); return fs; } diff --git a/packages/adp-tooling/src/writer/options.ts b/packages/adp-tooling/src/writer/options.ts index a75cba2c1d1..2e46fbc5b06 100644 --- a/packages/adp-tooling/src/writer/options.ts +++ b/packages/adp-tooling/src/writer/options.ts @@ -365,7 +365,8 @@ export function enhanceUI5YamlWithCfCustomTask(ui5Config: UI5Config, config: CfA org: cf.org.GUID, space: cf.space.GUID, sapCloudService: cf.businessSolutionName ?? '', - serviceInstanceName: cf.businessService + serviceInstanceName: cf.businessService, + serviceInstanceGuid: cf.serviceInstanceGuid } } ]); @@ -375,19 +376,42 @@ export function enhanceUI5YamlWithCfCustomTask(ui5Config: UI5Config, config: CfA * Generate custom configuration required for the ui5.yaml. * * @param {UI5Config} ui5Config - Configuration representing the ui5.yaml. + * @param {CfAdpWriterConfig} config - Full project configuration. */ -export function enhanceUI5YamlWithCfCustomMiddleware(ui5Config: UI5Config): void { +export function enhanceUI5YamlWithCfCustomMiddleware(ui5Config: UI5Config, config: CfAdpWriterConfig): void { const ui5ConfigOptions: Partial = { url: UI5_CDN_URL }; - ui5Config.addFioriToolsProxyMiddleware( - { - ui5: ui5ConfigOptions, - backend: [] - }, - 'compression' - ); + const oauthPaths = config.cf?.oauthPaths; + const backendUrl = config.cf?.backendUrl; + if (oauthPaths && oauthPaths.length > 0 && backendUrl) { + ui5Config.addCustomMiddleware([ + { + name: 'backend-proxy-middleware-cf', + afterMiddleware: 'compression', + configuration: { + url: backendUrl, + paths: oauthPaths + } + } + ]); + ui5Config.addFioriToolsProxyMiddleware( + { + ui5: ui5ConfigOptions, + backend: [] + }, + 'backend-proxy-middleware-cf' + ); + } else { + ui5Config.addFioriToolsProxyMiddleware( + { + ui5: ui5ConfigOptions, + backend: [] + }, + 'compression' + ); + } ui5Config.addCustomMiddleware([ { name: 'fiori-tools-preview', @@ -395,6 +419,9 @@ export function enhanceUI5YamlWithCfCustomMiddleware(ui5Config: UI5Config): void configuration: { flp: { theme: 'sap_horizon' + }, + adp: { + useLocal: 'dist' } } } diff --git a/packages/adp-tooling/src/writer/project-utils.ts b/packages/adp-tooling/src/writer/project-utils.ts index a928fa8366a..5f9942ba799 100644 --- a/packages/adp-tooling/src/writer/project-utils.ts +++ b/packages/adp-tooling/src/writer/project-utils.ts @@ -202,38 +202,16 @@ export async function writeCfUI5Yaml(projectPath: string, data: CfAdpWriterConfi const ui5ConfigPath = join(projectPath, 'ui5.yaml'); const baseUi5ConfigContent = fs.read(ui5ConfigPath); const ui5Config = await UI5Config.newInstance(baseUi5ConfigContent); - ui5Config.setConfiguration({ propertiesFileSourceEncoding: 'UTF-8', paths: { webapp: 'dist' } }); - - /** Middlewares */ - enhanceUI5YamlWithCfCustomMiddleware(ui5Config); - - fs.write(ui5ConfigPath, ui5Config.toString()); - } catch (e) { - throw new Error(`Could not write ui5.yaml file. Reason: ${e.message}`); - } -} - -/** - * Writes a ui5-build.yaml file for CF project within a specified folder in the project directory. - * - * @param {string} projectPath - The root path of the project. - * @param {CfAdpWriterConfig} data - The data to be populated in the template file. - * @param {Editor} fs - The `mem-fs-editor` instance used for file operations. - * @returns {void} - */ -export async function writeCfUI5BuildYaml(projectPath: string, data: CfAdpWriterConfig, fs: Editor): Promise { - try { - const ui5ConfigPath = join(projectPath, 'ui5-build.yaml'); - const baseUi5ConfigContent = fs.read(ui5ConfigPath); - const ui5Config = await UI5Config.newInstance(baseUi5ConfigContent); ui5Config.setConfiguration({ propertiesFileSourceEncoding: 'UTF-8' }); /** Builder task */ enhanceUI5YamlWithCfCustomTask(ui5Config, data); + /** Middlewares */ + enhanceUI5YamlWithCfCustomMiddleware(ui5Config, data); fs.write(ui5ConfigPath, ui5Config.toString()); } catch (e) { - throw new Error(`Could not write ui5-build.yaml file. Reason: ${e.message}`); + throw new Error(`Could not write ui5.yaml file. Reason: ${e.message}`); } } @@ -292,10 +270,6 @@ export async function writeCfTemplates( module: project.name }); - fs.copyTpl(join(templatePath, 'cf/ui5-build.yaml'), join(project.folder, 'ui5-build.yaml'), { - module: project.name - }); - fs.copyTpl(join(templatePath, 'cf/i18n/i18n.properties'), join(project.folder, 'webapp/i18n/i18n.properties'), { module: project.name, moduleTitle: app.title, diff --git a/packages/adp-tooling/src/writer/writer-config.ts b/packages/adp-tooling/src/writer/writer-config.ts index 97c0261d8d7..71117f7ead2 100644 --- a/packages/adp-tooling/src/writer/writer-config.ts +++ b/packages/adp-tooling/src/writer/writer-config.ts @@ -198,7 +198,10 @@ export function getCfConfig(params: CreateCfConfigParams): CfAdpWriterConfig { html5RepoRuntimeGuid: params.html5RepoRuntimeGuid, approuter: params.cfServicesAnswers.approuter ?? AppRouterType.MANAGED, businessService: params.cfServicesAnswers.businessService ?? '', - businessSolutionName: params.cfServicesAnswers.businessSolutionName + businessSolutionName: params.cfServicesAnswers.businessSolutionName, + serviceInstanceGuid: params.serviceInstanceGuid, + backendUrl: params.backendUrl, + oauthPaths: params.oauthPaths }, project: { name: params.attributeAnswers.projectName, diff --git a/packages/adp-tooling/templates/cf/_gitignore b/packages/adp-tooling/templates/cf/_gitignore index a77f953fb33..0ec276cdbd7 100644 --- a/packages/adp-tooling/templates/cf/_gitignore +++ b/packages/adp-tooling/templates/cf/_gitignore @@ -1,6 +1,5 @@ -/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html +node_modules/ +dist/ +.tmp +.env +*.zip \ No newline at end of file diff --git a/packages/adp-tooling/templates/cf/package.json b/packages/adp-tooling/templates/cf/package.json index 522508627ec..a7bef00d5d3 100644 --- a/packages/adp-tooling/templates/cf/package.json +++ b/packages/adp-tooling/templates/cf/package.json @@ -6,7 +6,8 @@ "scripts": { "prestart": "npm run build", "start": "fiori run --open /test/flp.html#app-preview", - "build": "npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip", + "start-editor": "fiori run --open /test/adaptation-editor.html", + "build": "npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip", "zip": "cd dist && npx bestzip ../<%= module %>.zip *", "clean": "npx rimraf <%= module %>.zip dist", "build-ui5": "npm explore @ui5/task-adaptation -- npm run rollup" diff --git a/packages/adp-tooling/templates/cf/ui5-build.yaml b/packages/adp-tooling/templates/cf/ui5-build.yaml deleted file mode 100644 index a38bf6790e9..00000000000 --- a/packages/adp-tooling/templates/cf/ui5-build.yaml +++ /dev/null @@ -1,5 +0,0 @@ ---- -specVersion: "2.2" -type: application -metadata: - name: <%= module %> diff --git a/packages/adp-tooling/templates/cf/ui5.yaml b/packages/adp-tooling/templates/cf/ui5.yaml index a38bf6790e9..bf1e8a468c9 100644 --- a/packages/adp-tooling/templates/cf/ui5.yaml +++ b/packages/adp-tooling/templates/cf/ui5.yaml @@ -1,5 +1,5 @@ --- -specVersion: "2.2" +specVersion: "3.1" type: application metadata: name: <%= module %> diff --git a/packages/adp-tooling/test/unit/base/helper.test.ts b/packages/adp-tooling/test/unit/base/helper.test.ts index 669bec5fd73..dfa044f90f9 100644 --- a/packages/adp-tooling/test/unit/base/helper.test.ts +++ b/packages/adp-tooling/test/unit/base/helper.test.ts @@ -1,12 +1,12 @@ import { join } from 'node:path'; import { existsSync, readFileSync } from 'node:fs'; import type { create, Editor } from 'mem-fs-editor'; +import type { ReaderCollection } from '@ui5/fs'; import { UI5Config } from '@sap-ux/ui5-config'; import type { Inbound } from '@sap-ux/axios-extension'; import type { DescriptorVariant } from '../../../src/types'; import type { CustomMiddleware } from '@sap-ux/ui5-config'; -import type { FioriToolsProxyConfig } from '@sap-ux/ui5-config'; import { getVariant, @@ -16,7 +16,10 @@ import { updateVariant, isTypescriptSupported, filterAndMapInboundsToManifest, - readUi5Config + readUi5Config, + extractCfBuildTask, + readLocalManifest, + loadAppVariant } from '../../../src/base/helper'; import { readUi5Yaml } from '@sap-ux/project-access'; @@ -331,4 +334,156 @@ describe('helper', () => { expect(result).toBeUndefined(); }); }); + + describe('extractCfBuildTask', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('should return CF build task configuration when found', () => { + const mockBuildTask = { + target: { + url: '/cf.example', + client: '100' + }, + serviceInstance: 'test-service-instance' + }; + + const mockUi5Config = { + findCustomTask: jest.fn().mockReturnValue({ + configuration: mockBuildTask + }) + } as unknown as UI5Config; + + const result = extractCfBuildTask(mockUi5Config); + + expect(mockUi5Config.findCustomTask).toHaveBeenCalledWith('app-variant-bundler-build'); + expect(result).toEqual(mockBuildTask); + }); + + test('should throw error when build task configuration is undefined', () => { + const mockUi5Config = { + findCustomTask: jest.fn().mockReturnValue({ + configuration: undefined + }) + } as unknown as UI5Config; + + expect(() => extractCfBuildTask(mockUi5Config)).toThrow('No CF ADP project found'); + expect(mockUi5Config.findCustomTask).toHaveBeenCalledWith('app-variant-bundler-build'); + }); + }); + + describe('readLocalManifest', () => { + const mockManifest = { + 'sap.app': { + id: 'test.app', + title: 'Test App' + } + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('should read manifest from local dist folder', () => { + const useLocal = 'dist'; + const expectedPath = join(process.cwd(), useLocal, 'manifest.json'); + const manifestContent = JSON.stringify(mockManifest); + + readFileSyncMock.mockReturnValueOnce(manifestContent); + + const result = readLocalManifest(useLocal); + + expect(readFileSyncMock).toHaveBeenCalledWith(expectedPath, 'utf-8'); + expect(result).toEqual(mockManifest); + }); + + test('should throw error when file does not exist', () => { + const useLocal = 'dist'; + const expectedPath = join(process.cwd(), useLocal, 'manifest.json'); + + readFileSyncMock.mockImplementationOnce(() => { + const error = new Error('ENOENT: no such file or directory'); + (error as NodeJS.ErrnoException).code = 'ENOENT'; + throw error; + }); + + expect(() => readLocalManifest(useLocal)).toThrow(); + expect(readFileSyncMock).toHaveBeenCalledWith(expectedPath, 'utf-8'); + }); + }); + + describe('loadAppVariant', () => { + const mockVariantContent = { + layer: 'VENDOR', + reference: 'base.app', + id: 'my.adaptation', + namespace: 'apps/base.app/appVariants/my.adaptation/', + content: [] + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('should load and parse app variant descriptor successfully', async () => { + const mockResource = { + getString: jest.fn().mockResolvedValue(JSON.stringify(mockVariantContent)) + }; + + const mockRootProject = { + byPath: jest.fn().mockResolvedValue(mockResource) + } as unknown as ReaderCollection; + + const result = await loadAppVariant(mockRootProject); + + expect(mockRootProject.byPath).toHaveBeenCalledWith('/manifest.appdescr_variant'); + expect(mockResource.getString).toHaveBeenCalled(); + expect(result).toEqual(mockVariantContent); + }); + + test('should throw error when manifest.appdescr_variant is not found', async () => { + const mockRootProject = { + byPath: jest.fn().mockResolvedValue(null) + } as unknown as ReaderCollection; + + await expect(loadAppVariant(mockRootProject)).rejects.toThrow( + 'ADP configured but no manifest.appdescr_variant found.' + ); + expect(mockRootProject.byPath).toHaveBeenCalledWith('/manifest.appdescr_variant'); + }); + + test('should throw error when manifest.appdescr_variant is empty', async () => { + const mockResource = { + getString: jest.fn().mockResolvedValue('') + }; + + const mockRootProject = { + byPath: jest.fn().mockResolvedValue(mockResource) + } as unknown as ReaderCollection; + + await expect(loadAppVariant(mockRootProject)).rejects.toThrow( + 'ADP configured but manifest.appdescr_variant file is empty.' + ); + expect(mockRootProject.byPath).toHaveBeenCalledWith('/manifest.appdescr_variant'); + expect(mockResource.getString).toHaveBeenCalled(); + }); + + test('should throw error when getString throws an error', async () => { + const mockError = new Error('File read error'); + const mockResource = { + getString: jest.fn().mockRejectedValue(mockError) + }; + + const mockRootProject = { + byPath: jest.fn().mockResolvedValue(mockResource) + } as unknown as ReaderCollection; + + await expect(loadAppVariant(mockRootProject)).rejects.toThrow( + 'Failed to parse manifest.appdescr_variant: File read error' + ); + expect(mockRootProject.byPath).toHaveBeenCalledWith('/manifest.appdescr_variant'); + expect(mockResource.getString).toHaveBeenCalled(); + }); + }); }); diff --git a/packages/adp-tooling/test/unit/cf/app/discovery.test.ts b/packages/adp-tooling/test/unit/cf/app/discovery.test.ts index b31bf0e5ad9..0feaf8643aa 100644 --- a/packages/adp-tooling/test/unit/cf/app/discovery.test.ts +++ b/packages/adp-tooling/test/unit/cf/app/discovery.test.ts @@ -1,16 +1,29 @@ +import type AdmZip from 'adm-zip'; import type { ToolsLogger } from '@sap-ux/logger'; import { initI18n, t } from '../../../../src/i18n'; import { getFDCApps } from '../../../../src/cf/services/api'; -import { getAppHostIds, getCfApps } from '../../../../src/cf/app/discovery'; -import type { CFApp, CfConfig, ServiceKeys, Organization, Space, Uaa } from '../../../../src/types'; +import { extractXSApp } from '../../../../src/cf/utils/validation'; +import { + getAppHostIds, + getBackendUrlFromServiceKeys, + getCfApps, + getOAuthPathsFromXsApp +} from '../../../../src/cf/app/discovery'; +import type { CFApp, CfConfig, ServiceKeys, Organization, Space, Uaa, XsApp } from '../../../../src/types'; jest.mock('../../../../src/cf/services/api', () => ({ ...jest.requireActual('../../../../src/cf/services/api'), getFDCApps: jest.fn() })); +jest.mock('../../../../src/cf/utils/validation', () => ({ + ...jest.requireActual('../../../../src/cf/utils/validation'), + extractXSApp: jest.fn() +})); + const mockGetFDCApps = getFDCApps as jest.MockedFunction; +const mockExtractXSApp = extractXSApp as jest.MockedFunction; const mockApps: CFApp[] = [ { @@ -319,4 +332,194 @@ describe('CF App Discovery', () => { await expect(getCfApps(serviceKeys, mockCfConfig, mockLogger)).rejects.toThrow('API Error'); }); }); + + describe('getBackendUrlFromServiceKeys', () => { + test('should extract backend URL from first endpoint with URL', () => { + const serviceKeys: ServiceKeys[] = [ + { + credentials: { + uaa: {} as Uaa, + uri: 'test-uri', + endpoints: { + endpoint1: { + url: '/backend.example' + }, + endpoint2: { + url: '/another-backend.example' + } + } + } + } + ]; + + const result = getBackendUrlFromServiceKeys(serviceKeys); + + expect(result).toBe('/backend.example'); + }); + + test('should return first endpoint with URL when multiple endpoints exist', () => { + const serviceKeys: ServiceKeys[] = [ + { + credentials: { + uaa: {} as Uaa, + uri: 'test-uri', + endpoints: { + endpoint1: {}, + endpoint2: { + url: '/backend.example' + }, + endpoint3: { + url: '/another-backend.example' + } + } + } + } + ]; + + const result = getBackendUrlFromServiceKeys(serviceKeys); + + expect(result).toBe('/backend.example'); + }); + + test('should return undefined when no endpoints have URL', () => { + const serviceKeys: ServiceKeys[] = [ + { + credentials: { + uaa: {} as Uaa, + uri: 'test-uri', + endpoints: { + endpoint1: {}, + endpoint2: {} + } + } + } + ]; + + const result = getBackendUrlFromServiceKeys(serviceKeys); + + expect(result).toBeUndefined(); + }); + + test('should return undefined for various edge cases', () => { + expect(getBackendUrlFromServiceKeys([])).toBeUndefined(); + expect(getBackendUrlFromServiceKeys(null as any)).toBeUndefined(); + expect(getBackendUrlFromServiceKeys(undefined as any)).toBeUndefined(); + expect( + getBackendUrlFromServiceKeys([ + { + credentials: { + uaa: {} as Uaa, + uri: 'test-uri', + endpoints: {} + } + } + ]) + ).toBeUndefined(); + }); + }); + + describe('getOAuthPathsFromXsApp', () => { + const mockZipEntries = [] as AdmZip.IZipEntry[]; + + beforeEach(() => { + mockExtractXSApp.mockReturnValue(undefined); + }); + + test('should return empty array when xs-app or routes are missing', () => { + mockExtractXSApp.mockReturnValue(undefined); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual([]); + + mockExtractXSApp.mockReturnValue({} as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual([]); + + mockExtractXSApp.mockReturnValue({ routes: [] } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual([]); + }); + + test('should extract paths from routes', () => { + mockExtractXSApp.mockReturnValue({ + routes: [ + { source: '/sap/opu/odata', service: 'odata-service' }, + { source: '/api/v1', service: 'api-service' }, + { source: '/static', service: 'html5-apps-repo-rt' }, + { service: 'api-service' } + ] + } as XsApp); + + const result = getOAuthPathsFromXsApp(mockZipEntries); + + expect(result).toEqual(['/sap/opu/odata', '/api/v1']); + }); + + test('should clean regex patterns from paths', () => { + // Test removing leading ^ and trailing $ + mockExtractXSApp.mockReturnValue({ + routes: [{ source: '^/sap/opu/odata$', service: 'odata-service' }] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata']); + + // Test removing capture groups (note: /api/(.*)/v1 becomes /api/v1 after normalization) + mockExtractXSApp.mockReturnValue({ + routes: [ + { source: '/sap/opu/odata(.*)', service: 'odata-service' }, + { source: '/api/(.*)/v1', service: 'api-service' } + ] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata', '/api/v1']); + + // Test removing regex quantifiers + mockExtractXSApp.mockReturnValue({ + routes: [ + { source: '/sap/opu/odata$1', service: 'odata-service' }, + { source: '/api/v1$2', service: 'api-service' } + ] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata', '/api/v1']); + + // Test removing trailing * and optional / + mockExtractXSApp.mockReturnValue({ + routes: [ + { source: '/sap/opu/odata/*', service: 'odata-service' }, + { source: '/api/v1*', service: 'api-service' } + ] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata', '/api/v1']); + + // Test complex regex pattern + mockExtractXSApp.mockReturnValue({ + routes: [{ source: '^/sap/opu/odata(.*)$1/*', service: 'odata-service' }] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata']); + }); + + test('should remove duplicate paths', () => { + mockExtractXSApp.mockReturnValue({ + routes: [ + { source: '/sap/opu/odata', service: 'odata-service' }, + { source: '/sap/opu/odata', service: 'another-service' }, + { source: '/api/v1', service: 'api-service' } + ] + } as XsApp); + + const result = getOAuthPathsFromXsApp(mockZipEntries); + + expect(result).toEqual(['/sap/opu/odata', '/api/v1']); + }); + + test('should handle edge cases', () => { + mockExtractXSApp.mockReturnValue({ + routes: [ + { source: '/sap/opu/odata', service: 'odata-service' }, + { source: '^$', service: 'api-service' }, + { source: '(.*)', service: 'another-service' } + ] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata']); + + mockExtractXSApp.mockReturnValue({ + routes: [{ source: '/sap/opu/odata(.*)(.*)', service: 'odata-service' }] + } as XsApp); + expect(getOAuthPathsFromXsApp(mockZipEntries)).toEqual(['/sap/opu/odata']); + }); + }); }); diff --git a/packages/adp-tooling/test/unit/cf/project/yaml.test.ts b/packages/adp-tooling/test/unit/cf/project/yaml.test.ts index 5b47f9dddae..725fb4643df 100644 --- a/packages/adp-tooling/test/unit/cf/project/yaml.test.ts +++ b/packages/adp-tooling/test/unit/cf/project/yaml.test.ts @@ -217,7 +217,9 @@ describe('YAML Project Functions', () => { org: 'test-org', space: 'test-space-guid', html5RepoRuntime: 'test-runtime', - sapCloudService: 'test-service' + sapCloudService: 'test-service', + serviceInstanceName: 'test-service-instance-name', + serviceInstanceGuid: 'test-service-instance-guid' } } ] diff --git a/packages/adp-tooling/test/unit/preview/adp-preview.test.ts b/packages/adp-tooling/test/unit/preview/adp-preview.test.ts index c074c1bdc5f..f75064b9e99 100644 --- a/packages/adp-tooling/test/unit/preview/adp-preview.test.ts +++ b/packages/adp-tooling/test/unit/preview/adp-preview.test.ts @@ -242,7 +242,32 @@ describe('AdaptationProject', () => { expect(() => adp.isCloudProject).toThrow(); await expect(() => adp.sync()).rejects.toEqual(Error('Not initialized')); }); + + test('should initialize with useLocal mode', async () => { + const adp = new AdpPreview( + { + target: { + url: backend + }, + useLocal: 'dist' + }, + mockProject as unknown as ReaderCollection, + middlewareUtil, + logger + ); + + const parsedVariant = JSON.parse(descriptorVariant); + const layer = await adp.init(parsedVariant); + + expect(layer).toBe(parsedVariant.layer); + expect(adp.isCloudProject).toBe(false); + expect(adp['descriptorVariantId']).toBe(parsedVariant.id); + expect(adp['routesHandler']).toBeDefined(); + expect(adp['provider']).toBeUndefined(); + expect(nock.isDone()).toBe(true); + }); }); + describe('sync', () => { let secondCall: boolean = false; beforeAll(() => { @@ -273,6 +298,32 @@ describe('AdaptationProject', () => { global.__SAP_UX_MANIFEST_SYNC_REQUIRED__ = false; }); + test('should return early when useLocal is set', async () => { + // Create a separate nock scope for this test to avoid interfering with other tests + const testBackend = 'https://test-backend.example'; + const adp = new AdpPreview( + { + target: { + url: testBackend + }, + useLocal: 'dist' + }, + mockProject as unknown as ReaderCollection, + middlewareUtil, + logger + ); + + const parsedVariant = JSON.parse(descriptorVariant); + await adp.init(parsedVariant); + + // sync should return immediately without making any backend calls + // Since useLocal is set, sync should return early + await adp.sync(); + + // Verify that sync completed without errors + expect(adp.isCloudProject).toBe(false); + }); + test('updates merged descriptor', async () => { global.__SAP_UX_MANIFEST_SYNC_REQUIRED__ = true; const adp = new AdpPreview( @@ -889,6 +940,7 @@ describe('AdaptationProject', () => { expect(e.message).toEqual(errorMsg); } }); + test('GET /adp/api/annotation', async () => { const response = await server.get('/adp/api/annotation').send().expect(200); @@ -931,4 +983,49 @@ describe('AdaptationProject', () => { ); }); }); + + describe('addApis - useLocal mode', () => { + let useLocalServer: SuperTest; + beforeAll(async () => { + const adp = new AdpPreview( + { + target: { + url: backend + }, + useLocal: 'dist' + }, + mockProject as unknown as ReaderCollection, + middlewareUtil, + logger + ); + await adp.init(JSON.parse(descriptorVariant)); + jest.spyOn(helper, 'getVariant').mockResolvedValue({ + content: [], + id: 'adp/project', + layer: 'VENDOR', + namespace: 'test', + reference: 'adp/project' + }); + + jest.spyOn(helper, 'getAdpConfig').mockResolvedValue({ + target: { + destination: 'testDestination' + }, + ignoreCertErrors: false + }); + jest.spyOn(helper, 'isTypescriptSupported').mockReturnValue(false); + + const app = express(); + app.use(express.json()); + adp.addApis(app); + useLocalServer = supertest(app); + }); + + test('GET /adp/api/annotation should return empty annotationDataSourceMap in useLocal mode', async () => { + const response = await useLocalServer.get('/adp/api/annotation').send().expect(200); + + const message = response.text; + expect(message).toMatchInlineSnapshot(`"{\\"isRunningInBAS\\":false,\\"annotationDataSourceMap\\":{}}"`); + }); + }); }); diff --git a/packages/adp-tooling/test/unit/writer/__snapshots__/cf.test.ts.snap b/packages/adp-tooling/test/unit/writer/__snapshots__/cf.test.ts.snap index 02d070a02c1..b4dcab15a7b 100644 --- a/packages/adp-tooling/test/unit/writer/__snapshots__/cf.test.ts.snap +++ b/packages/adp-tooling/test/unit/writer/__snapshots__/cf.test.ts.snap @@ -76,13 +76,11 @@ description: Test MTA Project for CF Writer Tests "state": "modified", }, "../minimal-cf/test-cf-project/.gitignore": Object { - "contents": "/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html -", + "contents": "node_modules/ +dist/ +.tmp +.env +*.zip", "state": "modified", }, "../minimal-cf/test-cf-project/package.json": Object { @@ -94,7 +92,8 @@ UIAdaptation*.html \\"scripts\\": { \\"prestart\\": \\"npm run build\\", \\"start\\": \\"fiori run --open /test/flp.html#app-preview\\", - \\"build\\": \\"npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip\\", + \\"start-editor\\": \\"fiori run --open /test/adaptation-editor.html\\", + \\"build\\": \\"npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip\\", \\"zip\\": \\"cd dist && npx bestzip ../test-cf-project.zip *\\", \\"clean\\": \\"npx rimraf test-cf-project.zip dist\\", \\"build-ui5\\": \\"npm explore @ui5/task-adaptation -- npm run rollup\\" @@ -122,9 +121,9 @@ UIAdaptation*.html ", "state": "modified", }, - "../minimal-cf/test-cf-project/ui5-build.yaml": Object { + "../minimal-cf/test-cf-project/ui5.yaml": Object { "contents": "--- -specVersion: \\"2.2\\" +specVersion: \\"3.1\\" type: application metadata: name: test-cf-project @@ -145,20 +144,6 @@ builder: space: space-guid sapCloudService: test-solution serviceInstanceName: test-service -", - "state": "modified", - }, - "../minimal-cf/test-cf-project/ui5.yaml": Object { - "contents": "--- -specVersion: \\"2.2\\" -type: application -metadata: - name: test-cf-project -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist server: customMiddleware: - name: fiori-tools-proxy @@ -175,6 +160,8 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist ", "state": "modified", }, @@ -323,13 +310,11 @@ description: Test MTA Project for CF Writer Tests "state": "modified", }, "test-cf-project/.gitignore": Object { - "contents": "/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html -", + "contents": "node_modules/ +dist/ +.tmp +.env +*.zip", "state": "modified", }, "test-cf-project/package.json": Object { @@ -341,7 +326,8 @@ UIAdaptation*.html \\"scripts\\": { \\"prestart\\": \\"npm run build\\", \\"start\\": \\"fiori run --open /test/flp.html#app-preview\\", - \\"build\\": \\"npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip\\", + \\"start-editor\\": \\"fiori run --open /test/adaptation-editor.html\\", + \\"build\\": \\"npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip\\", \\"zip\\": \\"cd dist && npx bestzip ../test-cf-project.zip *\\", \\"clean\\": \\"npx rimraf test-cf-project.zip dist\\", \\"build-ui5\\": \\"npm explore @ui5/task-adaptation -- npm run rollup\\" @@ -369,9 +355,9 @@ UIAdaptation*.html ", "state": "modified", }, - "test-cf-project/ui5-build.yaml": Object { + "test-cf-project/ui5.yaml": Object { "contents": "--- -specVersion: \\"2.2\\" +specVersion: \\"3.1\\" type: application metadata: name: test-cf-project @@ -392,20 +378,6 @@ builder: space: space-guid sapCloudService: test-solution serviceInstanceName: test-service -", - "state": "modified", - }, - "test-cf-project/ui5.yaml": Object { - "contents": "--- -specVersion: \\"2.2\\" -type: application -metadata: - name: test-cf-project -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist server: customMiddleware: - name: fiori-tools-proxy @@ -422,6 +394,8 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist ", "state": "modified", }, @@ -575,13 +549,11 @@ description: Test MTA Project for CF Writer Tests "state": "modified", }, "../managed-approuter/test-cf-project/.gitignore": Object { - "contents": "/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html -", + "contents": "node_modules/ +dist/ +.tmp +.env +*.zip", "state": "modified", }, "../managed-approuter/test-cf-project/package.json": Object { @@ -593,7 +565,8 @@ UIAdaptation*.html \\"scripts\\": { \\"prestart\\": \\"npm run build\\", \\"start\\": \\"fiori run --open /test/flp.html#app-preview\\", - \\"build\\": \\"npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip\\", + \\"start-editor\\": \\"fiori run --open /test/adaptation-editor.html\\", + \\"build\\": \\"npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip\\", \\"zip\\": \\"cd dist && npx bestzip ../test-cf-project.zip *\\", \\"clean\\": \\"npx rimraf test-cf-project.zip dist\\", \\"build-ui5\\": \\"npm explore @ui5/task-adaptation -- npm run rollup\\" @@ -621,9 +594,9 @@ UIAdaptation*.html ", "state": "modified", }, - "../managed-approuter/test-cf-project/ui5-build.yaml": Object { + "../managed-approuter/test-cf-project/ui5.yaml": Object { "contents": "--- -specVersion: \\"2.2\\" +specVersion: \\"3.1\\" type: application metadata: name: test-cf-project @@ -644,20 +617,6 @@ builder: space: space-guid sapCloudService: test-solution serviceInstanceName: test-service -", - "state": "modified", - }, - "../managed-approuter/test-cf-project/ui5.yaml": Object { - "contents": "--- -specVersion: \\"2.2\\" -type: application -metadata: - name: test-cf-project -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist server: customMiddleware: - name: fiori-tools-proxy @@ -674,6 +633,8 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist ", "state": "modified", }, @@ -796,13 +757,11 @@ description: Test MTA Project for CF Writer Tests "state": "modified", }, "../minimal-cf/test-cf-project/.gitignore": Object { - "contents": "/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html -", + "contents": "node_modules/ +dist/ +.tmp +.env +*.zip", "state": "modified", }, "../minimal-cf/test-cf-project/package.json": Object { @@ -814,7 +773,8 @@ UIAdaptation*.html \\"scripts\\": { \\"prestart\\": \\"npm run build\\", \\"start\\": \\"fiori run --open /test/flp.html#app-preview\\", - \\"build\\": \\"npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip\\", + \\"start-editor\\": \\"fiori run --open /test/adaptation-editor.html\\", + \\"build\\": \\"npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip\\", \\"zip\\": \\"cd dist && npx bestzip ../test-cf-project.zip *\\", \\"clean\\": \\"npx rimraf test-cf-project.zip dist\\", \\"build-ui5\\": \\"npm explore @ui5/task-adaptation -- npm run rollup\\" @@ -842,9 +802,9 @@ UIAdaptation*.html ", "state": "modified", }, - "../minimal-cf/test-cf-project/ui5-build.yaml": Object { + "../minimal-cf/test-cf-project/ui5.yaml": Object { "contents": "--- -specVersion: \\"2.2\\" +specVersion: \\"3.1\\" type: application metadata: name: test-cf-project @@ -865,20 +825,6 @@ builder: space: space-guid sapCloudService: test-solution serviceInstanceName: test-service -", - "state": "modified", - }, - "../minimal-cf/test-cf-project/ui5.yaml": Object { - "contents": "--- -specVersion: \\"2.2\\" -type: application -metadata: - name: test-cf-project -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist server: customMiddleware: - name: fiori-tools-proxy @@ -895,6 +841,8 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist ", "state": "modified", }, @@ -1079,13 +1027,11 @@ description: Test MTA Project for CF Writer Tests "state": "modified", }, "test-cf-project/.gitignore": Object { - "contents": "/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html -", + "contents": "node_modules/ +dist/ +.tmp +.env +*.zip", "state": "modified", }, "test-cf-project/package.json": Object { @@ -1097,7 +1043,8 @@ UIAdaptation*.html \\"scripts\\": { \\"prestart\\": \\"npm run build\\", \\"start\\": \\"fiori run --open /test/flp.html#app-preview\\", - \\"build\\": \\"npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip\\", + \\"start-editor\\": \\"fiori run --open /test/adaptation-editor.html\\", + \\"build\\": \\"npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip\\", \\"zip\\": \\"cd dist && npx bestzip ../test-cf-project.zip *\\", \\"clean\\": \\"npx rimraf test-cf-project.zip dist\\", \\"build-ui5\\": \\"npm explore @ui5/task-adaptation -- npm run rollup\\" @@ -1125,9 +1072,9 @@ UIAdaptation*.html ", "state": "modified", }, - "test-cf-project/ui5-build.yaml": Object { + "test-cf-project/ui5.yaml": Object { "contents": "--- -specVersion: \\"2.2\\" +specVersion: \\"3.1\\" type: application metadata: name: test-cf-project @@ -1148,20 +1095,6 @@ builder: space: space-guid sapCloudService: test-solution serviceInstanceName: test-service -", - "state": "modified", - }, - "test-cf-project/ui5.yaml": Object { - "contents": "--- -specVersion: \\"2.2\\" -type: application -metadata: - name: test-cf-project -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist server: customMiddleware: - name: fiori-tools-proxy @@ -1178,6 +1111,8 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist ", "state": "modified", }, @@ -1305,13 +1240,11 @@ description: Test MTA Project for CF Writer Tests "state": "modified", }, "test-cf-project/.gitignore": Object { - "contents": "/node_modules/ -/preview/ -/dist/ -*.tar -*.zip -UIAdaptation*.html -", + "contents": "node_modules/ +dist/ +.tmp +.env +*.zip", "state": "modified", }, "test-cf-project/package.json": Object { @@ -1323,7 +1256,8 @@ UIAdaptation*.html \\"scripts\\": { \\"prestart\\": \\"npm run build\\", \\"start\\": \\"fiori run --open /test/flp.html#app-preview\\", - \\"build\\": \\"npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip\\", + \\"start-editor\\": \\"fiori run --open /test/adaptation-editor.html\\", + \\"build\\": \\"npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip\\", \\"zip\\": \\"cd dist && npx bestzip ../test-cf-project.zip *\\", \\"clean\\": \\"npx rimraf test-cf-project.zip dist\\", \\"build-ui5\\": \\"npm explore @ui5/task-adaptation -- npm run rollup\\" @@ -1351,9 +1285,9 @@ UIAdaptation*.html ", "state": "modified", }, - "test-cf-project/ui5-build.yaml": Object { + "test-cf-project/ui5.yaml": Object { "contents": "--- -specVersion: \\"2.2\\" +specVersion: \\"3.1\\" type: application metadata: name: test-cf-project @@ -1374,20 +1308,6 @@ builder: space: space-guid sapCloudService: test-solution serviceInstanceName: test-service -", - "state": "modified", - }, - "test-cf-project/ui5.yaml": Object { - "contents": "--- -specVersion: \\"2.2\\" -type: application -metadata: - name: test-cf-project -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist server: customMiddleware: - name: fiori-tools-proxy @@ -1404,6 +1324,8 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist ", "state": "modified", }, diff --git a/packages/adp-tooling/test/unit/writer/project-utils.test.ts b/packages/adp-tooling/test/unit/writer/project-utils.test.ts index 214f9be8349..8d8929ca7ee 100644 --- a/packages/adp-tooling/test/unit/writer/project-utils.test.ts +++ b/packages/adp-tooling/test/unit/writer/project-utils.test.ts @@ -10,7 +10,6 @@ import { writeUI5Yaml, writeUI5DeployYaml, writeCfUI5Yaml, - writeCfUI5BuildYaml, getPackageJSONInfo, getTypes } from '../../../src/writer/project-utils'; @@ -57,7 +56,9 @@ const cfData = { space: { Name: 'test-space', GUID: 'space-guid' }, html5RepoRuntimeGuid: 'runtime-guid', approuter: AppRouterType.MANAGED, - businessService: 'business-service' + businessService: 'business-service', + backendUrl: '/backend.example', + oauthPaths: ['/sap/opu/odata', '/api/v1'] }, project: { name: 'my-test-cf-project', @@ -323,11 +324,7 @@ metadata: ); expect(writeFilesSpy).toHaveBeenCalledWith( path.join(projectPath, 'ui5.yaml'), - expect.stringContaining('paths:') - ); - expect(writeFilesSpy).toHaveBeenCalledWith( - path.join(projectPath, 'ui5.yaml'), - expect.stringContaining('webapp: dist') + expect.stringContaining('useLocal: dist') ); }); @@ -345,48 +342,4 @@ metadata: } }); }); - - describe('writeCfUI5BuildYaml', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - const projectPath = 'project'; - - const ui5BuildYamlContent = `# yaml-language-server: $schema=https://sap.github.io/ui5-tooling/schema/ui5-build.yaml.json -specVersion: "3.0" -metadata: - name: ${cfData.app.id} - type: application`; - - const writeFilesSpy = jest.fn(); - const mockFs = { - write: writeFilesSpy, - read: jest.fn().mockReturnValue(ui5BuildYamlContent) - }; - - it('should write ui5-build.yaml for CF project to the specified folder', async () => { - await writeCfUI5BuildYaml(projectPath, cfData, mockFs as unknown as Editor); - - expect(mockFs.read).toHaveBeenCalledWith(path.join(projectPath, 'ui5-build.yaml')); - expect(writeFilesSpy).toHaveBeenCalledWith( - path.join(projectPath, 'ui5-build.yaml'), - expect.stringContaining('propertiesFileSourceEncoding: UTF-8') - ); - }); - - it('should throw error when reading ui5-build.yaml fails', async () => { - const errMsg = 'File not found'; - mockFs.read.mockImplementation(() => { - throw new Error(errMsg); - }); - - try { - await writeCfUI5BuildYaml(projectPath, cfData, mockFs as unknown as Editor); - fail('Expected error to be thrown'); - } catch (error) { - expect(error.message).toBe(`Could not write ui5-build.yaml file. Reason: ${errMsg}`); - } - }); - }); }); diff --git a/packages/backend-proxy-middleware-cf/.eslintignore b/packages/backend-proxy-middleware-cf/.eslintignore new file mode 100644 index 00000000000..0fc18a40e56 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/.eslintignore @@ -0,0 +1,2 @@ +test +dist diff --git a/packages/backend-proxy-middleware-cf/.eslintrc.js b/packages/backend-proxy-middleware-cf/.eslintrc.js new file mode 100644 index 00000000000..b717f83ae98 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + extends: ['../../.eslintrc'], + parserOptions: { + project: './tsconfig.eslint.json', + tsconfigRootDir: __dirname + } +}; diff --git a/packages/backend-proxy-middleware-cf/LICENSE b/packages/backend-proxy-middleware-cf/LICENSE new file mode 100644 index 00000000000..261eeb9e9f8 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/backend-proxy-middleware-cf/README.md b/packages/backend-proxy-middleware-cf/README.md new file mode 100644 index 00000000000..55f4bb4619c --- /dev/null +++ b/packages/backend-proxy-middleware-cf/README.md @@ -0,0 +1,155 @@ +[![Changelog](https://img.shields.io/badge/changelog-8A2BE2)](https://github.com/SAP/open-ux-tools/blob/main/packages/backend-proxy-middleware-cf/CHANGELOG.md) [![Github repo](https://img.shields.io/badge/github-repo-blue)](https://github.com/SAP/open-ux-tools/tree/main/packages/backend-proxy-middleware-cf) + +# [`@sap-ux/backend-proxy-middleware-cf`](https://github.com/SAP/open-ux-tools/tree/main/packages/backend-proxy-middleware-cf) + +The `@sap-ux/backend-proxy-middleware-cf` is a [Custom UI5 Server Middleware](https://sap.github.io/ui5-tooling/pages/extensibility/CustomServerMiddleware) for proxying requests to Cloud Foundry destinations with OAuth2 authentication. It supports proxying multiple OData source paths to a single destination URL with automatic OAuth token management. + +> **⚠️ Experimental**: This middleware is currently experimental and may be subject to breaking changes or even removal in future versions. Use with caution and be prepared to update your configuration or migrate to alternative solutions if needed. + +It can be used either with the `ui5 serve` or the `fiori run` commands. + +## Configuration Options + +| Option | Value Type | Requirement Type | Default Value | Description | +| ------------------- | ---------- | ---------------- | ------------- | ---------------------------------------------------------------------------------------------------------------- | +| `url` | `string` | **required** | `undefined` | Destination URL to proxy requests to. | +| `paths` | `string[]` | **required** | `[]` | Array of OData source paths to proxy to this destination. Each path represents an OData service that should be proxied. Requests matching these paths will have the path prefix removed before forwarding. | +| `credentials` | object | optional | `undefined` | Manual OAuth credentials. If not provided, middleware attempts to auto-detect from Cloud Foundry ADP project. | +| `credentials.clientId` | `string` | mandatory (if credentials provided) | `undefined` | OAuth2 client ID. | +| `credentials.clientSecret` | `string` | mandatory (if credentials provided) | `undefined` | OAuth2 client secret. | +| `credentials.url` | `string` | mandatory (if credentials provided) | `undefined` | Base URL for the OAuth service. The token endpoint will be constructed as `{url}/oauth/token`. | +| `debug` | `boolean` | optional | `false` | Enable debug logging for troubleshooting. | + +## Usage + +### Basic Configuration + +```yaml +server: + customMiddleware: + - name: backend-proxy-middleware-cf + afterMiddleware: compression + configuration: + url: https://your-backend-service.cfapps.eu12.hana.ondemand.com + paths: + - /odata/v4/visitorservice + - /odata +``` + +### Automatic Detection (Recommended) + +For Cloud Foundry adaptation projects, the middleware automatically detects the project configuration from `ui5.yaml` and extracts OAuth credentials from service keys. You only need to provide the `url` and `paths`: + +```yaml +server: + customMiddleware: + - name: backend-proxy-middleware-cf + afterMiddleware: compression + configuration: + url: https://your-backend-service.cfapps.eu12.hana.ondemand.com + paths: + - /odata/v4/visitorservice + - /odata +``` + +The middleware will: + +1. Read the `app-variant-bundler-build` custom task from `ui5.yaml` +2. Extract `serviceInstanceName` and `serviceInstanceGuid` +3. Retrieve service keys using `@sap-ux/adp-tooling` +4. Extract UAA credentials and construct the token endpoint +5. Automatically add Bearer tokens to proxied requests + +### Manual Credentials + +For custom setups or when auto-detection is not available, you can provide OAuth credentials manually: + +```yaml +server: + customMiddleware: + - name: backend-proxy-middleware-cf + afterMiddleware: compression + configuration: + url: https://your-backend-service.cfapps.eu12.hana.ondemand.com + paths: + - /odata/v4/visitorservice + - /odata + credentials: + clientId: "sb-your-service-instance!b123|your-app!b456" + clientSecret: "your-client-secret" + url: "https://example.authentication.eu12.hana.ondemand.com" + debug: true +``` + +The `credentials.url` should be the base URL of the UAA service (without `/oauth/token`). The middleware will automatically construct the full token endpoint. + +### Multiple OData Sources + +You can proxy multiple OData paths to the same destination: + +```yaml +server: + customMiddleware: + - name: backend-proxy-middleware-cf + afterMiddleware: compression + configuration: + url: https://your-backend-service.cfapps.eu12.hana.ondemand.com + paths: + - /odata/v4/service1 + - /odata/v4/service2 + - /odata/v2/legacy +``` + +### With Debug Logging + +Enable debug logging to troubleshoot issues: + +```yaml +server: + customMiddleware: + - name: backend-proxy-middleware-cf + afterMiddleware: compression + configuration: + url: https://your-backend-service.cfapps.eu12.hana.ondemand.com + paths: + - /odata + debug: true +``` + +## How It Works + +1. **Proxy Setup**: Creates HTTP proxy middleware for each configured path, proxying to the destination URL. +2. **Path Rewriting**: Removes the matched path prefix before forwarding requests (e.g., `/odata/v4/service` → `/service`). +3. **OAuth Detection**: For automatic mode, checks if the project is a CF ADP project by reading `ui5.yaml` and looking for the `app-variant-bundler-build` custom task. +4. **Credentials**: Extracts `serviceInstanceName` and `serviceInstanceGuid` from the custom task configuration. +5. **Service Keys**: Retrieves service keys using `@sap-ux/adp-tooling`, which communicates with Cloud Foundry CLI. +6. **Token Endpoint**: Constructs the token endpoint from the UAA base URL as `{url}/oauth/token`. +7. **Token Management**: Requests OAuth tokens using client credentials flow. +8. **Caching**: Caches tokens in memory and refreshes them automatically 60 seconds before expiry. +9. **Request Proxying**: Adds `Authorization: Bearer ` header to proxied requests before forwarding. + +## Error Handling + +- If `url` is not provided, the middleware will be inactive and log a warning. +- If no paths are configured, the middleware will be inactive and log a warning. +- If auto-detection fails and no manual credentials are provided, the middleware will proxy requests without OAuth tokens (may fail if backend requires authentication). +- If token request fails, an error is logged but the request may still proceed (depending on the backend's authentication requirements). +- All errors are logged for debugging purposes. + +## Security Considerations + +- Credentials are never logged in production mode. +- Tokens are cached in memory only and never persisted to disk. +- Token refresh happens automatically 60 seconds before expiry to avoid using expired tokens. +- Service keys are obtained securely through Cloud Foundry CLI. +- The middleware only proxies requests matching any of the configured path prefixes. +- If no paths are configured, the middleware will be inactive and log a warning. + +## Keywords + +- OAuth2 Middleware +- Cloud Foundry ADP +- Bearer Token +- Fiori tools +- SAP UI5 +- Proxy Middleware diff --git a/packages/backend-proxy-middleware-cf/jest.config.js b/packages/backend-proxy-middleware-cf/jest.config.js new file mode 100644 index 00000000000..9e9be597ecb --- /dev/null +++ b/packages/backend-proxy-middleware-cf/jest.config.js @@ -0,0 +1,2 @@ +const config = require('../../jest.base'); +module.exports = config; diff --git a/packages/backend-proxy-middleware-cf/package.json b/packages/backend-proxy-middleware-cf/package.json new file mode 100644 index 00000000000..6898aeb06bb --- /dev/null +++ b/packages/backend-proxy-middleware-cf/package.json @@ -0,0 +1,52 @@ +{ + "name": "@sap-ux/backend-proxy-middleware-cf", + "description": "OAuth2 Bearer token middleware for Cloud Foundry adaptation projects", + "repository": { + "type": "git", + "url": "https://github.com/SAP/open-ux-tools.git", + "directory": "packages/backend-proxy-middleware-cf" + }, + "bugs": { + "url": "https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Abackend-proxy-middleware-cf" + }, + "version": "0.0.1", + "license": "Apache-2.0", + "author": "@SAP/ux-tools-team", + "main": "dist/index.js", + "scripts": { + "build": "tsc --build", + "watch": "tsc --watch", + "clean": "rimraf --glob dist test/test-output coverage *.tsbuildinfo", + "format": "prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "test": "jest --ci --forceExit --detectOpenHandles --colors" + }, + "files": [ + "LICENSE", + "dist", + "ui5.yaml", + "!dist/*.map", + "!dist/**/*.map" + ], + "dependencies": { + "@sap-ux/adp-tooling": "workspace:*", + "@sap-ux/logger": "workspace:*", + "@sap-ux/project-access": "workspace:*", + "axios": "1.12.2", + "http-proxy-middleware": "3.0.5" + }, + "devDependencies": { + "@types/express": "4.17.21", + "@types/http-proxy": "^1.17.5", + "@types/supertest": "2.0.12", + "express": "4.21.2", + "nock": "13.4.0", + "supertest": "7.1.4", + "connect": "^3.7.0", + "@types/connect": "^3.4.38" + }, + "engines": { + "node": ">=20.x" + } +} diff --git a/packages/backend-proxy-middleware-cf/src/index.ts b/packages/backend-proxy-middleware-cf/src/index.ts new file mode 100644 index 00000000000..32557d047a5 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/index.ts @@ -0,0 +1 @@ +export type { CfOAuthMiddlewareConfig } from './types'; diff --git a/packages/backend-proxy-middleware-cf/src/middleware.ts b/packages/backend-proxy-middleware-cf/src/middleware.ts new file mode 100644 index 00000000000..008413b3da9 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/middleware.ts @@ -0,0 +1,34 @@ +import type { RequestHandler } from 'express'; +import type { MiddlewareParameters } from '@ui5/server'; + +import { LogLevel, ToolsLogger, UI5ToolingTransport } from '@sap-ux/logger'; + +import { setupProxyRoutes } from './proxy'; +import { validateConfig } from './validation'; +import { createTokenProvider } from './token'; +import type { CfOAuthMiddlewareConfig } from './types'; + +/** + * UI5 middleware for proxying requests to Cloud Foundry destinations with OAuth2 authentication. + * Supports one destination URL with multiple OData source paths. + * + * @param {MiddlewareParameters} params - Input parameters for UI5 middleware. + * @param {CfOAuthMiddlewareConfig} params.options - Configuration options. + * @returns {Promise} Express middleware handler. + */ +module.exports = async ({ options }: MiddlewareParameters): Promise => { + const config = options.configuration; + if (!config) { + throw new Error('Backend proxy middleware (CF) has no configuration.'); + } + + const logger = new ToolsLogger({ + logLevel: config.debug ? LogLevel.Debug : LogLevel.Info, + transports: [new UI5ToolingTransport({ moduleName: 'backend-proxy-middleware-cf' })] + }); + + await validateConfig(config, logger); + + const tokenProvider = await createTokenProvider(config, logger); + return setupProxyRoutes(config.paths, config.url, tokenProvider, logger); +}; diff --git a/packages/backend-proxy-middleware-cf/src/proxy.ts b/packages/backend-proxy-middleware-cf/src/proxy.ts new file mode 100644 index 00000000000..580982c4ef1 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/proxy.ts @@ -0,0 +1,102 @@ +import type connect from 'connect'; +import type { Url } from 'node:url'; +import type { Socket } from 'node:net'; +import { type Request, Router } from 'express'; +import type { Options } from 'http-proxy-middleware'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { createProxyMiddleware } from 'http-proxy-middleware'; + +import type { ToolsLogger } from '@sap-ux/logger'; + +import type { OAuthTokenProvider } from './token'; + +export type EnhancedIncomingMessage = (IncomingMessage & Pick) | connect.IncomingMessage; + +/** + * Creates proxy options for http-proxy-middleware. + * + * @param {string} targetUrl - The target URL to proxy to. + * @param {ToolsLogger} logger - Logger instance. + * @returns {Options} Proxy options configuration. + */ +export function createProxyOptions(targetUrl: string, logger: ToolsLogger): Options { + return { + target: targetUrl, + changeOrigin: true, + pathRewrite: (path: string, req: EnhancedIncomingMessage): string => { + // Express router.use() strips the matched path from req.url, + // use originalUrl to get the full path before Express stripped it + const originalUrl = req.originalUrl ?? req.url ?? path; + const urlPath = originalUrl.split('?')?.[0]; + const queryString = originalUrl.includes('?') ? originalUrl.substring(originalUrl.indexOf('?')) : ''; + const fullPath = urlPath + queryString; + logger.debug(`Rewrite path ${path} > ${fullPath}`); + return fullPath; + }, + on: { + error: ( + err: Error & { code?: string }, + req: EnhancedIncomingMessage & { next?: Function }, + _res: ServerResponse | Socket, + _target: string | Partial | undefined + ): void => { + logger.error(`Proxy error for ${req.originalUrl ?? req.url}: ${err.message}`); + if (typeof req.next === 'function') { + req.next(err); + } + } + } + }; +} + +/** + * Registers a proxy route for a given path. + * + * @param {string} path - Path to register. + * @param {string} destinationUrl - Target URL for proxying. + * @param {OAuthTokenProvider} tokenProvider - Token provider instance. + * @param {ToolsLogger} logger - Logger instance. + * @param {Router} router - Express router instance. + */ +export function registerProxyRoute( + path: string, + destinationUrl: string, + tokenProvider: OAuthTokenProvider, + logger: ToolsLogger, + router: Router +): void { + const proxyOptions = createProxyOptions(destinationUrl, logger); + const proxyFn = createProxyMiddleware(proxyOptions); + const tokenMiddleware = tokenProvider.createTokenMiddleware(); + + router.use(path, tokenMiddleware, proxyFn); + logger.info(`Registered proxy for path: ${path} -> ${destinationUrl}`); +} + +/** + * Sets up all proxy routes for the configured paths. + * + * @param {string[]} paths - Array of paths to register. + * @param {string} destinationUrl - Target URL for proxying. + * @param {OAuthTokenProvider} tokenProvider - Token provider instance. + * @param {ToolsLogger} logger - Logger instance. + * @returns {Router} Configured Express router. + */ +export function setupProxyRoutes( + paths: string[], + destinationUrl: string, + tokenProvider: OAuthTokenProvider, + logger: ToolsLogger +): Router { + const router = Router(); + + for (const path of paths) { + try { + registerProxyRoute(path, destinationUrl, tokenProvider, logger, router); + } catch (e) { + throw new Error(`Failed to register proxy for ${path}. Check configuration in yaml file. \n\t${e.message}`); + } + } + + return router; +} diff --git a/packages/backend-proxy-middleware-cf/src/token/factory.ts b/packages/backend-proxy-middleware-cf/src/token/factory.ts new file mode 100644 index 00000000000..4df81d0611f --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/token/factory.ts @@ -0,0 +1,123 @@ +import type { ToolsLogger } from '@sap-ux/logger'; +import { extractCfBuildTask, getOrCreateServiceKeys } from '@sap-ux/adp-tooling'; +import { FileName, readUi5Yaml } from '@sap-ux/project-access'; +import type { ServiceKeys } from '@sap-ux/adp-tooling'; + +import { OAuthTokenProvider } from './provider'; +import type { CfOAuthMiddlewareConfig } from '../types'; + +const OAUTH_TOKEN_PATH = '/oauth/token'; + +/** + * Constructs the OAuth token endpoint URL from a base URL. + * + * @param {string} baseUrl - Base URL of the OAuth service. + * @returns {string} Full token endpoint URL. + */ +function buildTokenEndpoint(baseUrl: string): string { + return `${baseUrl}${OAUTH_TOKEN_PATH}`; +} + +/** + * Creates an OAuthTokenProvider from service keys (extracted from Cloud Foundry service instance). + * + * @param {ServiceKeys} serviceKeys - Service keys containing UAA information. + * @param {ToolsLogger} logger - Logger instance. + * @returns {OAuthTokenProvider} OAuthTokenProvider instance. + * @throws {Error} If service keys are invalid. + */ +export function createManagerFromServiceKeys(serviceKeys: ServiceKeys, logger: ToolsLogger): OAuthTokenProvider { + const { uaa } = serviceKeys.credentials; + + if (!uaa?.url) { + throw new Error('Invalid credentials: missing UAA URL'); + } + + if (!uaa?.clientid) { + throw new Error('Invalid credentials: missing client ID'); + } + + if (!uaa?.clientsecret) { + throw new Error('Invalid credentials: missing client secret'); + } + + const tokenEndpoint = buildTokenEndpoint(uaa.url); + return new OAuthTokenProvider(uaa.clientid, uaa.clientsecret, tokenEndpoint, logger); +} + +/** + * Creates an OAuthTokenProvider from direct OAuth credentials (provided in configuration). + * + * @param {string} clientId - OAuth2 client ID. + * @param {string} clientSecret - OAuth2 client secret. + * @param {string} baseUrl - Base URL for the OAuth service (token endpoint will be constructed as {baseUrl}/oauth/token). + * @param {ToolsLogger} logger - Logger instance. + * @returns {OAuthTokenProvider} OAuthTokenProvider instance. + */ +export function createManagerFromDirectCredentials( + clientId: string, + clientSecret: string, + baseUrl: string, + logger: ToolsLogger +): OAuthTokenProvider { + const tokenEndpoint = buildTokenEndpoint(baseUrl); + return new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); +} + +/** + * Creates an OAuth token provider based on configuration. + * + * @param {CfOAuthMiddlewareConfig} config - Configuration options. + * @param {ToolsLogger} logger - Logger instance. + * @returns {Promise} Token provider instance. + * @throws {Error} If token provider cannot be created. + */ +export async function createTokenProvider( + config: CfOAuthMiddlewareConfig, + logger: ToolsLogger +): Promise { + if (config.credentials) { + logger.info('Initializing backend proxy middleware (CF) with provided credentials'); + const { clientId, clientSecret, url } = config.credentials; + return createManagerFromDirectCredentials(clientId, clientSecret, url, logger); + } + + logger.info('Attempting to auto-detect CF ADP project for OAuth credentials'); + const tokenProvider = await createManagerFromCfAdpProject(process.cwd(), logger); + logger.info('CF ADP project detected, OAuth middleware enabled'); + return tokenProvider; +} + +/** + * Creates an OAuthTokenProvider from CF ADP project configuration (auto-detection). + * + * @param {string} projectPath - Path to the project root. + * @param {ToolsLogger} logger - Logger instance. + * @returns {Promise} Token provider instance. + */ +export async function createManagerFromCfAdpProject( + projectPath: string, + logger: ToolsLogger +): Promise { + const buildTask = extractCfBuildTask(await readUi5Yaml(projectPath, FileName.Ui5Yaml)); + const name = buildTask.serviceInstanceName; + const guid = buildTask.serviceInstanceGuid; + + if (!name || !guid) { + throw new Error('No service instance name or guid found in CF adaptation project build task'); + } + + const credentials = await getOrCreateServiceKeys( + { + name, + guid + }, + logger + ); + + if (!credentials || credentials.length === 0) { + throw new Error('No service keys found for CF ADP project'); + } + + return createManagerFromServiceKeys(credentials[0], logger); +} diff --git a/packages/backend-proxy-middleware-cf/src/token/index.ts b/packages/backend-proxy-middleware-cf/src/token/index.ts new file mode 100644 index 00000000000..3841b799e30 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/token/index.ts @@ -0,0 +1,2 @@ +export { OAuthTokenProvider } from './provider'; +export { createTokenProvider } from './factory'; diff --git a/packages/backend-proxy-middleware-cf/src/token/provider.ts b/packages/backend-proxy-middleware-cf/src/token/provider.ts new file mode 100644 index 00000000000..ce04ba374ed --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/token/provider.ts @@ -0,0 +1,111 @@ +import axios from 'axios'; +import type { Request, Response, NextFunction } from 'express'; + +import type { ToolsLogger } from '@sap-ux/logger'; + +/** + * Number of seconds before token expiry to refresh the token (safety buffer). + */ +const TOKEN_REFRESH_BUFFER_SECONDS = 60; + +/** + * Provides OAuth2 tokens with caching and automatic refresh. + */ +export class OAuthTokenProvider { + private token: string | null = null; + private tokenExpiry: number = 0; + private tokenFetchPromise: Promise | null = null; + + /** + * Creates a new OAuthTokenProvider instance. + * + * @param {string} clientId - OAuth2 client ID. + * @param {string} clientSecret - OAuth2 client secret. + * @param {string} tokenEndpoint - OAuth2 token endpoint URL. + * @param {ToolsLogger} logger - Logger instance. + */ + constructor( + private readonly clientId: string, + private readonly clientSecret: string, + private readonly tokenEndpoint: string, + private readonly logger: ToolsLogger + ) {} + + /** + * Get a valid OAuth token, refreshing if necessary. + * + * @returns {Promise} The access token. + */ + private async getAccessToken(): Promise { + if (this.token && Date.now() < this.tokenExpiry) { + return this.token; + } + + // If a token fetch is already in progress, wait for it + if (this.tokenFetchPromise) { + return this.tokenFetchPromise; + } + + this.tokenFetchPromise = this.fetchToken(); + + try { + const token = await this.tokenFetchPromise; + return token; + } finally { + // Clear the promise so future requests can start a new fetch if needed + this.tokenFetchPromise = null; + } + } + + /** + * Fetches a new OAuth2 token from the token endpoint. + * + * @returns {Promise} The access token. + */ + private async fetchToken(): Promise { + try { + this.logger.debug('Fetching new OAuth2 token...'); + + const formData = new URLSearchParams({ + grant_type: 'client_credentials', + client_id: this.clientId, + client_secret: this.clientSecret + }); + + const response = await axios.post(this.tokenEndpoint, formData.toString(), { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + }); + + this.token = response.data.access_token; + const expiresIn = response.data.expires_in ?? 3600; + this.tokenExpiry = Date.now() + (expiresIn - TOKEN_REFRESH_BUFFER_SECONDS) * 1000; + + this.logger.debug(`OAuth2 token obtained successfully (expires in ${expiresIn}s)`); + return this.token ?? ''; + } catch (e) { + throw new Error(`Failed to fetch OAuth2 token: ${e.message}`); + } + } + + /** + * Creates an Express middleware function that adds OAuth Bearer token to requests. + * + * @returns {RequestHandler} Express middleware function. + */ + createTokenMiddleware(): (req: Request, res: Response, next: NextFunction) => Promise { + return async (req: Request, _res: Response, next: NextFunction): Promise => { + this.logger.debug(`Token middleware: req.url=${req.url}, req.originalUrl=${req.originalUrl}`); + + try { + const token = await this.getAccessToken(); + req.headers.authorization = `Bearer ${token}`; + this.logger.debug(`Added Bearer token to request: ${req.url}`); + } catch (e) { + this.logger.error(`Failed to get access token: ${e.message}`); + } + next(); + }; + } +} diff --git a/packages/backend-proxy-middleware-cf/src/types.ts b/packages/backend-proxy-middleware-cf/src/types.ts new file mode 100644 index 00000000000..ea8ab0d9194 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/types.ts @@ -0,0 +1,38 @@ +/** + * Configuration for Cloud Foundry OAuth middleware. + */ +export interface CfOAuthMiddlewareConfig { + /** + * Destination URL to proxy requests to. + */ + url: string; + /** + * Array of OData source paths to proxy to this destination. + * Each path represents an OData service that should be proxied to the destination URL. + * Requests matching these paths will have the path prefix removed before forwarding. + */ + paths: string[]; + /** + * Manual OAuth credentials (optional). + * If not provided, middleware will attempt to auto-detect from Cloud Foundry ADP project. + */ + credentials?: { + /** + * OAuth2 client ID. + */ + clientId: string; + /** + * OAuth2 client secret. + */ + clientSecret: string; + /** + * Base URL for the OAuth token endpoint. + * The token endpoint will be constructed as: {url}/oauth/token + */ + url: string; + }; + /** + * Enable debug logging. + */ + debug?: boolean; +} diff --git a/packages/backend-proxy-middleware-cf/src/validation.ts b/packages/backend-proxy-middleware-cf/src/validation.ts new file mode 100644 index 00000000000..3eac683350c --- /dev/null +++ b/packages/backend-proxy-middleware-cf/src/validation.ts @@ -0,0 +1,26 @@ +import type { ToolsLogger } from '@sap-ux/logger'; +import { isLoggedInCf, loadCfConfig } from '@sap-ux/adp-tooling'; + +import type { CfOAuthMiddlewareConfig } from './types'; + +/** + * Validates the middleware configuration. + * + * @param {CfOAuthMiddlewareConfig} config - Configuration to validate. + * @param {ToolsLogger} logger - Logger instance. + * @throws {Error} If configuration is invalid. + */ +export async function validateConfig(config: CfOAuthMiddlewareConfig, logger: ToolsLogger): Promise { + if (!config.url) { + throw new Error('Backend proxy middleware (CF) requires url configuration.'); + } + + if (!config.paths || !Array.isArray(config.paths) || config.paths.length === 0) { + throw new Error('Backend proxy middleware (CF) has no paths configured.'); + } + + const cfConfig = loadCfConfig(logger); + if (!(await isLoggedInCf(cfConfig, logger))) { + throw new Error('User is not logged in to Cloud Foundry.'); + } +} diff --git a/packages/backend-proxy-middleware-cf/test/middleware.test.ts b/packages/backend-proxy-middleware-cf/test/middleware.test.ts new file mode 100644 index 00000000000..0a6f7f9667d --- /dev/null +++ b/packages/backend-proxy-middleware-cf/test/middleware.test.ts @@ -0,0 +1,127 @@ +import express from 'express'; +import supertest from 'supertest'; +import type { ToolsLogger } from '@sap-ux/logger'; + +import * as proxy from '../src/proxy'; +import * as middleware from '../src/middleware'; +import * as validation from '../src/validation'; +import * as tokenFactory from '../src/token/factory'; +import type { CfOAuthMiddlewareConfig } from '../src/types'; + +jest.mock('../src/proxy'); +jest.mock('../src/validation'); +jest.mock('../src/token/factory'); +jest.mock('@sap-ux/adp-tooling', () => ({ + ...jest.requireActual('@sap-ux/adp-tooling'), + isLoggedInCf: jest.fn().mockResolvedValue(true), + loadCfConfig: jest.fn().mockReturnValue({}) +})); + +jest.mock('@sap-ux/logger', () => ({ + ...jest.requireActual('@sap-ux/logger'), + ToolsLogger: jest.fn().mockReturnValue({ + debug: jest.fn(), + info: jest.fn(), + error: jest.fn(), + warn: jest.fn() + } as unknown as ToolsLogger) +})); + +const mockSetupProxyRoutes = proxy.setupProxyRoutes as jest.Mock; +const mockValidateConfig = validation.validateConfig as jest.Mock; +const mockCreateTokenProvider = tokenFactory.createTokenProvider as jest.Mock; + +async function getTestServer(configuration: CfOAuthMiddlewareConfig): Promise> { + const router = await (middleware as any).default({ + options: { configuration } + }); + const app = express(); + app.use(router); + return supertest(app); +} + +describe('backend-proxy-middleware-cf', () => { + const mockTokenProvider = { + createTokenMiddleware: jest.fn().mockReturnValue((req: any, res: any, next: any) => next()) + }; + + beforeEach(() => { + jest.clearAllMocks(); + mockValidateConfig.mockResolvedValue(undefined); + mockCreateTokenProvider.mockResolvedValue(mockTokenProvider); + mockSetupProxyRoutes.mockReturnValue(express.Router()); + }); + + describe('Middleware initialization', () => { + const baseConfig: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + + test('minimal configuration', async () => { + await getTestServer(baseConfig); + + expect(mockValidateConfig).toHaveBeenCalledWith(baseConfig, expect.any(Object)); + expect(mockCreateTokenProvider).toHaveBeenCalledWith(baseConfig, expect.any(Object)); + expect(mockSetupProxyRoutes).toHaveBeenCalledWith( + baseConfig.paths, + baseConfig.url, + mockTokenProvider, + expect.any(Object) + ); + }); + + test('with debug enabled', async () => { + const configWithDebug = { ...baseConfig, debug: true }; + await getTestServer(configWithDebug); + + expect(mockValidateConfig).toHaveBeenCalledWith(configWithDebug, expect.any(Object)); + }); + + test('with credentials', async () => { + const configWithCredentials: CfOAuthMiddlewareConfig = { + ...baseConfig, + credentials: { + clientId: 'test-client', + clientSecret: 'test-secret', + url: '/uaa.example' + } + }; + await getTestServer(configWithCredentials); + + expect(mockCreateTokenProvider).toHaveBeenCalledWith(configWithCredentials, expect.any(Object)); + }); + + test('with multiple paths', async () => { + const configWithMultiplePaths: CfOAuthMiddlewareConfig = { + ...baseConfig, + paths: ['/sap/opu/odata', '/sap/bc/ui5_ui5', '/api'] + }; + await getTestServer(configWithMultiplePaths); + + expect(mockSetupProxyRoutes).toHaveBeenCalledWith( + configWithMultiplePaths.paths, + configWithMultiplePaths.url, + mockTokenProvider, + expect.any(Object) + ); + }); + + test('throws error configuration is missing', async () => { + await expect(getTestServer(undefined as unknown as CfOAuthMiddlewareConfig)).rejects.toThrow( + 'Backend proxy middleware (CF) has no configuration.' + ); + }); + + test('throws error when validation fails', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + const validationError = new Error('Validation failed'); + mockValidateConfig.mockRejectedValueOnce(validationError); + + await expect(getTestServer(config)).rejects.toThrow('Validation failed'); + }); + }); +}); diff --git a/packages/backend-proxy-middleware-cf/test/proxy.test.ts b/packages/backend-proxy-middleware-cf/test/proxy.test.ts new file mode 100644 index 00000000000..31013a54039 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/test/proxy.test.ts @@ -0,0 +1,211 @@ +import nock from 'nock'; +import supertest from 'supertest'; +import express, { type Request, type Response, type NextFunction, Router } from 'express'; + +import type { ToolsLogger } from '@sap-ux/logger'; + +import type { OAuthTokenProvider } from '../src/token'; +import { createProxyOptions, registerProxyRoute, setupProxyRoutes } from '../src/proxy'; + +describe('proxy', () => { + const logger = { + debug: jest.fn(), + info: jest.fn(), + error: jest.fn(), + warn: jest.fn() + } as unknown as ToolsLogger; + + const mockTokenProvider = { + createTokenMiddleware: jest.fn().mockReturnValue((req: Request, _res: Response, next: NextFunction) => { + req.headers.authorization = 'Bearer mock-token'; + next(); + }) + } as unknown as OAuthTokenProvider; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + const targetUrl = '/backend.example'; + + describe('createProxyOptions', () => { + test('creates proxy options with correct target', () => { + const options = createProxyOptions(targetUrl, logger); + + expect(options.target).toBe(targetUrl); + expect(options.changeOrigin).toBe(true); + expect(options.pathRewrite).toBeDefined(); + expect(options.on).toBeDefined(); + expect(options.on?.error).toBeDefined(); + }); + + test('pathRewrite uses originalUrl when available', () => { + const options = createProxyOptions(targetUrl, logger); + const pathRewrite = options.pathRewrite as Function; + + const req = { + originalUrl: '/sap/opu/odata/srv/EntitySet', + url: '/srv/EntitySet' + }; + + const result = pathRewrite('/srv/EntitySet', req); + expect(result).toBe('/sap/opu/odata/srv/EntitySet'); + }); + + test('pathRewrite uses req.url when originalUrl is not available', () => { + const options = createProxyOptions(targetUrl, logger); + const pathRewrite = options.pathRewrite as Function; + + const req = { + url: '/srv/EntitySet' + }; + + const result = pathRewrite('/srv/EntitySet', req); + expect(result).toBe('/srv/EntitySet'); + }); + + test('pathRewrite preserves query string', () => { + const options = createProxyOptions(targetUrl, logger); + const pathRewrite = options.pathRewrite as Function; + + const req = { + originalUrl: '/sap/opu/odata/srv/EntitySet?$top=10&$skip=0', + url: '/srv/EntitySet?$top=10&$skip=0' + }; + + const result = pathRewrite('/srv/EntitySet?$top=10&$skip=0', req); + expect(result).toBe('/sap/opu/odata/srv/EntitySet?$top=10&$skip=0'); + }); + + test('error handler logs error and calls next if available', () => { + const options = createProxyOptions(targetUrl, logger); + const errorHandler = options.on?.error as Function; + + const error = new Error('Proxy error'); + const req = { + originalUrl: '/sap/opu/odata', + url: '/sap/opu/odata', + next: jest.fn() + }; + const res = {}; + const target = '/backend.example'; + + errorHandler(error, req, res, target); + expect(req.next).toHaveBeenCalledWith(error); + }); + + test('error handler does not throw if next is not available', () => { + const options = createProxyOptions(targetUrl, logger); + const errorHandler = options.on?.error as Function; + + const error = new Error('Proxy error'); + const req = { + originalUrl: '/sap/opu/odata', + url: '/sap/opu/odata' + }; + const res = {}; + + expect(() => errorHandler(error, req, res, targetUrl)).not.toThrow(); + }); + }); + + describe('registerProxyRoute', () => { + test('registers proxy route successfully', () => { + const router = Router(); + const path = '/sap/opu/odata'; + const destinationUrl = '/backend.example'; + + registerProxyRoute(path, destinationUrl, mockTokenProvider, logger, router); + + expect(mockTokenProvider.createTokenMiddleware).toHaveBeenCalled(); + expect(router.stack.length).toBeGreaterThan(0); + }); + }); + + describe('setupProxyRoutes', () => { + test('sets up multiple proxy routes', () => { + const paths = ['/sap/opu/odata', '/sap/bc/ui5_ui5', '/api']; + const destinationUrl = '/backend.example'; + + const router = setupProxyRoutes(paths, destinationUrl, mockTokenProvider, logger); + + expect(typeof router).toBe('function'); + expect(router.use).toBeDefined(); + expect(mockTokenProvider.createTokenMiddleware).toHaveBeenCalledTimes(paths.length); + }); + + test('throws error when route registration fails', () => { + const paths = ['/sap/opu/odata']; + const destinationUrl = '/backend.example'; + const failingTokenProvider = { + createTokenMiddleware: jest.fn().mockImplementation(() => { + throw new Error('Token middleware creation failed'); + }) + } as unknown as OAuthTokenProvider; + + expect(() => { + setupProxyRoutes(paths, destinationUrl, failingTokenProvider, logger); + }).toThrow('Failed to register proxy for /sap/opu/odata'); + }); + + test('handles empty paths array', () => { + const paths: string[] = []; + const destinationUrl = '/backend.example'; + + const router = setupProxyRoutes(paths, destinationUrl, mockTokenProvider, logger); + + expect(typeof router).toBe('function'); + expect(router.use).toBeDefined(); + expect(router.stack.length).toBe(0); + }); + }); + + describe('integration tests', () => { + const path = '/sap/opu/odata'; + const destinationUrl = 'https://backend.example'; + + test('proxies request with token middleware', async () => { + const router = setupProxyRoutes([path], destinationUrl, mockTokenProvider, logger); + + const app = express(); + app.use(router); + + nock(destinationUrl) + .get(`${path}/EntitySet`) + .matchHeader('authorization', 'Bearer mock-token') + .reply(200, { value: [] }); + + const server = supertest(app); + const response = await server.get(`${path}/EntitySet`); + + expect(response.status).toBe(200); + expect(response.body).toEqual({ value: [] }); + }); + + test('proxies request with query parameters', async () => { + const router = setupProxyRoutes([path], destinationUrl, mockTokenProvider, logger); + + const app = express(); + app.use(router); + + nock(destinationUrl).get(`${path}/EntitySet`).query({ $top: '10', $skip: '0' }).reply(200, { value: [] }); + + const server = supertest(app); + const response = await server.get(`${path}/EntitySet?$top=10&$skip=0`); + + expect(response.status).toBe(200); + }); + + test('handles non-proxied paths', async () => { + const router = setupProxyRoutes([path], destinationUrl, mockTokenProvider, logger); + + const app = express(); + app.use(router); + + const server = supertest(app); + const response = await server.get('/not/proxied/path'); + + expect(response.status).toBe(404); + }); + }); +}); diff --git a/packages/backend-proxy-middleware-cf/test/token/factory.test.ts b/packages/backend-proxy-middleware-cf/test/token/factory.test.ts new file mode 100644 index 00000000000..bd05e77fb79 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/test/token/factory.test.ts @@ -0,0 +1,290 @@ +import type { ToolsLogger } from '@sap-ux/logger'; +import { readUi5Yaml, FileName } from '@sap-ux/project-access'; +import { extractCfBuildTask, getOrCreateServiceKeys } from '@sap-ux/adp-tooling'; + +import { + createManagerFromServiceKeys, + createManagerFromDirectCredentials, + createTokenProvider, + createManagerFromCfAdpProject +} from '../../src/token/factory'; +import { OAuthTokenProvider } from '../../src/token/provider'; +import type { CfOAuthMiddlewareConfig } from '../../src/types'; + +jest.mock('@sap-ux/adp-tooling', () => ({ + ...(jest.requireActual('@sap-ux/adp-tooling') as object), + extractCfBuildTask: jest.fn(), + getOrCreateServiceKeys: jest.fn() +})); + +jest.mock('@sap-ux/project-access', () => ({ + ...(jest.requireActual('@sap-ux/project-access') as object), + readUi5Yaml: jest.fn() +})); + +const mockExtractCfBuildTask = extractCfBuildTask as jest.Mock; +const mockGetOrCreateServiceKeys = getOrCreateServiceKeys as jest.Mock; +const mockReadUi5Yaml = readUi5Yaml as jest.Mock; + +describe('token factory', () => { + const logger = { + debug: jest.fn(), + info: jest.fn(), + error: jest.fn(), + warn: jest.fn() + } as unknown as ToolsLogger; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('createManagerFromServiceKeys', () => { + test('creates provider from valid service keys', () => { + const serviceKeys = { + credentials: { + uaa: { + url: '/uaa.example', + clientid: 'test-client-id', + clientsecret: 'test-client-secret' + } + } + }; + + const provider = createManagerFromServiceKeys(serviceKeys as any, logger); + + expect(provider).toBeInstanceOf(OAuthTokenProvider); + }); + + test('throws error when UAA URL is missing', () => { + const serviceKeys = { + credentials: { + uaa: { + clientid: 'test-client-id', + clientsecret: 'test-client-secret' + } + } + }; + + expect(() => { + createManagerFromServiceKeys(serviceKeys as any, logger); + }).toThrow('Invalid credentials: missing UAA URL'); + }); + + test('throws error when client ID is missing', () => { + const serviceKeys = { + credentials: { + uaa: { + url: '/uaa.example', + clientsecret: 'test-client-secret' + } + } + }; + + expect(() => { + createManagerFromServiceKeys(serviceKeys as any, logger); + }).toThrow('Invalid credentials: missing client ID'); + }); + + test('throws error when client secret is missing', () => { + const serviceKeys = { + credentials: { + uaa: { + url: '/uaa.example', + clientid: 'test-client-id' + } + } + }; + + expect(() => { + createManagerFromServiceKeys(serviceKeys as any, logger); + }).toThrow('Invalid credentials: missing client secret'); + }); + }); + + describe('createManagerFromDirectCredentials', () => { + test('creates provider from direct credentials', () => { + const clientId = 'test-client-id'; + const clientSecret = 'test-client-secret'; + const baseUrl = '/uaa.example'; + + const provider = createManagerFromDirectCredentials(clientId, clientSecret, baseUrl, logger); + + expect(provider).toBeInstanceOf(OAuthTokenProvider); + expect(provider['tokenEndpoint']).toBe(`${baseUrl}/oauth/token`); + }); + }); + + describe('createTokenProvider', () => { + test('creates provider from credentials in config', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'], + credentials: { + clientId: 'test-client-id', + clientSecret: 'test-client-secret', + url: '/uaa.example' + } + }; + + const provider = await createTokenProvider(config, logger); + + expect(provider).toBeInstanceOf(OAuthTokenProvider); + expect(provider['tokenEndpoint']).toBe(`${config.credentials?.url}/oauth/token`); + }); + + test('creates provider from CF ADP project when credentials not provided', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + + const mockUi5Yaml = { + builder: { + customTasks: [ + { + name: 'app-variant-bundler-build', + configuration: { + serviceInstanceName: 'test-service', + serviceInstanceGuid: 'test-guid' + } + } + ] + } + }; + + const mockServiceKeys = [ + { + credentials: { + uaa: { + url: '/uaa.example', + clientid: 'test-client-id', + clientsecret: 'test-client-secret' + } + } + } + ]; + + mockReadUi5Yaml.mockResolvedValueOnce(mockUi5Yaml); + mockExtractCfBuildTask.mockReturnValueOnce({ + serviceInstanceName: 'test-service', + serviceInstanceGuid: 'test-guid' + }); + mockGetOrCreateServiceKeys.mockResolvedValueOnce(mockServiceKeys); + + const provider = await createTokenProvider(config, logger); + + expect(provider).toBeInstanceOf(OAuthTokenProvider); + expect(provider['tokenEndpoint']).toBe('/uaa.example/oauth/token'); + expect(mockReadUi5Yaml).toHaveBeenCalledWith(process.cwd(), FileName.Ui5Yaml); + expect(mockExtractCfBuildTask).toHaveBeenCalledWith(mockUi5Yaml); + expect(mockGetOrCreateServiceKeys).toHaveBeenCalledWith( + { + name: 'test-service', + guid: 'test-guid' + }, + logger + ); + }); + + test('throws error when service instance name is missing', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + + const mockUi5Yaml = { + builder: { + customTasks: [ + { + name: 'app-variant-bundler-build', + configuration: {} + } + ] + } + }; + + mockReadUi5Yaml.mockResolvedValueOnce(mockUi5Yaml); + mockExtractCfBuildTask.mockReturnValueOnce({ + serviceInstanceName: undefined, + serviceInstanceGuid: 'test-guid' + }); + + await expect(createTokenProvider(config, logger)).rejects.toThrow( + 'No service instance name or guid found in CF adaptation project build task' + ); + }); + + test('throws error when no service keys found', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + + const mockUi5Yaml = { + builder: { + customTasks: [ + { + name: 'app-variant-bundler-build', + configuration: {} + } + ] + } + }; + + mockReadUi5Yaml.mockResolvedValueOnce(mockUi5Yaml); + mockExtractCfBuildTask.mockReturnValueOnce({ + serviceInstanceName: 'test-service', + serviceInstanceGuid: 'test-guid' + }); + mockGetOrCreateServiceKeys.mockResolvedValueOnce([]); + + await expect(createTokenProvider(config, logger)).rejects.toThrow( + 'No service keys found for CF ADP project' + ); + }); + }); + + describe('createManagerFromCfAdpProject', () => { + test('creates provider from CF ADP project', async () => { + const projectPath = '/test/project'; + const mockUi5Yaml = { + builder: { + customTasks: [ + { + name: 'app-variant-bundler-build', + configuration: { + serviceInstanceName: 'test-service', + serviceInstanceGuid: 'test-guid' + } + } + ] + } + }; + + const mockServiceKeys = [ + { + credentials: { + uaa: { + url: '/uaa.example', + clientid: 'test-client-id', + clientsecret: 'test-client-secret' + } + } + } + ]; + + mockReadUi5Yaml.mockResolvedValueOnce(mockUi5Yaml); + mockExtractCfBuildTask.mockReturnValueOnce({ + serviceInstanceName: 'test-service', + serviceInstanceGuid: 'test-guid' + }); + mockGetOrCreateServiceKeys.mockResolvedValueOnce(mockServiceKeys); + + const provider = await createManagerFromCfAdpProject(projectPath, logger); + + expect(provider).toBeInstanceOf(OAuthTokenProvider); + expect(provider['tokenEndpoint']).toBe('/uaa.example/oauth/token'); + expect(mockReadUi5Yaml).toHaveBeenCalledWith(projectPath, FileName.Ui5Yaml); + }); + }); +}); diff --git a/packages/backend-proxy-middleware-cf/test/token/provider.test.ts b/packages/backend-proxy-middleware-cf/test/token/provider.test.ts new file mode 100644 index 00000000000..94f8ee27edb --- /dev/null +++ b/packages/backend-proxy-middleware-cf/test/token/provider.test.ts @@ -0,0 +1,224 @@ +import axios from 'axios'; +import type { Request, Response } from 'express'; + +import type { ToolsLogger } from '@sap-ux/logger'; + +import { OAuthTokenProvider } from '../../src/token/provider'; + +jest.mock('axios'); + +const mockedAxios = axios as jest.Mocked; + +describe('OAuthTokenProvider', () => { + const logger = { + debug: jest.fn(), + info: jest.fn(), + error: jest.fn(), + warn: jest.fn() + } as unknown as ToolsLogger; + + const clientId = 'test-client-id'; + const clientSecret = 'test-client-secret'; + const tokenEndpoint = '/uaa.example/oauth/token'; + + beforeEach(() => { + jest.clearAllMocks(); + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + describe('constructor', () => { + test('creates instance with correct parameters', () => { + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + expect(provider).toBeInstanceOf(OAuthTokenProvider); + }); + }); + + describe('token fetching through middleware', () => { + test('fetches new token on first call', async () => { + const mockResponse = { + data: { + access_token: 'new-access-token', + expires_in: 3600 + } + }; + mockedAxios.post.mockResolvedValueOnce(mockResponse); + + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + const middleware = provider.createTokenMiddleware(); + + const req = { + url: '/test', + headers: {} + } as Request; + const res = {} as Response; + const next = jest.fn(); + + await middleware(req, res, next); + + expect(req.headers.authorization).toBe('Bearer new-access-token'); + expect(mockedAxios.post).toHaveBeenCalledWith( + tokenEndpoint, + expect.stringContaining('grant_type=client_credentials'), + expect.objectContaining({ + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + }) + ); + }); + + test('returns cached token if not expired', async () => { + const mockResponse = { + data: { + access_token: 'cached-token', + expires_in: 3600 + } + }; + mockedAxios.post.mockResolvedValueOnce(mockResponse); + + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + const middleware = provider.createTokenMiddleware(); + + const req1 = { url: '/test1', headers: {} } as Request; + const req2 = { url: '/test2', headers: {} } as Request; + const res = {} as Response; + const next = jest.fn(); + + await middleware(req1, res, next); + await middleware(req2, res, next); + + expect(req1.headers.authorization).toBe('Bearer cached-token'); + expect(req2.headers.authorization).toBe('Bearer cached-token'); + expect(mockedAxios.post).toHaveBeenCalledTimes(1); + }); + + test('refreshes token when expired', async () => { + const mockResponse1 = { + data: { + access_token: 'first-token', + expires_in: 60 // 60 seconds + } + }; + const mockResponse2 = { + data: { + access_token: 'second-token', + expires_in: 3600 + } + }; + mockedAxios.post.mockResolvedValueOnce(mockResponse1).mockResolvedValueOnce(mockResponse2); + + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + const middleware = provider.createTokenMiddleware(); + + const req1 = { url: '/test1', headers: {} } as Request; + const req2 = { url: '/test2', headers: {} } as Request; + const res = {} as Response; + const next = jest.fn(); + + await middleware(req1, res, next); + + // Advance time past expiry (with buffer) + jest.advanceTimersByTime(2000 * 1000); // 2000 seconds + + await middleware(req2, res, next); + + expect(req1.headers.authorization).toBe('Bearer first-token'); + expect(req2.headers.authorization).toBe('Bearer second-token'); + expect(mockedAxios.post).toHaveBeenCalledTimes(2); + }); + + test('throws error when token fetch fails', async () => { + const error = new Error('Network error'); + mockedAxios.post.mockRejectedValueOnce(error); + + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + const middleware = provider.createTokenMiddleware(); + + const req = { url: '/test', headers: {} } as Request; + const res = {} as Response; + const next = jest.fn(); + + await middleware(req, res, next); + + expect(next).toHaveBeenCalled(); + expect(req.headers.authorization).toBeUndefined(); + }); + + test('sends correct form data', async () => { + const mockResponse = { + data: { + access_token: 'test-token', + expires_in: 3600 + } + }; + mockedAxios.post.mockResolvedValueOnce(mockResponse); + + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + const middleware = provider.createTokenMiddleware(); + + const req = { url: '/test', headers: {} } as Request; + const res = {} as Response; + const next = jest.fn(); + + await middleware(req, res, next); + + const callArgs = mockedAxios.post.mock.calls[0]; + const formData = callArgs[1] as string; + const params = new URLSearchParams(formData); + + expect(params.get('grant_type')).toBe('client_credentials'); + expect(params.get('client_id')).toBe(clientId); + expect(params.get('client_secret')).toBe(clientSecret); + }); + + test('prevents concurrent token fetches - multiple requests wait for same in-flight fetch', async () => { + const mockResponse = { + data: { + access_token: 'shared-token', + expires_in: 3600 + } + }; + + // Create a delayed promise to simulate network latency + let resolveTokenFetch: ((value: typeof mockResponse) => void) | undefined; + const delayedTokenFetch = new Promise((resolve) => { + resolveTokenFetch = resolve; + }); + + mockedAxios.post.mockImplementation(() => delayedTokenFetch); + + const provider = new OAuthTokenProvider(clientId, clientSecret, tokenEndpoint, logger); + const middleware = provider.createTokenMiddleware(); + + const req1 = { url: '/test1', headers: {} } as Request; + const req2 = { url: '/test2', headers: {} } as Request; + const req3 = { url: '/test3', headers: {} } as Request; + const res = {} as Response; + const next = jest.fn(); + + // Start all three requests simultaneously (before token is cached) + const promise1 = middleware(req1, res, next); + const promise2 = middleware(req2, res, next); + const promise3 = middleware(req3, res, next); + + expect(mockedAxios.post).toHaveBeenCalledTimes(1); + + if (!resolveTokenFetch) { + throw new Error('resolveTokenFetch was not initialized'); + } + resolveTokenFetch(mockResponse); + + await Promise.all([promise1, promise2, promise3]); + + expect(req1.headers.authorization).toBe('Bearer shared-token'); + expect(req2.headers.authorization).toBe('Bearer shared-token'); + expect(req3.headers.authorization).toBe('Bearer shared-token'); + + expect(mockedAxios.post).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/packages/backend-proxy-middleware-cf/test/validation.test.ts b/packages/backend-proxy-middleware-cf/test/validation.test.ts new file mode 100644 index 00000000000..15f2053fe53 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/test/validation.test.ts @@ -0,0 +1,104 @@ +import type { ToolsLogger } from '@sap-ux/logger'; +import { isLoggedInCf, loadCfConfig } from '@sap-ux/adp-tooling'; + +import { validateConfig } from '../src/validation'; +import type { CfOAuthMiddlewareConfig } from '../src/types'; + +jest.mock('@sap-ux/adp-tooling', () => ({ + ...(jest.requireActual('@sap-ux/adp-tooling') as object), + isLoggedInCf: jest.fn(), + loadCfConfig: jest.fn() +})); + +const mockIsLoggedInCf = isLoggedInCf as jest.Mock; +const mockLoadCfConfig = loadCfConfig as jest.Mock; + +describe('validation', () => { + const logger = { + debug: jest.fn(), + info: jest.fn(), + error: jest.fn(), + warn: jest.fn() + } as unknown as ToolsLogger; + + beforeEach(() => { + jest.clearAllMocks(); + mockLoadCfConfig.mockReturnValue({}); + mockIsLoggedInCf.mockResolvedValue(true); + }); + + describe('validateConfig', () => { + test('validates successfully with valid config', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + + await expect(validateConfig(config, logger)).resolves.not.toThrow(); + expect(mockLoadCfConfig).toHaveBeenCalledWith(logger); + expect(mockIsLoggedInCf).toHaveBeenCalledWith({}, logger); + }); + + test('throws error when url is empty string', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '', + paths: ['/sap/opu/odata'] + }; + + await expect(validateConfig(config, logger)).rejects.toThrow( + 'Backend proxy middleware (CF) requires url configuration.' + ); + }); + + test('throws error when paths is missing', async () => { + const config = { + url: '/backend.example' + } as CfOAuthMiddlewareConfig; + + await expect(validateConfig(config, logger)).rejects.toThrow( + 'Backend proxy middleware (CF) has no paths configured.' + ); + }); + + test('throws error when paths is empty array', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: [] + }; + + await expect(validateConfig(config, logger)).rejects.toThrow( + 'Backend proxy middleware (CF) has no paths configured.' + ); + }); + + test('throws error when paths is not an array', async () => { + const config = { + url: '/backend.example', + paths: 'not-an-array' + } as unknown as CfOAuthMiddlewareConfig; + + await expect(validateConfig(config, logger)).rejects.toThrow( + 'Backend proxy middleware (CF) has no paths configured.' + ); + }); + + test('throws error when user is not logged in to CF', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata'] + }; + mockIsLoggedInCf.mockResolvedValue(false); + + await expect(validateConfig(config, logger)).rejects.toThrow('User is not logged in to Cloud Foundry.'); + }); + + test('validates successfully with multiple paths', async () => { + const config: CfOAuthMiddlewareConfig = { + url: '/backend.example', + paths: ['/sap/opu/odata', '/sap/bc/ui5_ui5', '/api'] + }; + + await expect(validateConfig(config, logger)).resolves.not.toThrow(); + }); + }); +}); diff --git a/packages/backend-proxy-middleware-cf/tsconfig.eslint.json b/packages/backend-proxy-middleware-cf/tsconfig.eslint.json new file mode 100644 index 00000000000..bf4ea1679e4 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/tsconfig.eslint.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "include": ["src", "test", "*.ts", "*.js"] +} diff --git a/packages/backend-proxy-middleware-cf/tsconfig.json b/packages/backend-proxy-middleware-cf/tsconfig.json new file mode 100644 index 00000000000..94b6998b94f --- /dev/null +++ b/packages/backend-proxy-middleware-cf/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src", "src/**/*.json", "../../types/ui5.d.ts"], + "compilerOptions": { + "rootDir": "src", + "outDir": "dist" + }, + "references": [{ "path": "../adp-tooling" }, { "path": "../logger" }, { "path": "../project-access" }] +} diff --git a/packages/backend-proxy-middleware-cf/ui5.yaml b/packages/backend-proxy-middleware-cf/ui5.yaml new file mode 100644 index 00000000000..573e34a4293 --- /dev/null +++ b/packages/backend-proxy-middleware-cf/ui5.yaml @@ -0,0 +1,7 @@ +specVersion: '2.6' +metadata: + name: backend-proxy-middleware-cf +kind: extension +type: server-middleware +middleware: + path: dist/middleware.js diff --git a/packages/generator-adp/src/app/index.ts b/packages/generator-adp/src/app/index.ts index 84ed7cd636b..8fbdd820187 100644 --- a/packages/generator-adp/src/app/index.ts +++ b/packages/generator-adp/src/app/index.ts @@ -27,7 +27,6 @@ import { isExtensionInstalled, sendTelemetry } from '@sap-ux/fiori-generator-shared'; -import { isAppStudio } from '@sap-ux/btp-utils'; import { ToolsLogger } from '@sap-ux/logger'; import type { Manifest } from '@sap-ux/project-access'; import type { AbapServiceProvider } from '@sap-ux/axios-extension'; @@ -234,7 +233,7 @@ export default class extends Generator { const isInternalUsage = isInternalFeaturesSettingEnabled(); if (!this.jsonInput) { - const shouldShowTargetEnv = isAppStudio() && this.cfInstalled && this.isCfFeatureEnabled; + const shouldShowTargetEnv = this.cfInstalled && this.isCfFeatureEnabled; this.prompts.splice(0, 0, getWizardPages(shouldShowTargetEnv)); this.prompter = this._getOrCreatePrompter(); this.cfPrompter = new CFServicesPrompter(isInternalUsage, this.isCfLoggedIn, this.logger); @@ -455,7 +454,7 @@ export default class extends Generator { private async _determineTargetEnv(): Promise { const hasRequiredExtensions = this.isCfFeatureEnabled && this.cfInstalled; - if (isAppStudio() && hasRequiredExtensions) { + if (hasRequiredExtensions) { await this._promptForTargetEnvironment(); } else { this.targetEnv = TargetEnv.ABAP; @@ -467,7 +466,7 @@ export default class extends Generator { */ private async _promptForTargetEnvironment(): Promise { const targetEnvAnswers = await this.prompt([ - getTargetEnvPrompt(this.appWizard, this.cfInstalled, this.isCfLoggedIn, this.cfConfig, this.vscode) + getTargetEnvPrompt(this.appWizard, this.cfInstalled, this.isCfLoggedIn, this.cfConfig) ]); this.targetEnv = targetEnvAnswers.targetEnv; @@ -546,7 +545,10 @@ export default class extends Generator { throw new Error('Manifest not found for base app.'); } - const html5RepoRuntimeGuid = this.cfPrompter.serviceInstanceGuid; + const html5RepoRuntimeGuid = this.cfPrompter.html5RepoRuntimeGuid; + const serviceInstanceGuid = this.cfPrompter.serviceInstanceGuid; + const backendUrl = this.cfPrompter.backendUrl; + const oauthPaths = this.cfPrompter.oauthPaths; const config = getCfConfig({ attributeAnswers: this.attributeAnswers, cfServicesAnswers: this.cfServicesAnswers, @@ -554,6 +556,9 @@ export default class extends Generator { layer: this.layer, manifest, html5RepoRuntimeGuid, + serviceInstanceGuid, + backendUrl, + oauthPaths, projectPath, publicVersions }); diff --git a/packages/generator-adp/src/app/questions/cf-services.ts b/packages/generator-adp/src/app/questions/cf-services.ts index 11981b8b4c1..2e69adae3b8 100644 --- a/packages/generator-adp/src/app/questions/cf-services.ts +++ b/packages/generator-adp/src/app/questions/cf-services.ts @@ -7,7 +7,8 @@ import type { AppRouterType, CfConfig, CFApp, - ServiceInfo + ServiceInfo, + HTML5Content } from '@sap-ux/adp-tooling'; import { cfServicesPromptNames, @@ -20,7 +21,9 @@ import { downloadAppContent, validateSmartTemplateApplication, validateODataEndpoints, - getBusinessServiceInfo + getBusinessServiceInfo, + getOAuthPathsFromXsApp, + getBackendUrlFromServiceKeys } from '@sap-ux/adp-tooling'; import type { ToolsLogger } from '@sap-ux/logger'; import type { Manifest } from '@sap-ux/project-access'; @@ -68,6 +71,10 @@ export class CFServicesPrompter { * The manifest. */ private appManifest: Manifest | undefined; + /** + * The zip entries from the downloaded app content. + */ + private appContentEntries: HTML5Content['entries'] | undefined; /** * Returns the loaded application manifest. @@ -79,14 +86,45 @@ export class CFServicesPrompter { } /** - * Returns the service instance GUID. + * Returns the HTML5 repo service instance GUID. * - * @returns Service instance GUID. + * @returns {string} HTML5 repo service instance GUID. */ - public get serviceInstanceGuid(): string { + public get html5RepoRuntimeGuid(): string { return this.html5RepoServiceInstanceGuid; } + /** + * Returns the business service instance GUID. + * + * @returns {string | undefined} Business service instance GUID. + */ + public get serviceInstanceGuid(): string | undefined { + return this.businessServiceInfo?.serviceInstance?.guid; + } + + /** + * Returns the backend URL from service keys endpoints. + * + * @returns {string | undefined} Backend URL from the first endpoint that has a url property, or undefined. + */ + public get backendUrl(): string | undefined { + const serviceKeys = this.businessServiceInfo?.serviceKeys ?? []; + return getBackendUrlFromServiceKeys(serviceKeys); + } + + /** + * Returns the OAuth paths extracted from xs-app.json routes that have a source property. + * + * @returns {string[]} Array of path patterns that should receive OAuth Bearer tokens. + */ + public get oauthPaths(): string[] { + if (!this.appContentEntries) { + return []; + } + return getOAuthPathsFromXsApp(this.appContentEntries); + } + /** * Constructor for CFServicesPrompter. * @@ -236,6 +274,7 @@ export class CFServicesPrompter { ); this.appManifest = manifest; this.html5RepoServiceInstanceGuid = serviceInstanceGuid; + this.appContentEntries = entries; await validateSmartTemplateApplication(manifest); await validateODataEndpoints(entries, this.businessServiceInfo!.serviceKeys, this.logger); diff --git a/packages/generator-adp/src/app/questions/helper/validators.ts b/packages/generator-adp/src/app/questions/helper/validators.ts index fffd529da59..a1b41b0f7ba 100644 --- a/packages/generator-adp/src/app/questions/helper/validators.ts +++ b/packages/generator-adp/src/app/questions/helper/validators.ts @@ -1,8 +1,7 @@ import fs from 'node:fs'; -import { isAppStudio } from '@sap-ux/btp-utils'; import type { ToolsLogger } from '@sap-ux/logger'; -import { getMtaServices, isExternalLoginEnabled, isMtaProject, type SystemLookup } from '@sap-ux/adp-tooling'; +import { getMtaServices, isMtaProject, type SystemLookup } from '@sap-ux/adp-tooling'; import { validateEmptyString, validateNamespaceAdp, validateProjectName } from '@sap-ux/project-input-validator'; import { t } from '../../../utils/i18n'; @@ -92,25 +91,13 @@ export async function validateJsonInput( * * @param {string} value - The value to validate. * @param {boolean} isCFLoggedIn - Whether Cloud Foundry is logged in. - * @param {any} vscode - The vscode instance. * @returns {Promise} Returns true if the environment is valid, otherwise returns an error message. */ -export async function validateEnvironment( - value: string, - isCFLoggedIn: boolean, - vscode: any -): Promise { +export async function validateEnvironment(value: string, isCFLoggedIn: boolean): Promise { if (value === 'CF' && !isCFLoggedIn) { return t('error.cfNotLoggedIn'); } - if (value === 'CF' && !isAppStudio()) { - const isExtLoginEnabled = await isExternalLoginEnabled(vscode); - if (!isExtLoginEnabled) { - return t('error.cfLoginCannotBeDetected'); - } - } - return true; } diff --git a/packages/generator-adp/src/app/questions/target-env.ts b/packages/generator-adp/src/app/questions/target-env.ts index 01d525190ec..57da92692d7 100644 --- a/packages/generator-adp/src/app/questions/target-env.ts +++ b/packages/generator-adp/src/app/questions/target-env.ts @@ -21,15 +21,13 @@ type EnvironmentChoice = { name: string; value: TargetEnv }; * @param {boolean} isCfInstalled - Whether Cloud Foundry is installed. * @param {boolean} isCFLoggedIn - Whether Cloud Foundry is logged in. * @param {CfConfig} cfConfig - The CF config service instance. - * @param {any} vscode - The vscode instance. * @returns {object[]} The target environment prompt. */ export function getTargetEnvPrompt( appWizard: AppWizard, isCfInstalled: boolean, isCFLoggedIn: boolean, - cfConfig: CfConfig, - vscode: any + cfConfig: CfConfig ): TargetEnvQuestion { return { type: 'list', @@ -42,7 +40,7 @@ export function getTargetEnvPrompt( hint: t('prompts.targetEnvTooltip'), breadcrumb: t('prompts.targetEnvBreadcrumb') }, - validate: (value: string) => validateEnvironment(value, isCFLoggedIn, vscode), + validate: (value: string) => validateEnvironment(value, isCFLoggedIn), additionalMessages: (value: string) => getTargetEnvAdditionalMessages(value, isCFLoggedIn, cfConfig) } as ListQuestion; } diff --git a/packages/generator-adp/test/__snapshots__/app.test.ts.snap b/packages/generator-adp/test/__snapshots__/app.test.ts.snap index eaf06fb7eb5..c1971f120cd 100644 --- a/packages/generator-adp/test/__snapshots__/app.test.ts.snap +++ b/packages/generator-adp/test/__snapshots__/app.test.ts.snap @@ -200,15 +200,27 @@ app.variant_sap.app.title=App Title" exports[`Adaptation Project Generator Integration Test CF Environment should generate an adaptation project successfully 3`] = ` "--- -specVersion: "2.2" +specVersion: "3.1" type: application metadata: name: app.variant resources: configuration: propertiesFileSourceEncoding: UTF-8 - paths: - webapp: dist +builder: + customTasks: + - name: app-variant-bundler-build + beforeTask: escapeNonAsciiCharacters + configuration: + module: app.variant + appHostId: test-app-host-id + appName: test-app-name + appVersion: test-app-version + org: org-guid + space: space-guid + sapCloudService: test-solution + serviceInstanceName: test-service + serviceInstanceGuid: test-guid server: customMiddleware: - name: fiori-tools-proxy @@ -225,36 +237,12 @@ server: configuration: flp: theme: sap_horizon + adp: + useLocal: dist " `; exports[`Adaptation Project Generator Integration Test CF Environment should generate an adaptation project successfully 4`] = ` -"--- -specVersion: "2.2" -type: application -metadata: - name: app.variant -resources: - configuration: - propertiesFileSourceEncoding: UTF-8 -builder: - customTasks: - - name: app-variant-bundler-build - beforeTask: escapeNonAsciiCharacters - configuration: - module: app.variant - appHostId: test-app-host-id - appName: test-app-name - appVersion: test-app-version - html5RepoRuntime: test-guid - org: org-guid - space: space-guid - sapCloudService: test-solution - serviceInstanceName: test-service -" -`; - -exports[`Adaptation Project Generator Integration Test CF Environment should generate an adaptation project successfully 5`] = ` "ID: mta-project version: 1.0.0 modules: @@ -353,7 +341,7 @@ description: Test MTA Project for CF Writer Tests " `; -exports[`Adaptation Project Generator Integration Test CF Environment should generate an adaptation project successfully 6`] = ` +exports[`Adaptation Project Generator Integration Test CF Environment should generate an adaptation project successfully 5`] = ` "{ "name": "app.variant", "version": "1.0.0", @@ -362,7 +350,8 @@ exports[`Adaptation Project Generator Integration Test CF Environment should gen "scripts": { "prestart": "npm run build", "start": "fiori run --open /test/flp.html#app-preview", - "build": "npm run clean && ui5 build --config ui5-build.yaml --include-task=generateCachebusterInfo && npm run zip", + "start-editor": "fiori run --open /test/adaptation-editor.html", + "build": "npm run clean && ui5 build --include-task=generateCachebusterInfo && npm run zip", "zip": "cd dist && npx bestzip ../app.variant.zip *", "clean": "npx rimraf app.variant.zip dist", "build-ui5": "npm explore @ui5/task-adaptation -- npm run rollup" diff --git a/packages/generator-adp/test/app.test.ts b/packages/generator-adp/test/app.test.ts index c0f1e755ecb..6fa449fa38c 100644 --- a/packages/generator-adp/test/app.test.ts +++ b/packages/generator-adp/test/app.test.ts @@ -652,27 +652,23 @@ describe('Adaptation Project Generator Integration Test', () => { const manifestPath = join(projectFolder, 'webapp', 'manifest.appdescr_variant'); const i18nPath = join(projectFolder, 'webapp', 'i18n', 'i18n.properties'); const ui5Yaml = join(projectFolder, 'ui5.yaml'); - const ui5BuildYaml = join(projectFolder, 'ui5-build.yaml'); const mtaYaml = join(cfTestOutputDir, 'mta.yaml'); const packageJson = join(projectFolder, 'package.json'); expect(fs.existsSync(manifestPath)).toBe(true); expect(fs.existsSync(i18nPath)).toBe(true); expect(fs.existsSync(ui5Yaml)).toBe(true); - expect(fs.existsSync(ui5BuildYaml)).toBe(true); expect(fs.existsSync(mtaYaml)).toBe(true); expect(fs.existsSync(packageJson)).toBe(true); const manifestContent = fs.readFileSync(manifestPath, 'utf8'); const i18nContent = fs.readFileSync(i18nPath, 'utf8'); const ui5Content = fs.readFileSync(ui5Yaml, 'utf8'); - const ui5BuildContent = fs.readFileSync(ui5BuildYaml, 'utf8'); const mtaContent = fs.readFileSync(mtaYaml, 'utf8'); const packageJsonContent = fs.readFileSync(packageJson, 'utf8'); expect(manifestContent).toMatchSnapshot(); expect(i18nContent).toMatchSnapshot(); expect(ui5Content).toMatchSnapshot(); - expect(ui5BuildContent).toMatchSnapshot(); expect(mtaContent).toMatchSnapshot(); expect(packageJsonContent).toMatchSnapshot(); }); diff --git a/packages/generator-adp/test/unit/questions/cf-services.test.ts b/packages/generator-adp/test/unit/questions/cf-services.test.ts index f6cda114a90..078bb2abd90 100644 --- a/packages/generator-adp/test/unit/questions/cf-services.test.ts +++ b/packages/generator-adp/test/unit/questions/cf-services.test.ts @@ -367,7 +367,7 @@ describe('CFServicesPrompter', () => { expect(mockValidateODataEndpoints).toHaveBeenCalledWith([], mockServiceKeys.serviceKeys, mockLogger); expect(result).toBe(true); expect(prompter['manifest']).toBe(mockManifest); - expect(prompter['serviceInstanceGuid']).toBe('test-guid'); + expect(prompter['serviceInstanceGuid']).toBe(mockServiceKeys.serviceInstance.guid); }); test('should return error when app is not selected', async () => { diff --git a/packages/generator-adp/test/unit/questions/helper/validators.test.ts b/packages/generator-adp/test/unit/questions/helper/validators.test.ts index a27b9bdcab5..7ed41980f05 100644 --- a/packages/generator-adp/test/unit/questions/helper/validators.test.ts +++ b/packages/generator-adp/test/unit/questions/helper/validators.test.ts @@ -4,7 +4,7 @@ import { isAppStudio } from '@sap-ux/btp-utils'; import type { ToolsLogger } from '@sap-ux/logger'; import type { SystemLookup } from '@sap-ux/adp-tooling'; import { isExternalLoginEnabled, isMtaProject, getMtaServices } from '@sap-ux/adp-tooling'; -import { validateNamespaceAdp, validateProjectName, validateEmptyString } from '@sap-ux/project-input-validator'; +import { validateNamespaceAdp, validateProjectName } from '@sap-ux/project-input-validator'; import { validateJsonInput, @@ -191,7 +191,7 @@ describe('validateEnvironment', () => { }); test('should return true for ABAP environment', async () => { - const result = await validateEnvironment('ABAP', false, mockVscode); + const result = await validateEnvironment('ABAP', false); expect(result).toBe(true); }); @@ -199,19 +199,19 @@ describe('validateEnvironment', () => { mockIsAppStudio.mockReturnValue(false); mockIsExternalLoginEnabled.mockResolvedValue(true); - const result = await validateEnvironment('CF', true, mockVscode); + const result = await validateEnvironment('CF', true); expect(result).toBe(true); }); test('should return error when CF selected but not logged in', async () => { - const result = await validateEnvironment('CF', false, mockVscode); + const result = await validateEnvironment('CF', false); expect(result).toBe(t('error.cfNotLoggedIn')); }); test('should return true for CF when logged in and in AppStudio', async () => { mockIsAppStudio.mockReturnValue(true); - const result = await validateEnvironment('CF', true, mockVscode); + const result = await validateEnvironment('CF', true); expect(result).toBe(true); }); @@ -219,17 +219,8 @@ describe('validateEnvironment', () => { mockIsAppStudio.mockReturnValue(false); mockIsExternalLoginEnabled.mockResolvedValue(true); - const result = await validateEnvironment('CF', true, mockVscode); + const result = await validateEnvironment('CF', true); expect(result).toBe(true); - expect(mockIsExternalLoginEnabled).toHaveBeenCalledWith(mockVscode); - }); - - test('should return error when external login not enabled', async () => { - mockIsAppStudio.mockReturnValue(false); - mockIsExternalLoginEnabled.mockResolvedValue(false); - - const result = await validateEnvironment('CF', true, mockVscode); - expect(result).toBe(t('error.cfLoginCannotBeDetected')); }); }); diff --git a/packages/generator-adp/test/unit/questions/target-env.test.ts b/packages/generator-adp/test/unit/questions/target-env.test.ts index 96cf7a7bfa5..6b341c609b7 100644 --- a/packages/generator-adp/test/unit/questions/target-env.test.ts +++ b/packages/generator-adp/test/unit/questions/target-env.test.ts @@ -62,7 +62,7 @@ describe('Target Environment', () => { describe('getTargetEnvPrompt', () => { test('should create target environment prompt with correct structure', () => { - const prompt = getTargetEnvPrompt(mockAppWizard, true, true, mockCfConfig, mockVscode); + const prompt = getTargetEnvPrompt(mockAppWizard, true, true, mockCfConfig); expect(prompt.type).toBe('list'); expect(prompt.name).toBe('targetEnv'); @@ -79,8 +79,7 @@ describe('Target Environment', () => { mockAppWizard, true, true, - mockCfConfig, - mockVscode + mockCfConfig ) as ListQuestion; const choicesFn = envPrompt!.choices; @@ -98,8 +97,7 @@ describe('Target Environment', () => { mockAppWizard, true, true, - mockCfConfig, - mockVscode + mockCfConfig ) as ListQuestion; const defaultFn = envPrompt!.default; @@ -110,15 +108,15 @@ describe('Target Environment', () => { }); test('should set up validation function', () => { - const prompt = getTargetEnvPrompt(mockAppWizard, true, true, mockCfConfig, mockVscode); + const prompt = getTargetEnvPrompt(mockAppWizard, true, true, mockCfConfig); const validateResult = prompt.validate!('ABAP'); - expect(mockValidateEnvironment).toHaveBeenCalledWith('ABAP', true, mockVscode); + expect(mockValidateEnvironment).toHaveBeenCalledWith('ABAP', true); expect(validateResult).toBeUndefined(); }); test('should set up additional messages function', () => { - const prompt = getTargetEnvPrompt(mockAppWizard, true, true, mockCfConfig, mockVscode); + const prompt = getTargetEnvPrompt(mockAppWizard, true, true, mockCfConfig); const additionalMessages = prompt.additionalMessages!('ABAP'); expect(mockGetTargetEnvAdditionalMessages).toHaveBeenCalledWith('ABAP', true, mockCfConfig); diff --git a/packages/preview-middleware/README.md b/packages/preview-middleware/README.md index da1615a3353..a5c1a996dae 100644 --- a/packages/preview-middleware/README.md +++ b/packages/preview-middleware/README.md @@ -29,6 +29,7 @@ When this middleware is used together with the `reload-middleware`, then the ord | `flp.enhancedHomePage` | `boolean` | optional | `false` | Flag for enabling enhanced FLP homepage, available only from UI5 version 1.123.0 onwards | | `adp.target` | --- | mandatory for adaptation projects | --- | Configuration object defining the connected back end | | `adp.ignoreCertErrors` | `boolean` | optional | `false` | Flag to ignore certification validation errors when working with development systems with self-signed certificates, for example | +| `adp.useLocal` | `string` | optional (experimental, CF only) | `undefined` | **Experimental**: For CF ADP projects only. Path to local dist folder (e.g., `dist`) to serve built resources directly instead of merging from backend. When set, the middleware serves static files from this path and reads manifest.json from it. | | `rta` | --- | 🚫 deprecated
*use `editors.rta` instead* | --- | Configuration allowing to add mount points for runtime adaptation | | `editors` | `array` | optional | `undefined` | List of configurations allowing to add mount points for additional editors | | `editors.rta` | `array` | optional | `undefined` | Configuration allowing to add mount points for runtime adaptation | @@ -171,6 +172,31 @@ server: - path: /test/adaptation-editor.html developerMode: true ``` + +### [CF ADP Local Mode (Experimental)](#cf-adp-local-mode-experimental) +**⚠️ Experimental feature - CF ADP projects only** + +For Cloud Foundry ADP projects, you can use the `useLocal` option to serve built resources directly from a local dist folder instead of merging from the backend. This is useful for testing locally built applications without requiring backend connectivity. + +When `useLocal` is set: +- The middleware serves static files directly from the specified path (e.g., `dist` or `build/dist`) +- The manifest.json is read from the local dist folder +- Backend merging is bypassed +- The FLP is initialized without backend merge + +**Note:** This feature is experimental and only works with CF ADP projects. The path should be relative to the project root and must contain a `manifest.json` file. + +```Yaml +server: + customMiddleware: + - name: preview-middleware + afterMiddleware: compression + configuration: + adp: + target: + url: http://sap.example + useLocal: dist # Path to local dist folder (experimental, CF only) +``` When the middleware is used in an adaptation project together with a middleware proxying requests to the back end e.g. the `backend-proxy-middleware`, then it is critically important that the `preview-middleware` is handling requests before the back-end proxy because it intercepts requests to the `manifest.json` of the original application and merges it with the local variant. ```Yaml - name: preview-middleware diff --git a/packages/preview-middleware/src/base/flp.ts b/packages/preview-middleware/src/base/flp.ts index 8a6fed129c0..c600f23858d 100644 --- a/packages/preview-middleware/src/base/flp.ts +++ b/packages/preview-middleware/src/base/flp.ts @@ -18,15 +18,17 @@ import { type Manifest, FileName, type ManifestNamespace, - createApplicationAccess + createApplicationAccess, + type UI5FlexLayer } from '@sap-ux/project-access'; import { AdpPreview, type AdpPreviewConfig, type CommonChangeProperties, - type DescriptorVariant, type OperationType, - type CommonAdditionalChangeInfoProperties + type CommonAdditionalChangeInfoProperties, + loadAppVariant, + readLocalManifest } from '@sap-ux/adp-tooling'; import { isAppStudio, exposePort } from '@sap-ux/btp-utils'; import { FeatureToggleAccess } from '@sap-ux/feature-toggle'; @@ -1124,6 +1126,58 @@ export class FlpSandbox { await this.storeI18nKeysHandler(req, res); }); } + + /** + * Initialize the preview for an adaptation project. + * + * @param config configuration from the ui5.yaml + * @throws Error in case no manifest.appdescr_variant found + */ + async initAdp(config: AdpPreviewConfig): Promise { + const variant = await loadAppVariant(this.project); + const adp = new AdpPreview(config, this.project, this.utils, this.logger as ToolsLogger); + const layer = await adp.init(variant); + + // CF ADP local dist mode: serve built resources directly and initialize FLP without backend merge + if (config.useLocal) { + const manifest = this.setupUseLocalMode(config.useLocal); + configureRta(this.rta, layer, variant.id, false); + await this.init(manifest, variant.reference); + this.setupAdpCommonHandlers(adp); + return; + } + + configureRta(this.rta, layer, variant.id, adp.isCloudProject); + const descriptor = adp.descriptor; + const { name, manifest } = descriptor; + await this.init(manifest, name, adp.resources, adp); + this.router.use(adp.descriptor.url, adp.proxy.bind(adp)); + this.setupAdpCommonHandlers(adp); + } + + /** + * Setup common ADP middleware and handlers. + * + * @param adp AdpPreview instance + */ + private setupAdpCommonHandlers(adp: AdpPreview): void { + this.addOnChangeRequestHandler(adp.onChangeRequest.bind(adp)); + this.router.use(json()); + adp.addApis(this.router); + } + + /** + * Setup the use local mode for the ADP project. + * + * @param useLocal path to the dist folder + * @returns the manifest + */ + private setupUseLocalMode(useLocal: string): Manifest { + const manifest = readLocalManifest(useLocal); + this.router.use('/', serveStatic(useLocal)); + this.logger.info(`Initialized CF ADP in useLocal mode, serving from ${useLocal}`); + return manifest; + } } /** @@ -1153,48 +1207,27 @@ function serializeUi5Configuration(config: Map): string { } /** - * Initialize the preview for an adaptation project. + * Configure RTA (Runtime Adaptation) for the FLP sandbox. * - * @param rootProject reference to the project - * @param config configuration from the ui5.yaml - * @param flp FlpSandbox instance - * @param util middleware utilities provided by the UI5 CLI - * @param logger logger instance - * @throws Error in case no manifest.appdescr_variant found + * @param rta RtaConfig instance + * @param layer UI5 flex layer + * @param variantId variant identifier + * @param isCloud whether this is a cloud project */ -export async function initAdp( - rootProject: ReaderCollection, - config: AdpPreviewConfig, - flp: FlpSandbox, - util: MiddlewareUtils, - logger: ToolsLogger -): Promise { - const appVariant = await rootProject.byPath('/manifest.appdescr_variant'); - if (appVariant) { - const adp = new AdpPreview(config, rootProject, util, logger); - const variant = JSON.parse(await appVariant.getString()) as DescriptorVariant; - const layer = await adp.init(variant); - if (flp.rta) { - flp.rta.layer = layer; - flp.rta.options = { - ...flp.rta.options, - projectId: variant.id, - scenario: 'ADAPTATION_PROJECT', - isCloud: adp.isCloudProject - }; - for (const editor of flp.rta.endpoints) { - editor.pluginScript ??= 'open/ux/preview/client/adp/init'; - } - } +function configureRta(rta: RtaConfig | undefined, layer: UI5FlexLayer, variantId: string, isCloud: boolean): void { + if (!rta) { + return; + } - const descriptor = adp.descriptor; - const { name, manifest } = descriptor; - await flp.init(manifest, name, adp.resources, adp); - flp.router.use(adp.descriptor.url, adp.proxy.bind(adp)); - flp.addOnChangeRequestHandler(adp.onChangeRequest.bind(adp)); - flp.router.use(json()); - adp.addApis(flp.router); - } else { - throw new Error('ADP configured but no manifest.appdescr_variant found.'); + rta.layer = layer; + rta.options = { + ...rta.options, + projectId: variantId, + scenario: 'ADAPTATION_PROJECT', + isCloud + }; + + for (const editor of rta.endpoints) { + editor.pluginScript ??= 'open/ux/preview/client/adp/init'; } } diff --git a/packages/preview-middleware/src/base/index.ts b/packages/preview-middleware/src/base/index.ts index ffd1091fc7c..a0386149e2d 100644 --- a/packages/preview-middleware/src/base/index.ts +++ b/packages/preview-middleware/src/base/index.ts @@ -1,3 +1,3 @@ -export { FlpSandbox, initAdp } from './flp'; +export { FlpSandbox } from './flp'; export { generatePreviewFiles, getPreviewPaths, sanitizeRtaConfig } from './config'; export { logRemoteUrl, isRemoteConnectionsEnabled } from './remote-url'; diff --git a/packages/preview-middleware/src/index.ts b/packages/preview-middleware/src/index.ts index 1a472d3a071..4d5481a2709 100644 --- a/packages/preview-middleware/src/index.ts +++ b/packages/preview-middleware/src/index.ts @@ -1,7 +1,6 @@ export * from './ui5/middleware'; export { FlpSandbox, - initAdp, generatePreviewFiles, getPreviewPaths, sanitizeRtaConfig, diff --git a/packages/preview-middleware/src/ui5/middleware.ts b/packages/preview-middleware/src/ui5/middleware.ts index de2cb42f366..92d878790d3 100644 --- a/packages/preview-middleware/src/ui5/middleware.ts +++ b/packages/preview-middleware/src/ui5/middleware.ts @@ -1,7 +1,7 @@ import { LogLevel, ToolsLogger, UI5ToolingTransport } from '@sap-ux/logger'; import type { RequestHandler } from 'express'; import type { MiddlewareParameters } from '@ui5/server'; -import { type EnhancedRouter, FlpSandbox, initAdp } from '../base/flp'; +import { type EnhancedRouter, FlpSandbox } from '../base/flp'; import type { MiddlewareConfig } from '../types'; import { getPreviewPaths, sanitizeConfig } from '../base/config'; import { logRemoteUrl, isRemoteConnectionsEnabled } from '../base/remote-url'; @@ -29,7 +29,7 @@ async function createRouter( const flp = new FlpSandbox(config, resources.rootProject, middlewareUtil, logger); if (config.adp) { - await initAdp(resources.rootProject, config.adp, flp, middlewareUtil, logger); + await flp.initAdp(config.adp); } else { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const manifest = await resources.rootProject.byPath('/manifest.json'); diff --git a/packages/preview-middleware/test/unit/base/flp.test.ts b/packages/preview-middleware/test/unit/base/flp.test.ts index 6ac4b14a720..0802a77a8ca 100644 --- a/packages/preview-middleware/test/unit/base/flp.test.ts +++ b/packages/preview-middleware/test/unit/base/flp.test.ts @@ -1,6 +1,6 @@ import type { ReaderCollection } from '@ui5/fs'; import { CARD_GENERATOR_DEFAULT, type TemplateConfig } from '../../../src/base/config'; -import { FlpSandbox as FlpSandboxUnderTest, initAdp } from '../../../src'; +import { FlpSandbox as FlpSandboxUnderTest } from '../../../src'; import type { FlpConfig, MiddlewareConfig } from '../../../src'; import type { MiddlewareUtils } from '@ui5/server'; import type { Logger, ToolsLogger } from '@sap-ux/logger'; @@ -1436,7 +1436,7 @@ describe('initAdp', () => { test('initAdp: throw an error if no adp project', async () => { const flp = new FlpSandbox({}, mockNonAdpProject, {} as MiddlewareUtils, logger); try { - await initAdp(mockNonAdpProject, {} as AdpPreviewConfig, flp, {} as MiddlewareUtils, logger); + await flp.initAdp({} as AdpPreviewConfig); } catch (error) { expect(error).toBeDefined(); } @@ -1448,7 +1448,7 @@ describe('initAdp', () => { const flpInitMock = jest.spyOn(flp, 'init').mockImplementation(async (): Promise => { jest.fn(); }); - await initAdp(mockAdpProject, config.adp, flp, {} as MiddlewareUtils, logger); + await flp.initAdp(config.adp); expect(adpToolingMock).toHaveBeenCalled(); expect(flpInitMock).toHaveBeenCalled(); }); @@ -1483,9 +1483,63 @@ describe('initAdp', () => { const flpInitMock = jest.spyOn(flp, 'init').mockImplementation(async (): Promise => { jest.fn(); }); - await initAdp(mockAdpProject, config.adp as AdpPreviewConfig, flp, {} as MiddlewareUtils, logger); + await flp.initAdp(config.adp as AdpPreviewConfig); expect(adpToolingMock).toHaveBeenCalled(); expect(flpInitMock).toHaveBeenCalled(); expect(flp.rta?.options?.isCloud).toBe(true); }); + + test('initAdp with useLocal mode', async () => { + const mockManifest = { + 'sap.app': { + id: 'test.app', + title: 'Test App', + type: 'application', + applicationVersion: { + version: '1.0.0' + } + } + } as Manifest; + const useLocal = 'dist'; + const readLocalManifestMock = jest.spyOn(adpTooling, 'readLocalManifest').mockReturnValue(mockManifest); + const adpToolingMock = jest.spyOn(adpTooling, 'AdpPreview').mockImplementation((): adpTooling.AdpPreview => { + return { + init: jest.fn().mockResolvedValue('CUSTOMER_BASE'), + descriptor: { + manifest: {}, + name: 'descriptorName', + url, + asyncHints: { + requests: [] + } + }, + resources: [], + proxy: jest.fn(), + sync: syncSpy, + onChangeRequest: jest.fn(), + addApis: jest.fn(), + isCloudProject: false + } as unknown as adpTooling.AdpPreview; + }); + + const config: AdpPreviewConfig = { + target: { url }, + useLocal + }; + const flpConfig = { + adp: config, + rta: { options: {}, editors: [] } + } as unknown as Partial; + const flp = new FlpSandbox(flpConfig, mockAdpProject, {} as MiddlewareUtils, logger); + const flpInitMock = jest.spyOn(flp, 'init').mockImplementation(async (): Promise => { + jest.fn(); + }); + + await flp.initAdp(config); + + expect(readLocalManifestMock).toHaveBeenCalledWith(useLocal); + expect(adpToolingMock).toHaveBeenCalled(); + expect(flpInitMock).toHaveBeenCalledWith(mockManifest, expect.any(String)); + expect(flp.rta?.options?.isCloud).toBe(false); + }); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ea25396988c..91d6353bacb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -952,6 +952,49 @@ importers: specifier: 2.2.2 version: 2.2.2 + packages/backend-proxy-middleware-cf: + dependencies: + '@sap-ux/adp-tooling': + specifier: workspace:* + version: link:../adp-tooling + '@sap-ux/logger': + specifier: workspace:* + version: link:../logger + '@sap-ux/project-access': + specifier: workspace:* + version: link:../project-access + axios: + specifier: 1.12.2 + version: 1.12.2(debug@4.4.3) + http-proxy-middleware: + specifier: 3.0.5 + version: 3.0.5 + devDependencies: + '@types/connect': + specifier: ^3.4.38 + version: 3.4.38 + '@types/express': + specifier: 4.17.21 + version: 4.17.21 + '@types/http-proxy': + specifier: ^1.17.5 + version: 1.17.16 + '@types/supertest': + specifier: 2.0.12 + version: 2.0.12 + connect: + specifier: ^3.7.0 + version: 3.7.0 + express: + specifier: 4.21.2 + version: 4.21.2 + nock: + specifier: 13.4.0 + version: 13.4.0 + supertest: + specifier: 7.1.4 + version: 7.1.4 + packages/btp-utils: dependencies: '@sap/bas-sdk': @@ -13188,7 +13231,6 @@ packages: resolution: {integrity: sha512-sdWoUajOB1cd0A8cRRQ1cfyWNbmFKLAqBB89Y8x5iYyG/mkJHc0YUH8pdWBy2omi9qtCpiIgGjuwO0dQST2l5w==} dependencies: '@types/node': 20.0.0 - dev: false /@types/http-proxy@1.17.8: resolution: {integrity: sha512-5kPLG5BKpWYkw/LVOGWpiq3nEVqxiN32rTgI53Sk12/xHFQ2rG3ehI9IO+O3W2QoKeyB92dJkoka8SUm6BX1pA==} @@ -19790,18 +19832,6 @@ packages: - supports-color dev: false - /follow-redirects@1.15.6(debug@4.4.1): - resolution: {integrity: sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==} - engines: {node: '>=4.0'} - peerDependencies: - debug: '*' - peerDependenciesMeta: - debug: - optional: true - dependencies: - debug: 4.4.1 - dev: false - /follow-redirects@1.15.6(debug@4.4.3): resolution: {integrity: sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==} engines: {node: '>=4.0'} @@ -20837,8 +20867,8 @@ packages: '@types/express': optional: true dependencies: - '@types/http-proxy': 1.17.8 - http-proxy: 1.18.1 + '@types/http-proxy': 1.17.16 + http-proxy: 1.18.1(debug@4.4.3) is-glob: 4.0.3 is-plain-obj: 3.0.0 micromatch: 4.0.8 @@ -20851,8 +20881,8 @@ packages: engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} dependencies: '@types/http-proxy': 1.17.16 - debug: 4.4.1 - http-proxy: 1.18.1(debug@4.4.1) + debug: 4.4.3 + http-proxy: 1.18.1(debug@4.4.3) is-glob: 4.0.3 is-plain-object: 5.0.0 micromatch: 4.0.8 @@ -20860,7 +20890,7 @@ packages: - supports-color dev: false - /http-proxy@1.18.1: + /http-proxy@1.18.1(debug@4.4.3): resolution: {integrity: sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==} engines: {node: '>=8.0.0'} dependencies: @@ -20869,18 +20899,6 @@ packages: requires-port: 1.0.0 transitivePeerDependencies: - debug - dev: true - - /http-proxy@1.18.1(debug@4.4.1): - resolution: {integrity: sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==} - engines: {node: '>=8.0.0'} - dependencies: - eventemitter3: 4.0.7 - follow-redirects: 1.15.6(debug@4.4.1) - requires-port: 1.0.0 - transitivePeerDependencies: - - debug - dev: false /http-server@14.1.1: resolution: {integrity: sha512-+cbxadF40UXd9T01zUHgA+rlo2Bg1Srer4+B4NwIHdaGxAGGv59nYRnGGDJ9LBk7alpS0US+J+bLLdQOOkJq4A==} @@ -20892,7 +20910,7 @@ packages: corser: 2.0.1 he: 1.2.0 html-encoding-sniffer: 3.0.0 - http-proxy: 1.18.1 + http-proxy: 1.18.1(debug@4.4.3) mime: 1.6.0 minimist: 1.2.8 opener: 1.5.2 @@ -23701,6 +23719,7 @@ packages: /mime@2.6.0: resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} engines: {node: '>=4.0.0'} + hasBin: true dev: true /mimic-fn@2.1.0: @@ -24153,7 +24172,7 @@ packages: resolution: {integrity: sha512-W8NVHjO/LCTNA64yxAPHV/K47LpGYcVzgKd3Q0n6owhwvD0Dgoterc25R4rnZbckJEb6Loxz1f5QMuJpJnbSyQ==} engines: {node: '>= 10.13'} dependencies: - debug: 4.3.4 + debug: 4.4.3 json-stringify-safe: 5.0.1 propagate: 2.0.1 transitivePeerDependencies: diff --git a/sonar-project.properties b/sonar-project.properties index 04bacdc26aa..18f2fea32da 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -15,6 +15,7 @@ sonar.javascript.lcov.reportPaths=packages/abap-deploy-config-inquirer/coverage/ packages/adp-flp-config-sub-generator/coverage/lcov.info, \ packages/axios-extension/coverage/lcov.info, \ packages/backend-proxy-middleware/coverage/lcov.info, \ + packages/backend-proxy-middleware-cf/coverage/lcov.info, \ packages/btp-utils/coverage/lcov.info, \ packages/cap-config-writer/coverage/lcov.info, \ packages/cds-annotation-parser/coverage/lcov.info, \ @@ -101,6 +102,7 @@ sonar.testExecutionReportPaths=packages/abap-deploy-config-inquirer/coverage/son packages/adp-flp-config-sub-generator/coverage/sonar-report.xml, \ packages/axios-extension/coverage/sonar-report.xml, \ packages/backend-proxy-middleware/coverage/sonar-report.xml, \ + packages/backend-proxy-middleware-cf/coverage/sonar-report.xml, \ packages/btp-utils/coverage/sonar-report.xml, \ packages/repo-app-import-sub-generator/coverage/sonar-report.xml, \ packages/cap-config-writer/coverage/sonar-report.xml, \ diff --git a/tsconfig.json b/tsconfig.json index f8b513234bb..3878cbaca0a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -48,6 +48,9 @@ { "path": "packages/axios-extension" }, + { + "path": "packages/backend-proxy-middleware-cf" + }, { "path": "packages/backend-proxy-middleware" },