diff --git a/.github/workflows/mfe-runtime.yml b/.github/workflows/mfe-runtime.yml
new file mode 100644
index 0000000000000..392d9157d87c7
--- /dev/null
+++ b/.github/workflows/mfe-runtime.yml
@@ -0,0 +1,28 @@
+name: MFE runtime
+on:
+ pull_request:
+ paths:
+ - "datahub-web-react/devtools/mfe-fixture/**"
+ - "datahub-web-react/src/app/mfeframework/**"
+ - "datahub-web-react/vite.config.ts"
+ - "datahub-web-react/package.json"
+ - "datahub-web-react/yarn.lock"
+ - ".github/workflows/mfe-runtime.yml"
+permissions:
+ contents: read
+jobs:
+ browser:
+ runs-on: ubuntu-24.04
+ defaults:
+ run:
+ working-directory: datahub-web-react
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: "22"
+ cache: yarn
+ cache-dependency-path: datahub-web-react/yarn.lock
+ - run: yarn install --frozen-lockfile
+ - run: npm ci --prefix devtools/mfe-fixture/remote --ignore-scripts
+ - run: node devtools/mfe-fixture/build.mjs && python3 devtools/mfe-fixture/verify.py
diff --git a/.github/workflows/post-workflow-actions.yml b/.github/workflows/post-workflow-actions.yml
index 091da5b0ee822..dac7382c810c4 100644
--- a/.github/workflows/post-workflow-actions.yml
+++ b/.github/workflows/post-workflow-actions.yml
@@ -31,6 +31,7 @@ on:
- "metadata model generate"
- "Metadata Models Custom CI"
- "metadata-io"
+ - "MFE runtime"
- "Nightly Docker Test"
- "OAuth Smoke Test"
- "PR Title Check"
diff --git a/datahub-web-react/.eslintrc.js b/datahub-web-react/.eslintrc.js
index 165514b20593c..742eead19acf8 100644
--- a/datahub-web-react/.eslintrc.js
+++ b/datahub-web-react/.eslintrc.js
@@ -333,6 +333,11 @@ module.exports = {
},
},
overrides: [
+ {
+ files: ['devtools/mfe-fixture/host/main.js'],
+ env: { browser: true },
+ rules: { 'import/no-unresolved': ['error', { ignore: ['^virtual:__federation__$'] }] },
+ },
{
files: ['src/app/searchV2/**/*.tsx', 'src/app/entityV2/**/*.tsx'],
rules: { 'import/no-cycle': 'off' },
diff --git a/datahub-web-react/devtools/mfe-fixture/.gitignore b/datahub-web-react/devtools/mfe-fixture/.gitignore
new file mode 100644
index 0000000000000..712d2a5fcae0d
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/.gitignore
@@ -0,0 +1,2 @@
+build/
+remote/node_modules/
diff --git a/datahub-web-react/devtools/mfe-fixture/build.mjs b/datahub-web-react/devtools/mfe-fixture/build.mjs
new file mode 100644
index 0000000000000..a9f89d97496df
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/build.mjs
@@ -0,0 +1,34 @@
+import federation from '@originjs/vite-plugin-federation';
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { build } from 'vite';
+
+const fixture = path.dirname(fileURLToPath(import.meta.url));
+const name = process.argv[2];
+if (!name) {
+ // The federation plugin keeps its Rollup file references in module-level state.
+ for (const target of ['host', 'remote']) {
+ execFileSync(process.execPath, [fileURLToPath(import.meta.url), target], { stdio: 'inherit' });
+ }
+} else {
+ const root = path.join(fixture, name);
+ const remote = name === 'remote';
+ await build({
+ configFile: false,
+ root,
+ base: name === 'host' ? '/' : `/${name}/`,
+ build: {
+ target: 'esnext',
+ outDir: path.join(fixture, 'build', name === 'host' ? '.' : name),
+ emptyOutDir: true,
+ rollupOptions: { input: path.join(root, 'index.html') },
+ },
+ plugins: [
+ federation({
+ name,
+ ...(remote ? { exposes: { './mount': path.join(root, 'mount.jsx') } } : { remotes: { fixture: '' } }),
+ }),
+ ],
+ });
+}
diff --git a/datahub-web-react/devtools/mfe-fixture/host/index.html b/datahub-web-react/devtools/mfe-fixture/host/index.html
new file mode 100644
index 0000000000000..e1427b92fe3f2
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/host/index.html
@@ -0,0 +1,2 @@
+
+
diff --git a/datahub-web-react/devtools/mfe-fixture/host/main.js b/datahub-web-react/devtools/mfe-fixture/host/main.js
new file mode 100644
index 0000000000000..84b9cbfd329df
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/host/main.js
@@ -0,0 +1,45 @@
+import React from 'react';
+import {
+ __federation_method_getRemote as getRemote,
+ __federation_method_setRemote as setRemote,
+} from 'virtual:__federation__';
+
+async function verify() {
+ setRemote('fixture', { format: 'esm', from: 'vite', url: '/remote/assets/remoteEntry.js' });
+ const remote = await getRemote('fixture', './mount');
+ if (!React.version.startsWith('17.') || !remote.reactVersion.startsWith('19.')) {
+ throw Error('Expected a React 17 host and an independent React 19 remote');
+ }
+ let listener;
+ const element = document.getElementById('root');
+ const cleanup = remote.mount(element, {
+ contractVersion: 1,
+ slot: 'nav.page',
+ area: 'app',
+ basePath: '/fixture',
+ theme: { id: 'light', colors: { textBrand: '#123456' }, styles: {} },
+ subscribeTheme(cb) {
+ listener = cb;
+ return () => {
+ listener = undefined;
+ };
+ },
+ navigate() {},
+ });
+ const label = element.firstElementChild;
+ if (label.textContent !== 'light' || getComputedStyle(label).color !== 'rgb(18, 52, 86)')
+ throw Error('Initial theme mismatch');
+ listener({ id: 'themeV2Dark', colors: { textBrand: '#abcdef' }, styles: {} });
+ if (
+ label !== element.firstElementChild ||
+ label.textContent !== 'themeV2Dark' ||
+ getComputedStyle(label).color !== 'rgb(171, 205, 239)'
+ )
+ throw Error('Live switch failed');
+ cleanup();
+ if (listener || element.childElementCount) throw Error('Cleanup failed');
+ document.body.dataset.fixture = 'passed';
+}
+verify().catch((error) => {
+ document.body.textContent = String(error);
+});
diff --git a/datahub-web-react/devtools/mfe-fixture/remote/index.html b/datahub-web-react/devtools/mfe-fixture/remote/index.html
new file mode 100644
index 0000000000000..7daf4c08f7291
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/remote/index.html
@@ -0,0 +1 @@
+
diff --git a/datahub-web-react/devtools/mfe-fixture/remote/mount.jsx b/datahub-web-react/devtools/mfe-fixture/remote/mount.jsx
new file mode 100644
index 0000000000000..493aedbaf3b0a
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/remote/mount.jsx
@@ -0,0 +1,24 @@
+import React, { useState } from 'react';
+import { flushSync } from 'react-dom';
+import { createRoot } from 'react-dom/client';
+
+export const reactVersion = React.version;
+
+export function mount(element, props) {
+ if (
+ props.contractVersion !== 1 ||
+ props.slot !== 'nav.page' ||
+ props.area !== 'app' ||
+ props.basePath !== '/fixture'
+ ) {
+ throw Error('Expected the app page mount context');
+ }
+ const root = createRoot(element);
+ function Label() {
+ const [theme, setTheme] = useState(props.theme);
+ React.useLayoutEffect(() => props.subscribeTheme((value) => flushSync(() => setTheme(value))), []);
+ return {theme.id};
+ }
+ flushSync(() => root.render());
+ return () => root.unmount();
+}
diff --git a/datahub-web-react/devtools/mfe-fixture/remote/package-lock.json b/datahub-web-react/devtools/mfe-fixture/remote/package-lock.json
new file mode 100644
index 0000000000000..8a3f75b180045
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/remote/package-lock.json
@@ -0,0 +1,41 @@
+{
+ "name": "datahub-mfe-test-remote",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "datahub-mfe-test-remote",
+ "dependencies": {
+ "react": "19.2.4",
+ "react-dom": "19.2.4"
+ }
+ },
+ "node_modules/react": {
+ "version": "19.2.4",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
+ "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.2.4",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",
+ "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.27.0"
+ },
+ "peerDependencies": {
+ "react": "^19.2.4"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.27.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
+ "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/datahub-web-react/devtools/mfe-fixture/remote/package.json b/datahub-web-react/devtools/mfe-fixture/remote/package.json
new file mode 100644
index 0000000000000..0a07dc875c7a7
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/remote/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "datahub-mfe-test-remote",
+ "private": true,
+ "dependencies": {
+ "react": "19.2.4",
+ "react-dom": "19.2.4"
+ }
+}
diff --git a/datahub-web-react/devtools/mfe-fixture/verify.py b/datahub-web-react/devtools/mfe-fixture/verify.py
new file mode 100644
index 0000000000000..c4064a4205da7
--- /dev/null
+++ b/datahub-web-react/devtools/mfe-fixture/verify.py
@@ -0,0 +1,19 @@
+"""Serve both production builds on one origin and check the browser result."""
+import functools
+import http.server
+import os
+from pathlib import Path
+import subprocess
+import threading
+
+root = Path(__file__).resolve().parent / "build"
+handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=root)
+with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ page = subprocess.check_output([
+ os.environ.get("CHROME_BIN", "google-chrome"), "--headless", "--no-sandbox",
+ "--disable-dev-shm-usage", "--dump-dom", "--virtual-time-budget=15000",
+ f"http://127.0.0.1:{server.server_port}/",
+ ], timeout=60, text=True)
+ if 'data-fixture="passed"' not in page:
+ raise SystemExit(page)
diff --git a/datahub-web-react/src/app/mfeframework/MFEConfigurableContainer.tsx b/datahub-web-react/src/app/mfeframework/MFEConfigurableContainer.tsx
index c1c06813d69f5..059c621735b28 100644
--- a/datahub-web-react/src/app/mfeframework/MFEConfigurableContainer.tsx
+++ b/datahub-web-react/src/app/mfeframework/MFEConfigurableContainer.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
@@ -10,8 +10,11 @@ import {
import analytics, { EventType, MfeLoadOutcome } from '@app/analytics';
import { ErrorComponent } from '@app/mfeframework/ErrorComponent';
-import { MFEConfig } from '@app/mfeframework/mfeConfigLoader';
+import type { MountProps, PresentationTheme, SlotContext } from '@app/mfeframework/contract';
+import { EntityTabConfig, MFEConfig } from '@app/mfeframework/mfeConfigLoader';
import { useShowNavBarRedesign } from '@app/useShowNavBarRedesign';
+import themeV2 from '@conf/theme/themeV2';
+import { useCustomTheme } from '@src/customThemeContext';
// Used when the MFE config yaml specifies no loadTimeoutMs.
export const DEFAULT_LOAD_TIMEOUT_MS = 10000;
@@ -39,7 +42,8 @@ const MFEConfigurableContainer = styled.div<{ $isShowNavBarRedesign?: boolean }>
`;
interface MountMFEParams {
- config: MFEConfig;
+ config: MFEConfig | EntityTabConfig;
+ getMountProps: () => MountProps;
containerElement: HTMLDivElement | null;
onError: () => void;
aliveRef: { current: boolean };
@@ -48,6 +52,7 @@ interface MountMFEParams {
async function mountMFE({
config,
+ getMountProps,
containerElement,
onError,
aliveRef,
@@ -72,6 +77,10 @@ async function mountMFE({
if (import.meta.env.DEV) {
console.log('MFE id: ', config.id, ' Mounting start ');
}
+ if (!config.flags.enabled) {
+ trackLoad('disabled');
+ return undefined;
+ }
try {
if (import.meta.env.DEV) {
console.log('[HOST] mount path: ', module);
@@ -90,8 +99,8 @@ async function mountMFE({
// Configure the dynamic remote
const remoteConfig = {
url: remoteEntry,
- format: 'var' as const,
- from: 'webpack' as const,
+ format: config.format ?? ('var' as const),
+ from: config.from ?? ('webpack' as const),
};
setRemote(remoteName, remoteConfig);
@@ -119,7 +128,7 @@ async function mountMFE({
console.log('[HOST] Remote module loaded, unwrapping...');
}
const unwrapStart = performance.now();
- const mod = await unwrapModule(remoteModule);
+ const mod = (await unwrapModule(remoteModule)) ?? remoteModule;
const unwrapEnd = performance.now();
if (import.meta.env.DEV) {
console.log(`latency for module unwrap: ${config.id}`, unwrapEnd - unwrapStart, 'ms');
@@ -138,14 +147,6 @@ async function mountMFE({
trackLoad('abandoned');
return undefined;
}
- if (!config.flags.enabled) {
- console.warn(
- '[HOST] skipping remote module loading for because planning not to show it, enabled=false',
- );
- trackLoad('disabled');
- return undefined;
- }
-
if (!containerElement) {
console.warn('[HOST] ref is null (container div not in DOM');
trackLoad('container_missing');
@@ -157,11 +158,17 @@ async function mountMFE({
console.warn('MFE id: ', config.id, ' Mounting failed');
console.warn('[HOST] mount is not a function; got: ', maybeFn);
}
+ onError();
trackLoad('invalid_mount');
return undefined;
}
const mountFnStart = performance.now();
- const cleanup = maybeFn(containerElement, {});
+ const cleanup = maybeFn(containerElement, getMountProps());
+ if (cleanup !== undefined && typeof cleanup !== 'function') {
+ // Observe rejected promises from remotes that accidentally export an async mount.
+ Promise.resolve(cleanup).catch((error) => console.error('[MFE Loader] Async mount failed', error));
+ throw new TypeError('MFE mount must return a synchronous cleanup function or undefined');
+ }
const mountFnEnd = performance.now();
if (import.meta.env.DEV) {
console.log(`latency for mount function execution: ${config.id}`, mountFnEnd - mountFnStart, 'ms');
@@ -173,7 +180,14 @@ async function mountMFE({
console.log(`latency for successful MFE id: ${config.id}`, latency, 'ms');
}
trackLoad('success');
- return cleanup;
+ if (!cleanup) return undefined;
+ return () => {
+ try {
+ cleanup();
+ } catch (error) {
+ console.error('[MFE Loader] Remote cleanup failed', config.id, error);
+ }
+ };
} catch (e) {
if (import.meta.env.DEV) {
console.log(`latency for unsuccessful MFE id: ${config.id}`, performance.now() - mountStart, 'ms');
@@ -195,40 +209,81 @@ interface MFEBaseConfigurablePageProps {
loadTimeoutMs?: number;
}
-export const MFEBaseConfigurablePage = ({
- config,
- loadTimeoutMs = DEFAULT_LOAD_TIMEOUT_MS,
-}: MFEBaseConfigurablePageProps) => {
+type ContainerProps = { loadTimeoutMs?: number } & (
+ | { config: MFEConfig; context: Extract }
+ | { config: EntityTabConfig; context: Extract }
+);
+
+const MountedRemote = (props: ContainerProps) => {
+ const [{ config, context }] = useState(props);
+ const { loadTimeoutMs = DEFAULT_LOAD_TIMEOUT_MS } = props;
const { t } = useTranslation('misc');
const isShowNavBarRedesign = useShowNavBarRedesign();
const box = useRef(null);
const history = useHistory();
- const [hasError, setHasError] = useState(false);
- const aliveRef = useRef(true);
+ useEffect(() => {
+ if (context.slot !== 'nav.page') return undefined;
+ return history.listen(() => {
+ const { pathname, search, hash } = history.location;
+ window.dispatchEvent(new CustomEvent('datahub:mfe-location', { detail: { pathname, search, hash } }));
+ });
+ }, [context, history]);
+ const [failedConfig, setFailedConfig] = useState();
+ const hasError = failedConfig === config;
+ const { theme = themeV2 } = useCustomTheme();
+ const snapshot = useRef(theme);
+ const listeners = useRef(new Map<(value: PresentationTheme) => void, ContainerProps['config']>());
+ useLayoutEffect(() => {
+ const { id, brandSeed, colors, styles }: PresentationTheme = theme;
+ snapshot.current = { id, brandSeed, colors, styles };
+ listeners.current.forEach((owner, listener) => {
+ if (owner !== config) return;
+ try {
+ listener(snapshot.current);
+ } catch (error) {
+ console.error('[MFE Loader] Theme subscriber failed', error);
+ setFailedConfig(config);
+ }
+ });
+ }, [theme, config]);
useEffect(() => {
- aliveRef.current = true;
+ if (hasError) return undefined;
+ const aliveRef = { current: true };
+ const subscriptions = listeners.current;
let cleanup: (() => void) | undefined;
analytics.event({
type: EventType.MfePageViewEvent,
mfeId: config.id,
mfeLabel: config.label,
- mfePath: config.path,
+ mfePath: 'path' in config ? config.path : window.location.pathname,
});
mountMFE({
config,
+ getMountProps: () => ({
+ contractVersion: 1,
+ ...context,
+ theme: snapshot.current,
+ navigate: (path) => history.push(path),
+ subscribeTheme: (listener) => {
+ if (aliveRef.current) subscriptions.set(listener, config);
+ return () => subscriptions.delete(listener);
+ },
+ }),
containerElement: box.current,
- onError: () => setHasError(true),
+ onError: () => setFailedConfig(config),
aliveRef,
loadTimeoutMs,
}).then((cleanupFn) => {
- cleanup = cleanupFn;
+ if (aliveRef.current) cleanup = cleanupFn;
+ else cleanupFn?.();
});
return () => {
aliveRef.current = false;
+ subscriptions.clear();
if (cleanup) {
if (import.meta.env.DEV) {
console.log('[HOST] Executing cleanup method provided by mount');
@@ -241,13 +296,13 @@ export const MFEBaseConfigurablePage = ({
}
}
};
- }, [config, history, loadTimeoutMs]);
+ }, [config, context, hasError, history, loadTimeoutMs]);
if (hasError) {
- return ;
+ return ;
}
if (!config.flags.enabled) {
- return ;
+ return ;
}
return (
@@ -256,3 +311,31 @@ export const MFEBaseConfigurablePage = ({
);
};
+
+export function MFEContainer(props: ContainerProps) {
+ const { config, context, loadTimeoutMs } = props;
+ const key = JSON.stringify([
+ config.id,
+ config.module,
+ config.remoteEntry,
+ config.from,
+ config.format,
+ config.flags.enabled,
+ context.slot,
+ context.slot === 'nav.page' ? [context.area, context.basePath] : [context.entity.type, context.entity.urn],
+ loadTimeoutMs,
+ ]);
+ return ;
+}
+
+export const MFEBaseConfigurablePage = ({ config, loadTimeoutMs }: MFEBaseConfigurablePageProps) => (
+
+);
diff --git a/datahub-web-react/src/app/mfeframework/README-MFE.md b/datahub-web-react/src/app/mfeframework/README-MFE.md
index b9cfd922a274b..7578595c1b9a4 100644
--- a/datahub-web-react/src/app/mfeframework/README-MFE.md
+++ b/datahub-web-react/src/app/mfeframework/README-MFE.md
@@ -175,3 +175,61 @@ volumes:
```
Then include the file in the ConfigMap following Kubernetes best practices.
+
+## Vite remotes and mount contract v1
+
+Set `format: esm` and `from: vite` on the YAML entry for a Vite remote. Its
+Path-relative entries resolve from the deployment base, including on trailing-slash routes. The
+remoteEntry must resolve to a same-origin HTTP(S) URL. Existing entries default
+to `var` and `webpack`.
+
+The remote bundles its own UI dependencies and mounts an independent root. Copy
+the v1 interface from [contract.ts](./contract.ts) into the remote:
+
+```ts
+export interface HostServices {
+ theme: PresentationTheme;
+ subscribeTheme: (listener: (theme: PresentationTheme) => void) => () => void;
+ navigate: (path: string) => void;
+}
+
+export type SlotContext =
+ | { slot: 'nav.page'; area: 'app' | 'settings'; basePath: string }
+ | { slot: 'entity.detail.tab'; entity: { urn: string; type: string } };
+
+export type MountProps = HostServices & { contractVersion: 1 } & SlotContext;
+
+export type Mount = (element: HTMLElement, props: MountProps) => () => void;
+```
+
+`PresentationTheme` contains the resolved host theme’s `id`, optional
+`brandSeed`, `colors` and `styles`. The field definitions are in
+[Theme](../../conf/theme/types.ts) and [ColorTheme](../../conf/theme/colorThemes/types.ts).
+Map the tokens you use onto the remote’s own styling. Render from the initial
+theme, then subscribe to live updates, including tenant branding and dark mode.
+Use `navigate(path)` for host links. Navigation pages use `nav.page`. Settings pages also have a route prefix and differ only in which host navigation owns them, so they use `area: settings` (default: app).
+
+Declare placement inside the registry entry. For example, replace the legacy fields:
+
+```yaml
+slot: settings
+path: /settings/example
+navIcon: AppWindow
+flags: { enabled: true, showInNav: true }
+```
+
+with:
+
+```yaml
+flags: { enabled: true }
+placement: { slot: nav.page, area: settings, path: /settings/example, navIcon: AppWindow, showInNav: true }
+```
+
+Keep id, label, remoteEntry and module on the entry. Flat YAML remains accepted. A placement without a slot defaults to nav.page. For a component use `placement: { slot: entity.detail.tab, entityTypes: [dataset], tabName: Extra details }`. The entity URN and type come from the host at mount time. Registry parsing discovers these entries separately from routes. The entity detail page does not register tabs yet.
+
+Roll out a remote that accepts both flat-slot mount props and named-slot mount props before switching the host.
+
+Return cleanup synchronously. During cleanup, unsubscribe from theme changes,
+remove listeners and unmount the independent root.
+
+Page remotes can read the initial window location and listen for `datahub:mfe-location` events with pathname, search and hash on host history changes. Remove listeners during cleanup. App routes retain the /mfe prefix; settings pages use a path under /settings. Enabled pages with showInNav appear in their own area.
diff --git a/datahub-web-react/src/app/mfeframework/_tests_/MFEConfigurableContainer.test.tsx b/datahub-web-react/src/app/mfeframework/_tests_/MFEConfigurableContainer.test.tsx
index a601850c5e47b..727ef6c792d21 100644
--- a/datahub-web-react/src/app/mfeframework/_tests_/MFEConfigurableContainer.test.tsx
+++ b/datahub-web-react/src/app/mfeframework/_tests_/MFEConfigurableContainer.test.tsx
@@ -1,11 +1,14 @@
-import { act, render, screen } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { ThemeProvider } from 'styled-components';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { MFEBaseConfigurablePage } from '@app/mfeframework/MFEConfigurableContainer';
+import { MFEBaseConfigurablePage, MFEContainer } from '@app/mfeframework/MFEConfigurableContainer';
+import type { MountProps } from '@app/mfeframework/contract';
import * as navBarHooks from '@app/useShowNavBarRedesign';
+import themeV2 from '@conf/theme/themeV2';
+import { CustomThemeContext } from '@src/customThemeContext';
// Mock theme and navbar hooks
vi.spyOn(navBarHooks, 'useShowNavBarRedesign').mockReturnValue(true);
@@ -47,11 +50,16 @@ const sampleTheme = {
// Mock useHistory
const pushMock = vi.fn();
+const historyMock = {
+ push: pushMock,
+ location: { pathname: '/mfe/example/child', search: '?q=1', hash: '#section' },
+ listen: vi.fn((_listener: () => void) => () => {}),
+};
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual('react-router-dom');
return {
...actual,
- useHistory: () => ({ push: pushMock }),
+ useHistory: () => historyMock,
};
});
@@ -85,7 +93,7 @@ describe('MFEBaseConfigurablePage', () => {
});
const renderPage = (yaml: any, loadTimeoutMs?: number) => {
- render(
+ return render(
@@ -94,6 +102,136 @@ describe('MFEBaseConfigurablePage', () => {
);
};
+ it('delivers resolved theme changes until unsubscribe without remounting', async () => {
+ const listener = vi.fn();
+ let unsubscribe: () => void;
+ const cleanup = vi.fn();
+ const mount = vi.fn((_element: HTMLElement, props: MountProps) => {
+ expect(props.theme).toEqual({
+ id: themeV2.id,
+ colors: themeV2.colors,
+ styles: themeV2.styles,
+ brandSeed: undefined,
+ });
+ expect(props.slot === 'nav.page' && props.basePath).toBe('/mfe/example-mfe-item');
+ props.navigate('/datasets');
+ unsubscribe = props.subscribeTheme(listener);
+ return () => {
+ unsubscribe();
+ cleanup();
+ };
+ });
+ unwrapModuleMock.mockResolvedValue({ mount });
+ const config = validParsedYaml.microFrontends[0];
+ const page = (theme: typeof themeV2 & { brandSeed?: string }) => (
+
+
+
+
+
+ );
+ const view = render(page(themeV2));
+ await waitFor(() => expect(mount).toHaveBeenCalledTimes(1));
+ expect(pushMock).toHaveBeenCalledWith('/datasets');
+ const onLocation = vi.fn();
+ window.addEventListener('datahub:mfe-location', onLocation, { once: true });
+ historyMock.listen.mock.lastCall?.[0]();
+ expect(onLocation).toHaveBeenCalledWith(expect.objectContaining({ detail: historyMock.location }));
+ view.rerender(page({ ...themeV2, brandSeed: '#888888' }));
+ expect(listener).toHaveBeenCalledWith(expect.objectContaining({ brandSeed: '#888888' }));
+ expect(mount).toHaveBeenCalledTimes(1);
+ unsubscribe!();
+ view.rerender(page({ ...themeV2, brandSeed: '#999999' }));
+ expect(listener).toHaveBeenCalledTimes(1);
+ view.unmount();
+ expect(cleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it('isolates a replacement from the previous remote’s listeners and cleanup', async () => {
+ const fail = vi.fn(() => {
+ throw Error('Retired remote');
+ });
+ const mount = vi.fn((_element: HTMLElement, props: MountProps) => {
+ props.subscribeTheme(fail);
+ return fail;
+ });
+ unwrapModuleMock.mockResolvedValue({ mount });
+ const config = validParsedYaml.microFrontends[0];
+ const page = (id: string) => (
+
+
+
+ );
+ const view = render(page('old'));
+ await waitFor(() => expect(mount).toHaveBeenCalledTimes(1));
+ view.rerender(page('new'));
+ await waitFor(() => expect(mount).toHaveBeenCalledTimes(2));
+ expect(fail).toHaveBeenCalledTimes(1);
+ view.unmount();
+ expect(fail).toHaveBeenCalledTimes(2);
+ });
+
+ it('remounts only when entity identity changes and cleans up on removal', async () => {
+ const cleanup = vi.fn();
+ const mount = vi.fn(() => cleanup);
+ unwrapModuleMock.mockResolvedValue({ mount });
+ const config = {
+ ...validParsedYaml.microFrontends[0],
+ placement: { slot: 'entity.detail.tab' as const, tabName: 'Details', entityTypes: ['dataset'] },
+ };
+ const page = (urn: string) => (
+
+
+
+ );
+ const view = render(page('first'));
+ await waitFor(() => expect(mount).toHaveBeenCalledTimes(1));
+ view.rerender(page('first'));
+ expect(cleanup).not.toHaveBeenCalled();
+ view.rerender(page('second'));
+ await waitFor(() => expect(mount).toHaveBeenCalledTimes(2));
+ expect(mount).toHaveBeenLastCalledWith(
+ expect.any(HTMLElement),
+ expect.objectContaining({ slot: 'entity.detail.tab', entity: { urn: 'second', type: 'dataset' } }),
+ );
+ expect(cleanup).toHaveBeenCalledTimes(1);
+ view.unmount();
+ expect(cleanup).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not mount a late import after the host unmounts', async () => {
+ let finish!: (module: unknown) => void;
+ const mount = vi.fn();
+ getRemoteMock.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ unwrapModuleMock.mockResolvedValueOnce({ mount });
+ const view = renderPage(validParsedYaml.microFrontends[0]);
+ view.unmount();
+ await act(async () => {
+ finish({ mount });
+ });
+ expect(mount).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['var', 'webpack'],
+ ['esm', 'vite'],
+ ])('registers %s from %s', async (format, from) => {
+ const entry = validParsedYaml.microFrontends[0];
+ const config = format === 'var' ? entry : { ...entry, format, from };
+ await act(async () => {
+ renderPage(config);
+ });
+ expect(setRemoteMock).toHaveBeenCalledWith('exampleApplication', { url: entry.remoteEntry, format, from });
+ });
+
it('renders the container div', () => {
const yaml = validParsedYaml.microFrontends[0];
render(
@@ -133,7 +271,10 @@ describe('MFEBaseConfigurablePage', () => {
const container = screen.getByTestId('mfe-configurable-container');
const mountTarget = container.querySelector('div');
- expect(mountFn).toHaveBeenCalledWith(mountTarget, {});
+ expect(mountFn).toHaveBeenCalledWith(
+ mountTarget,
+ expect.objectContaining({ contractVersion: 1, slot: 'nav.page' }),
+ );
});
it('shows error UI when remote module times out', async () => {
diff --git a/datahub-web-react/src/app/mfeframework/_tests_/mfeConfigLoader.test.tsx b/datahub-web-react/src/app/mfeframework/_tests_/mfeConfigLoader.test.tsx
index a0949f2f40627..01b06d58982da 100644
--- a/datahub-web-react/src/app/mfeframework/_tests_/mfeConfigLoader.test.tsx
+++ b/datahub-web-react/src/app/mfeframework/_tests_/mfeConfigLoader.test.tsx
@@ -118,6 +118,53 @@ describe('mfeConfigLoader', () => {
expect(result.microFrontends[1]).toMatchObject(validParsedYaml.microFrontends[1]);
});
+ it('resolves same-origin ESM entries and keeps the first matching route', async () => {
+ const entry = { ...validParsedYaml.microFrontends[0], format: 'esm', from: 'vite', remoteEntry: '/remote.js' };
+ mockYamlLoad({ microFrontends: [entry, { ...entry, path: entry.path.toUpperCase() }] });
+ const { loadMFEConfigFromYAML } = await import('../mfeConfigLoader');
+ expect(loadMFEConfigFromYAML('').microFrontends).toEqual([
+ { ...entry, remoteEntry: new URL('/remote.js', window.location.href).href },
+ ]);
+ });
+
+ it('normalizes page placement and discovers valid entity tabs independently', async () => {
+ const common = {
+ id: 'example',
+ label: 'Example',
+ remoteEntry: '/entry.js',
+ module: 'example/mount',
+ flags: { enabled: true },
+ };
+ const placement = { slot: 'entity.detail.tab', entityTypes: ['dataset'], tabName: 'Details' };
+ mockYamlLoad({
+ microFrontends: [
+ { ...common, placement: { path: '/one', navIcon: 'Gear', showInNav: true } },
+ { ...common, id: 'tab', placement },
+ { ...common, id: 'invalid', placement: { ...placement, path: '/invalid' } },
+ ],
+ });
+ const { loadMFEConfigFromYAML } = await import('../mfeConfigLoader');
+ const parsed = loadMFEConfigFromYAML('');
+ expect(parsed.microFrontends.map((entry) => entry.path)).toEqual(['/one']);
+ expect(parsed.entityTabs?.map((entry) => entry.id)).toEqual(['tab']);
+ });
+
+ it.each([
+ // eslint-disable-next-line no-script-url
+ 'javascript:alert(1)',
+ '//example.org/remote.js',
+ 'data:text/javascript,42',
+ `blob:${window.location.origin}/remote`,
+ '',
+ 'https://[',
+ ])('rejects ESM entry %s', async (remoteEntry) => {
+ mockYamlLoad({
+ microFrontends: [{ ...validParsedYaml.microFrontends[0], format: 'esm', from: 'vite', remoteEntry }],
+ });
+ const { loadMFEConfigFromYAML } = await import('../mfeConfigLoader');
+ expect(loadMFEConfigFromYAML('').microFrontends).toEqual([]);
+ });
+
it('loadMFEConfigFromYAML filters out entries with missing required fields', async () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
mockYamlLoad({
diff --git a/datahub-web-react/src/app/mfeframework/_tests_/mfeNavBarMenuUtils.test.tsx b/datahub-web-react/src/app/mfeframework/_tests_/mfeNavBarMenuUtils.test.tsx
index c03df28c2d186..6763692350201 100644
--- a/datahub-web-react/src/app/mfeframework/_tests_/mfeNavBarMenuUtils.test.tsx
+++ b/datahub-web-react/src/app/mfeframework/_tests_/mfeNavBarMenuUtils.test.tsx
@@ -6,6 +6,29 @@ import { MFESchema } from '@app/mfeframework/mfeConfigLoader';
import { getMfeMenuDropdownItems, getMfeMenuItems } from '@app/mfeframework/mfeNavBarMenuUtils';
describe('getMfeMenuItems and getMfeMenuDropdownItems', () => {
+ it('lists enabled settings entries only in the settings area', () => {
+ const config: MFESchema = {
+ topLevelMenuTitle: '',
+ subNavigationMode: false,
+ microFrontends: [
+ {
+ id: 'example',
+ label: 'Example',
+ slot: 'settings',
+ path: '/settings/example',
+ module: 'example/mount',
+ remoteEntry: '/entry.js',
+ navIcon: 'Package',
+ flags: { enabled: true, showInNav: true },
+ },
+ ],
+ };
+ expect(getMfeMenuItems(config)).toEqual([]);
+ expect(getMfeMenuDropdownItems(config)).toEqual([]);
+ expect(getMfeMenuItems(config, 'settings')[0].link).toBe('/settings/example');
+ config.microFrontends[0].flags.enabled = false;
+ expect(getMfeMenuItems(config, 'settings')).toEqual([]);
+ });
it('returns only showInNav=true items with valid icon elements', () => {
const mfeConfig: MFESchema = {
topLevelMenuTitle: 'My Apps',
diff --git a/datahub-web-react/src/app/mfeframework/contract.ts b/datahub-web-react/src/app/mfeframework/contract.ts
new file mode 100644
index 0000000000000..e2f19f16e4cd9
--- /dev/null
+++ b/datahub-web-react/src/app/mfeframework/contract.ts
@@ -0,0 +1,17 @@
+import type { Theme } from '@conf/theme/types';
+
+export type PresentationTheme = Pick & { brandSeed?: string };
+
+export interface HostServices {
+ theme: PresentationTheme;
+ subscribeTheme: (listener: (theme: PresentationTheme) => void) => () => void;
+ navigate: (path: string) => void;
+}
+
+export type SlotContext =
+ | { slot: 'nav.page'; area: 'app' | 'settings'; basePath: string }
+ | { slot: 'entity.detail.tab'; entity: { urn: string; type: string } };
+
+export type MountProps = HostServices & { contractVersion: 1 } & SlotContext;
+
+export type Mount = (element: HTMLElement, props: MountProps) => () => void;
diff --git a/datahub-web-react/src/app/mfeframework/mfeConfigLoader.tsx b/datahub-web-react/src/app/mfeframework/mfeConfigLoader.tsx
index f3740373d5663..398fde048fb5a 100644
--- a/datahub-web-react/src/app/mfeframework/mfeConfigLoader.tsx
+++ b/datahub-web-react/src/app/mfeframework/mfeConfigLoader.tsx
@@ -16,18 +16,27 @@ export interface MFEConfig {
id: string;
label: string;
path: string;
+ slot?: 'app' | 'settings';
remoteEntry: string;
+ format?: 'var' | 'esm';
+ from?: 'webpack' | 'vite';
// Must look like 'myRemoteModule/mount' which is exposed remote followed by exposed mount function inside it
module: string;
flags: MFEFlags;
navIcon: string;
}
+export type EntityTabConfig = Omit & {
+ flags: { enabled: boolean };
+ placement: { slot: 'entity.detail.tab'; tabName: string; entityTypes: string[] };
+};
+
// MFESchema: The overall config schema.
export interface MFESchema {
topLevelMenuTitle: string;
subNavigationMode: boolean;
microFrontends: MFEConfig[];
+ entityTabs?: EntityTabConfig[];
// Optional remote-module load timeout, applied to every MFE. Falls back to DEFAULT_LOAD_TIMEOUT_MS.
loadTimeoutMs?: number;
}
@@ -61,37 +70,98 @@ function parseLoadTimeoutMs(value: unknown, context: string): number | undefined
* - Collects all validation errors for the entry.
* - Returns the valid MFEConfig if no errors, otherwise returns null and logs all errors.
*/
-function validateMFEConfig(config: any): MFEConfig | null {
+function validateMFEConfig(entry: any): MFEConfig | EntityTabConfig | null {
+ let config = entry;
+ if (!config || typeof config !== 'object') return null;
const errors: string[] = [];
+ const { placement } = entry;
+ const entityTab = placement?.slot === 'entity.detail.tab';
+ if (placement !== undefined) {
+ if (!placement || typeof placement !== 'object' || Array.isArray(placement)) {
+ console.error('[MFE Loader] Invalid placement', entry.id);
+ return null;
+ }
+ if (entityTab) {
+ if (
+ ['path', 'navIcon', 'slot'].some((key) => key in entry) ||
+ entry.flags?.showInNav !== undefined ||
+ !Array.isArray(placement.entityTypes) ||
+ !placement.entityTypes.length ||
+ !placement.entityTypes.every((t: unknown) => typeof t === 'string' && t.trim()) ||
+ typeof placement.tabName !== 'string' ||
+ !placement.tabName.trim() ||
+ ['path', 'navIcon', 'showInNav', 'area'].some((key) => key in placement)
+ )
+ errors.push('Invalid entity tab placement');
+ } else {
+ if ((placement.slot ?? 'nav.page') !== 'nav.page' || 'tabName' in placement || 'entityTypes' in placement)
+ errors.push('Invalid page placement');
+ config = {
+ ...entry,
+ path: placement.path,
+ slot: placement.area ?? 'app',
+ navIcon: placement.navIcon,
+ flags: { ...entry.flags, showInNav: placement.showInNav },
+ };
+ }
+ }
+ if (!entityTab && config.slot !== undefined && !['app', 'settings'].includes(config.slot))
+ errors.push('Invalid page area');
REQUIRED_FIELDS.forEach((field) => {
+ if (entityTab && (field === 'path' || field === 'navIcon')) return;
if (config[field] === undefined || config[field] === null) {
errors.push(`[MFE Loader] Missing required field: ${field}`);
}
});
if (typeof config.id !== 'string') errors.push('[MFE Loader] id must be a string');
if (typeof config.label !== 'string') errors.push('[MFE Loader] label must be a string');
- if (typeof config.path !== 'string' || !config.path.startsWith('/'))
+ if (!entityTab && (typeof config.path !== 'string' || !config.path.startsWith('/')))
errors.push('[MFE Loader] path must be a string starting with "/"');
+ if (config.slot === 'settings' && (typeof config.path !== 'string' || !/^\/settings\/[^/]/.test(config.path)))
+ errors.push('Settings placement requires a path under /settings/');
if (typeof config.remoteEntry !== 'string') errors.push('[MFE Loader] remoteEntry must be a string');
if (typeof config.module !== 'string' || !config.module.includes('/'))
errors.push('[MFE Loader] module must be a string with pattern "moduleName/functionName"');
if (typeof config.flags !== 'object' || config.flags === null) errors.push('[MFE Loader] flags must be an object');
if (config.flags) {
if (typeof config.flags.enabled !== 'boolean') errors.push('[MFE Loader] flags.enabled must be boolean');
- if (typeof config.flags.showInNav !== 'boolean') errors.push('[MFE Loader] flags.showInNav must be boolean');
+ if (!entityTab && typeof config.flags.showInNav !== 'boolean')
+ errors.push('[MFE Loader] flags.showInNav must be boolean');
}
- if (typeof config.navIcon !== 'string' || !config.navIcon.length) {
+ if (!entityTab && (typeof config.navIcon !== 'string' || !config.navIcon.length)) {
errors.push('[MFE Loader] navIcon must be a non-empty string');
}
+ if (config.format !== undefined && !['var', 'esm'].includes(config.format)) errors.push('Invalid remote format');
+ if (config.from !== undefined && !['webpack', 'vite'].includes(config.from)) errors.push('Invalid remote source');
+ let { remoteEntry } = config;
+ if (config.format === 'esm') {
+ try {
+ const deploymentBase = new URL(resolveRuntimePath('/'), window.location.origin);
+ const url = new URL(remoteEntry, deploymentBase);
+ if (
+ !remoteEntry?.trim() ||
+ !['http:', 'https:'].includes(url.protocol) ||
+ url.origin !== window.location.origin ||
+ url.username ||
+ url.password
+ ) {
+ errors.push('Expected a same-origin ESM entry');
+ }
+ remoteEntry = url.href;
+ } catch {
+ errors.push('Invalid ESM entry URL');
+ }
+ }
+
// If any errors, log them and return null
if (errors.length > 0) {
console.error(`[MFE Loader] Invalid config for entry (id: ${config.id || 'unknown'}):`, errors);
return null;
}
// Otherwise, return as valid MFEConfig
- return config as MFEConfig;
+ return { ...config, remoteEntry };
}
/**
@@ -111,9 +181,26 @@ export function loadMFEConfigFromYAML(yamlString: string): MFESchema {
throw new Error('[MFE Loader] Invalid YAML: missing microFrontends array');
}
// Validate each entry, filtering out invalid ones
- parsed.microFrontends = parsed.microFrontends
- .map(validateMFEConfig)
- .filter((config): config is MFEConfig => config !== null);
+ const routes = new Set();
+ const entries = parsed.microFrontends.map(validateMFEConfig);
+ const tabs = entries.filter(
+ (config): config is EntityTabConfig =>
+ config !== null && 'placement' in config && config.placement.slot === 'entity.detail.tab',
+ );
+ delete parsed.entityTabs;
+ if (tabs.length) parsed.entityTabs = tabs;
+ parsed.microFrontends = entries
+ .filter((config): config is MFEConfig => config !== null && 'path' in config)
+ .filter(({ path, slot }) => {
+ const basePath = slot === 'settings' ? path : `/mfe${path}`;
+ const route = basePath.replace(/\/$/, '').toLowerCase();
+ if (routes.has(route)) {
+ console.error('[MFE Loader] Duplicate route:', path);
+ return false;
+ }
+ routes.add(route);
+ return true;
+ });
parsed.loadTimeoutMs = parseLoadTimeoutMs(parsed.loadTimeoutMs, 'the top-level config');
return parsed;
} catch (e) {
@@ -148,23 +235,28 @@ export function useMFEConfigFromBackend(): MFESchema | null {
return config;
}
-export function useDynamicRoutes(): JSX.Element[] {
- const mfeConfig = useMFEConfigFromBackend();
+export function getPlacementRoutes(mfeConfig: MFESchema | null, area: 'app' | 'settings'): JSX.Element[] {
if (!mfeConfig) return [];
// TODO- Reintroduce useMemo() hook here. Make it work with getting yaml from api as a react hook.
- return mfeConfig.microFrontends.map((mfe) => (
- (
-
- )}
- />
- ));
+ return mfeConfig.microFrontends
+ .filter((mfe) => (mfe.slot ?? 'app') === area)
+ .sort((a, b) => b.path.length - a.path.length)
+ .map((mfe) => (
+ (
+
+ )}
+ />
+ ));
+}
+
+export function useDynamicRoutes(): JSX.Element[] {
+ return getPlacementRoutes(useMFEConfigFromBackend(), 'app');
}
export const MFERoutes = () => {
diff --git a/datahub-web-react/src/app/mfeframework/mfeNavBarMenuUtils.tsx b/datahub-web-react/src/app/mfeframework/mfeNavBarMenuUtils.tsx
index 246b58d0ee6de..96e2ab31b5cad 100644
--- a/datahub-web-react/src/app/mfeframework/mfeNavBarMenuUtils.tsx
+++ b/datahub-web-react/src/app/mfeframework/mfeNavBarMenuUtils.tsx
@@ -10,17 +10,17 @@ import { MFESchema } from '@app/mfeframework/mfeConfigLoader';
* Returns menu items for MFEs when subNavigationMode is FALSE.
* Only MFEs with showInNav=true are included.
*/
-export function getMfeMenuItems(mfeConfig: MFESchema): NavBarMenuLinkItem[] {
+export function getMfeMenuItems(mfeConfig: MFESchema, area: 'app' | 'settings' = 'app'): NavBarMenuLinkItem[] {
if (!mfeConfig?.microFrontends) return [];
return mfeConfig.microFrontends
- .filter((mfe) => mfe.flags?.showInNav)
+ .filter((mfe) => (mfe.slot ?? 'app') === area && mfe.flags?.enabled && mfe.flags.showInNav)
.map((mfe) => ({
type: NavBarMenuItemTypes.Item,
title: mfe.label,
key: mfe.id,
icon: getLazyIcon(mfe.navIcon),
- link: `/mfe${mfe.path}`,
+ link: area === 'settings' ? mfe.path : `/mfe${mfe.path}`,
onClick: () => {
console.log(`[MFE Nav] Clicked MFE nav item: ${mfe.label}, path: ${mfe.path}`);
},
@@ -35,7 +35,7 @@ export function getMfeMenuDropdownItems(mfeConfig: MFESchema): NavBarMenuDropdow
if (!mfeConfig?.microFrontends) return [];
return mfeConfig.microFrontends
- .filter((mfe) => mfe.flags?.showInNav)
+ .filter((mfe) => mfe.slot !== 'settings' && mfe.flags?.enabled && mfe.flags.showInNav)
.map((mfe) => ({
type: NavBarMenuItemTypes.DropdownElement,
title: mfe.label,
diff --git a/datahub-web-react/src/app/settingsV2/SettingsPage.tsx b/datahub-web-react/src/app/settingsV2/SettingsPage.tsx
index 7b4ad17a8abc6..f44d8d2b76d0a 100644
--- a/datahub-web-react/src/app/settingsV2/SettingsPage.tsx
+++ b/datahub-web-react/src/app/settingsV2/SettingsPage.tsx
@@ -20,6 +20,8 @@ import useGetLogoutHandler from '@app/auth/useGetLogoutHandler';
import { useUserContext } from '@app/context/useUserContext';
import NavBarMenu from '@app/homeV2/layout/navBarRedesign/NavBarMenu';
import { NavBarMenuItemTypes, NavBarMenuItems } from '@app/homeV2/layout/navBarRedesign/types';
+import { getPlacementRoutes, useMFEConfigFromBackend } from '@app/mfeframework/mfeConfigLoader';
+import { getMfeMenuItems } from '@app/mfeframework/mfeNavBarMenuUtils';
import { useCanManageMcpServers } from '@app/settingsV2/platform/ai/mcpServers/hooks/useCanManageMcpServers';
import { DEFAULT_PATH, PATHS } from '@app/settingsV2/settingsPaths';
import { SuspenseBlock } from '@app/sharedV2/SuspenseBlock';
@@ -125,6 +127,9 @@ const SettingsPageContent = () => {
const isShowNavBarRedesign = useShowNavBarRedesign();
const { config } = useAppConfig();
+ const mfeConfig = useMFEConfigFromBackend();
+ const extensionRoutes = getPlacementRoutes(mfeConfig, 'settings');
+ const extensionItems = mfeConfig ? getMfeMenuItems(mfeConfig, 'settings') : [];
const subRoutes = PATHS.map((p) => p.path.replace('/', ''));
const currPathName = pathname.replace(path, '');
const trimmedPathName = currPathName.endsWith('/') ? pathname.slice(0, pathname.length - 1) : currPathName;
@@ -149,6 +154,7 @@ const SettingsPageContent = () => {
// Menu Items based on PATHS
const menuItems: NavBarMenuItems = {
items: [
+ ...extensionItems,
// Personal Section
{
type: NavBarMenuItemTypes.Group,
@@ -341,7 +347,16 @@ const SettingsPageContent = () => {
-
+ item.link && (pathname === item.link || pathname.startsWith(`${item.link}/`)),
+ )?.key ?? activePath
+ }
+ menu={menuItems}
+ iconSize={16}
+ />
{/* Main Content */}
@@ -357,6 +372,7 @@ const SettingsPageContent = () => {
render={() => }>{p.content}}
/>
))}
+ {extensionRoutes}
diff --git a/e2e-test/ui/playwright/tests/mfeframework/fixtures/__federation_expose_Mount-CtTVcBCc.js.txt b/e2e-test/ui/playwright/tests/mfeframework/fixtures/__federation_expose_Mount-CtTVcBCc.js.txt
new file mode 100644
index 0000000000000..5e72e0085b647
--- /dev/null
+++ b/e2e-test/ui/playwright/tests/mfeframework/fixtures/__federation_expose_Mount-CtTVcBCc.js.txt
@@ -0,0 +1,6 @@
+function mount(element, props) {
+ element.textContent = [props.slot, props.area, props.basePath].join(':');
+ return () => element.replaceChildren();
+}
+
+export { mount };
diff --git a/e2e-test/ui/playwright/tests/mfeframework/fixtures/remoteEntry.js.txt b/e2e-test/ui/playwright/tests/mfeframework/fixtures/remoteEntry.js.txt
new file mode 100644
index 0000000000000..1e6a45778ea1b
--- /dev/null
+++ b/e2e-test/ui/playwright/tests/mfeframework/fixtures/remoteEntry.js.txt
@@ -0,0 +1,81 @@
+const currentImports = {};
+ const exportSet = new Set(['Module', '__esModule', 'default', '_export_sfc']);
+ let moduleMap = {
+"./mount":()=>{
+ dynamicLoadingCss([], false, './mount');
+ return __federation_import('./__federation_expose_Mount-CtTVcBCc.js').then(module =>Object.keys(module).every(item => exportSet.has(item)) ? () => module.default : () => module)},};
+ const seen = {};
+ const dynamicLoadingCss = (cssFilePaths, dontAppendStylesToHead, exposeItemName) => {
+ const metaUrl = import.meta.url;
+ if (typeof metaUrl === 'undefined') {
+ console.warn('The remote style takes effect only when the build.target option in the vite.config.ts file is higher than that of "es2020".');
+ return;
+ }
+
+ const curUrl = metaUrl.substring(0, metaUrl.lastIndexOf('remoteEntry.js'));
+ const base = '/';
+ 'assets';
+
+ cssFilePaths.forEach(cssPath => {
+ let href = '';
+ const baseUrl = base || curUrl;
+ if (baseUrl) {
+ const trimmer = {
+ trailing: (path) => (path.endsWith('/') ? path.slice(0, -1) : path),
+ leading: (path) => (path.startsWith('/') ? path.slice(1) : path)
+ };
+ const isAbsoluteUrl = (url) => url.startsWith('http') || url.startsWith('//');
+
+ const cleanBaseUrl = trimmer.trailing(baseUrl);
+ const cleanCssPath = trimmer.leading(cssPath);
+ const cleanCurUrl = trimmer.trailing(curUrl);
+
+ if (isAbsoluteUrl(baseUrl)) {
+ href = [cleanBaseUrl, cleanCssPath].filter(Boolean).join('/');
+ } else {
+ if (cleanCurUrl.includes(cleanBaseUrl)) {
+ href = [cleanCurUrl, cleanCssPath].filter(Boolean).join('/');
+ } else {
+ href = [cleanCurUrl + cleanBaseUrl, cleanCssPath].filter(Boolean).join('/');
+ }
+ }
+ } else {
+ href = cssPath;
+ }
+
+ if (dontAppendStylesToHead) {
+ const key = 'css__named__' + exposeItemName;
+ window[key] = window[key] || [];
+ window[key].push(href);
+ return;
+ }
+
+ if (href in seen) return;
+ seen[href] = true;
+
+ const element = document.createElement('link');
+ element.rel = 'stylesheet';
+ element.href = href;
+ document.head.appendChild(element);
+ });
+ };
+ async function __federation_import(name) {
+ currentImports[name] ??= import(name);
+ return currentImports[name]
+ } const get =(module) => {
+ if(!moduleMap[module]) throw new Error('Can not find remote module ' + module)
+ return moduleMap[module]();
+ };
+ const init =(shareScope) => {
+ globalThis.__federation_shared__= globalThis.__federation_shared__|| {};
+ Object.entries(shareScope).forEach(([key, value]) => {
+ for (const [versionKey, versionValue] of Object.entries(value)) {
+ const scope = versionValue.scope || 'default';
+ globalThis.__federation_shared__[scope] = globalThis.__federation_shared__[scope] || {};
+ const shared= globalThis.__federation_shared__[scope];
+ (shared[key] = shared[key]||{})[versionKey] = versionValue;
+ }
+ });
+ };
+
+export { dynamicLoadingCss, get, init };
diff --git a/e2e-test/ui/playwright/tests/mfeframework/valid-config-mfe.spec.ts b/e2e-test/ui/playwright/tests/mfeframework/valid-config-mfe.spec.ts
index ea1515bff8754..23d94240c0c52 100644
--- a/e2e-test/ui/playwright/tests/mfeframework/valid-config-mfe.spec.ts
+++ b/e2e-test/ui/playwright/tests/mfeframework/valid-config-mfe.spec.ts
@@ -1,7 +1,8 @@
+import path from 'node:path';
import { test, expect } from '../../fixtures/base-test';
import { MFEFrameworkPage } from '../../pages/mfe-framework.page';
import { TIMEOUTS } from '../../utils/constants';
-import { DomainTag } from '../../utils/test-tags';
+import { DomainTag, TestTag } from '../../utils/test-tags';
const MFE_CONFIG_YAML = `subNavigationMode: false
microFrontends:
@@ -25,7 +26,10 @@ window.helloWorldMFE = {
return Promise.resolve(() => {
return function mount(containerElement, props) {
if (containerElement) {
- containerElement.innerHTML = 'HelloWorld Cypress MFE Mounted
';
+ const heading = document.createElement('h1');
+ heading.textContent = 'HelloWorld Cypress MFE Mounted';
+ heading.dataset.contract = [props.contractVersion, props.slot, props.basePath].join(':');
+ containerElement.appendChild(heading);
}
return () => console.log('cleanup called');
};
@@ -80,3 +84,46 @@ test.describe('MFE Framework Configuration', () => {
},
);
});
+
+test('passes the app mount contract to a legacy remote', { tag: [DomainTag.Catalog, TestTag.P0] }, async ({ page }) => {
+ const mfePage = new MFEFrameworkPage(page);
+ await mfePage.mockFetchForMFEConfig(MFE_CONFIG_YAML);
+ await mfePage.mockRemoteEntry(200, REMOTE_ENTRY_SUCCESS);
+ await page.goto(`/mfe${MFE_PATH}`);
+ await expect(page.getByRole('heading', { name: MFE_CONTENT })).toHaveAttribute(
+ 'data-contract',
+ `1:nav.page:/mfe${MFE_PATH}`,
+ {
+ timeout: TIMEOUTS.LONG,
+ },
+ );
+});
+
+// Serve the two production chunks emitted by Vite and OriginJS for a named-only mount.
+test(
+ 'loads a built named ESM mount from the same entry on a trailing-slash route',
+ { tag: [DomainTag.Catalog, TestTag.P0] },
+ async ({ page }) => {
+ const mfePage = new MFEFrameworkPage(page);
+ await mfePage.mockFetchForMFEConfig(
+ MFE_CONFIG_YAML.replace(
+ 'remoteEntry: http://localhost:3002/remoteEntry.js',
+ 'format: esm\n from: vite\n remoteEntry: assets/remoteEntry.js',
+ ),
+ );
+ for (const chunk of ['remoteEntry.js', '__federation_expose_Mount-CtTVcBCc.js']) {
+ await page.route(
+ (url) => url.pathname === `/assets/${chunk}`,
+ (route) =>
+ route.fulfill({
+ contentType: 'application/javascript',
+ path: path.join(__dirname, 'fixtures', `${chunk}.txt`),
+ }),
+ );
+ }
+ await page.goto(`/mfe${MFE_PATH}/`);
+ await expect(page.getByText(`nav.page:app:/mfe${MFE_PATH}`, { exact: true })).toBeVisible({
+ timeout: TIMEOUTS.LONG,
+ });
+ },
+);