@module-federation/bridge-react 0.0.0-feat-support-bridge-react-router-v7-20251015102312

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +670 -0
  2. package/LICENSE +21 -0
  3. package/README.md +131 -0
  4. package/__tests__/bridge.spec.tsx +160 -0
  5. package/__tests__/createLazyComponent.spec.tsx +209 -0
  6. package/__tests__/prefetch.spec.ts +156 -0
  7. package/__tests__/router.spec.tsx +82 -0
  8. package/__tests__/setupTests.ts +8 -0
  9. package/__tests__/util.ts +36 -0
  10. package/dist/bridge-base-29j7dZKh.mjs +201 -0
  11. package/dist/bridge-base-CTNdBioh.js +216 -0
  12. package/dist/data-fetch-server-middleware.cjs.js +163 -0
  13. package/dist/data-fetch-server-middleware.d.ts +15 -0
  14. package/dist/data-fetch-server-middleware.es.js +164 -0
  15. package/dist/data-fetch-utils.cjs.js +24 -0
  16. package/dist/data-fetch-utils.d.ts +81 -0
  17. package/dist/data-fetch-utils.es.js +26 -0
  18. package/dist/index-Dm-M9ouh.mjs +46 -0
  19. package/dist/index-DqCpgmgH.js +45 -0
  20. package/dist/index.cjs.js +293 -0
  21. package/dist/index.d.ts +274 -0
  22. package/dist/index.es.js +276 -0
  23. package/dist/index.esm-CzoIcLts.js +459 -0
  24. package/dist/index.esm-JLwyxgUK.mjs +460 -0
  25. package/dist/lazy-load-component-plugin-B4fdMQTL.js +521 -0
  26. package/dist/lazy-load-component-plugin-ijw36GA0.mjs +522 -0
  27. package/dist/lazy-load-component-plugin.cjs.js +6 -0
  28. package/dist/lazy-load-component-plugin.d.ts +16 -0
  29. package/dist/lazy-load-component-plugin.es.js +6 -0
  30. package/dist/lazy-utils.cjs.js +24 -0
  31. package/dist/lazy-utils.d.ts +149 -0
  32. package/dist/lazy-utils.es.js +24 -0
  33. package/dist/plugin.cjs.js +14 -0
  34. package/dist/plugin.d.ts +22 -0
  35. package/dist/plugin.es.js +14 -0
  36. package/dist/prefetch-Bgm31z9s.js +1272 -0
  37. package/dist/prefetch-DjeoxOeZ.mjs +1273 -0
  38. package/dist/router-v5.cjs.js +55 -0
  39. package/dist/router-v5.d.ts +18 -0
  40. package/dist/router-v5.es.js +32 -0
  41. package/dist/router-v6.cjs.js +84 -0
  42. package/dist/router-v6.d.ts +20 -0
  43. package/dist/router-v6.es.js +61 -0
  44. package/dist/router-v7.cjs.js +83 -0
  45. package/dist/router-v7.d.ts +20 -0
  46. package/dist/router-v7.es.js +61 -0
  47. package/dist/router.cjs.js +82 -0
  48. package/dist/router.d.ts +20 -0
  49. package/dist/router.es.js +60 -0
  50. package/dist/utils-0HFFqmd4.js +2015 -0
  51. package/dist/utils-BTpxHmva.mjs +2016 -0
  52. package/dist/v18.cjs.js +15 -0
  53. package/dist/v18.d.ts +114 -0
  54. package/dist/v18.es.js +15 -0
  55. package/dist/v19.cjs.js +15 -0
  56. package/dist/v19.d.ts +115 -0
  57. package/dist/v19.es.js +15 -0
  58. package/jest.config.ts +21 -0
  59. package/package.json +144 -0
  60. package/project.json +23 -0
  61. package/src/index.ts +45 -0
  62. package/src/lazy/AwaitDataFetch.tsx +215 -0
  63. package/src/lazy/constant.ts +30 -0
  64. package/src/lazy/createLazyComponent.tsx +411 -0
  65. package/src/lazy/data-fetch/cache.ts +291 -0
  66. package/src/lazy/data-fetch/call-data-fetch.ts +13 -0
  67. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +196 -0
  68. package/src/lazy/data-fetch/index.ts +16 -0
  69. package/src/lazy/data-fetch/inject-data-fetch.ts +109 -0
  70. package/src/lazy/data-fetch/prefetch.ts +112 -0
  71. package/src/lazy/data-fetch/runtime-plugin.ts +115 -0
  72. package/src/lazy/index.ts +35 -0
  73. package/src/lazy/logger.ts +6 -0
  74. package/src/lazy/types.ts +75 -0
  75. package/src/lazy/utils.ts +372 -0
  76. package/src/lazy/wrapNoSSR.tsx +10 -0
  77. package/src/modern-app-env.d.ts +2 -0
  78. package/src/plugins/lazy-load-component-plugin.spec.ts +21 -0
  79. package/src/plugins/lazy-load-component-plugin.ts +57 -0
  80. package/src/provider/context.tsx +4 -0
  81. package/src/provider/plugin.ts +22 -0
  82. package/src/provider/versions/bridge-base.tsx +127 -0
  83. package/src/provider/versions/legacy.ts +87 -0
  84. package/src/provider/versions/v18.ts +47 -0
  85. package/src/provider/versions/v19.ts +48 -0
  86. package/src/remote/component.tsx +211 -0
  87. package/src/remote/create.tsx +103 -0
  88. package/src/router/default.tsx +73 -0
  89. package/src/router/v5.tsx +43 -0
  90. package/src/router/v6.tsx +74 -0
  91. package/src/router/v7.tsx +75 -0
  92. package/src/types.ts +147 -0
  93. package/src/utils/index.ts +44 -0
  94. package/src/v18.ts +9 -0
  95. package/src/v19.ts +9 -0
  96. package/tsconfig.json +42 -0
  97. package/tsconfig.node.json +11 -0
  98. package/tsconfig.spec.json +26 -0
  99. package/vite.config.ts +106 -0
  100. package/vitest.config.ts +27 -0
