@module-federation/bridge-react 0.0.0-fix-lazy-comile-20250925082726

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 (96) hide show
  1. package/CHANGELOG.md +657 -0
  2. package/LICENSE +21 -0
  3. package/README.md +131 -0
  4. package/__tests__/bridge.spec.tsx +137 -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-BwHtOqw_.mjs +199 -0
  11. package/dist/bridge-base-Ds850AOx.js +214 -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-eN2xRRXs.js +45 -0
  19. package/dist/index-rAO0Wr0M.mjs +46 -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-CtI0uQUR.mjs +430 -0
  24. package/dist/index.esm-Ju4RY-yW.js +429 -0
  25. package/dist/lazy-load-component-plugin-BLfwTMtM.mjs +522 -0
  26. package/dist/lazy-load-component-plugin-C0zAoMq3.js +521 -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-BkgTf4W6.mjs +1371 -0
  37. package/dist/prefetch-DX29k_gH.js +1370 -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.cjs.js +82 -0
  45. package/dist/router.d.ts +20 -0
  46. package/dist/router.es.js +60 -0
  47. package/dist/utils-VSOJTX_o.mjs +2016 -0
  48. package/dist/utils-vIpCrZmn.js +2015 -0
  49. package/dist/v18.cjs.js +15 -0
  50. package/dist/v18.d.ts +114 -0
  51. package/dist/v18.es.js +15 -0
  52. package/dist/v19.cjs.js +15 -0
  53. package/dist/v19.d.ts +115 -0
  54. package/dist/v19.es.js +15 -0
  55. package/jest.config.ts +21 -0
  56. package/package.json +129 -0
  57. package/project.json +23 -0
  58. package/src/index.ts +45 -0
  59. package/src/lazy/AwaitDataFetch.tsx +215 -0
  60. package/src/lazy/constant.ts +30 -0
  61. package/src/lazy/createLazyComponent.tsx +411 -0
  62. package/src/lazy/data-fetch/cache.ts +291 -0
  63. package/src/lazy/data-fetch/call-data-fetch.ts +13 -0
  64. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +196 -0
  65. package/src/lazy/data-fetch/index.ts +16 -0
  66. package/src/lazy/data-fetch/inject-data-fetch.ts +109 -0
  67. package/src/lazy/data-fetch/prefetch.ts +112 -0
  68. package/src/lazy/data-fetch/runtime-plugin.ts +115 -0
  69. package/src/lazy/index.ts +35 -0
  70. package/src/lazy/logger.ts +6 -0
  71. package/src/lazy/types.ts +75 -0
  72. package/src/lazy/utils.ts +372 -0
  73. package/src/lazy/wrapNoSSR.tsx +10 -0
  74. package/src/modern-app-env.d.ts +2 -0
  75. package/src/plugins/lazy-load-component-plugin.spec.ts +21 -0
  76. package/src/plugins/lazy-load-component-plugin.ts +57 -0
  77. package/src/provider/context.tsx +4 -0
  78. package/src/provider/plugin.ts +22 -0
  79. package/src/provider/versions/bridge-base.tsx +122 -0
  80. package/src/provider/versions/legacy.ts +86 -0
  81. package/src/provider/versions/v18.ts +47 -0
  82. package/src/provider/versions/v19.ts +48 -0
  83. package/src/remote/component.tsx +211 -0
  84. package/src/remote/create.tsx +103 -0
  85. package/src/router/default.tsx +73 -0
  86. package/src/router/v5.tsx +43 -0
  87. package/src/router/v6.tsx +74 -0
  88. package/src/types.ts +147 -0
  89. package/src/utils/index.ts +44 -0
  90. package/src/v18.ts +9 -0
  91. package/src/v19.ts +9 -0
  92. package/tsconfig.json +42 -0
  93. package/tsconfig.node.json +11 -0
  94. package/tsconfig.spec.json +26 -0
  95. package/vite.config.ts +87 -0
  96. package/vitest.config.ts +27 -0
@@ -0,0 +1,8 @@
1
+ // In vitest, you can use the setupFiles option in your configuration file to import any necessary setup files for your tests.
2
+ // For example, if you want to use testing-library's custom matchers, you can import them in a setup file like this:
3
+ import '@testing-library/jest-dom';
4
+
5
+ // Fix TextEncoder/TextDecoder not defined in Node.js
6
+ import { TextEncoder, TextDecoder } from 'util';
7
+ global.TextEncoder = TextEncoder;
8
+ global.TextDecoder = TextDecoder as any;
@@ -0,0 +1,36 @@
1
+ import { JSDOM } from 'jsdom';
2
+ import { prettyDOM } from '@testing-library/react';
3
+
4
+ export async function sleep(time: number) {
5
+ return new Promise((resolve) => {
6
+ setTimeout(() => {
7
+ resolve(null);
8
+ }, time);
9
+ });
10
+ }
11
+
12
+ export function createContainer() {
13
+ const container = document.createElement('div');
14
+ container.setAttribute('id', 'container');
15
+ document.body.appendChild(container);
16
+
17
+ return {
18
+ clean: () => {
19
+ document.body.removeChild(container);
20
+ },
21
+ container,
22
+ };
23
+ }
24
+
25
+ export function getWindowImpl(initialUrl: string, isHash = false): Window {
26
+ // Need to use our own custom DOM in order to get a working history
27
+ const dom = new JSDOM(`<!DOCTYPE html>`, { url: 'http://localhost/' });
28
+ dom.window.history.replaceState(null, '', (isHash ? '#' : '') + initialUrl);
29
+ return dom.window as unknown as Window;
30
+ }
31
+
32
+ export function getHtml(container: HTMLElement) {
33
+ return prettyDOM(container, undefined, {
34
+ highlight: false,
35
+ });
36
+ }
@@ -0,0 +1,199 @@
1
+ import * as React from "react";
2
+ import { Component, createElement, createContext } from "react";
3
+ import { L as LoggerInstance, R as RouterContext } from "./index-rAO0Wr0M.mjs";
4
+ import { federationRuntime } from "./plugin.es.js";
5
+ const ErrorBoundaryContext = createContext(null);
6
+ const initialState = {
7
+ didCatch: false,
8
+ error: null
9
+ };
10
+ class ErrorBoundary extends Component {
11
+ constructor(props) {
12
+ super(props);
13
+ this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
14
+ this.state = initialState;
15
+ }
16
+ static getDerivedStateFromError(error) {
17
+ return {
18
+ didCatch: true,
19
+ error
20
+ };
21
+ }
22
+ resetErrorBoundary() {
23
+ const {
24
+ error
25
+ } = this.state;
26
+ if (error !== null) {
27
+ var _this$props$onReset, _this$props;
28
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
29
+ args[_key] = arguments[_key];
30
+ }
31
+ (_this$props$onReset = (_this$props = this.props).onReset) === null || _this$props$onReset === void 0 ? void 0 : _this$props$onReset.call(_this$props, {
32
+ args,
33
+ reason: "imperative-api"
34
+ });
35
+ this.setState(initialState);
36
+ }
37
+ }
38
+ componentDidCatch(error, info) {
39
+ var _this$props$onError, _this$props2;
40
+ (_this$props$onError = (_this$props2 = this.props).onError) === null || _this$props$onError === void 0 ? void 0 : _this$props$onError.call(_this$props2, error, info);
41
+ }
42
+ componentDidUpdate(prevProps, prevState) {
43
+ const {
44
+ didCatch
45
+ } = this.state;
46
+ const {
47
+ resetKeys
48
+ } = this.props;
49
+ if (didCatch && prevState.error !== null && hasArrayChanged(prevProps.resetKeys, resetKeys)) {
50
+ var _this$props$onReset2, _this$props3;
51
+ (_this$props$onReset2 = (_this$props3 = this.props).onReset) === null || _this$props$onReset2 === void 0 ? void 0 : _this$props$onReset2.call(_this$props3, {
52
+ next: resetKeys,
53
+ prev: prevProps.resetKeys,
54
+ reason: "keys"
55
+ });
56
+ this.setState(initialState);
57
+ }
58
+ }
59
+ render() {
60
+ const {
61
+ children,
62
+ fallbackRender,
63
+ FallbackComponent,
64
+ fallback
65
+ } = this.props;
66
+ const {
67
+ didCatch,
68
+ error
69
+ } = this.state;
70
+ let childToRender = children;
71
+ if (didCatch) {
72
+ const props = {
73
+ error,
74
+ resetErrorBoundary: this.resetErrorBoundary
75
+ };
76
+ if (typeof fallbackRender === "function") {
77
+ childToRender = fallbackRender(props);
78
+ } else if (FallbackComponent) {
79
+ childToRender = createElement(FallbackComponent, props);
80
+ } else if (fallback !== void 0) {
81
+ childToRender = fallback;
82
+ } else {
83
+ throw error;
84
+ }
85
+ }
86
+ return createElement(ErrorBoundaryContext.Provider, {
87
+ value: {
88
+ didCatch,
89
+ error,
90
+ resetErrorBoundary: this.resetErrorBoundary
91
+ }
92
+ }, childToRender);
93
+ }
94
+ }
95
+ function hasArrayChanged() {
96
+ let a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
97
+ let b = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
98
+ return a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]));
99
+ }
100
+ function createBaseBridgeComponent({
101
+ createRoot,
102
+ defaultRootOptions,
103
+ ...bridgeInfo
104
+ }) {
105
+ return () => {
106
+ const rootMap = /* @__PURE__ */ new Map();
107
+ const instance = federationRuntime.instance;
108
+ LoggerInstance.debug(
109
+ `createBridgeComponent instance from props >>>`,
110
+ instance
111
+ );
112
+ const RawComponent = (info) => {
113
+ const { appInfo, propsInfo, ...restProps } = info;
114
+ const { moduleName, memoryRoute, basename = "/" } = appInfo;
115
+ return /* @__PURE__ */ React.createElement(RouterContext.Provider, { value: { moduleName, basename, memoryRoute } }, /* @__PURE__ */ React.createElement(
116
+ bridgeInfo.rootComponent,
117
+ {
118
+ ...propsInfo,
119
+ basename,
120
+ ...restProps
121
+ }
122
+ ));
123
+ };
124
+ return {
125
+ async render(info) {
126
+ var _a, _b, _c, _d, _e, _f;
127
+ LoggerInstance.debug(`createBridgeComponent render Info`, info);
128
+ const {
129
+ moduleName,
130
+ dom,
131
+ basename,
132
+ memoryRoute,
133
+ fallback,
134
+ rootOptions,
135
+ ...propsInfo
136
+ } = info;
137
+ const mergedRootOptions = {
138
+ ...defaultRootOptions,
139
+ ...rootOptions
140
+ };
141
+ const beforeBridgeRenderRes = ((_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.beforeBridgeRender) == null ? void 0 : _c.emit(info)) || {};
142
+ const rootComponentWithErrorBoundary = /* @__PURE__ */ React.createElement(
143
+ ErrorBoundary,
144
+ {
145
+ FallbackComponent: fallback
146
+ },
147
+ /* @__PURE__ */ React.createElement(
148
+ RawComponent,
149
+ {
150
+ appInfo: {
151
+ moduleName,
152
+ basename,
153
+ memoryRoute
154
+ },
155
+ propsInfo: {
156
+ ...propsInfo,
157
+ ...beforeBridgeRenderRes == null ? void 0 : beforeBridgeRenderRes.extraProps
158
+ }
159
+ }
160
+ )
161
+ );
162
+ if (bridgeInfo.render) {
163
+ await Promise.resolve(
164
+ bridgeInfo.render(rootComponentWithErrorBoundary, dom)
165
+ ).then((root) => rootMap.set(dom, root));
166
+ } else {
167
+ let root = rootMap.get(dom);
168
+ if (!root && createRoot) {
169
+ root = createRoot(dom, mergedRootOptions);
170
+ rootMap.set(dom, root);
171
+ }
172
+ if (root && "render" in root) {
173
+ root.render(rootComponentWithErrorBoundary);
174
+ }
175
+ }
176
+ ((_f = (_e = (_d = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeRender) == null ? void 0 : _f.emit(info)) || {};
177
+ },
178
+ destroy(info) {
179
+ var _a, _b, _c;
180
+ const { dom } = info;
181
+ LoggerInstance.debug(`createBridgeComponent destroy Info`, info);
182
+ const root = rootMap.get(dom);
183
+ if (root) {
184
+ if ("unmount" in root) {
185
+ root.unmount();
186
+ } else {
187
+ console.warn("Root does not have unmount method");
188
+ }
189
+ rootMap.delete(dom);
190
+ }
191
+ (_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.afterBridgeDestroy) == null ? void 0 : _c.emit(info);
192
+ }
193
+ };
194
+ };
195
+ }
196
+ export {
197
+ ErrorBoundary as E,
198
+ createBaseBridgeComponent as c
199
+ };
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ const React = require("react");
3
+ const index = require("./index-eN2xRRXs.js");
4
+ const plugin = require("./plugin.cjs.js");
5
+ function _interopNamespaceDefault(e) {
6
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
7
+ if (e) {
8
+ for (const k in e) {
9
+ if (k !== "default") {
10
+ const d = Object.getOwnPropertyDescriptor(e, k);
11
+ Object.defineProperty(n, k, d.get ? d : {
12
+ enumerable: true,
13
+ get: () => e[k]
14
+ });
15
+ }
16
+ }
17
+ }
18
+ n.default = e;
19
+ return Object.freeze(n);
20
+ }
21
+ const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
22
+ const ErrorBoundaryContext = React.createContext(null);
23
+ const initialState = {
24
+ didCatch: false,
25
+ error: null
26
+ };
27
+ class ErrorBoundary extends React.Component {
28
+ constructor(props) {
29
+ super(props);
30
+ this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
31
+ this.state = initialState;
32
+ }
33
+ static getDerivedStateFromError(error) {
34
+ return {
35
+ didCatch: true,
36
+ error
37
+ };
38
+ }
39
+ resetErrorBoundary() {
40
+ const {
41
+ error
42
+ } = this.state;
43
+ if (error !== null) {
44
+ var _this$props$onReset, _this$props;
45
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
46
+ args[_key] = arguments[_key];
47
+ }
48
+ (_this$props$onReset = (_this$props = this.props).onReset) === null || _this$props$onReset === void 0 ? void 0 : _this$props$onReset.call(_this$props, {
49
+ args,
50
+ reason: "imperative-api"
51
+ });
52
+ this.setState(initialState);
53
+ }
54
+ }
55
+ componentDidCatch(error, info) {
56
+ var _this$props$onError, _this$props2;
57
+ (_this$props$onError = (_this$props2 = this.props).onError) === null || _this$props$onError === void 0 ? void 0 : _this$props$onError.call(_this$props2, error, info);
58
+ }
59
+ componentDidUpdate(prevProps, prevState) {
60
+ const {
61
+ didCatch
62
+ } = this.state;
63
+ const {
64
+ resetKeys
65
+ } = this.props;
66
+ if (didCatch && prevState.error !== null && hasArrayChanged(prevProps.resetKeys, resetKeys)) {
67
+ var _this$props$onReset2, _this$props3;
68
+ (_this$props$onReset2 = (_this$props3 = this.props).onReset) === null || _this$props$onReset2 === void 0 ? void 0 : _this$props$onReset2.call(_this$props3, {
69
+ next: resetKeys,
70
+ prev: prevProps.resetKeys,
71
+ reason: "keys"
72
+ });
73
+ this.setState(initialState);
74
+ }
75
+ }
76
+ render() {
77
+ const {
78
+ children,
79
+ fallbackRender,
80
+ FallbackComponent,
81
+ fallback
82
+ } = this.props;
83
+ const {
84
+ didCatch,
85
+ error
86
+ } = this.state;
87
+ let childToRender = children;
88
+ if (didCatch) {
89
+ const props = {
90
+ error,
91
+ resetErrorBoundary: this.resetErrorBoundary
92
+ };
93
+ if (typeof fallbackRender === "function") {
94
+ childToRender = fallbackRender(props);
95
+ } else if (FallbackComponent) {
96
+ childToRender = React.createElement(FallbackComponent, props);
97
+ } else if (fallback !== void 0) {
98
+ childToRender = fallback;
99
+ } else {
100
+ throw error;
101
+ }
102
+ }
103
+ return React.createElement(ErrorBoundaryContext.Provider, {
104
+ value: {
105
+ didCatch,
106
+ error,
107
+ resetErrorBoundary: this.resetErrorBoundary
108
+ }
109
+ }, childToRender);
110
+ }
111
+ }
112
+ function hasArrayChanged() {
113
+ let a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
114
+ let b = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
115
+ return a.length !== b.length || a.some((item, index2) => !Object.is(item, b[index2]));
116
+ }
117
+ function createBaseBridgeComponent({
118
+ createRoot,
119
+ defaultRootOptions,
120
+ ...bridgeInfo
121
+ }) {
122
+ return () => {
123
+ const rootMap = /* @__PURE__ */ new Map();
124
+ const instance = plugin.federationRuntime.instance;
125
+ index.LoggerInstance.debug(
126
+ `createBridgeComponent instance from props >>>`,
127
+ instance
128
+ );
129
+ const RawComponent = (info) => {
130
+ const { appInfo, propsInfo, ...restProps } = info;
131
+ const { moduleName, memoryRoute, basename = "/" } = appInfo;
132
+ return /* @__PURE__ */ React__namespace.createElement(index.RouterContext.Provider, { value: { moduleName, basename, memoryRoute } }, /* @__PURE__ */ React__namespace.createElement(
133
+ bridgeInfo.rootComponent,
134
+ {
135
+ ...propsInfo,
136
+ basename,
137
+ ...restProps
138
+ }
139
+ ));
140
+ };
141
+ return {
142
+ async render(info) {
143
+ var _a, _b, _c, _d, _e, _f;
144
+ index.LoggerInstance.debug(`createBridgeComponent render Info`, info);
145
+ const {
146
+ moduleName,
147
+ dom,
148
+ basename,
149
+ memoryRoute,
150
+ fallback,
151
+ rootOptions,
152
+ ...propsInfo
153
+ } = info;
154
+ const mergedRootOptions = {
155
+ ...defaultRootOptions,
156
+ ...rootOptions
157
+ };
158
+ const beforeBridgeRenderRes = ((_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.beforeBridgeRender) == null ? void 0 : _c.emit(info)) || {};
159
+ const rootComponentWithErrorBoundary = /* @__PURE__ */ React__namespace.createElement(
160
+ ErrorBoundary,
161
+ {
162
+ FallbackComponent: fallback
163
+ },
164
+ /* @__PURE__ */ React__namespace.createElement(
165
+ RawComponent,
166
+ {
167
+ appInfo: {
168
+ moduleName,
169
+ basename,
170
+ memoryRoute
171
+ },
172
+ propsInfo: {
173
+ ...propsInfo,
174
+ ...beforeBridgeRenderRes == null ? void 0 : beforeBridgeRenderRes.extraProps
175
+ }
176
+ }
177
+ )
178
+ );
179
+ if (bridgeInfo.render) {
180
+ await Promise.resolve(
181
+ bridgeInfo.render(rootComponentWithErrorBoundary, dom)
182
+ ).then((root) => rootMap.set(dom, root));
183
+ } else {
184
+ let root = rootMap.get(dom);
185
+ if (!root && createRoot) {
186
+ root = createRoot(dom, mergedRootOptions);
187
+ rootMap.set(dom, root);
188
+ }
189
+ if (root && "render" in root) {
190
+ root.render(rootComponentWithErrorBoundary);
191
+ }
192
+ }
193
+ ((_f = (_e = (_d = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeRender) == null ? void 0 : _f.emit(info)) || {};
194
+ },
195
+ destroy(info) {
196
+ var _a, _b, _c;
197
+ const { dom } = info;
198
+ index.LoggerInstance.debug(`createBridgeComponent destroy Info`, info);
199
+ const root = rootMap.get(dom);
200
+ if (root) {
201
+ if ("unmount" in root) {
202
+ root.unmount();
203
+ } else {
204
+ console.warn("Root does not have unmount method");
205
+ }
206
+ rootMap.delete(dom);
207
+ }
208
+ (_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.afterBridgeDestroy) == null ? void 0 : _c.emit(info);
209
+ }
210
+ };
211
+ };
212
+ }
213
+ exports.ErrorBoundary = ErrorBoundary;
214
+ exports.createBaseBridgeComponent = createBaseBridgeComponent;
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ const lazyUtils = require("./utils-vIpCrZmn.js");
3
+ const index_esm = require("./index.esm-Ju4RY-yW.js");
4
+ function wrapSetTimeout(targetPromise, delay = 2e4, id) {
5
+ if (targetPromise && typeof targetPromise.then === "function") {
6
+ return new Promise((resolve, reject) => {
7
+ const timeoutId = setTimeout(() => {
8
+ lazyUtils.logger.warn(`Data fetch for ID ${id} timed out after 20 seconds.`);
9
+ reject(new Error(`Data fetch for ID ${id} timed out after 20 seconds`));
10
+ }, delay);
11
+ targetPromise.then((value) => {
12
+ clearTimeout(timeoutId);
13
+ resolve(value);
14
+ }).catch((err) => {
15
+ clearTimeout(timeoutId);
16
+ reject(err);
17
+ });
18
+ });
19
+ }
20
+ }
21
+ function addProtocol(url) {
22
+ if (url.startsWith("//")) {
23
+ return "https:" + url;
24
+ }
25
+ return url;
26
+ }
27
+ const getDecodeQuery = (url, name) => {
28
+ const res = url.searchParams.get(name);
29
+ if (!res) {
30
+ return null;
31
+ }
32
+ return decodeURIComponent(res);
33
+ };
34
+ const dataFetchServerMiddleware = async (ctx, next) => {
35
+ var _a, _b, _c;
36
+ let url;
37
+ let dataFetchKey;
38
+ let params;
39
+ let remoteInfo;
40
+ try {
41
+ url = new URL(ctx.req.url);
42
+ dataFetchKey = getDecodeQuery(url, lazyUtils.DATA_FETCH_QUERY);
43
+ params = JSON.parse(getDecodeQuery(url, "params") || "{}");
44
+ const remoteInfoQuery = getDecodeQuery(url, "remoteInfo");
45
+ remoteInfo = remoteInfoQuery ? JSON.parse(remoteInfoQuery) : null;
46
+ } catch (e) {
47
+ lazyUtils.logger.error("fetch data from server, error: ", e);
48
+ return next();
49
+ }
50
+ if (!dataFetchKey) {
51
+ return next();
52
+ }
53
+ lazyUtils.logger.log("fetch data from server, dataFetchKey: ", dataFetchKey);
54
+ lazyUtils.logger.debug(
55
+ "fetch data from server, moduleInfo: ",
56
+ (_a = globalThis.__FEDERATION__) == null ? void 0 : _a.moduleInfo
57
+ );
58
+ try {
59
+ const dataFetchMap = lazyUtils.getDataFetchMap();
60
+ if (!dataFetchMap) {
61
+ lazyUtils.initDataFetchMap();
62
+ }
63
+ const fetchDataPromise = (_b = dataFetchMap[dataFetchKey]) == null ? void 0 : _b[1];
64
+ lazyUtils.logger.debug(
65
+ "fetch data from server, fetchDataPromise: ",
66
+ fetchDataPromise
67
+ );
68
+ if (fetchDataPromise && ((_c = dataFetchMap[dataFetchKey]) == null ? void 0 : _c[2]) !== lazyUtils.MF_DATA_FETCH_STATUS.ERROR) {
69
+ const targetPromise = fetchDataPromise[0];
70
+ const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchKey);
71
+ if (wrappedPromise) {
72
+ const res = await wrappedPromise;
73
+ lazyUtils.logger.log("fetch data from server, fetchDataPromise res: ", res);
74
+ return ctx.json(res);
75
+ }
76
+ lazyUtils.logger.error(
77
+ `Expected a Promise from fetchDataPromise[0] for dataFetchKey ${dataFetchKey}, but received:`,
78
+ targetPromise,
79
+ "Will try call new dataFetch again..."
80
+ );
81
+ }
82
+ if (remoteInfo) {
83
+ try {
84
+ const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
85
+ const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
86
+ if (!hostInstance2) {
87
+ throw new Error("host instance not found!");
88
+ }
89
+ const remote = hostInstance2.options.remotes.find(
90
+ (remote2) => remote2.name === remoteInfo.name
91
+ );
92
+ lazyUtils.logger.debug("find remote: ", JSON.stringify(remote));
93
+ if (!remote) {
94
+ hostInstance2.registerRemotes([
95
+ {
96
+ name: remoteInfo.name,
97
+ entry: remoteEntry,
98
+ entryGlobalName: remoteInfo.globalName
99
+ }
100
+ ]);
101
+ } else if (!("entry" in remote) || !remote.entry.includes(index_esm.MANIFEST_EXT)) {
102
+ const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
103
+ lazyUtils.logger.debug(
104
+ "find hostGlobalSnapshot: ",
105
+ JSON.stringify(hostGlobalSnapshot)
106
+ );
107
+ lazyUtils.logger.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
108
+ if (!hostGlobalSnapshot || !remoteSnapshot) {
109
+ if ("version" in remote) {
110
+ delete remote.version;
111
+ }
112
+ remote.entry = remoteEntry;
113
+ remote.entryGlobalName = remoteInfo.globalName;
114
+ }
115
+ }
116
+ } catch (e) {
117
+ ctx.status(500);
118
+ return ctx.text(
119
+ `failed to fetch ${remoteInfo.name} data, error:
120
+ ${e}`
121
+ );
122
+ }
123
+ }
124
+ const dataFetchItem = dataFetchMap[dataFetchKey];
125
+ lazyUtils.logger.debug("fetch data from server, dataFetchItem: ", dataFetchItem);
126
+ if (dataFetchItem) {
127
+ const callFetchDataPromise = lazyUtils.fetchData(dataFetchKey, {
128
+ ...params,
129
+ isDowngrade: !remoteInfo,
130
+ _id: dataFetchKey
131
+ });
132
+ const wrappedPromise = wrapSetTimeout(
133
+ callFetchDataPromise,
134
+ 2e4,
135
+ dataFetchKey
136
+ );
137
+ if (wrappedPromise) {
138
+ const res = await wrappedPromise;
139
+ lazyUtils.logger.log("fetch data from server, dataFetchItem res: ", res);
140
+ return ctx.json(res);
141
+ }
142
+ }
143
+ const remoteId = dataFetchKey.split(index_esm.SEPARATOR)[0];
144
+ const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
145
+ if (!hostInstance) {
146
+ throw new Error("host instance not found!");
147
+ }
148
+ const dataFetchFn = await lazyUtils.loadDataFetchModule(hostInstance, remoteId);
149
+ const data = await dataFetchFn({
150
+ ...params,
151
+ isDowngrade: !remoteInfo,
152
+ _id: dataFetchKey
153
+ });
154
+ lazyUtils.logger.log("fetch data from server, loadDataFetchModule res: ", data);
155
+ return ctx.json(data);
156
+ } catch (e) {
157
+ lazyUtils.logger.error("server plugin data fetch error: ", e);
158
+ ctx.status(500);
159
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
160
+ ${e}`);
161
+ }
162
+ };
163
+ module.exports = dataFetchServerMiddleware;
@@ -0,0 +1,15 @@
1
+ import { MiddlewareHandler } from 'hono';
2
+
3
+ declare const dataFetchServerMiddleware: MiddlewareHandler;
4
+ export default dataFetchServerMiddleware;
5
+
6
+ export { }
7
+
8
+
9
+ declare module '@module-federation/runtime-core' {
10
+ interface ModuleFederation {
11
+ createLazyComponent<T, E extends keyof T>(options: Omit<CreateLazyComponentOptions<T, E>, 'instance'>): ReturnType<typeof createLazyComponent<T, E>>;
12
+ prefetch(options: Omit<PrefetchOptions, 'instance'>): ReturnType<typeof prefetch>;
13
+ collectSSRAssets(options: Omit<Parameters<typeof collectSSRAssets>[0], 'instance'>): ReturnType<typeof collectSSRAssets>;
14
+ }
15
+ }