@@ -0,0 +1,10 @@
1
+ import { createLazyComponent } from './createLazyComponent';
2
+ import type { CreateLazyComponentOptions } from './createLazyComponent';
3
+
4
+ export function wrapNoSSR<T, E extends keyof T>(
5
+ createLazyComponentFn: typeof createLazyComponent<T, E>,
6
+ ) {
7
+ return (options: Omit<CreateLazyComponentOptions<T, E>, 'noSSR'>) => {
8
+ return createLazyComponentFn({ ...options, noSSR: true });
9
+ };
10
+ }
@@ -0,0 +1,2 @@
1
+ /// <reference types='@modern-js/module-tools/types' />
2
+ /// <reference types='@modern-js/plugin-testing/types' />
@@ -0,0 +1,21 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { lazyLoadComponentPlugin } from './lazy-load-component-plugin';
3
+ import type { ModuleFederation } from '@module-federation/runtime';
4
+
5
+ describe('lazyLoadComponentPlugin', () => {
6
+ it('should register lazy load component methods on the instance', () => {
7
+ const instance = {
8
+ registerPlugins: vi.fn(),
9
+ } as unknown as ModuleFederation;
10
+
11
+ const plugin = lazyLoadComponentPlugin();
12
+ if (plugin.apply) {
13
+ plugin.apply(instance);
14
+ }
15
+
16
+ expect(instance.registerPlugins).toHaveBeenCalled();
17
+ expect(typeof instance.createLazyComponent).toBe('function');
18
+ expect(typeof instance.prefetch).toBe('function');
19
+ expect(typeof instance.collectSSRAssets).toBe('function');
20
+ });
21
+ });
@@ -0,0 +1,57 @@
1
+ import type {
2
+ ModuleFederation,
3
+ ModuleFederationRuntimePlugin,
4
+ } from '@module-federation/runtime';
5
+ import {
6
+ createLazyComponent,
7
+ prefetch,
8
+ collectSSRAssets,
9
+ autoFetchDataPlugin,
10
+ } from '../lazy';
11
+ import type { CreateLazyComponentOptions, PrefetchOptions } from '../lazy';
12
+
13
+ declare module '@module-federation/runtime-core' {
14
+ interface ModuleFederation {
15
+ createLazyComponent<T, E extends keyof T>(
16
+ options: Omit<CreateLazyComponentOptions<T, E>, 'instance'>,
17
+ ): ReturnType<typeof createLazyComponent<T, E>>;
18
+ prefetch(
19
+ options: Omit<PrefetchOptions, 'instance'>,
20
+ ): ReturnType<typeof prefetch>;
21
+ collectSSRAssets(
22
+ options: Omit<Parameters<typeof collectSSRAssets>[0], 'instance'>,
23
+ ): ReturnType<typeof collectSSRAssets>;
24
+ }
25
+ }
26
+
27
+ export function lazyLoadComponentPlugin(): ModuleFederationRuntimePlugin {
28
+ return {
29
+ name: 'lazy-load-component-plugin',
30
+ apply(instance: ModuleFederation) {
31
+ instance.registerPlugins([autoFetchDataPlugin()]);
32
+
33
+ instance.createLazyComponent = (options) => {
34
+ return createLazyComponent({
35
+ instance,
36
+ ...options,
37
+ });
38
+ };
39
+
40
+ instance.prefetch = (options) => {
41
+ return prefetch({
42
+ instance,
43
+ ...options,
44
+ });
45
+ };
46
+
47
+ instance.collectSSRAssets = (options) => {
48
+ return collectSSRAssets({
49
+ instance,
50
+ ...options,
51
+ });
52
+ };
53
+ },
54
+ };
55
+ }
56
+
57
+ export default lazyLoadComponentPlugin;
@@ -0,0 +1,4 @@
1
+ import React from 'react';
2
+ import { ProviderParams } from '../types';
3
+
4
+ export const RouterContext = React.createContext<ProviderParams | null>(null);
@@ -0,0 +1,22 @@
1
+ import type {
2
+ ModuleFederationRuntimePlugin,
3
+ ModuleFederation,
4
+ } from '@module-federation/runtime';
5
+
6
+ export type FederationRuntimeType = {
7
+ instance: ModuleFederation | null;
8
+ };
9
+
10
+ export const federationRuntime: FederationRuntimeType = { instance: null };
11
+
12
+ function BridgeReactPlugin(): ModuleFederationRuntimePlugin {
13
+ return {
14
+ name: 'bridge-react-plugin',
15
+ beforeInit(args) {
16
+ federationRuntime.instance = args.origin;
17
+ return args;
18
+ },
19
+ };
20
+ }
21
+
22
+ export default BridgeReactPlugin;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Base bridge component implementation
3
+ * This file contains bridge component logic shared across all React versions
4
+ */
5
+ import * as React from 'react';
6
+ import type {
7
+ ProviderParams,
8
+ ProviderFnParams,
9
+ RootType,
10
+ DestroyParams,
11
+ RenderParams,
12
+ CreateRootOptions,
13
+ } from '../../types';
14
+ import { ErrorBoundary, FallbackProps } from 'react-error-boundary';
15
+ import { RouterContext } from '../context';
16
+ import { LoggerInstance } from '../../utils';
17
+ import { federationRuntime } from '../plugin';
18
+
19
+ export function createBaseBridgeComponent<T>({
20
+ createRoot,
21
+ defaultRootOptions,
22
+ ...bridgeInfo
23
+ }: ProviderFnParams<T>) {
24
+ return () => {
25
+ const rootMap = new Map<any, RootType>();
26
+ const instance = federationRuntime.instance;
27
+ LoggerInstance.debug(
28
+ `createBridgeComponent instance from props >>>`,
29
+ instance,
30
+ );
31
+
32
+ const RawComponent = (info: { propsInfo: T; appInfo: ProviderParams }) => {
33
+ const { appInfo, propsInfo, ...restProps } = info;
34
+ const { moduleName, memoryRoute, basename = '/' } = appInfo;
35
+ return (
36
+ <RouterContext.Provider value={{ moduleName, basename, memoryRoute }}>
37
+ <bridgeInfo.rootComponent
38
+ {...propsInfo}
39
+ basename={basename}
40
+ {...restProps}
41
+ />
42
+ </RouterContext.Provider>
43
+ );
44
+ };
45
+
46
+ return {
47
+ async render(info: RenderParams) {
48
+ LoggerInstance.debug(`createBridgeComponent render Info`, info);
49
+ const {
50
+ moduleName,
51
+ dom,
52
+ basename,
53
+ memoryRoute,
54
+ fallback,
55
+ rootOptions,
56
+ ...propsInfo
57
+ } = info;
58
+
59
+ const mergedRootOptions: CreateRootOptions | undefined = {
60
+ ...defaultRootOptions,
61
+ ...(rootOptions as CreateRootOptions),
62
+ };
63
+
64
+ const beforeBridgeRenderRes =
65
+ instance?.bridgeHook?.lifecycle?.beforeBridgeRender?.emit(info) || {};
66
+
67
+ const BridgeWrapper = ({ basename }: { basename?: string }) => (
68
+ <ErrorBoundary
69
+ FallbackComponent={fallback as React.ComponentType<FallbackProps>}
70
+ >
71
+ <RawComponent
72
+ appInfo={{
73
+ moduleName,
74
+ basename,
75
+ memoryRoute,
76
+ }}
77
+ propsInfo={
78
+ {
79
+ ...propsInfo,
80
+ basename,
81
+ ...(beforeBridgeRenderRes as any)?.extraProps,
82
+ } as T
83
+ }
84
+ />
85
+ </ErrorBoundary>
86
+ );
87
+
88
+ const rootComponentWithErrorBoundary = (
89
+ <BridgeWrapper basename={basename} />
90
+ );
91
+
92
+ if (bridgeInfo.render) {
93
+ await Promise.resolve(
94
+ bridgeInfo.render(rootComponentWithErrorBoundary, dom),
95
+ ).then((root: RootType) => rootMap.set(dom, root));
96
+ } else {
97
+ let root = rootMap.get(dom);
98
+ // Do not call createRoot multiple times
99
+ if (!root && createRoot) {
100
+ root = createRoot(dom, mergedRootOptions);
101
+ rootMap.set(dom, root as any);
102
+ }
103
+
104
+ if (root && 'render' in root) {
105
+ root.render(rootComponentWithErrorBoundary);
106
+ }
107
+ }
108
+ instance?.bridgeHook?.lifecycle?.afterBridgeRender?.emit(info) || {};
109
+ },
110
+
111
+ destroy(info: DestroyParams) {
112
+ const { dom } = info;
113
+ LoggerInstance.debug(`createBridgeComponent destroy Info`, info);
114
+ const root = rootMap.get(dom);
115
+ if (root) {
116
+ if ('unmount' in root) {
117
+ root.unmount();
118
+ } else {
119
+ LoggerInstance.warn('Root does not have unmount method');
120
+ }
121
+ rootMap.delete(dom);
122
+ }
123
+ instance?.bridgeHook?.lifecycle?.afterBridgeDestroy?.emit(info);
124
+ },
125
+ };
126
+ };
127
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Entry point for React 16/17 (legacy) specific bridge components
3
+ * This file provides support for React 16 and 17 versions, using the traditional ReactDOM.render API
4
+ */
5
+ import type { ProviderFnParams } from '../../types';
6
+ import { createBaseBridgeComponent } from './bridge-base';
7
+ import ReactDOM from 'react-dom';
8
+ import { LoggerInstance } from '../../utils';
9
+
10
+ export interface CreateRootOptions {
11
+ identifierPrefix?: string;
12
+ onRecoverableError?: (error: unknown, errorInfo: unknown) => void;
13
+ }
14
+
15
+ export interface Root {
16
+ render(children: React.ReactNode): void;
17
+ unmount(): void;
18
+ }
19
+
20
+ /**
21
+ * Default createRoot function that automatically detects React version and uses the appropriate API(only support React 16/17, 18)
22
+ *
23
+ * Note: Users can also directly import version-specific bridge components:
24
+ * - import { createBridgeComponent } from '@module-federation/bridge-react'
25
+ * - import { createBridgeComponent } from '@module-federation/bridge-react/v18'
26
+ * - import { createBridgeComponent } from '@module-federation/bridge-react/v19'
27
+ */
28
+
29
+ export function createReact16Or17Root(
30
+ container: Element | DocumentFragment,
31
+ ): Root {
32
+ return {
33
+ render(children: React.ReactNode) {
34
+ /**
35
+ * Detect React version
36
+ */
37
+ const reactVersion = ReactDOM.version || '';
38
+ const isReact18 = reactVersion.startsWith('18');
39
+ const isReact19 = reactVersion.startsWith('19');
40
+
41
+ /**
42
+ * Throw error for React 19
43
+ *
44
+ * Note: Due to Module Federation sharing mechanism, the actual version detected here
45
+ * might be 18 or 19, even if the application itself uses React 16/17.
46
+ * This happens because in MF environments, different remote modules may share different React versions.
47
+ * The console may throw warnings about version and API mismatches. If you need to resolve these issues,
48
+ * consider disabling the shared configuration for React.
49
+ */
50
+ if (isReact19) {
51
+ throw new Error(
52
+ `React 19 detected in legacy mode. This is not supported. ` +
53
+ `Please use the version-specific import: ` +
54
+ `import { createBridgeComponent } from '@module-federation/bridge-react/v19'`,
55
+ );
56
+ }
57
+
58
+ /**
59
+ * Provide warning for React 18
60
+ */
61
+ if (isReact18) {
62
+ LoggerInstance.warn(
63
+ `[Bridge-React] React 18 detected in legacy mode. ` +
64
+ `For better compatibility, please use the version-specific import: ` +
65
+ `import { createBridgeComponent } from '@module-federation/bridge-react/v18'`,
66
+ );
67
+ }
68
+
69
+ // @ts-ignore - React 17's render method is deprecated but still functional
70
+ ReactDOM.render(children, container);
71
+ },
72
+ unmount() {
73
+ ReactDOM.unmountComponentAtNode(container as Element);
74
+ },
75
+ };
76
+ }
77
+
78
+ export function createBridgeComponent<T = any>(
79
+ bridgeInfo: Omit<ProviderFnParams<T>, 'createRoot'>,
80
+ ) {
81
+ const fullBridgeInfo = {
82
+ createRoot: createReact16Or17Root,
83
+ ...bridgeInfo,
84
+ } as unknown as ProviderFnParams<T>;
85
+
86
+ return createBaseBridgeComponent(fullBridgeInfo);
87
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Entry point for React 18 specific bridge components
3
+ */
4
+ import React from 'react';
5
+ import { createRoot as createReactRoot, hydrateRoot } from 'react-dom/client';
6
+ import { createBaseBridgeComponent } from './bridge-base';
7
+ import type { ProviderFnParams } from '../../types';
8
+
9
+ export interface CreateRootOptions {
10
+ identifierPrefix?: string;
11
+ onRecoverableError?: (error: unknown, errorInfo: unknown) => void;
12
+ }
13
+
14
+ export interface Root {
15
+ render(children: React.ReactNode): void;
16
+ unmount(): void;
17
+ }
18
+
19
+ export function createReact18Root(
20
+ container: Element | DocumentFragment,
21
+ options?: CreateRootOptions,
22
+ ): Root {
23
+ return createReactRoot(container, options);
24
+ }
25
+
26
+ export function hydrateReact18Root(
27
+ container: Element | DocumentFragment,
28
+ initialChildren: React.ReactNode,
29
+ options?: CreateRootOptions,
30
+ ) {
31
+ return hydrateRoot(
32
+ container as Element,
33
+ initialChildren as React.ReactElement,
34
+ options,
35
+ );
36
+ }
37
+
38
+ export function createBridgeComponent<T = any>(
39
+ bridgeInfo: Omit<ProviderFnParams<T>, 'createRoot'>,
40
+ ) {
41
+ const fullBridgeInfo = {
42
+ createRoot: createReact18Root,
43
+ ...bridgeInfo,
44
+ } as unknown as ProviderFnParams<T>;
45
+
46
+ return createBaseBridgeComponent(fullBridgeInfo);
47
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Entry point for React 19 specific bridge components
3
+ * This file provides support for React 19 version, using the new ReactDOM.createRoot API
4
+ */
5
+ import React from 'react';
6
+ import { createRoot, hydrateRoot } from 'react-dom/client';
7
+ import { createBaseBridgeComponent } from './bridge-base';
8
+ import type { ProviderFnParams } from '../../types';
9
+ export interface CreateRootOptions {
10
+ identifierPrefix?: string;
11
+ onRecoverableError?: (error: unknown, errorInfo: unknown) => void;
12
+ transitionCallbacks?: unknown;
13
+ }
14
+
15
+ export interface Root {
16
+ render(children: React.ReactNode): void;
17
+ unmount(): void;
18
+ }
19
+
20
+ export function createReact19Root(
21
+ container: Element | DocumentFragment,
22
+ options?: CreateRootOptions,
23
+ ): Root {
24
+ return createRoot(container as Element, options);
25
+ }
26
+
27
+ export function hydrateReact19Root(
28
+ container: Element | DocumentFragment,
29
+ initialChildren: React.ReactNode,
30
+ options?: CreateRootOptions,
31
+ ): Root {
32
+ return hydrateRoot(
33
+ container as Element,
34
+ initialChildren as React.ReactElement,
35
+ options,
36
+ );
37
+ }
38
+
39
+ export function createBridgeComponent<T = any>(
40
+ bridgeInfo: Omit<ProviderFnParams<T>, 'createRoot'>,
41
+ ) {
42
+ const fullBridgeInfo = {
43
+ createRoot: createReact19Root,
44
+ ...bridgeInfo,
45
+ } as unknown as ProviderFnParams<T>;
46
+
47
+ return createBaseBridgeComponent(fullBridgeInfo);
48
+ }
@@ -0,0 +1,211 @@
1
+ import React, {
2
+ useContext,
3
+ useEffect,
4
+ useRef,
5
+ useState,
6
+ forwardRef,
7
+ } from 'react';
8
+ import * as ReactRouterDOM from 'react-router-dom';
9
+ import { dispatchPopstateEnv } from '@module-federation/bridge-shared';
10
+ import { LoggerInstance, pathJoin, getRootDomDefaultClassName } from '../utils';
11
+ import { federationRuntime } from '../provider/plugin';
12
+ import { RemoteComponentProps, RemoteAppParams } from '../types';
13
+
14
+ const RemoteAppWrapper = forwardRef(function (
15
+ props: RemoteAppParams & RemoteComponentProps,
16
+ ref,
17
+ ) {
18
+ const {
19
+ moduleName,
20
+ memoryRoute,
21
+ basename,
22
+ providerInfo,
23
+ className,
24
+ style,
25
+ fallback,
26
+ loading,
27
+ ...resProps
28
+ } = props;
29
+
30
+ const instance = federationRuntime.instance;
31
+ const rootRef: React.MutableRefObject<HTMLDivElement | null> =
32
+ ref && 'current' in ref
33
+ ? (ref as React.MutableRefObject<HTMLDivElement | null>)
34
+ : useRef(null);
35
+
36
+ const renderDom: React.MutableRefObject<HTMLElement | null> = useRef(null);
37
+ const providerInfoRef = useRef<any>(null);
38
+ const [initialized, setInitialized] = useState(false);
39
+
40
+ LoggerInstance.debug(`RemoteAppWrapper instance from props >>>`, instance);
41
+
42
+ // 初始化远程组件
43
+ useEffect(() => {
44
+ if (initialized) return;
45
+ const providerReturn = providerInfo();
46
+ providerInfoRef.current = providerReturn;
47
+ setInitialized(true);
48
+
49
+ return () => {
50
+ if (providerInfoRef.current?.destroy) {
51
+ LoggerInstance.debug(
52
+ `createRemoteAppComponent LazyComponent destroy >>>`,
53
+ { moduleName, basename, dom: renderDom.current },
54
+ );
55
+
56
+ instance?.bridgeHook?.lifecycle?.beforeBridgeDestroy?.emit({
57
+ moduleName,
58
+ dom: renderDom.current,
59
+ basename,
60
+ memoryRoute,
61
+ fallback,
62
+ ...resProps,
63
+ });
64
+
65
+ providerInfoRef.current?.destroy({
66
+ moduleName,
67
+ dom: renderDom.current,
68
+ });
69
+
70
+ instance?.bridgeHook?.lifecycle?.afterBridgeDestroy?.emit({
71
+ moduleName,
72
+ dom: renderDom.current,
73
+ basename,
74
+ memoryRoute,
75
+ fallback,
76
+ ...resProps,
77
+ });
78
+ }
79
+ };
80
+ }, [moduleName]);
81
+
82
+ // trigger render after props updated
83
+ useEffect(() => {
84
+ if (!initialized || !providerInfoRef.current) return;
85
+
86
+ let renderProps = {
87
+ moduleName,
88
+ dom: rootRef.current,
89
+ basename,
90
+ memoryRoute,
91
+ fallback,
92
+ ...resProps,
93
+ };
94
+ renderDom.current = rootRef.current;
95
+
96
+ const beforeBridgeRenderRes =
97
+ instance?.bridgeHook?.lifecycle?.beforeBridgeRender?.emit(renderProps) ||
98
+ {};
99
+ // @ts-ignore
100
+ renderProps = { ...renderProps, ...beforeBridgeRenderRes.extraProps };
101
+ providerInfoRef.current.render(renderProps);
102
+ instance?.bridgeHook?.lifecycle?.afterBridgeRender?.emit(renderProps);
103
+ }, [initialized, ...Object.values(props)]);
104
+
105
+ // bridge-remote-root
106
+ const rootComponentClassName = `${getRootDomDefaultClassName(moduleName)} ${className || ''}`;
107
+ return (
108
+ <div className={rootComponentClassName} style={style} ref={rootRef}>
109
+ {loading}
110
+ </div>
111
+ );
112
+ });
113
+
114
+ interface ExtraDataProps {
115
+ basename?: string;
116
+ }
117
+
118
+ export function withRouterData<
119
+ P extends Parameters<typeof RemoteAppWrapper>[0],
120
+ >(
121
+ WrappedComponent: React.ComponentType<P & ExtraDataProps>,
122
+ ): React.FC<Omit<P, keyof ExtraDataProps>> {
123
+ const Component = forwardRef(function (props: any, ref) {
124
+ if (props?.basename) {
125
+ return (
126
+ <WrappedComponent {...props} basename={props.basename} ref={ref} />
127
+ );
128
+ }
129
+ let enableDispathPopstate = false;
130
+ let routerContextVal: any;
131
+ try {
132
+ ReactRouterDOM.useLocation();
133
+ enableDispathPopstate = true;
134
+ } catch {
135
+ enableDispathPopstate = false;
136
+ }
137
+ let basename = '/';
138
+
139
+ if (!props.basename && enableDispathPopstate) {
140
+ const ReactRouterDOMAny: any = ReactRouterDOM;
141
+ // Avoid building tools checking references
142
+ const useRouteMatch = ReactRouterDOMAny['use' + 'RouteMatch']; //v5
143
+ const useHistory = ReactRouterDOMAny['use' + 'History']; //v5
144
+ const useHref = ReactRouterDOMAny['use' + 'Href'];
145
+ const UNSAFE_RouteContext = ReactRouterDOMAny['UNSAFE_' + 'RouteContext'];
146
+
147
+ if (UNSAFE_RouteContext /* react-router@6 */) {
148
+ if (useHref) {
149
+ basename = useHref?.('/');
150
+ }
151
+ routerContextVal = useContext(UNSAFE_RouteContext);
152
+ if (
153
+ routerContextVal &&
154
+ routerContextVal.matches &&
155
+ routerContextVal.matches.length > 0
156
+ ) {
157
+ const matchIndex = routerContextVal.matches.length - 1;
158
+ const pathnameBase =
159
+ routerContextVal.matches[matchIndex].pathnameBase;
160
+ basename = pathJoin(basename, pathnameBase || '/');
161
+ }
162
+ } /* react-router@5 */ else {
163
+ const match = useRouteMatch?.(); // v5
164
+ if (useHistory /* react-router@5 */) {
165
+ // there is no dynamic switching of the router version in the project
166
+ // so hooks can be used in conditional judgment
167
+ const history = useHistory?.();
168
+ // To be compatible to history@4.10.1 and @5.3.0 we cannot write like this `history.createHref(pathname)`
169
+ basename = history?.createHref?.({ pathname: '/' });
170
+ }
171
+ if (match /* react-router@5 */) {
172
+ basename = pathJoin(basename, match?.path || '/');
173
+ }
174
+ }
175
+ }
176
+
177
+ LoggerInstance.debug(`createRemoteAppComponent withRouterData >>>`, {
178
+ ...props,
179
+ basename,
180
+ routerContextVal,
181
+ enableDispathPopstate,
182
+ });
183
+
184
+ if (enableDispathPopstate) {
185
+ const location = ReactRouterDOM.useLocation();
186
+ const [pathname, setPathname] = useState(location.pathname);
187
+
188
+ useEffect(() => {
189
+ if (pathname !== '' && pathname !== location.pathname) {
190
+ LoggerInstance.debug(
191
+ `createRemoteAppComponent dispatchPopstateEnv >>>`,
192
+ {
193
+ name: props.name,
194
+ pathname: location.pathname,
195
+ },
196
+ );
197
+ dispatchPopstateEnv();
198
+ }
199
+ setPathname(location.pathname);
200
+ }, [location]);
201
+ }
202
+
203
+ return <WrappedComponent {...(props as P)} basename={basename} ref={ref} />;
204
+ });
205
+
206
+ return forwardRef(function (props, ref) {
207
+ return <Component {...props} ref={ref} />;
208
+ }) as any;
209
+ }
210
+
211
+ export default withRouterData(RemoteAppWrapper);