@module-federation/playground 0.0.0-main-20260720131707 → 0.0.0-perf-website-code-usage-20260914033703
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.
- package/dist/cjs/index.js +1520 -1502
- package/dist/esm/index.mjs +18 -18
- package/dist/mf/130.js +1 -0
- package/dist/mf/{560.js → 215.js} +2 -2
- package/dist/mf/{952.js → 29.js} +2 -2
- package/dist/mf/{776.js → 47.js} +3 -3
- package/dist/mf/{453.js → 568.js} +2 -2
- package/dist/mf/749.js +1 -0
- package/dist/mf/806.js +1 -0
- package/dist/mf/{24.js → 897.js} +2 -2
- package/dist/mf/__federation_expose_default_export.js +5 -5
- package/dist/mf/__federation_expose_demo.js +1 -1
- package/dist/mf/index.js +8 -8
- package/dist/mf/mf-manifest.json +11 -8
- package/dist/mf/mf-stats.json +15 -12
- package/dist/mf/remoteEntry.js +6 -6
- package/dist/mf/{395.js → ssr/47mf_playground.js} +5 -5
- package/dist/mf/ssr/__federation_expose_default_exportmf_playground.js +8 -388
- package/dist/mf/ssr/index.js +13 -393
- package/dist/mf/ssr/mf-manifest.json +5 -3
- package/dist/mf/ssr/mf-stats.json +5 -3
- package/dist/mf/ssr/remoteEntry.js +5 -5
- package/dist/types/generated/bridgeRuntimeFiles.d.ts +6 -6
- package/package.json +4 -4
- package/dist/mf/ssr/__federation_expose_default_exportmf_playground.js.LICENSE.txt +0 -14
- package/dist/mf/ssr/index.js.LICENSE.txt +0 -14
- /package/dist/mf/{560.js.LICENSE.txt → 215.js.LICENSE.txt} +0 -0
- /package/dist/mf/{952.js.LICENSE.txt → 29.js.LICENSE.txt} +0 -0
- /package/dist/mf/{395.js.LICENSE.txt → 47.js.LICENSE.txt} +0 -0
- /package/dist/mf/{453.js.LICENSE.txt → 568.js.LICENSE.txt} +0 -0
- /package/dist/mf/{24.js.LICENSE.txt → 897.js.LICENSE.txt} +0 -0
- /package/dist/mf/{776.js.LICENSE.txt → ssr/47mf_playground.js.LICENSE.txt} +0 -0
package/dist/cjs/index.js
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var
|
|
2
|
+
var __webpack_modules__ = {
|
|
3
|
+
"typescript-compiler": function(module) {
|
|
4
|
+
module.exports = import("typescript-compiler").then(function(module) {
|
|
5
|
+
return module;
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
var __webpack_module_cache__ = {};
|
|
10
|
+
function __webpack_require__(moduleId) {
|
|
11
|
+
var cachedModule = __webpack_module_cache__[moduleId];
|
|
12
|
+
if (void 0 !== cachedModule) return cachedModule.exports;
|
|
13
|
+
var module = __webpack_module_cache__[moduleId] = {
|
|
14
|
+
exports: {}
|
|
15
|
+
};
|
|
16
|
+
__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
|
|
17
|
+
return module.exports;
|
|
18
|
+
}
|
|
3
19
|
(()=>{
|
|
4
20
|
__webpack_require__.n = (module)=>{
|
|
5
21
|
var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
|
|
@@ -31,178 +47,178 @@ var __webpack_require__ = {};
|
|
|
31
47
|
};
|
|
32
48
|
})();
|
|
33
49
|
var __webpack_exports__ = {};
|
|
34
|
-
|
|
35
|
-
__webpack_require__.
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
const
|
|
186
|
-
const
|
|
187
|
-
const BRIDGE_RUNTIME_FILES = {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
"lazy-load-component-plugin-DlagtX0O.mjs": 'import { i as injectDataFetch, p as prefetch } from "./prefetch-BzCq3MT3.mjs";\nimport { i as initDataFetchMap, k as isDataLoaderExpose, m as getDataFetchInfo, n as getDataFetchMapKey, l as logger, o as getDataFetchItem, p as DATA_FETCH_CLIENT_SUFFIX, q as MF_DATA_FETCH_TYPE, t as isCSROnly, M as MF_DATA_FETCH_STATUS, j as loadDataFetchModule, e as getDataFetchMap, u as isServerEnv, v as getDataFetchIdWithErrorMsgs, w as DATA_FETCH_ERROR_PREFIX, E as ERROR_TYPE, x as wrapDataFetchId, L as LOAD_REMOTE_ERROR_PREFIX, y as DATA_FETCH_FUNCTION, z as getLoadedRemoteInfos, h as fetchData$1, A as setDataFetchItemLoadedStatus, F as FS_HREF } from "./utils-BBP3hEeV.mjs";\nimport React__default, { useRef, useState, Suspense, useEffect } from "react";\nconst autoFetchData = () => {\n initDataFetchMap();\n injectDataFetch();\n return {\n name: "auto-fetch-data-plugin",\n afterLoadSnapshot(args) {\n const { id, moduleInfo, remoteSnapshot, host } = args;\n if (typeof id === "string" && isDataLoaderExpose(id)) {\n return args;\n }\n if (!remoteSnapshot || !id || !("modules" in remoteSnapshot)) {\n return args;\n }\n const { name, alias } = moduleInfo;\n const dataFetchInfo = getDataFetchInfo({\n name,\n alias,\n id,\n remoteSnapshot\n });\n if (!dataFetchInfo) {\n return args;\n }\n const { dataFetchId, dataFetchName } = dataFetchInfo;\n const dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {\n name: host.name,\n version: host.options.version\n });\n logger.debug(\n "======= auto fetch plugin dataFetchMapKey: ",\n dataFetchMapKey\n );\n if (!dataFetchMapKey) {\n return args;\n }\n const dataFetchItem = getDataFetchItem(dataFetchMapKey);\n if (dataFetchItem) {\n return args;\n }\n const dataFetchMap = getDataFetchMap();\n const hasSSRAsset = Boolean(remoteSnapshot.ssrRemoteEntry);\n const hasDataFetchClient = Boolean(\n remoteSnapshot.modules.find(\n (module) => module.moduleName === `${dataFetchName}${DATA_FETCH_CLIENT_SUFFIX}`\n )\n );\n const downgradeType = hasDataFetchClient ? MF_DATA_FETCH_TYPE.FETCH_CLIENT : hasSSRAsset ? MF_DATA_FETCH_TYPE.FETCH_SERVER : MF_DATA_FETCH_TYPE.FETCH_CLIENT;\n let finalDataFetchId = dataFetchId;\n if (!isServerEnv()) {\n finalDataFetchId = downgradeType === MF_DATA_FETCH_TYPE.FETCH_CLIENT ? hasDataFetchClient ? `${dataFetchId}${DATA_FETCH_CLIENT_SUFFIX}` : dataFetchId : dataFetchId;\n }\n const getDataFetchGetter = () => loadDataFetchModule(host, finalDataFetchId);\n const dataFetchFnItem = [\n getDataFetchGetter,\n downgradeType\n ];\n if (typeof window === "undefined" || isCSROnly()) {\n dataFetchFnItem.push(getDataFetchGetter());\n }\n dataFetchMap[dataFetchMapKey] = [\n dataFetchFnItem,\n void 0,\n MF_DATA_FETCH_STATUS.AWAIT\n ];\n return args;\n }\n };\n};\nfunction isPromise(obj) {\n return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";\n}\nconst AWAIT_ERROR_PREFIX = "<Await /> caught the following error during render: ";\nconst transformError = (err) => {\n const errMsg = err instanceof Error ? err.message : err;\n const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, "");\n const dataFetchMapKey = getDataFetchIdWithErrorMsgs(originalMsg);\n if (originalMsg.indexOf(DATA_FETCH_ERROR_PREFIX) === 0) {\n return {\n error: new Error(\n originalMsg.replace(DATA_FETCH_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")\n ),\n errorType: ERROR_TYPE.DATA_FETCH,\n dataFetchMapKey\n };\n }\n if (originalMsg.indexOf(LOAD_REMOTE_ERROR_PREFIX) === 0) {\n return {\n error: new Error(\n originalMsg.replace(LOAD_REMOTE_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")\n ),\n errorType: ERROR_TYPE.LOAD_REMOTE,\n dataFetchMapKey\n };\n }\n return {\n error: new Error(originalMsg.replace(wrapDataFetchId(dataFetchMapKey), "")),\n errorType: ERROR_TYPE.UNKNOWN,\n dataFetchMapKey\n };\n};\nconst DefaultLoading = /* @__PURE__ */ React__default.createElement(React__default.Fragment, null);\nconst DefaultErrorElement = (_data) => /* @__PURE__ */ React__default.createElement("div", null, "Error");\nfunction AwaitDataFetch({\n resolve,\n loading = DefaultLoading,\n errorElement = DefaultErrorElement,\n children,\n params,\n delayLoading\n}) {\n const dataRef = useRef();\n const data = dataRef.current || resolve;\n const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;\n return /* @__PURE__ */ React__default.createElement(\n AwaitSuspense,\n {\n params,\n loading,\n errorElement,\n delayLoading,\n resolve: getData\n },\n children\n );\n}\nconst DelayedLoading = ({\n delayLoading,\n children\n}) => {\n const [show, setShow] = useState(false);\n const timerSet = useRef(false);\n if (!delayLoading) {\n return children;\n }\n if (typeof window !== "undefined" && !show && !timerSet.current) {\n timerSet.current = true;\n setTimeout(() => {\n setShow(true);\n }, delayLoading);\n }\n return show ? children : null;\n};\nfunction AwaitSuspense({\n resolve,\n children,\n loading = DefaultLoading,\n errorElement = DefaultErrorElement,\n delayLoading\n}) {\n return /* @__PURE__ */ React__default.createElement(\n Suspense,\n {\n fallback: /* @__PURE__ */ React__default.createElement(DelayedLoading, { delayLoading }, loading)\n },\n /* @__PURE__ */ React__default.createElement(ResolveAwait, { resolve, errorElement }, children)\n );\n}\nfunction ResolveAwait({\n children,\n resolve,\n errorElement,\n params\n}) {\n const data = resolve();\n logger.debug("resolve data: ", data);\n if (typeof data === "string" && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {\n const transformedError = transformError(data);\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, typeof errorElement === "function" ? /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, globalThis.FEDERATION_SSR && /* @__PURE__ */ React__default.createElement(\n "script",\n {\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: {\n __html: String.raw`\n globalThis[\'${DATA_FETCH_FUNCTION}\'] = globalThis[\'${DATA_FETCH_FUNCTION}\'] || []\n globalThis[\'${DATA_FETCH_FUNCTION}\'].push([${transformedError.dataFetchMapKey ? `\'${transformedError.dataFetchMapKey}\'` : ""},${params ? JSON.stringify(params) : null},true]);`\n }\n }\n ), errorElement(transformedError)) : errorElement);\n }\n const toRender = typeof children === "function" ? children(data) : children;\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, toRender);\n}\nconst fetchData = (promise, ref) => {\n let data;\n let status = "pending";\n const suspender = promise.then((res) => {\n status = "success";\n data = res;\n ref.current = res;\n }).catch((e) => {\n status = "success";\n console.warn(e);\n data = AWAIT_ERROR_PREFIX + e;\n });\n return () => {\n if (status === "pending") {\n throw suspender;\n }\n return data;\n };\n};\nfunction getTargetModuleInfo(id, instance) {\n if (!instance) {\n return;\n }\n const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);\n if (!loadedRemoteInfo) {\n return;\n }\n const { snapshot } = loadedRemoteInfo;\n if (!snapshot) {\n return;\n }\n const publicPath = "publicPath" in snapshot ? snapshot.publicPath : "getPublicPath" in snapshot ? new Function(snapshot.getPublicPath)() : "";\n if (!publicPath) {\n return;\n }\n const modules = "modules" in snapshot ? snapshot.modules : [];\n const targetModule = modules.find(\n (m) => m.modulePath === loadedRemoteInfo.expose\n );\n if (!targetModule) {\n return;\n }\n const remoteEntry = "remoteEntry" in snapshot ? snapshot.remoteEntry : "";\n if (!remoteEntry) {\n return;\n }\n return {\n module: targetModule,\n publicPath,\n remoteEntry\n };\n}\nfunction collectSSRAssets(options) {\n const {\n id,\n injectLink = true,\n injectScript = false\n } = typeof options === "string" ? { id: options } : options;\n const links = [];\n const scripts = [];\n const instance = options.instance;\n if (!instance || !injectLink && !injectScript) {\n return [...scripts, ...links];\n }\n const moduleAndPublicPath = getTargetModuleInfo(id, instance);\n if (!moduleAndPublicPath) {\n return [...scripts, ...links];\n }\n const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;\n if (injectLink) {\n [...targetModule.assets.css.sync, ...targetModule.assets.css.async].sort().forEach((file, index) => {\n links.push(\n /* @__PURE__ */ React__default.createElement(\n "link",\n {\n key: `${file.split(".")[0]}_${index}`,\n href: `${publicPath}${file}`,\n rel: "stylesheet",\n type: "text/css"\n }\n )\n );\n });\n }\n if (injectScript) {\n scripts.push(\n /* @__PURE__ */ React__default.createElement(\n "script",\n {\n async: true,\n key: remoteEntry.split(".")[0],\n src: `${publicPath}${remoteEntry}`,\n crossOrigin: "anonymous"\n }\n )\n );\n [...targetModule.assets.js.sync].sort().forEach((file, index) => {\n scripts.push(\n /* @__PURE__ */ React__default.createElement(\n "script",\n {\n key: `${file.split(".")[0]}_${index}`,\n async: true,\n src: `${publicPath}${file}`,\n crossOrigin: "anonymous"\n }\n )\n );\n });\n }\n return [...scripts, ...links];\n}\nfunction getServerNeedRemoteInfo(loadedRemoteInfo, id, noSSR) {\n var _a;\n if (noSSR || typeof window !== "undefined" && window.location.href !== window[FS_HREF]) {\n if (!(loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.version)) {\n throw new Error(`${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} version is empty`);\n }\n const { snapshot } = loadedRemoteInfo;\n if (!snapshot) {\n throw new Error(`${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} snapshot is empty`);\n }\n const dataFetchItem = getDataFetchItem(id);\n const isFetchServer = ((_a = dataFetchItem == null ? void 0 : dataFetchItem[0]) == null ? void 0 : _a[1]) === MF_DATA_FETCH_TYPE.FETCH_SERVER;\n if (isFetchServer && (!("ssrPublicPath" in snapshot) || !snapshot.ssrPublicPath)) {\n throw new Error(\n `ssrPublicPath is required while fetching ${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} data in SSR project!`\n );\n }\n if (isFetchServer && (!("ssrRemoteEntry" in snapshot) || !snapshot.ssrRemoteEntry)) {\n throw new Error(\n `ssrRemoteEntry is required while loading ${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} data loader in SSR project!`\n );\n }\n return {\n name: loadedRemoteInfo.name,\n version: loadedRemoteInfo.version,\n ssrPublicPath: "ssrPublicPath" in snapshot ? snapshot.ssrPublicPath || "" : "",\n ssrRemoteEntry: "ssrRemoteEntry" in snapshot ? snapshot.ssrRemoteEntry || "" : "",\n globalName: loadedRemoteInfo.entryGlobalName\n };\n }\n return void 0;\n}\nfunction createLazyComponent(options) {\n const { instance, injectScript, injectLink } = options;\n if (!instance) {\n throw new Error("instance is required for createLazyComponent!");\n }\n const exportName = (options == null ? void 0 : options.export) || "default";\n const callLoader = async () => {\n logger.debug("callLoader start", Date.now());\n const m = await options.loader();\n logger.debug("callLoader end", Date.now());\n if (!m) {\n throw new Error("load remote failed");\n }\n return m;\n };\n const getData = async (noSSR) => {\n let loadedRemoteInfo;\n let moduleId;\n try {\n const m = await callLoader();\n moduleId = m && m[Symbol.for("mf_module_id")];\n if (!moduleId) {\n throw new Error("moduleId is empty");\n }\n loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);\n if (!loadedRemoteInfo) {\n throw new Error(`can not find loaded remote(\'${moduleId}\') info!`);\n }\n } catch (e) {\n const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;\n logger.debug(e);\n throw new Error(errMsg);\n }\n let dataFetchMapKey;\n try {\n dataFetchMapKey = getDataFetchMapKey(\n getDataFetchInfo({\n name: loadedRemoteInfo.name,\n alias: loadedRemoteInfo.alias,\n id: moduleId,\n remoteSnapshot: loadedRemoteInfo.snapshot\n }),\n { name: instance.name, version: instance.options.version }\n );\n logger.debug("getData dataFetchMapKey: ", dataFetchMapKey);\n if (!dataFetchMapKey) {\n return;\n }\n const data = await fetchData$1(\n dataFetchMapKey,\n {\n ...options.dataFetchParams,\n isDowngrade: false\n },\n getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR)\n );\n setDataFetchItemLoadedStatus(dataFetchMapKey);\n logger.debug("get data res: \\n", data);\n return data;\n } catch (err) {\n const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;\n logger.debug(errMsg);\n throw new Error(errMsg);\n }\n };\n const LazyComponent = React__default.lazy(async () => {\n const m = await callLoader();\n const moduleId = m && m[Symbol.for("mf_module_id")];\n const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);\n loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.snapshot;\n const dataFetchMapKey = loadedRemoteInfo ? getDataFetchMapKey(\n getDataFetchInfo({\n name: loadedRemoteInfo.name,\n alias: loadedRemoteInfo.alias,\n id: moduleId,\n remoteSnapshot: loadedRemoteInfo.snapshot\n }),\n { name: instance.name, version: instance == null ? void 0 : instance.options.version }\n ) : void 0;\n logger.debug("LazyComponent dataFetchMapKey: ", dataFetchMapKey);\n const assets = collectSSRAssets({\n id: moduleId,\n instance,\n injectLink,\n injectScript\n });\n const Com = m[exportName];\n if (exportName in m && typeof Com === "function") {\n return {\n default: (props) => /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, globalThis.FEDERATION_SSR && dataFetchMapKey && /* @__PURE__ */ React__default.createElement(\n "script",\n {\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: {\n __html: String.raw`\n globalThis[\'${DATA_FETCH_FUNCTION}\'] = globalThis[\'${DATA_FETCH_FUNCTION}\'] || [];\n globalThis[\'${DATA_FETCH_FUNCTION}\'].push([\'${dataFetchMapKey}\',${JSON.stringify(props.mfData)}]);\n `\n }\n }\n ), globalThis.FEDERATION_SSR && assets, /* @__PURE__ */ React__default.createElement(Com, { ...props }))\n };\n } else {\n throw Error(\n `Make sure that ${moduleId} has the correct export when export is ${String(\n exportName\n )}`\n );\n }\n });\n return (props) => {\n const { key, ...args } = props;\n if (!options.noSSR) {\n return /* @__PURE__ */ React__default.createElement(\n AwaitDataFetch,\n {\n resolve: getData(options.noSSR),\n loading: options.loading,\n delayLoading: options.delayLoading,\n errorElement: options.fallback\n },\n (data) => /* @__PURE__ */ React__default.createElement(LazyComponent, { ...args, mfData: data })\n );\n } else {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n let isMounted = true;\n const fetchDataAsync = async () => {\n try {\n setLoading(true);\n const result = await getData(options.noSSR);\n if (isMounted) {\n setData(result);\n }\n } catch (e) {\n if (isMounted) {\n setError(transformError(e));\n }\n } finally {\n if (isMounted) {\n setLoading(false);\n }\n }\n };\n fetchDataAsync();\n return () => {\n isMounted = false;\n };\n }, []);\n if (loading) {\n return /* @__PURE__ */ React__default.createElement(DelayedLoading, { delayLoading: options.delayLoading }, options.loading);\n }\n if (error) {\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, typeof options.fallback === "function" ? options.fallback(error) : options.fallback);\n }\n return /* @__PURE__ */ React__default.createElement(LazyComponent, { ...args, mfData: data });\n }\n };\n}\nfunction lazyLoadComponentPlugin() {\n return {\n name: "lazy-load-component-plugin",\n apply(instance) {\n instance.registerPlugins([autoFetchData()]);\n instance.createLazyComponent = (options) => {\n return createLazyComponent({\n instance,\n ...options\n });\n };\n instance.prefetch = (options) => {\n return prefetch({\n instance,\n ...options\n });\n };\n instance.collectSSRAssets = (options) => {\n return collectSSRAssets({\n instance,\n ...options\n });\n };\n }\n };\n}\nexport {\n autoFetchData as a,\n createLazyComponent as b,\n collectSSRAssets as c,\n lazyLoadComponentPlugin as l\n};\n',
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
"prefetch-BzCq3MT3.mjs": 'import { B as warn, y as DATA_FETCH_FUNCTION, F as FS_HREF, l as logger, e as getDataFetchMap, i as initDataFetchMap, o as getDataFetchItem, M as MF_DATA_FETCH_STATUS, q as MF_DATA_FETCH_TYPE, G as DOWNGRADE_KEY, H as callAllDowngrade, I as callDowngrade, J as getDowngradeTag, K as composeKeyWithSeparator, N as safeToString, m as getDataFetchInfo, n as getDataFetchMapKey } from "./utils-BBP3hEeV.mjs";\nimport { i as isBrowserEnvValue } from "./logger-DwWkXsWl.mjs";\nasync function safeWrapper(callback, disableWarn) {\n try {\n return await callback();\n } catch (e) {\n warn(e);\n return;\n }\n}\nfunction isStaticResourcesEqual(url1, url2) {\n const REG_EXP = /^(https?:)?\\/\\//i;\n return url1.replace(REG_EXP, "").replace(/\\/$/, "") === url2.replace(REG_EXP, "").replace(/\\/$/, "");\n}\nfunction createScript(info) {\n let script = null;\n let needAttach = true;\n let timeout = 2e4;\n let timeoutId;\n const scripts = document.getElementsByTagName("script");\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute("src");\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement("script");\n script.type = (attrs == null ? void 0 : attrs["type"]) === "module" ? "module" : "text/javascript";\n let createScriptRes = void 0;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n if (createScriptRes instanceof HTMLScriptElement) script = createScriptRes;\n else if (typeof createScriptRes === "object") {\n if ("script" in createScriptRes && createScriptRes.script) script = createScriptRes.script;\n if ("timeout" in createScriptRes && createScriptRes.timeout) timeout = createScriptRes.timeout;\n }\n }\n if (!script.src) script.src = info.url;\n if (attrs && !createScriptRes) Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === "async" || name === "defer") script[name] = attrs[name];\n else if (!script.getAttribute(name)) script.setAttribute(name, attrs[name]);\n }\n });\n }\n let executionError = null;\n const executionErrorHandler = typeof window !== "undefined" ? (evt) => {\n if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {\n const err = /* @__PURE__ */ new Error(`ScriptExecutionError: Script "${info.url}" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`);\n err.name = "ScriptExecutionError";\n executionError = err;\n }\n } : null;\n if (executionErrorHandler) window.addEventListener("error", executionErrorHandler);\n const onScriptComplete = async (prev, event) => {\n clearTimeout(timeoutId);\n if (executionErrorHandler) window.removeEventListener("error", executionErrorHandler);\n const onScriptCompleteCallback = () => {\n if ((event == null ? void 0 : event.type) === "error") {\n const networkError = /* @__PURE__ */ new Error((event == null ? void 0 : event.isTimeout) ? `ScriptNetworkError: Script "${info.url}" timed out.` : `ScriptNetworkError: Failed to load script "${info.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);\n networkError.name = "ScriptNetworkError";\n (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(networkError));\n } else if (executionError) (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(executionError));\n else (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());\n };\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);\n });\n if (prev && typeof prev === "function") {\n const result = prev(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n timeoutId = setTimeout(() => {\n onScriptComplete(null, {\n type: "error",\n isTimeout: true\n });\n }, timeout);\n return {\n script,\n needAttach\n };\n}\nfunction createLink(info) {\n let link = null;\n let needAttach = true;\n let timeout = 2e4;\n let timeoutId;\n const links = document.getElementsByTagName("link");\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute("href");\n const linkRel = l.getAttribute("rel");\n if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs["rel"]) {\n link = l;\n needAttach = false;\n break;\n }\n }\n if (!link) {\n link = document.createElement("link");\n link.setAttribute("href", info.url);\n let createLinkRes = void 0;\n let shouldApplyAttrs = true;\n const attrs = info.attrs;\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n shouldApplyAttrs = false;\n } else if (typeof createLinkRes === "object") {\n if ("link" in createLinkRes && createLinkRes.link) {\n link = createLinkRes.link;\n shouldApplyAttrs = false;\n }\n if ("timeout" in createLinkRes && createLinkRes.timeout) timeout = createLinkRes.timeout;\n }\n }\n if (attrs && shouldApplyAttrs) Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) link.setAttribute(name, attrs[name]);\n });\n }\n if (!needAttach) {\n Promise.resolve().then(() => {\n (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());\n });\n return {\n link,\n needAttach\n };\n }\n const onLinkComplete = (prev, event) => {\n if (timeoutId) clearTimeout(timeoutId);\n const onLinkCompleteCallback = () => {\n if ((event == null ? void 0 : event.type) === "error") {\n const linkError = /* @__PURE__ */ new Error((event == null ? void 0 : event.isTimeout) ? `LinkNetworkError: Link "${info.url}" timed out.` : `LinkNetworkError: Failed to load link "${info.url}" - the URL is unreachable or the server returned an error.`);\n linkError.name = "LinkNetworkError";\n (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(linkError));\n } else (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());\n };\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);\n });\n if (prev) {\n const res = prev(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n timeoutId = setTimeout(() => {\n onLinkComplete(null, {\n type: "error",\n isTimeout: true\n });\n }, timeout);\n return {\n link,\n needAttach\n };\n}\nfunction loadScript(url, info) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: "high",\n ...attrs\n },\n createScriptHook,\n needDeleteScript: true\n });\n needAttach && document.head.appendChild(script);\n });\n}\nconst sdkImportCache = /* @__PURE__ */ new Map();\nfunction importNodeModule(name) {\n if (!name) throw new Error("import specifier is required");\n if (sdkImportCache.has(name)) return sdkImportCache.get(name);\n const promise = new Function("name", `return import(name)`)(name).then((res) => res).catch((error2) => {\n console.error(`Error importing module ${name}:`, error2);\n sdkImportCache.delete(name);\n throw error2;\n });\n sdkImportCache.set(name, promise);\n return promise;\n}\nconst lazyLoaderHookFetch = async (input, init, loaderHook) => {\n const hook = (url, init2) => {\n return loaderHook.lifecycle.fetch.emit(url, init2);\n };\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) return fetch(input, init || {});\n return res;\n};\nconst createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {\n if (loaderHook == null ? void 0 : loaderHook.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (hookResult && typeof hookResult === "object" && "url" in hookResult) url = hookResult.url;\n }\n let urlObj;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error("Error constructing URL:", e);\n cb(/* @__PURE__ */ new Error(`Invalid URL: ${e}`));\n return;\n }\n const getFetch = async () => {\n if (loaderHook == null ? void 0 : loaderHook.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);\n return fetch;\n };\n const handleScriptFetch = async (f, urlObj2) => {\n var _a;\n try {\n const res = await f(urlObj2.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([importNodeModule("path"), importNodeModule("vm")]);\n const scriptContext = {\n exports: {},\n module: { exports: {} }\n };\n const urlDirname = urlObj2.pathname.split("/").slice(0, -1).join("/");\n const filename = path.basename(urlObj2.pathname);\n const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {\n filename,\n importModuleDynamically: ((_a = vm.constants) == null ? void 0 : _a.USE_MAIN_CONTEXT_DEFAULT_LOADER) ?? importNodeModule\n });\n let requireFn;\n requireFn = (await importNodeModule("node:module")).createRequire(urlObj2.protocol === "file:" || urlObj2.protocol === "node:" ? urlObj2.href : path.join(process.cwd(), "__mf_require_base__.js"));\n script.runInThisContext()(scriptContext.exports, scriptContext.module, requireFn, urlDirname, filename);\n const exportedInterface = scriptContext.module.exports || scriptContext.exports;\n if (attrs && exportedInterface && attrs["globalName"]) {\n cb(void 0, exportedInterface[attrs["globalName"]] || exportedInterface);\n return;\n }\n cb(void 0, exportedInterface);\n } catch (e) {\n cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));\n }\n };\n getFetch().then(async (f) => {\n if ((attrs == null ? void 0 : attrs["type"]) === "esm" || (attrs == null ? void 0 : attrs["type"]) === "module") return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule("vm")\n }).then(async (module) => {\n await module.evaluate();\n cb(void 0, module.namespace);\n }).catch((e) => {\n cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));\n });\n handleScriptFetch(f, urlObj);\n }).catch((err) => {\n cb(err);\n });\n} : (url, cb, attrs, loaderHook) => {\n cb(/* @__PURE__ */ new Error("createScriptNode is disabled in non-Node.js environment"));\n};\nconst loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, info) => {\n return new Promise((resolve, reject) => {\n createScriptNode(url, (error2, scriptContext) => {\n var _a, _b;\n if (error2) reject(error2);\n else {\n const remoteEntryKey = ((_a = info == null ? void 0 : info.attrs) == null ? void 0 : _a["globalName"]) || `__FEDERATION_${(_b = info == null ? void 0 : info.attrs) == null ? void 0 : _b["name"]}:custom__`;\n resolve(globalThis[remoteEntryKey] = scriptContext);\n }\n }, info.attrs, info.loaderHook);\n });\n} : (url, info) => {\n throw new Error("loadScriptNode is disabled in non-Node.js environment");\n};\nconst esmModuleCache = /* @__PURE__ */ new Map();\nconst isFetchableRemoteModuleUrl = (url) => url.startsWith("http:") || url.startsWith("https:");\nconst isBareModuleSpecifier = (specifier) => !specifier.startsWith("./") && !specifier.startsWith("../") && !specifier.startsWith("/") && !specifier.includes(":");\nfunction encodeRemoteModulePath(url) {\n const remoteUrl = new URL(url);\n const encodedProtocol = encodeURIComponent(remoteUrl.protocol.slice(0, -1));\n const encodedHost = encodeURIComponent(remoteUrl.host);\n const encodedPathname = remoteUrl.pathname.split("/").map((segment) => encodeURIComponent(segment)).join("/");\n const encodedSearchHash = encodeURIComponent(`${remoteUrl.search}${remoteUrl.hash}`);\n return `/${encodedProtocol}/${encodedHost}${encodedPathname}${encodedSearchHash ? `/${encodedSearchHash}` : ""}`;\n}\nfunction createImportMetaUrl(url, baseFileUrl) {\n const baseUrl = baseFileUrl.endsWith("/") ? baseFileUrl : `${baseFileUrl}/`;\n return new URL(`__module_federation_remote__${encodeRemoteModulePath(url)}`, baseUrl).href;\n}\nasync function isNodeBuiltinSpecifier(specifier) {\n if (specifier.startsWith("node:")) return true;\n if (!isBareModuleSpecifier(specifier)) return false;\n return (await importNodeModule("node:module")).builtinModules.includes(specifier);\n}\nfunction getSyntheticModuleExports(moduleExports) {\n const namespaceObject = moduleExports && (typeof moduleExports === "object" || typeof moduleExports === "function") ? moduleExports : { default: moduleExports };\n const effectiveExports = { ...namespaceObject };\n if (!Object.prototype.hasOwnProperty.call(effectiveExports, "default")) effectiveExports.default = namespaceObject;\n return effectiveExports;\n}\nasync function createSyntheticModuleFromExports(identifier, moduleExports, vm) {\n if (typeof vm.SyntheticModule !== "function") throw new Error("vm.SyntheticModule is required to load Node.js built-in modules in ESM remote entries.");\n const effectiveExports = getSyntheticModuleExports(moduleExports);\n const exportNames = Object.keys(effectiveExports);\n const syntheticModule = new vm.SyntheticModule(exportNames, function setSyntheticModuleExports() {\n for (const name of exportNames) this.setExport(name, effectiveExports[name]);\n }, { identifier });\n esmModuleCache.set(identifier, syntheticModule);\n await syntheticModule.link(async () => {\n throw new Error(`Node.js built-in module "${identifier}" should not request child modules.`);\n });\n await syntheticModule.evaluate();\n return syntheticModule;\n}\nasync function loadNodeBuiltinModule(specifier, vm) {\n const cacheKey = `node-builtin:${specifier}`;\n if (esmModuleCache.has(cacheKey)) return esmModuleCache.get(cacheKey);\n return createSyntheticModuleFromExports(cacheKey, await importNodeModule(specifier), vm);\n}\nasync function loadResolvedModule(specifier, parentUrl, options) {\n if (await isNodeBuiltinSpecifier(specifier)) return loadNodeBuiltinModule(specifier, options.vm);\n if (isBareModuleSpecifier(specifier)) throw new Error(`Unsupported ESM module specifier "${specifier}". Only relative or absolute http(s) remote modules and Node.js built-in modules are supported.`);\n const resolvedUrl = new URL(specifier, parentUrl).href;\n if (!isFetchableRemoteModuleUrl(resolvedUrl)) throw new Error(`Unsupported ESM module specifier "${specifier}" resolved to "${resolvedUrl}". Only http(s) remote modules and Node.js built-in modules are supported.`);\n return loadModule(resolvedUrl, options);\n}\nasync function evaluateDynamicModule(module) {\n if (module.status === "linked") await module.evaluate();\n if (module.status === "errored") throw module.error;\n return module;\n}\nasync function loadModule(url, options) {\n if (esmModuleCache.has(url)) return esmModuleCache.get(url);\n const { fetch: fetch2, vm } = options;\n if (!isFetchableRemoteModuleUrl(url)) throw new Error(`Unsupported ESM module URL "${url}". Only http(s) remote modules and Node.js built-in modules are supported.`);\n const code = await (await fetch2(url)).text();\n const cwdFileUrl = (await importNodeModule("node:url")).pathToFileURL(process.cwd()).href;\n const sourceTextModule = new vm.SourceTextModule(code, {\n identifier: url,\n initializeImportMeta: (meta) => {\n meta.url = createImportMetaUrl(url, cwdFileUrl);\n },\n importModuleDynamically: async (specifier) => {\n return evaluateDynamicModule(await loadResolvedModule(specifier, url, options));\n }\n });\n esmModuleCache.set(url, sourceTextModule);\n await sourceTextModule.link(async (specifier) => {\n return loadResolvedModule(specifier, url, options);\n });\n return sourceTextModule;\n}\nconst dataFetchFunction = async function(options) {\n var _a, _b;\n const [id, data, downgrade] = options;\n logger.debug("==========call data fetch function!");\n if (data) {\n if (!id) {\n throw new Error("id is required!");\n }\n if (!getDataFetchMap()) {\n initDataFetchMap();\n }\n const dataFetchItem = getDataFetchItem(id);\n if (dataFetchItem) {\n (_b = (_a = dataFetchItem[1]) == null ? void 0 : _a[1]) == null ? void 0 : _b.call(_a, data);\n dataFetchItem[2] = MF_DATA_FETCH_STATUS.LOADED;\n return;\n }\n if (!dataFetchItem) {\n const dataFetchMap = getDataFetchMap();\n let res;\n let rej;\n const p = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n dataFetchMap[id] = [\n [\n async () => async () => {\n return "";\n },\n MF_DATA_FETCH_TYPE.FETCH_SERVER\n ],\n [p, res, rej],\n MF_DATA_FETCH_STATUS.LOADED\n ];\n res && res(data);\n return;\n }\n }\n if (downgrade) {\n const mfDowngrade2 = getDowngradeTag();\n if (!mfDowngrade2) {\n globalThis[DOWNGRADE_KEY] = id ? [id] : true;\n } else if (Array.isArray(mfDowngrade2) && id && !mfDowngrade2.includes(id)) {\n mfDowngrade2.push(id);\n }\n }\n const mfDowngrade = getDowngradeTag();\n if (typeof mfDowngrade === "boolean") {\n return callAllDowngrade();\n }\n if (Array.isArray(mfDowngrade)) {\n if (!id) {\n globalThis[DOWNGRADE_KEY] = true;\n return callAllDowngrade();\n }\n if (!mfDowngrade.includes(id)) {\n mfDowngrade.push(id);\n }\n return callDowngrade(id);\n }\n};\nfunction injectDataFetch() {\n var _a;\n globalThis[_a = DATA_FETCH_FUNCTION] || (globalThis[_a] = []);\n const dataFetch = globalThis[DATA_FETCH_FUNCTION];\n if (dataFetch.push === dataFetchFunction) {\n return;\n }\n if (typeof window === "undefined") {\n return;\n }\n globalThis[FS_HREF] = window.location.href;\n dataFetch.push = dataFetchFunction;\n}\nconst getDocsUrl = (errorCode) => {\n return `View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${errorCode.split("-")[0].toLowerCase()}#${errorCode.toLowerCase()}`;\n};\nconst getShortErrorMsg = (errorCode, errorDescMap, args, originalErrorMsg) => {\n const msg = [`${[errorDescMap[errorCode]]} #${errorCode}`];\n args && msg.push(`args: ${JSON.stringify(args)}`);\n msg.push(getDocsUrl(errorCode));\n originalErrorMsg && msg.push(`Original Error Message:\n ${originalErrorMsg}`);\n return msg.join("\\n");\n};\nfunction logAndReport(code, descMap, args, logger2, originalErrorMsg, context) {\n return logger2(getShortErrorMsg(code, descMap, args, originalErrorMsg));\n}\nconst LOG_CATEGORY = "[ Federation Runtime ]";\nfunction assert(condition, msgOrCode, descMap, args, context) {\n if (!condition) error(msgOrCode);\n}\nfunction error(msgOrCode, descMap, args, originalErrorMsg, context) {\n if (descMap !== void 0) return logAndReport(msgOrCode, descMap, args ?? {}, (msg2) => {\n throw new Error(`${LOG_CATEGORY}: ${msg2}`);\n }, originalErrorMsg);\n const msg = msgOrCode;\n if (msg instanceof Error) {\n if (!msg.message.startsWith(LOG_CATEGORY)) msg.message = `${LOG_CATEGORY}: ${msg.message}`;\n throw msg;\n }\n throw new Error(`${LOG_CATEGORY}: ${msg}`);\n}\nconst processModuleAlias = (name, subPath) => {\n let moduleName;\n if (name.endsWith("/")) moduleName = name.slice(0, -1);\n else moduleName = name;\n if (subPath.startsWith(".")) subPath = subPath.slice(1);\n moduleName = moduleName + subPath;\n return moduleName;\n};\nconst CurrentGlobal = typeof globalThis === "object" ? globalThis : window;\nconst nativeGlobal = (() => {\n try {\n return document.defaultView;\n } catch {\n return CurrentGlobal;\n }\n})();\nfunction definePropertyGlobalVal(target, key, val) {\n Object.defineProperty(target, key, {\n value: val,\n configurable: false,\n writable: true\n });\n}\nfunction includeOwnProperty(target, key) {\n return Object.hasOwnProperty.call(target, key);\n}\nif (!includeOwnProperty(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__")) definePropertyGlobalVal(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__", {});\nconst globalLoading = CurrentGlobal.__GLOBAL_LOADING_REMOTE_ENTRY__;\nfunction setGlobalDefaultVal(target) {\n var _a, _b, _c, _d, _e, _f;\n if (includeOwnProperty(target, "__VMOK__") && !includeOwnProperty(target, "__FEDERATION__")) definePropertyGlobalVal(target, "__FEDERATION__", target.__VMOK__);\n if (!includeOwnProperty(target, "__FEDERATION__")) {\n definePropertyGlobalVal(target, "__FEDERATION__", {\n __GLOBAL_PLUGIN__: [],\n __INSTANCES__: [],\n moduleInfo: {},\n __SHARE__: {},\n __MANIFEST_LOADING__: {},\n __PRELOADED_MAP__: /* @__PURE__ */ new Map()\n });\n definePropertyGlobalVal(target, "__VMOK__", target.__FEDERATION__);\n }\n (_a = target.__FEDERATION__).__GLOBAL_PLUGIN__ ?? (_a.__GLOBAL_PLUGIN__ = []);\n (_b = target.__FEDERATION__).__INSTANCES__ ?? (_b.__INSTANCES__ = []);\n (_c = target.__FEDERATION__).moduleInfo ?? (_c.moduleInfo = {});\n (_d = target.__FEDERATION__).__SHARE__ ?? (_d.__SHARE__ = {});\n (_e = target.__FEDERATION__).__MANIFEST_LOADING__ ?? (_e.__MANIFEST_LOADING__ = {});\n (_f = target.__FEDERATION__).__PRELOADED_MAP__ ?? (_f.__PRELOADED_MAP__ = /* @__PURE__ */ new Map());\n}\nsetGlobalDefaultVal(CurrentGlobal);\nsetGlobalDefaultVal(nativeGlobal);\nconst getRemoteEntryExports = (name, globalName) => {\n const remoteEntryKey = globalName || `__FEDERATION_${name}:custom__`;\n return {\n remoteEntryKey,\n entryExports: CurrentGlobal[remoteEntryKey]\n };\n};\nconst DEFAULT_SCOPE = "default";\nconst DEFAULT_REMOTE_TYPE = "global";\nfunction composeRemoteRequestId(remoteName, expose) {\n if (!expose || expose === ".") return remoteName;\n return `${remoteName}/${expose.replace(/^\\.\\//, "")}`;\n}\nfunction matchRemoteWithNameAndExpose(remotes, id) {\n for (const remote of remotes) {\n const isNameMatched = id.startsWith(remote.name);\n let expose = id.replace(remote.name, "");\n if (isNameMatched) {\n if (expose.startsWith("/")) {\n const pkgNameOrAlias = remote.name;\n expose = `.${expose}`;\n return {\n pkgNameOrAlias,\n expose,\n remote\n };\n } else if (expose === "") return {\n pkgNameOrAlias: remote.name,\n expose: ".",\n remote\n };\n }\n const isAliasMatched = remote.alias && id.startsWith(remote.alias);\n let exposeWithAlias = remote.alias && id.replace(remote.alias, "");\n if (remote.alias && isAliasMatched) {\n if (exposeWithAlias && exposeWithAlias.startsWith("/")) {\n const pkgNameOrAlias = remote.alias;\n exposeWithAlias = `.${exposeWithAlias}`;\n return {\n pkgNameOrAlias,\n expose: exposeWithAlias,\n remote\n };\n } else if (exposeWithAlias === "") return {\n pkgNameOrAlias: remote.alias,\n expose: ".",\n remote\n };\n }\n }\n}\nconst RUNTIME_001 = "RUNTIME-001";\nconst RUNTIME_002 = "RUNTIME-002";\nconst RUNTIME_003 = "RUNTIME-003";\nconst RUNTIME_004 = "RUNTIME-004";\nconst RUNTIME_005 = "RUNTIME-005";\nconst RUNTIME_006 = "RUNTIME-006";\nconst RUNTIME_007 = "RUNTIME-007";\nconst RUNTIME_008 = "RUNTIME-008";\nconst RUNTIME_009 = "RUNTIME-009";\nconst RUNTIME_010 = "RUNTIME-010";\nconst RUNTIME_011 = "RUNTIME-011";\nconst RUNTIME_012 = "RUNTIME-012";\nconst RUNTIME_013 = "RUNTIME-013";\nconst RUNTIME_014 = "RUNTIME-014";\nconst RUNTIME_015 = "RUNTIME-015";\nconst runtimeDescMap = {\n [RUNTIME_001]: "Failed to get remoteEntry exports.",\n [RUNTIME_002]: \'The remote entry interface does not contain "init"\',\n [RUNTIME_003]: "Failed to get manifest.",\n [RUNTIME_004]: "Failed to locate remote.",\n [RUNTIME_005]: "Invalid loadShareSync function call from bundler runtime",\n [RUNTIME_006]: "Invalid loadShareSync function call from runtime",\n [RUNTIME_007]: "Failed to get remote snapshot.",\n [RUNTIME_008]: "Failed to load script resources.",\n [RUNTIME_009]: "Please call createInstance first.",\n [RUNTIME_010]: \'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.\',\n [RUNTIME_011]: "The remoteEntry URL is missing from the remote snapshot.",\n [RUNTIME_012]: \'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.\',\n [RUNTIME_013]: "The manifest is not a valid Module Federation manifest.",\n [RUNTIME_014]: "The remote does not expose the requested module.",\n [RUNTIME_015]: "Remote container initialization failed."\n};\n({\n ...runtimeDescMap\n});\nconst importCallback = ".then(callbacks[0]).catch(callbacks[1])";\nfunction isEsmRemoteType(type) {\n return type === "esm" || type === "module";\n}\nasync function loadEsmEntry({ entry, remoteEntryExports }) {\n return new Promise((resolve, reject) => {\n try {\n if (!remoteEntryExports) if (typeof FEDERATION_ALLOW_NEW_FUNCTION !== "undefined") new Function("callbacks", `import("${entry}")${importCallback}`)([resolve, reject]);\n else import(\n /* webpackIgnore: true */\n /* @vite-ignore */\n entry\n ).then(resolve).catch(reject);\n else resolve(remoteEntryExports);\n } catch (e) {\n error(`Failed to load ESM entry from "${entry}". ${e instanceof Error ? e.message : String(e)}`);\n }\n });\n}\nasync function loadSystemJsEntry({ entry, remoteEntryExports }) {\n return new Promise((resolve, reject) => {\n try {\n if (!remoteEntryExports) if (typeof __system_context__ === "undefined") System.import(entry).then(resolve).catch(reject);\n else new Function("callbacks", `System.import("${entry}")${importCallback}`)([resolve, reject]);\n else resolve(remoteEntryExports);\n } catch (e) {\n error(`Failed to load SystemJS entry from "${entry}". ${e instanceof Error ? e.message : String(e)}`);\n }\n });\n}\nfunction handleRemoteEntryLoaded(name, globalName, entry) {\n const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);\n if (!entryExports) error(RUNTIME_001, runtimeDescMap, {\n remoteName: name,\n remoteEntryUrl: entry,\n remoteEntryKey\n });\n return entryExports;\n}\nasync function loadEntryScript({ name, globalName, entry, remoteInfo, loaderHook, getEntryUrl, resourceContext }) {\n const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);\n if (remoteEntryExports) return remoteEntryExports;\n const url = getEntryUrl ? getEntryUrl(entry) : entry;\n return loadScript(url, {\n attrs: {},\n createScriptHook: (url2, attrs) => {\n const res = loaderHook.lifecycle.createScript.emit({\n url: url2,\n attrs,\n remoteInfo,\n resourceContext: resourceContext ? {\n ...resourceContext,\n url: url2\n } : void 0\n });\n if (!res) return;\n if (res instanceof HTMLScriptElement) return res;\n if ("script" in res || "timeout" in res) return res;\n }\n }).then(() => {\n return handleRemoteEntryLoaded(name, globalName, entry);\n }, (loadError) => {\n const originalMsg = loadError instanceof Error ? loadError.message : String(loadError);\n error(RUNTIME_008, runtimeDescMap, {\n remoteName: name,\n resourceUrl: url\n }, originalMsg);\n });\n}\nasync function loadEntryDom({ remoteInfo, remoteEntryExports, loaderHook, getEntryUrl, resourceContext }) {\n const { entry, entryGlobalName: globalName, name, type } = remoteInfo;\n if (isEsmRemoteType(type)) return loadEsmEntry({\n entry,\n remoteEntryExports\n });\n if (type === "system") return loadSystemJsEntry({\n entry,\n remoteEntryExports\n });\n return loadEntryScript({\n entry,\n globalName,\n name,\n remoteInfo,\n loaderHook,\n getEntryUrl,\n resourceContext\n });\n}\nasync function loadEntryNode({ remoteInfo, loaderHook, resourceContext }) {\n const { entry, entryGlobalName: globalName, name, type } = remoteInfo;\n const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);\n if (remoteEntryExports) return remoteEntryExports;\n return loadScriptNode(entry, {\n attrs: {\n name,\n globalName,\n type\n },\n loaderHook: { createScriptHook: (url, attrs = {}) => {\n const res = loaderHook.lifecycle.createScript.emit({\n url,\n attrs,\n remoteInfo,\n resourceContext: resourceContext ? {\n ...resourceContext,\n url\n } : void 0\n });\n if (!res) return;\n if ("url" in res) return res;\n } }\n }).then(() => {\n return handleRemoteEntryLoaded(name, globalName, entry);\n }).catch((e) => {\n error(`Failed to load Node.js entry for remote "${name}" from "${entry}". ${e instanceof Error ? e.message : String(e)}`);\n });\n}\nfunction getRemoteEntryUniqueKey(remoteInfo) {\n const { entry, name } = remoteInfo;\n return composeKeyWithSeparator(name, entry);\n}\nasync function getRemoteEntry(params) {\n const { origin, remoteEntryExports, remoteInfo, getEntryUrl, resourceContext, _inErrorHandling = false } = params;\n const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);\n if (remoteEntryExports) return remoteEntryExports;\n if (!globalLoading[uniqueKey]) {\n const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;\n const loaderHook = origin.loaderHook;\n globalLoading[uniqueKey] = loadEntryHook.emit({\n origin,\n loaderHook,\n remoteInfo,\n remoteEntryExports\n }).then((res) => {\n if (res) return res;\n return (typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : isBrowserEnvValue) ? loadEntryDom({\n remoteInfo,\n remoteEntryExports,\n loaderHook,\n getEntryUrl,\n resourceContext\n }) : loadEntryNode({\n remoteInfo,\n loaderHook,\n resourceContext\n });\n }).then(async (res) => {\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n remoteEntryExports: res\n });\n return res;\n }).catch(async (err) => {\n const uniqueKey2 = getRemoteEntryUniqueKey(remoteInfo);\n const isScriptExecutionError = err instanceof Error && err.message.includes("ScriptExecutionError");\n if (err instanceof Error && err.message.includes(RUNTIME_008) && !isScriptExecutionError && !_inErrorHandling) {\n const wrappedGetRemoteEntry = (params2) => {\n return getRemoteEntry({\n ...params2,\n _inErrorHandling: true\n });\n };\n const RemoteEntryExports = await origin.loaderHook.lifecycle.loadEntryError.emit({\n getRemoteEntry: wrappedGetRemoteEntry,\n origin,\n remoteInfo,\n remoteEntryExports,\n globalLoading,\n uniqueKey: uniqueKey2\n });\n if (RemoteEntryExports) {\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n remoteEntryExports: RemoteEntryExports,\n recovered: true\n });\n return RemoteEntryExports;\n }\n }\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n error: err\n });\n throw err;\n });\n }\n return globalLoading[uniqueKey];\n}\nfunction getRemoteInfo(remote) {\n return {\n ...remote,\n entry: "entry" in remote ? remote.entry : "",\n type: remote.type || DEFAULT_REMOTE_TYPE,\n entryGlobalName: remote.entryGlobalName || remote.name,\n shareScope: remote.shareScope || DEFAULT_SCOPE\n };\n}\nfunction remoteToEntry(r) {\n return {\n name: r.name,\n alias: r.alias,\n entry: "entry" in r ? r.entry : void 0,\n version: "version" in r ? r.version : void 0,\n type: r.type,\n entryGlobalName: r.entryGlobalName,\n shareScope: r.shareScope\n };\n}\nfunction optionsToMFContext(options) {\n var _a, _b, _c, _d, _e, _f;\n const shared = {};\n for (const [pkgName, versions] of Object.entries(options.shared)) {\n const first = versions[0];\n if (first) shared[pkgName] = {\n version: first.version,\n singleton: (_a = first.shareConfig) == null ? void 0 : _a.singleton,\n requiredVersion: ((_b = first.shareConfig) == null ? void 0 : _b.requiredVersion) === false ? false : (_c = first.shareConfig) == null ? void 0 : _c.requiredVersion,\n eager: first.eager,\n strictVersion: (_d = first.shareConfig) == null ? void 0 : _d.strictVersion\n };\n }\n return {\n project: {\n name: options.name,\n mfRole: ((_e = options.remotes) == null ? void 0 : _e.length) > 0 ? "host" : "unknown"\n },\n mfConfig: {\n name: options.name,\n remotes: ((_f = options.remotes) == null ? void 0 : _f.map(remoteToEntry)) ?? [],\n shared\n }\n };\n}\nfunction isTimeoutError(error2) {\n if (!(error2 instanceof Error)) return false;\n return error2.message.includes("timed out") || error2.name.includes("Timeout");\n}\nfunction createAssetResult(context, url, status, error2) {\n return {\n url,\n status,\n resourceType: context.resourceType,\n initiator: context.initiator,\n id: context.id,\n error: error2\n };\n}\nasync function waitForRemoteEntryPreload(host, remoteInfo, entryRemoteInfo, context) {\n const cachedRemote = host.moduleCache.get(entryRemoteInfo.name);\n const url = entryRemoteInfo.entry;\n if (cachedRemote == null ? void 0 : cachedRemote.remoteEntryExports) return createAssetResult(context, url, "cached");\n try {\n if (!await getRemoteEntry({\n origin: host,\n remoteInfo: entryRemoteInfo,\n remoteEntryExports: cachedRemote == null ? void 0 : cachedRemote.remoteEntryExports,\n resourceContext: {\n ...context,\n url\n }\n })) throw new Error(`Failed to load remoteEntry "${url}".`);\n return createAssetResult(context, url, "success");\n } catch (error2) {\n return createAssetResult(context, url, isTimeoutError(error2) ? "timeout" : "error", error2);\n }\n}\nfunction waitForLinkPreload({ host, remoteInfo, url, attrs, context, needDeleteLink }) {\n return new Promise((resolve) => {\n const { link, needAttach } = createLink({\n url,\n cb: () => {\n resolve(createAssetResult(context, url, needAttach ? "success" : "cached"));\n },\n onErrorCallback: (error2) => {\n resolve(createAssetResult(context, url, isTimeoutError(error2) ? "timeout" : "error", error2));\n },\n attrs,\n createLinkHook: (hookUrl, hookAttrs) => {\n const res = host.loaderHook.lifecycle.createLink.emit({\n url: hookUrl,\n attrs: hookAttrs,\n remoteInfo,\n resourceContext: {\n ...context,\n url: hookUrl\n }\n });\n if (res instanceof HTMLLinkElement) return res;\n return res;\n },\n needDeleteLink\n });\n needAttach && document.head.appendChild(link);\n });\n}\nfunction waitForScriptPreload({ host, remoteInfo, url, attrs, context }) {\n return new Promise((resolve) => {\n const { script, needAttach } = createScript({\n url,\n cb: () => {\n resolve(createAssetResult(context, url, needAttach ? "success" : "cached"));\n },\n onErrorCallback: (error2) => {\n resolve(createAssetResult(context, url, isTimeoutError(error2) ? "timeout" : "error", error2));\n },\n attrs,\n createScriptHook: (hookUrl, hookAttrs) => {\n const res = host.loaderHook.lifecycle.createScript.emit({\n url: hookUrl,\n attrs: hookAttrs,\n remoteInfo,\n resourceContext: {\n ...context,\n url: hookUrl\n }\n });\n if (res instanceof HTMLScriptElement) return res;\n return res;\n },\n needDeleteScript: true\n });\n needAttach && document.head.appendChild(script);\n });\n}\nfunction createResourceContext(baseContext, resourceType) {\n return {\n ...baseContext,\n resourceType\n };\n}\nfunction preloadAssets(remoteInfo, host, assets, useLinkPreload = true, baseContext = {\n initiator: "preloadRemote",\n id: remoteInfo.name\n}) {\n const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;\n const results = [];\n if (host.options.inBrowser) {\n entryAssets.forEach((asset) => {\n const { moduleInfo: entryRemoteInfo } = asset;\n results.push(waitForRemoteEntryPreload(host, remoteInfo, entryRemoteInfo, createResourceContext(baseContext, "remoteEntry")));\n });\n if (useLinkPreload) {\n const defaultAttrs2 = {\n rel: "preload",\n as: "style"\n };\n cssAssets.forEach((cssUrl) => {\n results.push(waitForLinkPreload({\n host,\n remoteInfo,\n url: cssUrl,\n attrs: defaultAttrs2,\n context: createResourceContext(baseContext, "css")\n }));\n });\n } else {\n const defaultAttrs2 = {\n rel: "stylesheet",\n type: "text/css"\n };\n cssAssets.forEach((cssUrl) => {\n results.push(waitForLinkPreload({\n host,\n remoteInfo,\n url: cssUrl,\n attrs: defaultAttrs2,\n needDeleteLink: false,\n context: createResourceContext(baseContext, "css")\n }));\n });\n }\n let preloadJsAsset = waitForScriptPreload;\n let defaultAttrs = {\n fetchpriority: "high",\n type: "text/javascript"\n };\n if (useLinkPreload) {\n preloadJsAsset = waitForLinkPreload;\n defaultAttrs = {\n rel: "preload",\n as: "script"\n };\n } else if (isEsmRemoteType(remoteInfo.type)) {\n preloadJsAsset = waitForLinkPreload;\n defaultAttrs = {\n rel: "modulepreload",\n fetchpriority: "high"\n };\n }\n jsAssetsWithoutEntry.forEach((jsUrl) => {\n results.push(preloadJsAsset({\n host,\n remoteInfo,\n url: jsUrl,\n attrs: defaultAttrs,\n context: createResourceContext(baseContext, "js")\n }));\n });\n }\n return Promise.all(results);\n}\nvar helpers_default = {\n utils: {\n matchRemoteWithNameAndExpose,\n preloadAssets,\n getRemoteInfo\n }\n};\nfunction getAvailableExposeNames(remoteSnapshot) {\n if (!remoteSnapshot || !("modules" in remoteSnapshot) || !Array.isArray(remoteSnapshot.modules)) return;\n const exposes = remoteSnapshot.modules.map((module) => module.moduleName).filter(Boolean);\n return exposes.length ? exposes.join(",") : void 0;\n}\nfunction createRemoteEntryInitOptions(remoteInfo, hostShareScopeMap, rawInitScope) {\n const localShareScopeMap = hostShareScopeMap;\n const shareScopeKeys = Array.isArray(remoteInfo.shareScope) ? remoteInfo.shareScope : [remoteInfo.shareScope];\n if (!shareScopeKeys.length) shareScopeKeys.push("default");\n shareScopeKeys.forEach((shareScopeKey) => {\n if (!localShareScopeMap[shareScopeKey]) localShareScopeMap[shareScopeKey] = {};\n });\n const remoteEntryInitOptions = {\n version: remoteInfo.version || "",\n shareScopeKeys: Array.isArray(remoteInfo.shareScope) ? shareScopeKeys : remoteInfo.shareScope || "default"\n };\n Object.defineProperty(remoteEntryInitOptions, "shareScopeMap", {\n value: localShareScopeMap,\n enumerable: false\n });\n return {\n remoteEntryInitOptions,\n shareScope: localShareScopeMap[shareScopeKeys[0]],\n initScope: rawInitScope ?? []\n };\n}\nvar Module$1 = class {\n constructor({ remoteInfo, host }) {\n this.inited = false;\n this.initing = false;\n this.lib = void 0;\n this.remoteInfo = remoteInfo;\n this.host = host;\n }\n async getEntry(expose) {\n if (this.remoteEntryExports) return this.remoteEntryExports;\n const remoteEntryExports = await getRemoteEntry({\n origin: this.host,\n remoteInfo: this.remoteInfo,\n remoteEntryExports: this.remoteEntryExports,\n resourceContext: {\n initiator: "loadRemote",\n id: composeRemoteRequestId(this.remoteInfo.name, expose),\n resourceType: "remoteEntry"\n }\n });\n assert(remoteEntryExports, `remoteEntryExports is undefined \n ${safeToString(this.remoteInfo)}`);\n this.remoteEntryExports = remoteEntryExports;\n return this.remoteEntryExports;\n }\n async init(id, remoteSnapshot, rawInitScope, expose) {\n const remoteEntryExports = await this.getEntry(expose);\n if (this.inited) {\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n cached: true,\n origin: this.host\n });\n return remoteEntryExports;\n }\n if (this.initPromise) {\n try {\n await this.initPromise;\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n cached: true,\n origin: this.host\n });\n } catch (initError) {\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n error: initError,\n cached: true,\n origin: this.host\n });\n throw initError;\n }\n return remoteEntryExports;\n }\n this.initing = true;\n this.initPromise = (async () => {\n await this.host.loaderHook.lifecycle.beforeInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n origin: this.host\n });\n const { remoteEntryInitOptions, shareScope, initScope } = createRemoteEntryInitOptions(this.remoteInfo, this.host.shareScopeMap, rawInitScope);\n const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({\n shareScope,\n remoteEntryInitOptions,\n initScope,\n remoteInfo: this.remoteInfo,\n origin: this.host\n });\n if (typeof (remoteEntryExports == null ? void 0 : remoteEntryExports.init) === "undefined") error(RUNTIME_002, runtimeDescMap, {\n hostName: this.host.name,\n remoteName: this.remoteInfo.name,\n remoteEntryUrl: this.remoteInfo.entry,\n remoteEntryKey: this.remoteInfo.entryGlobalName\n }, void 0, optionsToMFContext(this.host.options));\n try {\n await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);\n } catch (initError) {\n error(RUNTIME_015, runtimeDescMap, {\n hostName: this.host.name,\n remoteName: this.remoteInfo.name,\n remoteEntryUrl: this.remoteInfo.entry,\n remoteEntryKey: this.remoteInfo.entryGlobalName,\n shareScope: this.remoteInfo.shareScope\n }, `${initError}`, optionsToMFContext(this.host.options));\n }\n await this.host.hooks.lifecycle.initContainer.emit({\n ...initContainerOptions,\n id,\n remoteSnapshot,\n remoteEntryExports\n });\n this.inited = true;\n })();\n try {\n await this.initPromise;\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n origin: this.host\n });\n } catch (initError) {\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n error: initError,\n origin: this.host\n });\n throw initError;\n } finally {\n this.initing = false;\n this.initPromise = void 0;\n }\n return remoteEntryExports;\n }\n async get(id, expose, options, remoteSnapshot) {\n const { loadFactory = true } = options || { loadFactory: true };\n const remoteEntryExports = await this.init(id, remoteSnapshot, void 0, expose);\n this.lib = remoteEntryExports;\n await this.host.loaderHook.lifecycle.beforeGetExpose.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n remoteEntryExports,\n origin: this.host\n });\n let moduleFactory;\n try {\n const hookModuleFactory = await this.host.loaderHook.lifecycle.getModuleFactory.emit({\n remoteEntryExports,\n expose,\n moduleInfo: this.remoteInfo\n });\n moduleFactory = typeof hookModuleFactory === "function" ? hookModuleFactory : void 0;\n if (!moduleFactory) moduleFactory = await remoteEntryExports.get(expose);\n if (!moduleFactory) error(RUNTIME_014, runtimeDescMap, {\n hostName: this.host.name,\n remoteName: this.remoteInfo.name,\n remoteEntryUrl: this.remoteInfo.entry,\n expose,\n requestId: id,\n availableExposes: getAvailableExposeNames(remoteSnapshot)\n }, void 0, optionsToMFContext(this.host.options));\n await this.host.loaderHook.lifecycle.afterGetExpose.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n remoteEntryExports,\n moduleFactory,\n origin: this.host\n });\n } catch (getExposeError) {\n await this.host.loaderHook.lifecycle.afterGetExpose.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n remoteEntryExports,\n error: getExposeError,\n origin: this.host\n });\n throw getExposeError;\n }\n const symbolName = processModuleAlias(this.remoteInfo.name, expose);\n const wrapModuleFactory = this.wraperFactory(moduleFactory, symbolName);\n if (!loadFactory) return wrapModuleFactory;\n await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n loadFactory,\n origin: this.host\n });\n try {\n const exposeContent = await wrapModuleFactory();\n await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n loadFactory,\n exposeModule: exposeContent,\n origin: this.host\n });\n return exposeContent;\n } catch (executeFactoryError) {\n await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n loadFactory,\n error: executeFactoryError,\n origin: this.host\n });\n throw executeFactoryError;\n }\n }\n wraperFactory(moduleFactory, id) {\n function defineModuleId(res, id2) {\n if (res && typeof res === "object" && Object.isExtensible(res) && !Object.getOwnPropertyDescriptor(res, Symbol.for("mf_module_id"))) Object.defineProperty(res, Symbol.for("mf_module_id"), {\n value: id2,\n enumerable: false\n });\n }\n return () => {\n const res = moduleFactory();\n if (res instanceof Promise) return res.then((asyncRes) => {\n defineModuleId(asyncRes, id);\n return asyncRes;\n });\n defineModuleId(res, id);\n return res;\n };\n }\n};\nconst REMOTE_DISABLED_MESSAGE = "Remote loading is disabled by experiments.optimization.disableRemote.";\nvar UnavailableRemoteModule = class {\n constructor() {\n throw new Error(REMOTE_DISABLED_MESSAGE);\n }\n};\ntypeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN === "boolean" ? !FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN : true;\ntypeof FEDERATION_OPTIMIZE_NO_REMOTE === "boolean" ? !FEDERATION_OPTIMIZE_NO_REMOTE : true;\ntypeof FEDERATION_OPTIMIZE_NO_SHARED === "boolean" ? !FEDERATION_OPTIMIZE_NO_SHARED : true;\nconst helpers = helpers_default;\ntypeof FEDERATION_OPTIMIZE_NO_REMOTE === "boolean" && FEDERATION_OPTIMIZE_NO_REMOTE ? UnavailableRemoteModule : Module$1;\nconst utils = helpers.utils;\nconst runtimeHelpers = {\n utils\n};\nasync function prefetch(options) {\n const { instance, id, dataFetchParams, preloadComponentResource } = options;\n if (!id) {\n logger.error("id is required for prefetch!");\n return;\n }\n if (!instance) {\n logger.error("instance is required for prefetch!");\n return;\n }\n const matchedRemoteInfo = runtimeHelpers.utils.matchRemoteWithNameAndExpose(\n instance.options.remotes,\n id\n );\n if (!matchedRemoteInfo) {\n logger.error(`Can not found \'${id}\' in instance.options.remotes!`);\n return;\n }\n const { remote, expose } = matchedRemoteInfo;\n const { remoteSnapshot, globalSnapshot } = await instance.snapshotHandler.loadRemoteSnapshotInfo({\n moduleInfo: remote,\n id\n });\n if (preloadComponentResource) {\n const remoteInfo = runtimeHelpers.utils.getRemoteInfo(remote);\n Promise.resolve(\n instance.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({\n origin: instance,\n preloadOptions: {\n remote,\n preloadConfig: {\n nameOrAlias: remote.name,\n exposes: [expose]\n }\n },\n remote,\n remoteInfo,\n globalSnapshot,\n remoteSnapshot\n })\n ).then((assets) => {\n if (assets) {\n runtimeHelpers.utils.preloadAssets(remoteInfo, instance, assets);\n }\n });\n }\n const dataFetchMap = getDataFetchMap();\n if (!dataFetchMap) {\n return;\n }\n const dataFetchInfo = getDataFetchInfo({\n name: remote.name,\n alias: remote.alias,\n id,\n remoteSnapshot\n });\n const dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {\n name: instance.name,\n version: instance.options.version\n });\n if (!dataFetchMapKey) {\n return;\n }\n const dataFetchItem = dataFetchMap[dataFetchMapKey];\n if (!dataFetchItem) {\n return;\n }\n const [getDataFetchGetter, _type, getDataFetchPromise] = dataFetchItem[0];\n let _getDataFetchPromise = getDataFetchPromise;\n if (!getDataFetchPromise) {\n if (!getDataFetchGetter) {\n return;\n }\n _getDataFetchPromise = getDataFetchGetter();\n }\n _getDataFetchPromise.then((dataFetchFn) => {\n return dataFetchFn({\n ...dataFetchParams,\n _id: dataFetchMapKey,\n isDowngrade: false\n });\n });\n}\nexport {\n dataFetchFunction as d,\n injectDataFetch as i,\n prefetch as p\n};\n',
|
|
197
|
-
|
|
198
|
-
"utils-BBP3hEeV.mjs": "import { S as SEPARATOR, c as createLogger, i as isBrowserEnvValue } from \"./logger-DwWkXsWl.mjs\";\nimport { SizeLimitedCache } from \"./size-limited-cache.es.js\";\nconst LOG_CATEGORY = \"[ Federation Runtime ]\";\nconst composeKeyWithSeparator = function(...args) {\n if (!args.length) return \"\";\n return args.reduce((sum, cur) => {\n if (!cur) return sum;\n if (!sum) return cur;\n return `${sum}${SEPARATOR}${cur}`;\n }, \"\");\n};\nconst warn = (msg) => {\n console.warn(`${LOG_CATEGORY}: ${msg}`);\n};\nfunction safeToString(info) {\n try {\n return JSON.stringify(info, null, 2);\n } catch (e) {\n return \"\";\n }\n}\nconst PLUGIN_IDENTIFIER = \"[ Module Federation React ]\";\nconst DOWNGRADE_KEY = \"_mfSSRDowngrade\";\nconst DATA_FETCH_FUNCTION = \"_mfDataFetch\";\nconst FS_HREF = \"_mfFSHref\";\nconst ERROR_TYPE = {\n DATA_FETCH: 1,\n LOAD_REMOTE: 2,\n UNKNOWN: 3\n};\nconst WRAP_DATA_FETCH_ID_IDENTIFIER = \"wrap_dfip_identifier\";\nvar MF_DATA_FETCH_TYPE = /* @__PURE__ */ ((MF_DATA_FETCH_TYPE2) => {\n MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2[\"FETCH_SERVER\"] = 1] = \"FETCH_SERVER\";\n MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2[\"FETCH_CLIENT\"] = 2] = \"FETCH_CLIENT\";\n return MF_DATA_FETCH_TYPE2;\n})(MF_DATA_FETCH_TYPE || {});\nvar MF_DATA_FETCH_STATUS = /* @__PURE__ */ ((MF_DATA_FETCH_STATUS2) => {\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"LOADED\"] = 1] = \"LOADED\";\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"LOADING\"] = 2] = \"LOADING\";\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"AWAIT\"] = 0] = \"AWAIT\";\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"ERROR\"] = 3] = \"ERROR\";\n return MF_DATA_FETCH_STATUS2;\n})(MF_DATA_FETCH_STATUS || {});\nconst DATA_FETCH_IDENTIFIER = \"data\";\nconst DATA_FETCH_CLIENT_SUFFIX = \".client\";\nconst DATA_FETCH_QUERY = \"x-mf-data-fetch\";\nconst DATA_FETCH_ERROR_PREFIX = \"caught the following error during dataFetch: \";\nconst LOAD_REMOTE_ERROR_PREFIX = \"caught the following error during loadRemote: \";\nconst logger = createLogger(PLUGIN_IDENTIFIER);\nconst CacheSize = {\n KB: 1024,\n MB: 1024 * 1024,\n GB: 1024 * 1024 * 1024\n};\nconst CacheTime = {\n SECOND: 1e3,\n MINUTE: 60 * 1e3,\n HOUR: 60 * 60 * 1e3,\n DAY: 24 * 60 * 60 * 1e3,\n WEEK: 7 * 24 * 60 * 60 * 1e3,\n MONTH: 30 * 24 * 60 * 60 * 1e3\n};\nfunction getTagKeyMap() {\n const dataFetchCache = getDataFetchCache();\n if (!dataFetchCache || !dataFetchCache.tagKeyMap) {\n const tagKeyMap = /* @__PURE__ */ new Map();\n globalThis.__MF_DATA_FETCH_CACHE__ || (globalThis.__MF_DATA_FETCH_CACHE__ = {});\n globalThis.__MF_DATA_FETCH_CACHE__.tagKeyMap = tagKeyMap;\n return tagKeyMap;\n }\n return dataFetchCache.tagKeyMap;\n}\nfunction addTagKeyRelation(tag, key) {\n const tagKeyMap = getTagKeyMap();\n let keys = tagKeyMap.get(tag);\n if (!keys) {\n keys = /* @__PURE__ */ new Set();\n tagKeyMap.set(tag, keys);\n }\n keys.add(key);\n}\nfunction getCacheConfig() {\n const dataFetchCache = getDataFetchCache();\n if (!dataFetchCache || !dataFetchCache.cacheConfig) {\n const cacheConfig = {\n maxSize: CacheSize.GB\n };\n globalThis.__MF_DATA_FETCH_CACHE__ || (globalThis.__MF_DATA_FETCH_CACHE__ = {});\n globalThis.__MF_DATA_FETCH_CACHE__.cacheConfig = cacheConfig;\n return cacheConfig;\n }\n return dataFetchCache.cacheConfig;\n}\nfunction configureCache(config) {\n const cacheConfig = getCacheConfig();\n Object.assign(cacheConfig, config);\n}\nfunction getSizeLimitedCache() {\n const dataFetchCache = getDataFetchCache();\n const cacheConfig = getCacheConfig();\n if (!dataFetchCache || !dataFetchCache.cacheStore) {\n const cacheStore = new SizeLimitedCache({\n maxSize: cacheConfig.maxSize ?? CacheSize.GB,\n sizeCalculation: (value) => {\n if (!value.size) {\n return 1;\n }\n let size = 0;\n for (const [k, item] of value.entries()) {\n size += k.length * 2;\n size += estimateObjectSize(item.data);\n size += 8;\n }\n return size;\n }\n });\n globalThis.__MF_DATA_FETCH_CACHE__ || (globalThis.__MF_DATA_FETCH_CACHE__ = {});\n globalThis.__MF_DATA_FETCH_CACHE__.cacheStore = cacheStore;\n return cacheStore;\n }\n return dataFetchCache.cacheStore;\n}\nfunction estimateObjectSize(data) {\n const type = typeof data;\n if (type === \"number\") return 8;\n if (type === \"boolean\") return 4;\n if (type === \"string\") return Math.max(data.length * 2, 1);\n if (data === null || data === void 0) return 1;\n if (ArrayBuffer.isView(data)) {\n return Math.max(data.byteLength, 1);\n }\n if (Array.isArray(data)) {\n return Math.max(\n data.reduce((acc, item) => acc + estimateObjectSize(item), 0),\n 1\n );\n }\n if (data instanceof Map || data instanceof Set) {\n return 1024;\n }\n if (data instanceof Date) {\n return 8;\n }\n if (type === \"object\") {\n return Math.max(\n Object.entries(data).reduce(\n (acc, [key, value]) => acc + key.length * 2 + estimateObjectSize(value),\n 0\n ),\n 1\n );\n }\n return 1;\n}\nfunction generateKey(dataFetchOptions) {\n return JSON.stringify(dataFetchOptions, (_, value) => {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return Object.keys(value).sort().reduce((result, key) => {\n result[key] = value[key];\n return result;\n }, {});\n }\n return value;\n });\n}\nfunction cache(fn, options) {\n const {\n tag = \"default\",\n maxAge = CacheTime.MINUTE * 5,\n revalidate = 0,\n onCache,\n getKey\n } = options || {};\n const tags = Array.isArray(tag) ? tag : [tag];\n return async (dataFetchOptions) => {\n if (dataFetchOptions.isDowngrade || !dataFetchOptions._id) {\n return fn(dataFetchOptions);\n }\n const store = getSizeLimitedCache();\n const now = Date.now();\n const storeKey = dataFetchOptions._id;\n const cacheKey = getKey ? getKey(dataFetchOptions) : generateKey(dataFetchOptions);\n tags.forEach((t) => addTagKeyRelation(t, cacheKey));\n let cacheStore = store.get(cacheKey);\n if (!cacheStore) {\n cacheStore = /* @__PURE__ */ new Map();\n }\n const cached = cacheStore.get(storeKey);\n if (cached) {\n const age = now - cached.timestamp;\n if (age < maxAge) {\n if (onCache) {\n const useCache = onCache({\n status: \"hit\",\n key: cacheKey,\n params: dataFetchOptions,\n result: cached.data\n });\n if (!useCache) {\n return fn(dataFetchOptions);\n }\n }\n return cached.data;\n }\n if (revalidate > 0 && age < maxAge + revalidate) {\n if (onCache) {\n onCache({\n status: \"stale\",\n key: cacheKey,\n params: dataFetchOptions,\n result: cached.data\n });\n }\n if (!cached.isRevalidating) {\n cached.isRevalidating = true;\n Promise.resolve().then(async () => {\n try {\n const newData = await fn(dataFetchOptions);\n cacheStore.set(storeKey, {\n data: newData,\n timestamp: Date.now(),\n isRevalidating: false\n });\n store.set(cacheKey, cacheStore);\n } catch (error) {\n cached.isRevalidating = false;\n console.error(\"Background revalidation failed:\", error);\n }\n });\n }\n return cached.data;\n }\n }\n const data = await fn(dataFetchOptions);\n cacheStore.set(storeKey, {\n data,\n timestamp: now,\n isRevalidating: false\n });\n store.set(cacheKey, cacheStore);\n if (onCache) {\n onCache({\n status: \"miss\",\n key: cacheKey,\n params: dataFetchOptions,\n result: data\n });\n }\n return data;\n };\n}\nfunction revalidateTag(tag) {\n const tagKeyMap = getTagKeyMap();\n const keys = tagKeyMap.get(tag);\n const cacheStore = getSizeLimitedCache();\n if (keys) {\n keys.forEach((key) => {\n cacheStore == null ? void 0 : cacheStore.delete(key);\n });\n }\n}\nfunction clearStore() {\n var _a;\n const cacheStore = getSizeLimitedCache();\n const tagKeyMap = getTagKeyMap();\n cacheStore == null ? void 0 : cacheStore.clear();\n (_a = globalThis.__MF_DATA_FETCH_CACHE__) == null ? true : delete _a.cacheStore;\n tagKeyMap.clear();\n}\nconst getDataFetchInfo = ({\n name,\n alias,\n id,\n remoteSnapshot\n}) => {\n if (!remoteSnapshot) {\n return;\n }\n if (!(\"modules\" in remoteSnapshot)) {\n return;\n }\n const regex = new RegExp(`^${name}(/[^/].*|)$`);\n const nameOrAlias = regex.test(id) ? name : alias || name;\n const expose = id.replace(nameOrAlias, \"\");\n let dataFetchName = \"\";\n let dataFetchId = \"\";\n let dataFetchKey = \"\";\n if (expose.startsWith(\"/\")) {\n dataFetchName = `${expose.slice(1)}.${DATA_FETCH_IDENTIFIER}`;\n dataFetchId = `${id}.${DATA_FETCH_IDENTIFIER}`;\n dataFetchKey = `${name}${expose}.${DATA_FETCH_IDENTIFIER}`;\n } else if (expose === \"\") {\n dataFetchName = DATA_FETCH_IDENTIFIER;\n dataFetchId = `${id}/${DATA_FETCH_IDENTIFIER}`;\n dataFetchKey = `${name}/${DATA_FETCH_IDENTIFIER}`;\n } else {\n return;\n }\n if (!dataFetchName || !dataFetchId || !dataFetchKey) {\n return;\n }\n if (!remoteSnapshot.modules.find(\n (module) => module.moduleName === dataFetchName\n )) {\n return;\n }\n return {\n dataFetchName,\n dataFetchId,\n dataFetchKey\n };\n};\nfunction initDataFetchMap() {\n globalThis.__MF_DATA_FETCH_MAP__ || (globalThis.__MF_DATA_FETCH_MAP__ = {});\n}\nfunction getDataFetchItem(id) {\n var _a;\n return (_a = globalThis.__MF_DATA_FETCH_MAP__) == null ? void 0 : _a[id];\n}\nfunction getDataFetchMap() {\n return globalThis.__MF_DATA_FETCH_MAP__;\n}\nfunction getDataFetchCache() {\n return globalThis.__MF_DATA_FETCH_CACHE__;\n}\nconst flushDataFetch = () => {\n globalThis.__MF_DATA_FETCH_MAP__ = {};\n globalThis[DOWNGRADE_KEY] = void 0;\n clearStore();\n};\nfunction setDataFetchItemLoadedStatus(id) {\n const dataFetchItem = getDataFetchItem(id);\n if (!dataFetchItem) {\n return;\n }\n dataFetchItem[2] = MF_DATA_FETCH_STATUS.LOADED;\n}\nconst wrapDataFetchId = (id) => {\n return `${WRAP_DATA_FETCH_ID_IDENTIFIER}${id}${WRAP_DATA_FETCH_ID_IDENTIFIER}`;\n};\nconst getDataFetchIdWithErrorMsgs = (errMsgs) => {\n const firstIdentifierIndex = errMsgs.indexOf(WRAP_DATA_FETCH_ID_IDENTIFIER);\n if (firstIdentifierIndex === -1) {\n return void 0;\n }\n const secondIdentifierIndex = errMsgs.indexOf(\n WRAP_DATA_FETCH_ID_IDENTIFIER,\n firstIdentifierIndex + WRAP_DATA_FETCH_ID_IDENTIFIER.length\n );\n if (secondIdentifierIndex === -1) {\n return void 0;\n }\n return errMsgs.substring(\n firstIdentifierIndex + WRAP_DATA_FETCH_ID_IDENTIFIER.length,\n secondIdentifierIndex\n );\n};\nasync function fetchData(id, params, remoteInfo) {\n var _a;\n const callFetchData = async () => {\n const item = getDataFetchItem(id);\n if (!item) {\n return;\n }\n const [fetchDataFnArr, ..._rest] = item;\n const fetchDataFn = await fetchDataFnArr[2];\n if (!fetchDataFn) {\n return;\n }\n return fetchDataFn({\n ...params,\n _id: id\n });\n };\n if (isBrowserEnvValue) {\n const dataFetchItem = getDataFetchItem(id);\n if (!dataFetchItem) {\n throw new Error(`dataFetchItem not found, id: ${id}`);\n }\n if ((_a = dataFetchItem[1]) == null ? void 0 : _a[0]) {\n return dataFetchItem[1][0];\n }\n if (isCSROnly()) {\n logger.debug(\"==========csr only!\");\n return callFetchData();\n }\n if (remoteInfo) {\n return callDowngrade(id, params, remoteInfo);\n }\n const mfDowngrade = getDowngradeTag();\n if (mfDowngrade && (typeof mfDowngrade === \"boolean\" || mfDowngrade.includes(id))) {\n return callDowngrade(id, { ...params, isDowngrade: true });\n }\n let res;\n let rej;\n const p = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n dataFetchItem[1] = [p, res, rej];\n dataFetchItem[2] = MF_DATA_FETCH_STATUS.AWAIT;\n return dataFetchItem[1][0];\n }\n return callFetchData();\n}\nfunction getDataFetchMapKey(dataFetchInfo, hostInfo) {\n if (!dataFetchInfo || !hostInfo) {\n return;\n }\n const { dataFetchKey } = dataFetchInfo;\n return composeKeyWithSeparator(dataFetchKey, hostInfo.name, hostInfo.version);\n}\nasync function loadDataFetchModule(instance, id) {\n return instance.loadRemote(id).then((m) => {\n if (m && typeof m === \"object\" && \"fetchData\" in m && typeof m.fetchData === \"function\") {\n return m.fetchData;\n }\n throw new Error(\n `fetchData not found in remote ${id}, ${JSON.stringify(m)}`\n );\n });\n}\nfunction isDataLoaderExpose(exposeKey) {\n return exposeKey.endsWith(DATA_FETCH_IDENTIFIER) || exposeKey.endsWith(DATA_FETCH_CLIENT_SUFFIX);\n}\nfunction getDowngradeTag() {\n return globalThis[DOWNGRADE_KEY];\n}\nfunction callAllDowngrade() {\n const dataFetchMap = getDataFetchMap();\n if (!dataFetchMap) {\n return;\n }\n Object.keys(dataFetchMap).forEach((key) => {\n callDowngrade(key);\n });\n}\nasync function callDowngrade(id, params, remoteInfo) {\n const dataFetchMap = getDataFetchMap();\n if (!dataFetchMap) {\n return;\n }\n const mfDataFetch = dataFetchMap[id];\n if ((mfDataFetch == null ? void 0 : mfDataFetch[2]) === MF_DATA_FETCH_STATUS.AWAIT) {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADING;\n let promise;\n let res;\n let rej;\n if (mfDataFetch[1]) {\n promise = mfDataFetch[1][0];\n res = mfDataFetch[1][1];\n rej = mfDataFetch[1][2];\n } else {\n promise = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n mfDataFetch[1] = [promise, res, rej];\n }\n const dataFetchType = mfDataFetch[0][1];\n if (dataFetchType === MF_DATA_FETCH_TYPE.FETCH_CLIENT) {\n try {\n mfDataFetch[0][0]().then(async (getDataFetchFn) => {\n return getDataFetchFn({\n ...params,\n isDowngrade: true,\n _id: id\n }).then((data) => {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADED;\n res && res(data);\n });\n });\n } catch (e) {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.ERROR;\n rej && rej(e);\n }\n } else if (dataFetchType === MF_DATA_FETCH_TYPE.FETCH_SERVER) {\n try {\n const currentUrl = new URL(window.location.href);\n currentUrl.searchParams.set(DATA_FETCH_QUERY, encodeURIComponent(id));\n if (params) {\n currentUrl.searchParams.set(\n \"params\",\n encodeURIComponent(JSON.stringify(params))\n );\n }\n if (remoteInfo) {\n currentUrl.searchParams.set(\n \"remoteInfo\",\n encodeURIComponent(JSON.stringify(remoteInfo))\n );\n }\n const fetchServerQuery = globalThis.FEDERATION_SERVER_QUERY;\n if (fetchServerQuery && typeof fetchServerQuery === \"object\") {\n Object.keys(fetchServerQuery).forEach((key) => {\n currentUrl.searchParams.set(\n key,\n JSON.stringify(fetchServerQuery[key])\n );\n });\n }\n const fetchUrl = currentUrl.toString();\n const data = await fetch(fetchUrl).then((res2) => res2.json());\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADED;\n res && res(data);\n } catch (e) {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.ERROR;\n rej && rej(e);\n }\n }\n return promise;\n }\n}\nfunction isCSROnly() {\n return window._SSR_DATA === void 0;\n}\nfunction isServerEnv() {\n return typeof window === \"undefined\";\n}\nfunction setSSREnv({\n fetchServerQuery\n}) {\n globalThis.FEDERATION_SSR = true;\n globalThis.FEDERATION_SERVER_QUERY = fetchServerQuery;\n}\nfunction getLoadedRemoteInfos(id, instance) {\n if (!instance) {\n return;\n }\n const { name, expose } = instance.remoteHandler.idToRemoteMap[id] || {};\n if (!name) {\n return;\n }\n const module = instance.moduleCache.get(name);\n if (!module) {\n return;\n }\n const { remoteSnapshot } = instance.snapshotHandler.getGlobalRemoteInfo(\n module.remoteInfo\n );\n return {\n ...module.remoteInfo,\n snapshot: remoteSnapshot,\n expose\n };\n}\nexport {\n setDataFetchItemLoadedStatus as A,\n warn as B,\n CacheSize as C,\n DATA_FETCH_QUERY as D,\n ERROR_TYPE as E,\n FS_HREF as F,\n DOWNGRADE_KEY as G,\n callAllDowngrade as H,\n callDowngrade as I,\n getDowngradeTag as J,\n composeKeyWithSeparator as K,\n LOAD_REMOTE_ERROR_PREFIX as L,\n MF_DATA_FETCH_STATUS as M,\n safeToString as N,\n getDataFetchCache as O,\n CacheTime as a,\n clearStore as b,\n cache as c,\n configureCache as d,\n getDataFetchMap as e,\n flushDataFetch as f,\n generateKey as g,\n fetchData as h,\n initDataFetchMap as i,\n loadDataFetchModule as j,\n isDataLoaderExpose as k,\n logger as l,\n getDataFetchInfo as m,\n getDataFetchMapKey as n,\n getDataFetchItem as o,\n DATA_FETCH_CLIENT_SUFFIX as p,\n MF_DATA_FETCH_TYPE as q,\n revalidateTag as r,\n setSSREnv as s,\n isCSROnly as t,\n isServerEnv as u,\n getDataFetchIdWithErrorMsgs as v,\n DATA_FETCH_ERROR_PREFIX as w,\n wrapDataFetchId as x,\n DATA_FETCH_FUNCTION as y,\n getLoadedRemoteInfos as z\n};\n"
|
|
199
|
-
};
|
|
200
|
-
const ENTRY_FILE = 'entry.ts';
|
|
201
|
-
const APP_FILE = 'app.tsx';
|
|
202
|
-
const BRIDGE_ROOT = 'bridge';
|
|
203
|
-
const BRIDGE_INDEX_FILE = `${BRIDGE_ROOT}/index.es.js`;
|
|
204
|
-
const BRIDGE_ROUTER_STUB_FILE = `${BRIDGE_ROOT}/react-router-dom-stub.js`;
|
|
205
|
-
const BRIDGE_ROUTER_STUB_SOURCE = `export function useLocation() {
|
|
50
|
+
(()=>{
|
|
51
|
+
__webpack_require__.r(__webpack_exports__);
|
|
52
|
+
__webpack_require__.d(__webpack_exports__, {
|
|
53
|
+
ModuleFederationPlayground: ()=>App,
|
|
54
|
+
default: ()=>App
|
|
55
|
+
});
|
|
56
|
+
const App_module = {
|
|
57
|
+
"vp-root": "vp-root-o94tBV",
|
|
58
|
+
vpRoot: "vp-root-o94tBV",
|
|
59
|
+
"vp-main": "vp-main-ukILls",
|
|
60
|
+
vpMain: "vp-main-ukILls",
|
|
61
|
+
"vp-left": "vp-left-wWIJZj",
|
|
62
|
+
vpLeft: "vp-left-wWIJZj",
|
|
63
|
+
"vp-splitter": "vp-splitter-C3LUiw",
|
|
64
|
+
vpSplitter: "vp-splitter-C3LUiw",
|
|
65
|
+
"vp-card": "vp-card-OxIN8P",
|
|
66
|
+
vpCard: "vp-card-OxIN8P",
|
|
67
|
+
"vp-cardHeader": "vp-cardHeader-yl8bmF",
|
|
68
|
+
vpCardHeader: "vp-cardHeader-yl8bmF",
|
|
69
|
+
"vp-cardTitle": "vp-cardTitle-iRjbB2",
|
|
70
|
+
vpCardTitle: "vp-cardTitle-iRjbB2",
|
|
71
|
+
"vp-editorTabs": "vp-editorTabs-P8EPHu",
|
|
72
|
+
vpEditorTabs: "vp-editorTabs-P8EPHu",
|
|
73
|
+
"vp-editorTab": "vp-editorTab-en3Nbi",
|
|
74
|
+
vpEditorTab: "vp-editorTab-en3Nbi",
|
|
75
|
+
"vp-editorTabActive": "vp-editorTabActive-j1OAlc",
|
|
76
|
+
vpEditorTabActive: "vp-editorTabActive-j1OAlc",
|
|
77
|
+
"vp-cardBody": "vp-cardBody-UdVf2N",
|
|
78
|
+
vpCardBody: "vp-cardBody-UdVf2N",
|
|
79
|
+
"vp-paneActions": "vp-paneActions-l5K74Q",
|
|
80
|
+
vpPaneActions: "vp-paneActions-l5K74Q",
|
|
81
|
+
"vp-collapse": "vp-collapse-VViOM4",
|
|
82
|
+
vpCollapse: "vp-collapse-VViOM4",
|
|
83
|
+
"vp-collapseItem": "vp-collapseItem-MtDnlb",
|
|
84
|
+
vpCollapseItem: "vp-collapseItem-MtDnlb",
|
|
85
|
+
"vp-collapseHeader": "vp-collapseHeader-Y1drUL",
|
|
86
|
+
vpCollapseHeader: "vp-collapseHeader-Y1drUL",
|
|
87
|
+
"vp-collapseHeaderActive": "vp-collapseHeaderActive-d5oo1z",
|
|
88
|
+
vpCollapseHeaderActive: "vp-collapseHeaderActive-d5oo1z",
|
|
89
|
+
"vp-collapseLabel": "vp-collapseLabel-SYefMk",
|
|
90
|
+
vpCollapseLabel: "vp-collapseLabel-SYefMk",
|
|
91
|
+
"vp-collapseArrow": "vp-collapseArrow-s7319m",
|
|
92
|
+
vpCollapseArrow: "vp-collapseArrow-s7319m",
|
|
93
|
+
"vp-collapseArrowOpen": "vp-collapseArrowOpen-NQp4Jq",
|
|
94
|
+
vpCollapseArrowOpen: "vp-collapseArrowOpen-NQp4Jq",
|
|
95
|
+
"vp-collapseBody": "vp-collapseBody-ig7Trn",
|
|
96
|
+
vpCollapseBody: "vp-collapseBody-ig7Trn",
|
|
97
|
+
"vp-collapseBodyCode": "vp-collapseBodyCode-ACBnWh",
|
|
98
|
+
vpCollapseBodyCode: "vp-collapseBodyCode-ACBnWh",
|
|
99
|
+
"vp-form": "vp-form-pITn1W",
|
|
100
|
+
vpForm: "vp-form-pITn1W",
|
|
101
|
+
"vp-fieldGrid": "vp-fieldGrid-SR9eJh",
|
|
102
|
+
vpFieldGrid: "vp-fieldGrid-SR9eJh",
|
|
103
|
+
"vp-field": "vp-field-NzMT8s",
|
|
104
|
+
vpField: "vp-field-NzMT8s",
|
|
105
|
+
"vp-labelRow": "vp-labelRow-DlcEeA",
|
|
106
|
+
vpLabelRow: "vp-labelRow-DlcEeA",
|
|
107
|
+
"vp-label": "vp-label-KGpsbl",
|
|
108
|
+
vpLabel: "vp-label-KGpsbl",
|
|
109
|
+
"vp-hint": "vp-hint-fYzOU2",
|
|
110
|
+
vpHint: "vp-hint-fYzOU2",
|
|
111
|
+
"vp-input": "vp-input-UHKU2F",
|
|
112
|
+
vpInput: "vp-input-UHKU2F",
|
|
113
|
+
"vp-select": "vp-select-Tk6IhF",
|
|
114
|
+
vpSelect: "vp-select-Tk6IhF",
|
|
115
|
+
"vp-codeEditor": "vp-codeEditor-bXbNn1",
|
|
116
|
+
vpCodeEditor: "vp-codeEditor-bXbNn1",
|
|
117
|
+
"vp-editorToolbar": "vp-editorToolbar-SVglCq",
|
|
118
|
+
vpEditorToolbar: "vp-editorToolbar-SVglCq",
|
|
119
|
+
"vp-loadingSimple": "vp-loadingSimple-t3py2h",
|
|
120
|
+
vpLoadingSimple: "vp-loadingSimple-t3py2h",
|
|
121
|
+
"vp-loadingSpinner": "vp-loadingSpinner-YRww21",
|
|
122
|
+
vpLoadingSpinner: "vp-loadingSpinner-YRww21",
|
|
123
|
+
"vp-spin": "vp-spin-vqXwPJ",
|
|
124
|
+
vpSpin: "vp-spin-vqXwPJ",
|
|
125
|
+
"vp-previewFrame": "vp-previewFrame-K_cT99",
|
|
126
|
+
vpPreviewFrame: "vp-previewFrame-K_cT99",
|
|
127
|
+
"vp-actions": "vp-actions-kW_pM2",
|
|
128
|
+
vpActions: "vp-actions-kW_pM2",
|
|
129
|
+
"vp-button": "vp-button-jQtwaB",
|
|
130
|
+
vpButton: "vp-button-jQtwaB",
|
|
131
|
+
"vp-buttonGhost": "vp-buttonGhost-wKOfIf",
|
|
132
|
+
vpButtonGhost: "vp-buttonGhost-wKOfIf",
|
|
133
|
+
"vp-buttonPrimary": "vp-buttonPrimary-SYnJ9I",
|
|
134
|
+
vpButtonPrimary: "vp-buttonPrimary-SYnJ9I",
|
|
135
|
+
vpShimmer: "vpShimmer-XeNYGG",
|
|
136
|
+
"vp-codeBlock": "vp-codeBlock-CMSobd",
|
|
137
|
+
vpCodeBlock: "vp-codeBlock-CMSobd",
|
|
138
|
+
"vp-emptyTitle": "vp-emptyTitle-LUdxhN",
|
|
139
|
+
vpEmptyTitle: "vp-emptyTitle-LUdxhN",
|
|
140
|
+
"vp-copyBtn": "vp-copyBtn-rEbuE6",
|
|
141
|
+
vpCopyBtn: "vp-copyBtn-rEbuE6",
|
|
142
|
+
"vp-copyIcon": "vp-copyIcon-C8ndDr",
|
|
143
|
+
vpCopyIcon: "vp-copyIcon-C8ndDr",
|
|
144
|
+
"vp-right": "vp-right-Pdn7k6",
|
|
145
|
+
vpRight: "vp-right-Pdn7k6",
|
|
146
|
+
"vp-ide": "vp-ide-MCK1rq",
|
|
147
|
+
vpIde: "vp-ide-MCK1rq",
|
|
148
|
+
"vp-ideTitlebar": "vp-ideTitlebar-xV_SLu",
|
|
149
|
+
vpIdeTitlebar: "vp-ideTitlebar-xV_SLu",
|
|
150
|
+
"vp-ideDots": "vp-ideDots-rmPPqM",
|
|
151
|
+
vpIdeDots: "vp-ideDots-rmPPqM",
|
|
152
|
+
"vp-dot": "vp-dot-QAY3S7",
|
|
153
|
+
vpDot: "vp-dot-QAY3S7",
|
|
154
|
+
"vp-dotRed": "vp-dotRed-qBSHb4",
|
|
155
|
+
vpDotRed: "vp-dotRed-qBSHb4",
|
|
156
|
+
"vp-dotYellow": "vp-dotYellow-JiMbQd",
|
|
157
|
+
vpDotYellow: "vp-dotYellow-JiMbQd",
|
|
158
|
+
"vp-dotGreen": "vp-dotGreen-p1oJVa",
|
|
159
|
+
vpDotGreen: "vp-dotGreen-p1oJVa",
|
|
160
|
+
"vp-ideTitle": "vp-ideTitle-pyBOAZ",
|
|
161
|
+
vpIdeTitle: "vp-ideTitle-pyBOAZ",
|
|
162
|
+
"vp-ideMeta": "vp-ideMeta-IwLWqJ",
|
|
163
|
+
vpIdeMeta: "vp-ideMeta-IwLWqJ",
|
|
164
|
+
"vp-ideMetaText": "vp-ideMetaText-hM7Yjo",
|
|
165
|
+
vpIdeMetaText: "vp-ideMetaText-hM7Yjo",
|
|
166
|
+
"vp-ideStatus": "vp-ideStatus-CNZYH6",
|
|
167
|
+
vpIdeStatus: "vp-ideStatus-CNZYH6",
|
|
168
|
+
"vp-ideBody": "vp-ideBody-iRMqXK",
|
|
169
|
+
vpIdeBody: "vp-ideBody-iRMqXK",
|
|
170
|
+
"vp-empty": "vp-empty-WMX1Vp",
|
|
171
|
+
vpEmpty: "vp-empty-WMX1Vp",
|
|
172
|
+
"vp-kv": "vp-kv-HhceUA",
|
|
173
|
+
vpKv: "vp-kv-HhceUA",
|
|
174
|
+
"vp-renderArea": "vp-renderArea-UsEDCB",
|
|
175
|
+
vpRenderArea: "vp-renderArea-UsEDCB",
|
|
176
|
+
"vp-terminal": "vp-terminal-F6_CEQ",
|
|
177
|
+
vpTerminal: "vp-terminal-F6_CEQ",
|
|
178
|
+
"vp-terminalHeader": "vp-terminalHeader-BG3x8z",
|
|
179
|
+
vpTerminalHeader: "vp-terminalHeader-BG3x8z",
|
|
180
|
+
"vp-terminalClear": "vp-terminalClear-N0wY3l",
|
|
181
|
+
vpTerminalClear: "vp-terminalClear-N0wY3l",
|
|
182
|
+
"vp-terminalBody": "vp-terminalBody-Fn12Co",
|
|
183
|
+
vpTerminalBody: "vp-terminalBody-Fn12Co",
|
|
184
|
+
"vp-terminalLine": "vp-terminalLine-V8_M04",
|
|
185
|
+
vpTerminalLine: "vp-terminalLine-V8_M04",
|
|
186
|
+
"vp-terminalLineError": "vp-terminalLineError-puKD3j",
|
|
187
|
+
vpTerminalLineError: "vp-terminalLineError-puKD3j",
|
|
188
|
+
"vp-terminalLineWarn": "vp-terminalLineWarn-BIZDl_",
|
|
189
|
+
vpTerminalLineWarn: "vp-terminalLineWarn-BIZDl_",
|
|
190
|
+
"vp-terminalEmpty": "vp-terminalEmpty-pYP34A",
|
|
191
|
+
vpTerminalEmpty: "vp-terminalEmpty-pYP34A",
|
|
192
|
+
"vp-errorPanel": "vp-errorPanel-zDWm6k",
|
|
193
|
+
vpErrorPanel: "vp-errorPanel-zDWm6k",
|
|
194
|
+
"vp-errorTitle": "vp-errorTitle-ykARVb",
|
|
195
|
+
vpErrorTitle: "vp-errorTitle-ykARVb"
|
|
196
|
+
};
|
|
197
|
+
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
|
|
198
|
+
const react_namespaceObject = require("@monaco-editor/react");
|
|
199
|
+
var react_default = /*#__PURE__*/ __webpack_require__.n(react_namespaceObject);
|
|
200
|
+
const external_react_namespaceObject = require("react");
|
|
201
|
+
const external_react_dom_namespaceObject = require("react-dom");
|
|
202
|
+
const client_namespaceObject = require("react-dom/client");
|
|
203
|
+
const BRIDGE_RUNTIME_FILES = {
|
|
204
|
+
"bridge-base-CHnL6Q9P.mjs": "var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nimport * as React from \"react\";\nimport { L as LoggerInstance, R as RouterContext } from \"./index-Bs2NxD2z.mjs\";\nimport { federationRuntime } from \"./plugin.es.js\";\nconst initialState = { didCatch: false, error: null };\nclass ErrorBoundary extends React.Component {\n constructor() {\n super(...arguments);\n __publicField(this, \"state\", initialState);\n __publicField(this, \"resetErrorBoundary\", (..._args) => {\n if (this.state.didCatch) {\n this.setState(initialState);\n }\n });\n }\n static getDerivedStateFromError(error) {\n return { didCatch: true, error };\n }\n render() {\n if (this.state.didCatch) {\n return /* @__PURE__ */ React.createElement(\n this.props.FallbackComponent,\n {\n error: this.state.error,\n resetErrorBoundary: this.resetErrorBoundary\n }\n );\n }\n return this.props.children;\n }\n}\nfunction createBaseBridgeComponent({\n createRoot,\n defaultRootOptions,\n ...bridgeInfo\n}) {\n return () => {\n const rootMap = /* @__PURE__ */ new Map();\n const instance = federationRuntime.instance;\n LoggerInstance.debug(\n `createBridgeComponent instance from props >>>`,\n instance\n );\n const RawComponent = (info) => {\n const { appInfo, propsInfo, ...restProps } = info;\n const { moduleName, memoryRoute, basename = \"/\" } = appInfo;\n return /* @__PURE__ */ React.createElement(RouterContext.Provider, { value: { moduleName, basename, memoryRoute } }, /* @__PURE__ */ React.createElement(\n bridgeInfo.rootComponent,\n {\n ...propsInfo,\n basename,\n ...restProps\n }\n ));\n };\n const DefaultFallback = ({ error }) => /* @__PURE__ */ React.createElement(\"div\", { role: \"alert\" }, /* @__PURE__ */ React.createElement(\"p\", null, \"Something went wrong:\"), /* @__PURE__ */ React.createElement(\"pre\", { style: { color: \"red\" } }, error instanceof Error ? error.message : String(error)));\n const omitHostFallback = (props) => {\n const nextProps = { ...props };\n delete nextProps.fallback;\n return nextProps;\n };\n const BridgeWrapper = ({\n basename,\n moduleName,\n memoryRoute,\n propsInfo\n }) => /* @__PURE__ */ React.createElement(ErrorBoundary, { FallbackComponent: DefaultFallback }, /* @__PURE__ */ React.createElement(\n RawComponent,\n {\n appInfo: {\n moduleName,\n basename,\n memoryRoute\n },\n propsInfo\n }\n ));\n return {\n async render(info) {\n var _a, _b, _c, _d, _e, _f;\n LoggerInstance.debug(`createBridgeComponent render Info`, info);\n const {\n moduleName,\n dom,\n basename,\n memoryRoute,\n rootOptions,\n ...propsInfo\n } = info;\n const operationContext = {\n side: \"producer\",\n framework: \"react\",\n operation: rootMap.has(dom) ? \"update\" : \"render\",\n reason: \"direct\"\n };\n const mergedRootOptions = {\n ...defaultRootOptions,\n ...rootOptions\n };\n 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(\n info,\n operationContext\n )) || {};\n const rootComponentWithErrorBoundary = /* @__PURE__ */ React.createElement(\n BridgeWrapper,\n {\n basename,\n moduleName,\n memoryRoute,\n propsInfo: {\n ...omitHostFallback(propsInfo),\n basename,\n ...beforeBridgeRenderRes == null ? void 0 : beforeBridgeRenderRes.extraProps\n }\n }\n );\n if (bridgeInfo.render) {\n const root = await Promise.resolve(\n bridgeInfo.render(rootComponentWithErrorBoundary, dom)\n );\n rootMap.set(dom, root);\n } else {\n let root = rootMap.get(dom);\n if (!root && createRoot) {\n root = createRoot(dom, mergedRootOptions);\n rootMap.set(dom, root);\n }\n if (root && \"render\" in root) {\n root.render(rootComponentWithErrorBoundary);\n }\n }\n ((_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, {\n context: operationContext\n })) || {};\n },\n destroy(info) {\n var _a, _b, _c, _d, _e, _f;\n const { dom } = info;\n LoggerInstance.debug(`createBridgeComponent destroy Info`, info);\n const root = rootMap.get(dom);\n const operationContext = {\n side: \"producer\",\n framework: \"react\",\n operation: \"destroy\",\n reason: \"direct\"\n };\n (_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.beforeBridgeDestroy) == null ? void 0 : _c.emit(\n info,\n operationContext\n );\n if (root) {\n if (\"unmount\" in root) {\n root.unmount();\n } else {\n LoggerInstance.warn(\"Root does not have unmount method\");\n }\n rootMap.delete(dom);\n }\n (_f = (_e = (_d = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeDestroy) == null ? void 0 : _f.emit(info, {\n context: operationContext\n });\n }\n };\n };\n}\nexport {\n ErrorBoundary as E,\n createBaseBridgeComponent as c\n};\n",
|
|
205
|
+
"createHelpers-D3Sg5lKp.mjs": "import { c as createBaseBridgeComponent, E as ErrorBoundary } from \"./bridge-base-CHnL6Q9P.mjs\";\nimport ReactDOM from \"react-dom\";\nimport { L as LoggerInstance, g as getRootDomDefaultClassName } from \"./index-Bs2NxD2z.mjs\";\nimport React__default, { forwardRef, useRef, useState, useEffect } from \"react\";\nimport { federationRuntime } from \"./plugin.es.js\";\nfunction createReact16Or17Root(container) {\n return {\n render(children) {\n const reactVersion = ReactDOM.version || \"\";\n const isReact18 = reactVersion.startsWith(\"18\");\n const isReact19 = reactVersion.startsWith(\"19\");\n if (isReact19) {\n throw new Error(\n `React 19 detected in legacy mode. This is not supported. Please use the version-specific import: import { createBridgeComponent } from '@module-federation/bridge-react/v19'`\n );\n }\n if (isReact18) {\n LoggerInstance.warn(\n `[Bridge-React] React 18 detected in legacy mode. For better compatibility, please use the version-specific import: import { createBridgeComponent } from '@module-federation/bridge-react/v18'`\n );\n }\n ReactDOM.render(children, container);\n },\n unmount() {\n ReactDOM.unmountComponentAtNode(container);\n }\n };\n}\nfunction createBridgeComponent(bridgeInfo) {\n const fullBridgeInfo = {\n createRoot: createReact16Or17Root,\n ...bridgeInfo\n };\n return createBaseBridgeComponent(fullBridgeInfo);\n}\nconst RemoteAppWrapper = forwardRef(function(props, ref) {\n const {\n moduleName,\n memoryRoute,\n basename,\n providerInfo,\n className,\n style,\n fallback,\n loading,\n ...resProps\n } = props;\n const instance = federationRuntime.instance;\n const rootRef = ref && \"current\" in ref ? ref : useRef(null);\n const renderDom = useRef(null);\n const providerInfoRef = useRef(null);\n const [initialized, setInitialized] = useState(false);\n LoggerInstance.debug(`RemoteAppWrapper instance from props >>>`, instance);\n useEffect(() => {\n if (initialized) return;\n const providerReturn = providerInfo();\n providerInfoRef.current = providerReturn;\n setInitialized(true);\n return () => {\n var _a, _b, _c, _d, _e, _f, _g;\n if ((_a = providerInfoRef.current) == null ? void 0 : _a.destroy) {\n LoggerInstance.debug(\n `createRemoteAppComponent LazyComponent destroy >>>`,\n { moduleName, basename, dom: renderDom.current }\n );\n const destroyInfo = {\n moduleName,\n dom: renderDom.current,\n basename,\n memoryRoute,\n fallback,\n ...resProps\n };\n const operationContext = {\n side: \"consumer\",\n framework: \"react\",\n operation: \"destroy\",\n reason: \"unmount\"\n };\n (_d = (_c = (_b = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _b.lifecycle) == null ? void 0 : _c.beforeBridgeDestroy) == null ? void 0 : _d.emit(\n destroyInfo,\n operationContext\n );\n providerInfoRef.current.destroy({\n moduleName,\n dom: renderDom.current\n });\n (_g = (_f = (_e = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _e.lifecycle) == null ? void 0 : _f.afterBridgeDestroy) == null ? void 0 : _g.emit(destroyInfo, {\n context: operationContext\n });\n }\n };\n }, [moduleName]);\n useEffect(() => {\n var _a, _b, _c, _d, _e, _f;\n if (!initialized || !providerInfoRef.current) return;\n let renderProps = {\n moduleName,\n dom: rootRef.current,\n basename,\n memoryRoute,\n fallback,\n ...resProps\n };\n renderDom.current = rootRef.current;\n const operationContext = {\n side: \"consumer\",\n framework: \"react\",\n operation: \"render\"\n };\n 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(\n renderProps,\n operationContext\n )) || {};\n renderProps = { ...renderProps, ...beforeBridgeRenderRes.extraProps };\n providerInfoRef.current.render(renderProps);\n (_f = (_e = (_d = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeRender) == null ? void 0 : _f.emit(renderProps, {\n context: operationContext\n });\n }, [initialized, ...Object.values(props)]);\n const rootComponentClassName = `${getRootDomDefaultClassName(moduleName)} ${className || \"\"}`;\n return /* @__PURE__ */ React__default.createElement(\"div\", { className: rootComponentClassName, style, ref: rootRef }, loading);\n});\nfunction createLazyRemoteComponentFactory(RemoteApp) {\n return function createLazyRemoteComponent(info) {\n const exportName = (info == null ? void 0 : info.export) || \"default\";\n return React__default.lazy(async () => {\n LoggerInstance.debug(\n `createRemoteAppComponent LazyComponent create >>>`,\n {\n lazyComponent: info.loader,\n exportName\n }\n );\n try {\n const m = await info.loader();\n const moduleName = m && m[Symbol.for(\"mf_module_id\")];\n LoggerInstance.debug(\n `createRemoteAppComponent LazyComponent loadRemote info >>>`,\n { name: moduleName, module: m, exportName }\n );\n const exportFn = m[exportName];\n if (exportName in m && typeof exportFn === \"function\") {\n const RemoteAppComponent = forwardRef((props, ref) => {\n return /* @__PURE__ */ React__default.createElement(\n RemoteApp,\n {\n moduleName,\n providerInfo: exportFn,\n exportName: info.export || \"default\",\n fallback: info.fallback,\n loading: info.loading,\n ref,\n ...props\n }\n );\n });\n return {\n default: RemoteAppComponent\n };\n } else {\n LoggerInstance.debug(\n `createRemoteAppComponent LazyComponent module not found >>>`,\n { name: moduleName, module: m, exportName }\n );\n throw Error(\n `Make sure that ${moduleName} has the correct export when export is ${String(\n exportName\n )}`\n );\n }\n } catch (error) {\n throw error;\n }\n });\n };\n}\nfunction createRemoteAppComponentFactory(RemoteApp) {\n const createLazyRemoteComponent = createLazyRemoteComponentFactory(RemoteApp);\n return function createRemoteAppComponent(info) {\n const LazyComponent = createLazyRemoteComponent(info);\n return forwardRef((props, ref) => {\n return /* @__PURE__ */ React__default.createElement(\n ErrorBoundary,\n {\n FallbackComponent: info.fallback\n },\n /* @__PURE__ */ React__default.createElement(React__default.Suspense, { fallback: info.loading }, /* @__PURE__ */ React__default.createElement(LazyComponent, { ...props, ref }))\n );\n });\n };\n}\nfunction createDeprecatedRemoteComponentFactory(createFn) {\n return function createRemoteComponent(info) {\n LoggerInstance.warn(\n `createRemoteComponent is deprecated, please use createRemoteAppComponent instead!`\n );\n return createFn(info);\n };\n}\nexport {\n RemoteAppWrapper as R,\n createDeprecatedRemoteComponentFactory as a,\n createBridgeComponent as b,\n createRemoteAppComponentFactory as c\n};\n",
|
|
206
|
+
"data-fetch-utils.es.js": "import { y as DATA_FETCH_FUNCTION } from \"./utils-BBP3hEeV.mjs\";\nimport { C, a, c, b, d, g, r } from \"./utils-BBP3hEeV.mjs\";\nimport { d as dataFetchFunction } from \"./prefetch-TKq_EK_q.mjs\";\nimport { i, p } from \"./prefetch-TKq_EK_q.mjs\";\nasync function callDataFetch() {\n const dataFetch = globalThis[DATA_FETCH_FUNCTION];\n if (dataFetch) {\n await Promise.all(\n dataFetch.map(async (options) => {\n await dataFetchFunction(options);\n })\n );\n }\n}\nexport {\n C as CacheSize,\n a as CacheTime,\n c as cache,\n callDataFetch,\n b as clearStore,\n d as configureCache,\n g as generateKey,\n i as injectDataFetch,\n p as prefetch,\n r as revalidateTag\n};\n",
|
|
207
|
+
"index-Bs2NxD2z.mjs": "import React__default from \"react\";\nimport { c as createLogger } from \"./logger-DwWkXsWl.mjs\";\nconst RouterContext = React__default.createContext(null);\nconst LoggerInstance = createLogger(\n \"[ Module Federation Bridge React ]\"\n);\nfunction pathJoin(...args) {\n const res = args.reduce((res2, path) => {\n let nPath = path;\n if (!nPath || typeof nPath !== \"string\") {\n return res2;\n }\n if (nPath[0] !== \"/\") {\n nPath = `/${nPath}`;\n }\n const lastIndex = nPath.length - 1;\n if (nPath[lastIndex] === \"/\") {\n nPath = nPath.substring(0, lastIndex);\n }\n return res2 + nPath;\n }, \"\");\n return res || \"/\";\n}\nconst getModuleName = (id) => {\n if (!id) {\n return id;\n }\n const idArray = id.split(\"/\");\n if (idArray.length < 2) {\n return id;\n }\n return idArray[0] + \"/\" + idArray[1];\n};\nconst getRootDomDefaultClassName = (moduleName) => {\n if (!moduleName) {\n return \"\";\n }\n const name = getModuleName(moduleName).replace(/\\@/, \"\").replace(/\\//, \"-\");\n return `bridge-root-component-${name}`;\n};\nexport {\n LoggerInstance as L,\n RouterContext as R,\n getRootDomDefaultClassName as g,\n pathJoin as p\n};\n",
|
|
208
|
+
"index.es.js": "import { R as RemoteAppWrapper, c as createRemoteAppComponentFactory, a as createDeprecatedRemoteComponentFactory } from \"./createHelpers-D3Sg5lKp.mjs\";\nimport { b } from \"./createHelpers-D3Sg5lKp.mjs\";\nimport { a, c, b as b2, l } from \"./lazy-load-component-plugin-NZphPG7_.mjs\";\nimport { C, a as a2, E, c as c2, b as b3, d, g, r, s } from \"./utils-BBP3hEeV.mjs\";\nimport { callDataFetch } from \"./data-fetch-utils.es.js\";\nimport React__default, { forwardRef, useContext, useState, useEffect } from \"react\";\nimport * as ReactRouterDOM from \"react-router-dom\";\nimport { p as pathJoin, L as LoggerInstance } from \"./index-Bs2NxD2z.mjs\";\nimport { federationRuntime } from \"./plugin.es.js\";\nimport { p } from \"./prefetch-TKq_EK_q.mjs\";\nfunction e() {\n const t = new PopStateEvent(\"popstate\", { state: window.history.state });\n window.dispatchEvent(t);\n}\nfunction withRouterData(WrappedComponent) {\n const Component = forwardRef(function(props, ref) {\n var _a;\n if (props == null ? void 0 : props.basename) {\n return /* @__PURE__ */ React__default.createElement(WrappedComponent, { ...props, basename: props.basename, ref });\n }\n let enableDispathPopstate = false;\n let routerContextVal;\n try {\n ReactRouterDOM.useLocation();\n enableDispathPopstate = true;\n } catch {\n enableDispathPopstate = false;\n }\n let basename = \"/\";\n if (!props.basename && enableDispathPopstate) {\n const ReactRouterDOMAny = ReactRouterDOM;\n const useRouteMatch = ReactRouterDOMAny[\"useRouteMatch\"];\n const useHistory = ReactRouterDOMAny[\"useHistory\"];\n const useHref = ReactRouterDOMAny[\"useHref\"];\n const UNSAFE_RouteContext = ReactRouterDOMAny[\"UNSAFE_RouteContext\"];\n if (UNSAFE_RouteContext) {\n if (useHref) {\n basename = useHref == null ? void 0 : useHref(\"/\");\n }\n routerContextVal = useContext(UNSAFE_RouteContext);\n if (routerContextVal && routerContextVal.matches && routerContextVal.matches.length > 0) {\n const matchIndex = routerContextVal.matches.length - 1;\n const pathnameBase = routerContextVal.matches[matchIndex].pathnameBase;\n basename = pathJoin(basename, pathnameBase || \"/\");\n }\n } else {\n const match = useRouteMatch == null ? void 0 : useRouteMatch();\n if (useHistory) {\n const history = useHistory == null ? void 0 : useHistory();\n basename = (_a = history == null ? void 0 : history.createHref) == null ? void 0 : _a.call(history, { pathname: \"/\" });\n }\n if (match) {\n basename = pathJoin(basename, (match == null ? void 0 : match.path) || \"/\");\n }\n }\n }\n LoggerInstance.debug(`createRemoteAppComponent withRouterData >>>`, {\n ...props,\n basename,\n routerContextVal,\n enableDispathPopstate\n });\n if (enableDispathPopstate) {\n const location = ReactRouterDOM.useLocation();\n const [pathname, setPathname] = useState(location.pathname);\n useEffect(() => {\n var _a2;\n if (pathname !== \"\" && pathname !== location.pathname) {\n LoggerInstance.debug(\n `createRemoteAppComponent dispatchPopstateEnv >>>`,\n {\n name: props.name,\n pathname: location.pathname\n }\n );\n const route = {\n action: \"host-to-remote\",\n mechanism: \"popstate\",\n from: pathname,\n to: location.pathname,\n basename\n };\n const operationContext = {\n side: \"consumer\",\n framework: \"react\",\n operation: \"route-sync\",\n moduleName: props.moduleName,\n route\n };\n e();\n (_a2 = federationRuntime.instance) == null ? void 0 : _a2.bridgeHook.lifecycle.afterBridgeRouteSync.emit(\n {\n context: operationContext\n }\n );\n }\n setPathname(location.pathname);\n }, [location]);\n }\n return /* @__PURE__ */ React__default.createElement(WrappedComponent, { ...props, basename, ref });\n });\n return forwardRef(function(props, ref) {\n return /* @__PURE__ */ React__default.createElement(Component, { ...props, ref });\n });\n}\nconst RemoteApp = withRouterData(RemoteAppWrapper);\nconst createRemoteAppComponent = createRemoteAppComponentFactory(RemoteApp);\nconst createRemoteComponent = createDeprecatedRemoteComponentFactory(\n createRemoteAppComponent\n);\nexport {\n C as CacheSize,\n a2 as CacheTime,\n E as ERROR_TYPE,\n a as autoFetchDataPlugin,\n c2 as cache,\n callDataFetch,\n b3 as clearStore,\n c as collectSSRAssets,\n d as configureCache,\n b as createBridgeComponent,\n b2 as createLazyComponent,\n createRemoteAppComponent,\n createRemoteComponent,\n g as generateKey,\n l as lazyLoadComponentPlugin,\n p as prefetch,\n r as revalidateTag,\n s as setSSREnv\n};\n",
|
|
209
|
+
"lazy-load-component-plugin-NZphPG7_.mjs": 'import { i as injectDataFetch, p as prefetch } from "./prefetch-TKq_EK_q.mjs";\nimport { i as initDataFetchMap, k as isDataLoaderExpose, m as getDataFetchInfo, n as getDataFetchMapKey, l as logger, o as getDataFetchItem, p as DATA_FETCH_CLIENT_SUFFIX, q as MF_DATA_FETCH_TYPE, t as isCSROnly, M as MF_DATA_FETCH_STATUS, j as loadDataFetchModule, e as getDataFetchMap, u as isServerEnv, v as getDataFetchIdWithErrorMsgs, w as DATA_FETCH_ERROR_PREFIX, E as ERROR_TYPE, x as wrapDataFetchId, L as LOAD_REMOTE_ERROR_PREFIX, y as DATA_FETCH_FUNCTION, z as getLoadedRemoteInfos, h as fetchData$1, A as setDataFetchItemLoadedStatus, F as FS_HREF } from "./utils-BBP3hEeV.mjs";\nimport React__default, { useRef, useState, useEffect, Suspense } from "react";\nconst autoFetchData = () => {\n initDataFetchMap();\n injectDataFetch();\n return {\n name: "auto-fetch-data-plugin",\n afterLoadSnapshot(args) {\n const { id, moduleInfo, remoteSnapshot, host } = args;\n if (typeof id === "string" && isDataLoaderExpose(id)) {\n return args;\n }\n if (!remoteSnapshot || !id || !("modules" in remoteSnapshot)) {\n return args;\n }\n const { name, alias } = moduleInfo;\n const dataFetchInfo = getDataFetchInfo({\n name,\n alias,\n id,\n remoteSnapshot\n });\n if (!dataFetchInfo) {\n return args;\n }\n const { dataFetchId, dataFetchName } = dataFetchInfo;\n const dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {\n name: host.name,\n version: host.options.version\n });\n logger.debug(\n "======= auto fetch plugin dataFetchMapKey: ",\n dataFetchMapKey\n );\n if (!dataFetchMapKey) {\n return args;\n }\n const dataFetchItem = getDataFetchItem(dataFetchMapKey);\n if (dataFetchItem) {\n return args;\n }\n const dataFetchMap = getDataFetchMap();\n const hasSSRAsset = Boolean(remoteSnapshot.ssrRemoteEntry);\n const hasDataFetchClient = Boolean(\n remoteSnapshot.modules.find(\n (module) => module.moduleName === `${dataFetchName}${DATA_FETCH_CLIENT_SUFFIX}`\n )\n );\n const downgradeType = hasDataFetchClient ? MF_DATA_FETCH_TYPE.FETCH_CLIENT : hasSSRAsset ? MF_DATA_FETCH_TYPE.FETCH_SERVER : MF_DATA_FETCH_TYPE.FETCH_CLIENT;\n let finalDataFetchId = dataFetchId;\n if (!isServerEnv()) {\n finalDataFetchId = downgradeType === MF_DATA_FETCH_TYPE.FETCH_CLIENT ? hasDataFetchClient ? `${dataFetchId}${DATA_FETCH_CLIENT_SUFFIX}` : dataFetchId : dataFetchId;\n }\n const getDataFetchGetter = () => loadDataFetchModule(host, finalDataFetchId);\n const dataFetchFnItem = [\n getDataFetchGetter,\n downgradeType\n ];\n if (typeof window === "undefined" || isCSROnly()) {\n dataFetchFnItem.push(getDataFetchGetter());\n }\n dataFetchMap[dataFetchMapKey] = [\n dataFetchFnItem,\n void 0,\n MF_DATA_FETCH_STATUS.AWAIT\n ];\n return args;\n }\n };\n};\nconst EMPTY_HREFS = /* @__PURE__ */ new Set();\nconst stylesheetStores = /* @__PURE__ */ new WeakMap();\nfunction isActiveStylesheet(link) {\n const rel = link.rel.toLowerCase().split(/\\s+/u);\n const media = link.media.trim().toLowerCase();\n const type = link.type.trim().toLowerCase().split(";", 1)[0].trim();\n return rel.includes("stylesheet") && !rel.includes("alternate") && !link.disabled && !link.hasAttribute("disabled") && (!media || media === "all") && (!type || type === "text/css");\n}\nfunction collectHeadStylesheetHrefs(document) {\n var _a;\n const hrefs = /* @__PURE__ */ new Set();\n (_a = document.head) == null ? void 0 : _a.querySelectorAll("link[href]").forEach((link) => {\n if (isActiveStylesheet(link)) {\n hrefs.add(link.href);\n }\n });\n return hrefs;\n}\nfunction haveSameHrefs(current, next) {\n if (current.size !== next.size) {\n return false;\n }\n for (const href of current) {\n if (!next.has(href)) {\n return false;\n }\n }\n return true;\n}\nfunction observeHead(store) {\n store.observer.disconnect();\n const { document, head, observer } = store;\n if (head) {\n observer.observe(head, {\n attributes: true,\n attributeFilter: ["disabled", "href", "media", "rel", "type"],\n childList: true,\n subtree: true\n });\n }\n if (document.documentElement) {\n observer.observe(document.documentElement, { childList: true });\n }\n}\nfunction refreshHeadStylesheets(store) {\n if (!store.subscribers.size) {\n return;\n }\n const head = store.document.head;\n if (head !== store.head) {\n store.head = head;\n observeHead(store);\n }\n const hrefs = collectHeadStylesheetHrefs(store.document);\n if (haveSameHrefs(store.hrefs, hrefs)) {\n return;\n }\n store.hrefs = hrefs;\n store.subscribers.forEach((subscriber) => subscriber(hrefs));\n}\nfunction getStylesheetStore(document) {\n var _a;\n const current = stylesheetStores.get(document);\n if (current) {\n return current;\n }\n const MutationObserver = ((_a = document.defaultView) == null ? void 0 : _a.MutationObserver) ?? globalThis.MutationObserver;\n let store;\n const observer = new MutationObserver(() => refreshHeadStylesheets(store));\n store = {\n document,\n head: document.head,\n hrefs: collectHeadStylesheetHrefs(document),\n observer,\n subscribers: /* @__PURE__ */ new Set()\n };\n observeHead(store);\n stylesheetStores.set(document, store);\n return store;\n}\nfunction subscribeToHeadStylesheets(document, subscriber) {\n const store = getStylesheetStore(document);\n let subscribed = true;\n store.subscribers.add(subscriber);\n subscriber(store.hrefs);\n return () => {\n if (!subscribed) {\n return;\n }\n subscribed = false;\n store.subscribers.delete(subscriber);\n if (!store.subscribers.size) {\n store.observer.disconnect();\n if (stylesheetStores.get(document) === store) {\n stylesheetStores.delete(document);\n }\n }\n };\n}\nfunction resolveHref(href, document) {\n try {\n return new URL(href, document.baseURI).href;\n } catch {\n return href;\n }\n}\nfunction HydratedStylesheetAssets({ hrefs }) {\n const firstLinkRef = useRef(null);\n const ownerDocumentRef = useRef(null);\n const [headHrefs, setHeadHrefs] = useState(EMPTY_HREFS);\n useEffect(() => {\n var _a;\n const link = firstLinkRef.current;\n if (!link) {\n return;\n }\n const ownerDocument = link.ownerDocument;\n ownerDocumentRef.current = ownerDocument;\n if (link.getRootNode() !== ownerDocument || ((_a = ownerDocument.head) == null ? void 0 : _a.contains(link))) {\n return;\n }\n return subscribeToHeadStylesheets(ownerDocument, setHeadHrefs);\n }, []);\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, hrefs.map(\n (href, index) => ownerDocumentRef.current && headHrefs.has(resolveHref(href, ownerDocumentRef.current)) ? null : /* @__PURE__ */ React__default.createElement(\n "link",\n {\n key: href,\n ref: index === 0 ? firstLinkRef : void 0,\n href,\n rel: "stylesheet",\n type: "text/css"\n }\n )\n ));\n}\nfunction isPromise(obj) {\n return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";\n}\nconst AWAIT_ERROR_PREFIX = "<Await /> caught the following error during render: ";\nconst transformError = (err) => {\n const errMsg = err instanceof Error ? err.message : err;\n const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, "");\n const dataFetchMapKey = getDataFetchIdWithErrorMsgs(originalMsg);\n if (originalMsg.indexOf(DATA_FETCH_ERROR_PREFIX) === 0) {\n return {\n error: new Error(\n originalMsg.replace(DATA_FETCH_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")\n ),\n errorType: ERROR_TYPE.DATA_FETCH,\n dataFetchMapKey\n };\n }\n if (originalMsg.indexOf(LOAD_REMOTE_ERROR_PREFIX) === 0) {\n return {\n error: new Error(\n originalMsg.replace(LOAD_REMOTE_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")\n ),\n errorType: ERROR_TYPE.LOAD_REMOTE,\n dataFetchMapKey\n };\n }\n return {\n error: new Error(originalMsg.replace(wrapDataFetchId(dataFetchMapKey), "")),\n errorType: ERROR_TYPE.UNKNOWN,\n dataFetchMapKey\n };\n};\nconst DefaultLoading = /* @__PURE__ */ React__default.createElement(React__default.Fragment, null);\nconst DefaultErrorElement = (_data) => /* @__PURE__ */ React__default.createElement("div", null, "Error");\nfunction AwaitDataFetch({\n resolve,\n loading = DefaultLoading,\n errorElement = DefaultErrorElement,\n children,\n params,\n delayLoading\n}) {\n const dataRef = useRef();\n const data = dataRef.current || resolve;\n const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;\n return /* @__PURE__ */ React__default.createElement(\n AwaitSuspense,\n {\n params,\n loading,\n errorElement,\n delayLoading,\n resolve: getData\n },\n children\n );\n}\nconst DelayedLoading = ({\n delayLoading,\n children\n}) => {\n const [show, setShow] = useState(false);\n const timerSet = useRef(false);\n if (!delayLoading) {\n return children;\n }\n if (typeof window !== "undefined" && !show && !timerSet.current) {\n timerSet.current = true;\n setTimeout(() => {\n setShow(true);\n }, delayLoading);\n }\n return show ? children : null;\n};\nfunction AwaitSuspense({\n resolve,\n children,\n loading = DefaultLoading,\n errorElement = DefaultErrorElement,\n delayLoading\n}) {\n return /* @__PURE__ */ React__default.createElement(\n Suspense,\n {\n fallback: /* @__PURE__ */ React__default.createElement(DelayedLoading, { delayLoading }, loading)\n },\n /* @__PURE__ */ React__default.createElement(ResolveAwait, { resolve, errorElement }, children)\n );\n}\nfunction ResolveAwait({\n children,\n resolve,\n errorElement,\n params\n}) {\n const data = resolve();\n logger.debug("resolve data: ", data);\n if (typeof data === "string" && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {\n const transformedError = transformError(data);\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, typeof errorElement === "function" ? /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, globalThis.FEDERATION_SSR && /* @__PURE__ */ React__default.createElement(\n "script",\n {\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: {\n __html: String.raw`\n globalThis[\'${DATA_FETCH_FUNCTION}\'] = globalThis[\'${DATA_FETCH_FUNCTION}\'] || []\n globalThis[\'${DATA_FETCH_FUNCTION}\'].push([${transformedError.dataFetchMapKey ? `\'${transformedError.dataFetchMapKey}\'` : ""},${params ? JSON.stringify(params) : null},true]);`\n }\n }\n ), errorElement(transformedError)) : errorElement);\n }\n const toRender = typeof children === "function" ? children(data) : children;\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, toRender);\n}\nconst fetchData = (promise, ref) => {\n let data;\n let status = "pending";\n const suspender = promise.then((res) => {\n status = "success";\n data = res;\n ref.current = res;\n }).catch((e) => {\n status = "success";\n console.warn(e);\n data = AWAIT_ERROR_PREFIX + e;\n });\n return () => {\n if (status === "pending") {\n throw suspender;\n }\n return data;\n };\n};\nfunction getTargetModuleInfo(id, instance) {\n if (!instance) {\n return;\n }\n const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);\n if (!loadedRemoteInfo) {\n return;\n }\n const { snapshot } = loadedRemoteInfo;\n if (!snapshot) {\n return;\n }\n const publicPath = "publicPath" in snapshot ? snapshot.publicPath : "getPublicPath" in snapshot ? new Function(snapshot.getPublicPath)() : "";\n if (!publicPath) {\n return;\n }\n const modules = "modules" in snapshot ? snapshot.modules : [];\n const targetModule = modules.find(\n (m) => m.modulePath === loadedRemoteInfo.expose\n );\n if (!targetModule) {\n return;\n }\n const remoteEntry = "remoteEntry" in snapshot ? snapshot.remoteEntry : "";\n if (!remoteEntry) {\n return;\n }\n return {\n module: targetModule,\n publicPath,\n remoteEntry\n };\n}\nfunction collectSSRAssetDescriptors(options) {\n const {\n id,\n injectLink = true,\n injectScript = false\n } = typeof options === "string" ? { id: options } : options;\n const stylesheetHrefs = [];\n const scriptSrcs = [];\n const instance = options.instance;\n if (!instance || !injectLink && !injectScript) {\n return { scriptSrcs, stylesheetHrefs };\n }\n const moduleAndPublicPath = getTargetModuleInfo(id, instance);\n if (!moduleAndPublicPath) {\n return { scriptSrcs, stylesheetHrefs };\n }\n const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;\n if (injectLink) {\n const seenStylesheetHrefs = /* @__PURE__ */ new Set();\n [...targetModule.assets.css.sync, ...targetModule.assets.css.async].sort().forEach((file) => {\n const href = `${publicPath}${file}`;\n if (seenStylesheetHrefs.has(href)) {\n return;\n }\n seenStylesheetHrefs.add(href);\n stylesheetHrefs.push(href);\n });\n }\n if (injectScript) {\n scriptSrcs.push(`${publicPath}${remoteEntry}`);\n [...targetModule.assets.js.sync].sort().forEach((file) => {\n scriptSrcs.push(`${publicPath}${file}`);\n });\n }\n return { scriptSrcs, stylesheetHrefs };\n}\nfunction renderScriptAssets(scriptSrcs) {\n return scriptSrcs.map((src) => /* @__PURE__ */ React__default.createElement("script", { key: src, async: true, src, crossOrigin: "anonymous" }));\n}\nfunction collectSSRAssets(options) {\n const { scriptSrcs, stylesheetHrefs } = collectSSRAssetDescriptors(options);\n return [\n ...renderScriptAssets(scriptSrcs),\n ...stylesheetHrefs.map((href) => /* @__PURE__ */ React__default.createElement("link", { key: href, href, rel: "stylesheet", type: "text/css" }))\n ];\n}\nfunction getServerNeedRemoteInfo(loadedRemoteInfo, id, noSSR) {\n var _a;\n if (noSSR || typeof window !== "undefined" && window.location.href !== window[FS_HREF]) {\n if (!(loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.version)) {\n throw new Error(`${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} version is empty`);\n }\n const { snapshot } = loadedRemoteInfo;\n if (!snapshot) {\n throw new Error(`${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} snapshot is empty`);\n }\n const dataFetchItem = getDataFetchItem(id);\n const isFetchServer = ((_a = dataFetchItem == null ? void 0 : dataFetchItem[0]) == null ? void 0 : _a[1]) === MF_DATA_FETCH_TYPE.FETCH_SERVER;\n if (isFetchServer && (!("ssrPublicPath" in snapshot) || !snapshot.ssrPublicPath)) {\n throw new Error(\n `ssrPublicPath is required while fetching ${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} data in SSR project!`\n );\n }\n if (isFetchServer && (!("ssrRemoteEntry" in snapshot) || !snapshot.ssrRemoteEntry)) {\n throw new Error(\n `ssrRemoteEntry is required while loading ${loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.name} data loader in SSR project!`\n );\n }\n return {\n name: loadedRemoteInfo.name,\n version: loadedRemoteInfo.version,\n ssrPublicPath: "ssrPublicPath" in snapshot ? snapshot.ssrPublicPath || "" : "",\n ssrRemoteEntry: "ssrRemoteEntry" in snapshot ? snapshot.ssrRemoteEntry || "" : "",\n globalName: loadedRemoteInfo.entryGlobalName\n };\n }\n return void 0;\n}\nfunction createLazyComponent(options) {\n const { instance, injectScript, injectLink } = options;\n if (!instance) {\n throw new Error("instance is required for createLazyComponent!");\n }\n const exportName = (options == null ? void 0 : options.export) || "default";\n const callLoader = async () => {\n logger.debug("callLoader start", Date.now());\n const m = await options.loader();\n logger.debug("callLoader end", Date.now());\n if (!m) {\n throw new Error("load remote failed");\n }\n return m;\n };\n const getData = async (noSSR) => {\n let loadedRemoteInfo;\n let moduleId;\n try {\n const m = await callLoader();\n moduleId = m && m[Symbol.for("mf_module_id")];\n if (!moduleId) {\n throw new Error("moduleId is empty");\n }\n loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);\n if (!loadedRemoteInfo) {\n throw new Error(`can not find loaded remote(\'${moduleId}\') info!`);\n }\n } catch (e) {\n const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;\n logger.debug(e);\n throw new Error(errMsg);\n }\n let dataFetchMapKey;\n try {\n dataFetchMapKey = getDataFetchMapKey(\n getDataFetchInfo({\n name: loadedRemoteInfo.name,\n alias: loadedRemoteInfo.alias,\n id: moduleId,\n remoteSnapshot: loadedRemoteInfo.snapshot\n }),\n { name: instance.name, version: instance.options.version }\n );\n logger.debug("getData dataFetchMapKey: ", dataFetchMapKey);\n if (!dataFetchMapKey) {\n return;\n }\n const data = await fetchData$1(\n dataFetchMapKey,\n {\n ...options.dataFetchParams,\n isDowngrade: false\n },\n getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR)\n );\n setDataFetchItemLoadedStatus(dataFetchMapKey);\n logger.debug("get data res: \\n", data);\n return data;\n } catch (err) {\n const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;\n logger.debug(errMsg);\n throw new Error(errMsg);\n }\n };\n const LazyComponent = React__default.lazy(async () => {\n const m = await callLoader();\n const moduleId = m && m[Symbol.for("mf_module_id")];\n const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);\n loadedRemoteInfo == null ? void 0 : loadedRemoteInfo.snapshot;\n const dataFetchMapKey = loadedRemoteInfo ? getDataFetchMapKey(\n getDataFetchInfo({\n name: loadedRemoteInfo.name,\n alias: loadedRemoteInfo.alias,\n id: moduleId,\n remoteSnapshot: loadedRemoteInfo.snapshot\n }),\n { name: instance.name, version: instance == null ? void 0 : instance.options.version }\n ) : void 0;\n logger.debug("LazyComponent dataFetchMapKey: ", dataFetchMapKey);\n const { scriptSrcs, stylesheetHrefs } = collectSSRAssetDescriptors({\n id: moduleId,\n instance,\n injectLink,\n injectScript\n });\n const assets = [\n ...renderScriptAssets(scriptSrcs),\n /* @__PURE__ */ React__default.createElement(HydratedStylesheetAssets, { key: "stylesheets", hrefs: stylesheetHrefs })\n ];\n const Com = m[exportName];\n if (exportName in m && typeof Com === "function") {\n return {\n default: (props) => /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, globalThis.FEDERATION_SSR && dataFetchMapKey && /* @__PURE__ */ React__default.createElement(\n "script",\n {\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: {\n __html: String.raw`\n globalThis[\'${DATA_FETCH_FUNCTION}\'] = globalThis[\'${DATA_FETCH_FUNCTION}\'] || [];\n globalThis[\'${DATA_FETCH_FUNCTION}\'].push([\'${dataFetchMapKey}\',${JSON.stringify(props.mfData)}]);\n `\n }\n }\n ), globalThis.FEDERATION_SSR && assets, /* @__PURE__ */ React__default.createElement(Com, { ...props }))\n };\n } else {\n throw Error(\n `Make sure that ${moduleId} has the correct export when export is ${String(\n exportName\n )}`\n );\n }\n });\n return (props) => {\n const { key, ...args } = props;\n if (!options.noSSR) {\n return /* @__PURE__ */ React__default.createElement(\n AwaitDataFetch,\n {\n resolve: getData(options.noSSR),\n loading: options.loading,\n delayLoading: options.delayLoading,\n errorElement: options.fallback\n },\n (data) => /* @__PURE__ */ React__default.createElement(LazyComponent, { ...args, mfData: data })\n );\n } else {\n const [data, setData] = useState(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n let isMounted = true;\n const fetchDataAsync = async () => {\n try {\n setLoading(true);\n const result = await getData(options.noSSR);\n if (isMounted) {\n setData(result);\n }\n } catch (e) {\n if (isMounted) {\n setError(transformError(e));\n }\n } finally {\n if (isMounted) {\n setLoading(false);\n }\n }\n };\n fetchDataAsync();\n return () => {\n isMounted = false;\n };\n }, []);\n if (loading) {\n return /* @__PURE__ */ React__default.createElement(DelayedLoading, { delayLoading: options.delayLoading }, options.loading);\n }\n if (error) {\n return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, typeof options.fallback === "function" ? options.fallback(error) : options.fallback);\n }\n return /* @__PURE__ */ React__default.createElement(LazyComponent, { ...args, mfData: data });\n }\n };\n}\nfunction lazyLoadComponentPlugin() {\n return {\n name: "lazy-load-component-plugin",\n apply(instance) {\n instance.registerPlugins([autoFetchData()]);\n instance.createLazyComponent = (options) => {\n return createLazyComponent({\n instance,\n ...options\n });\n };\n instance.prefetch = (options) => {\n return prefetch({\n instance,\n ...options\n });\n };\n instance.collectSSRAssets = (options) => {\n return collectSSRAssets({\n instance,\n ...options\n });\n };\n }\n };\n}\nexport {\n autoFetchData as a,\n createLazyComponent as b,\n collectSSRAssets as c,\n lazyLoadComponentPlugin as l\n};\n',
|
|
210
|
+
"logger-DwWkXsWl.mjs": "const MANIFEST_EXT = \".json\";\nconst BROWSER_LOG_KEY = \"FEDERATION_DEBUG\";\nconst SEPARATOR = \":\";\nconst isBrowserEnvValue = typeof ENV_TARGET !== \"undefined\" ? ENV_TARGET === \"web\" : typeof window !== \"undefined\" && typeof window.document !== \"undefined\";\nfunction isBrowserEnv() {\n return isBrowserEnvValue;\n}\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n } catch (error) {\n return false;\n }\n return false;\n}\nfunction isDebugMode() {\n if (typeof process !== \"undefined\" && process.env && process.env[\"FEDERATION_DEBUG\"]) return Boolean(process.env[\"FEDERATION_DEBUG\"]);\n if (typeof FEDERATION_DEBUG !== \"undefined\" && Boolean(FEDERATION_DEBUG)) return true;\n return isBrowserDebug();\n}\nconst PREFIX = \"[ Module Federation ]\";\nconst DEFAULT_DELEGATE = console;\nconst LOGGER_STACK_SKIP_TOKENS = [\n \"logger.ts\",\n \"logger.js\",\n \"captureStackTrace\",\n \"Logger.emit\",\n \"Logger.log\",\n \"Logger.info\",\n \"Logger.warn\",\n \"Logger.error\",\n \"Logger.debug\"\n];\nfunction captureStackTrace() {\n try {\n const stack = (/* @__PURE__ */ new Error()).stack;\n if (!stack) return;\n const [, ...rawLines] = stack.split(\"\\n\");\n const filtered = rawLines.filter((line) => !LOGGER_STACK_SKIP_TOKENS.some((token) => line.includes(token)));\n if (!filtered.length) return;\n return `Stack trace:\n${filtered.slice(0, 5).join(\"\\n\")}`;\n } catch {\n return;\n }\n}\nvar Logger = class {\n constructor(prefix, delegate = DEFAULT_DELEGATE) {\n this.prefix = prefix;\n this.delegate = delegate ?? DEFAULT_DELEGATE;\n }\n setPrefix(prefix) {\n this.prefix = prefix;\n }\n setDelegate(delegate) {\n this.delegate = delegate ?? DEFAULT_DELEGATE;\n }\n emit(method, args) {\n const delegate = this.delegate;\n const stackTrace = isDebugMode() ? captureStackTrace() : void 0;\n const enrichedArgs = stackTrace ? [...args, stackTrace] : args;\n const order = (() => {\n switch (method) {\n case \"log\":\n return [\"log\", \"info\"];\n case \"info\":\n return [\"info\", \"log\"];\n case \"warn\":\n return [\n \"warn\",\n \"info\",\n \"log\"\n ];\n case \"error\":\n return [\n \"error\",\n \"warn\",\n \"log\"\n ];\n default:\n return [\"debug\", \"log\"];\n }\n })();\n for (const candidate of order) {\n const handler = delegate[candidate];\n if (typeof handler === \"function\") {\n handler.call(delegate, this.prefix, ...enrichedArgs);\n return;\n }\n }\n for (const candidate of order) {\n const handler = DEFAULT_DELEGATE[candidate];\n if (typeof handler === \"function\") {\n handler.call(DEFAULT_DELEGATE, this.prefix, ...enrichedArgs);\n return;\n }\n }\n }\n log(...args) {\n this.emit(\"log\", args);\n }\n warn(...args) {\n this.emit(\"warn\", args);\n }\n error(...args) {\n this.emit(\"error\", args);\n }\n success(...args) {\n this.emit(\"info\", args);\n }\n info(...args) {\n this.emit(\"info\", args);\n }\n ready(...args) {\n this.emit(\"info\", args);\n }\n debug(...args) {\n if (isDebugMode()) this.emit(\"debug\", args);\n }\n};\nfunction createLogger(prefix) {\n return new Logger(prefix);\n}\nfunction createInfrastructureLogger(prefix) {\n const infrastructureLogger = new Logger(prefix);\n Object.defineProperty(infrastructureLogger, \"__mf_infrastructure_logger__\", {\n value: true,\n enumerable: false,\n configurable: false\n });\n return infrastructureLogger;\n}\ncreateInfrastructureLogger(PREFIX);\nexport {\n MANIFEST_EXT as M,\n SEPARATOR as S,\n createLogger as c,\n isBrowserEnvValue as i\n};\n",
|
|
211
|
+
"plugin.es.js": "const federationRuntime = { instance: null };\nfunction BridgeReactPlugin() {\n return {\n name: \"bridge-react-plugin\",\n beforeInit(args) {\n federationRuntime.instance = args.origin;\n return args;\n }\n };\n}\nexport {\n BridgeReactPlugin as default,\n federationRuntime\n};\n",
|
|
212
|
+
"prefetch-TKq_EK_q.mjs": 'import { B as warn, y as DATA_FETCH_FUNCTION, F as FS_HREF, l as logger, e as getDataFetchMap, i as initDataFetchMap, o as getDataFetchItem, M as MF_DATA_FETCH_STATUS, q as MF_DATA_FETCH_TYPE, G as DOWNGRADE_KEY, H as callAllDowngrade, I as callDowngrade, J as getDowngradeTag, K as composeKeyWithSeparator, N as safeToString, m as getDataFetchInfo, n as getDataFetchMapKey } from "./utils-BBP3hEeV.mjs";\nimport { i as isBrowserEnvValue } from "./logger-DwWkXsWl.mjs";\nasync function safeWrapper(callback, disableWarn) {\n try {\n return await callback();\n } catch (e) {\n warn(e);\n return;\n }\n}\nfunction isStaticResourcesEqual(url1, url2) {\n const REG_EXP = /^(https?:)?\\/\\//i;\n return url1.replace(REG_EXP, "").replace(/\\/$/, "") === url2.replace(REG_EXP, "").replace(/\\/$/, "");\n}\nfunction createScript(info) {\n let script = null;\n let needAttach = true;\n let timeout = 2e4;\n let timeoutId;\n const scripts = document.getElementsByTagName("script");\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute("src");\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement("script");\n script.type = (attrs == null ? void 0 : attrs["type"]) === "module" ? "module" : "text/javascript";\n let createScriptRes = void 0;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n if (createScriptRes instanceof HTMLScriptElement) script = createScriptRes;\n else if (typeof createScriptRes === "object") {\n if ("script" in createScriptRes && createScriptRes.script) script = createScriptRes.script;\n if ("timeout" in createScriptRes && createScriptRes.timeout) timeout = createScriptRes.timeout;\n }\n }\n if (!script.src) script.src = info.url;\n if (attrs && !createScriptRes) Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === "async" || name === "defer") script[name] = attrs[name];\n else if (!script.getAttribute(name)) script.setAttribute(name, attrs[name]);\n }\n });\n }\n let executionError = null;\n const executionErrorHandler = typeof window !== "undefined" ? (evt) => {\n if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {\n const err = /* @__PURE__ */ new Error(`ScriptExecutionError: Script "${info.url}" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`);\n err.name = "ScriptExecutionError";\n executionError = err;\n }\n } : null;\n if (executionErrorHandler) window.addEventListener("error", executionErrorHandler);\n const onScriptComplete = async (prev, event) => {\n clearTimeout(timeoutId);\n if (executionErrorHandler) window.removeEventListener("error", executionErrorHandler);\n const onScriptCompleteCallback = () => {\n if ((event == null ? void 0 : event.type) === "error") {\n const networkError = /* @__PURE__ */ new Error((event == null ? void 0 : event.isTimeout) ? `ScriptNetworkError: Script "${info.url}" timed out.` : `ScriptNetworkError: Failed to load script "${info.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);\n networkError.name = "ScriptNetworkError";\n (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(networkError));\n } else if (executionError) (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(executionError));\n else (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());\n };\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);\n });\n if (prev && typeof prev === "function") {\n const result = prev(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n timeoutId = setTimeout(() => {\n onScriptComplete(null, {\n type: "error",\n isTimeout: true\n });\n }, timeout);\n return {\n script,\n needAttach\n };\n}\nfunction createLink(info) {\n let link = null;\n let needAttach = true;\n let timeout = 2e4;\n let timeoutId;\n const links = document.getElementsByTagName("link");\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute("href");\n const linkRel = l.getAttribute("rel");\n if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs["rel"]) {\n link = l;\n needAttach = false;\n break;\n }\n }\n if (!link) {\n link = document.createElement("link");\n link.setAttribute("href", info.url);\n let createLinkRes = void 0;\n let shouldApplyAttrs = true;\n const attrs = info.attrs;\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n shouldApplyAttrs = false;\n } else if (typeof createLinkRes === "object") {\n if ("link" in createLinkRes && createLinkRes.link) {\n link = createLinkRes.link;\n shouldApplyAttrs = false;\n }\n if ("timeout" in createLinkRes && createLinkRes.timeout) timeout = createLinkRes.timeout;\n }\n }\n if (attrs && shouldApplyAttrs) Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) link.setAttribute(name, attrs[name]);\n });\n }\n if (!needAttach) {\n Promise.resolve().then(() => {\n (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());\n });\n return {\n link,\n needAttach\n };\n }\n const onLinkComplete = (prev, event) => {\n if (timeoutId) clearTimeout(timeoutId);\n const onLinkCompleteCallback = () => {\n if ((event == null ? void 0 : event.type) === "error") {\n const linkError = /* @__PURE__ */ new Error((event == null ? void 0 : event.isTimeout) ? `LinkNetworkError: Link "${info.url}" timed out.` : `LinkNetworkError: Failed to load link "${info.url}" - the URL is unreachable or the server returned an error.`);\n linkError.name = "LinkNetworkError";\n (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(linkError));\n } else (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());\n };\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);\n });\n if (prev) {\n const res = prev(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n timeoutId = setTimeout(() => {\n onLinkComplete(null, {\n type: "error",\n isTimeout: true\n });\n }, timeout);\n return {\n link,\n needAttach\n };\n}\nfunction loadScript(url, info) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: "high",\n ...attrs\n },\n createScriptHook,\n needDeleteScript: true\n });\n needAttach && document.head.appendChild(script);\n });\n}\nconst sdkImportCache = /* @__PURE__ */ new Map();\nfunction importNodeModule(name) {\n if (!name) throw new Error("import specifier is required");\n if (sdkImportCache.has(name)) return sdkImportCache.get(name);\n const promise = new Function("name", `return import(name)`)(name).then((res) => res).catch((error2) => {\n console.error(`Error importing module ${name}:`, error2);\n sdkImportCache.delete(name);\n throw error2;\n });\n sdkImportCache.set(name, promise);\n return promise;\n}\nconst lazyLoaderHookFetch = async (input, init, loaderHook) => {\n const hook = (url, init2) => {\n return loaderHook.lifecycle.fetch.emit(url, init2);\n };\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) return fetch(input, init || {});\n return res;\n};\nconst createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {\n if (loaderHook == null ? void 0 : loaderHook.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (hookResult && typeof hookResult === "object" && "url" in hookResult) url = hookResult.url;\n }\n let urlObj;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error("Error constructing URL:", e);\n cb(/* @__PURE__ */ new Error(`Invalid URL: ${e}`));\n return;\n }\n const getFetch = async () => {\n if (loaderHook == null ? void 0 : loaderHook.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);\n return fetch;\n };\n const handleScriptFetch = async (f, urlObj2) => {\n var _a;\n try {\n const res = await f(urlObj2.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([importNodeModule("path"), importNodeModule("vm")]);\n const scriptContext = {\n exports: {},\n module: { exports: {} }\n };\n const urlDirname = urlObj2.pathname.split("/").slice(0, -1).join("/");\n const filename = path.basename(urlObj2.pathname);\n const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {\n filename,\n importModuleDynamically: ((_a = vm.constants) == null ? void 0 : _a.USE_MAIN_CONTEXT_DEFAULT_LOADER) ?? importNodeModule\n });\n let requireFn;\n requireFn = (await importNodeModule("node:module")).createRequire(urlObj2.protocol === "file:" || urlObj2.protocol === "node:" ? urlObj2.href : path.join(process.cwd(), "__mf_require_base__.js"));\n script.runInThisContext()(scriptContext.exports, scriptContext.module, requireFn, urlDirname, filename);\n const exportedInterface = scriptContext.module.exports || scriptContext.exports;\n if (attrs && exportedInterface && attrs["globalName"]) {\n cb(void 0, exportedInterface[attrs["globalName"]] || exportedInterface);\n return;\n }\n cb(void 0, exportedInterface);\n } catch (e) {\n cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));\n }\n };\n getFetch().then(async (f) => {\n if ((attrs == null ? void 0 : attrs["type"]) === "esm" || (attrs == null ? void 0 : attrs["type"]) === "module") return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule("vm")\n }).then(async (module) => {\n await module.evaluate();\n cb(void 0, module.namespace);\n }).catch((e) => {\n cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));\n });\n handleScriptFetch(f, urlObj);\n }).catch((err) => {\n cb(err);\n });\n} : (url, cb, attrs, loaderHook) => {\n cb(/* @__PURE__ */ new Error("createScriptNode is disabled in non-Node.js environment"));\n};\nconst loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, info) => {\n return new Promise((resolve, reject) => {\n createScriptNode(url, (error2, scriptContext) => {\n var _a, _b;\n if (error2) reject(error2);\n else {\n const remoteEntryKey = ((_a = info == null ? void 0 : info.attrs) == null ? void 0 : _a["globalName"]) || `__FEDERATION_${(_b = info == null ? void 0 : info.attrs) == null ? void 0 : _b["name"]}:custom__`;\n resolve(globalThis[remoteEntryKey] = scriptContext);\n }\n }, info.attrs, info.loaderHook);\n });\n} : (url, info) => {\n throw new Error("loadScriptNode is disabled in non-Node.js environment");\n};\nconst esmModuleCache = /* @__PURE__ */ new Map();\nconst isFetchableRemoteModuleUrl = (url) => url.startsWith("http:") || url.startsWith("https:");\nconst isBareModuleSpecifier = (specifier) => !specifier.startsWith("./") && !specifier.startsWith("../") && !specifier.startsWith("/") && !specifier.includes(":");\nfunction encodeRemoteModulePath(url) {\n const remoteUrl = new URL(url);\n const encodedProtocol = encodeURIComponent(remoteUrl.protocol.slice(0, -1));\n const encodedHost = encodeURIComponent(remoteUrl.host);\n const encodedPathname = remoteUrl.pathname.split("/").map((segment) => encodeURIComponent(segment)).join("/");\n const encodedSearchHash = encodeURIComponent(`${remoteUrl.search}${remoteUrl.hash}`);\n return `/${encodedProtocol}/${encodedHost}${encodedPathname}${encodedSearchHash ? `/${encodedSearchHash}` : ""}`;\n}\nfunction createImportMetaUrl(url, baseFileUrl) {\n const baseUrl = baseFileUrl.endsWith("/") ? baseFileUrl : `${baseFileUrl}/`;\n return new URL(`__module_federation_remote__${encodeRemoteModulePath(url)}`, baseUrl).href;\n}\nasync function isNodeBuiltinSpecifier(specifier) {\n if (specifier.startsWith("node:")) return true;\n if (!isBareModuleSpecifier(specifier)) return false;\n return (await importNodeModule("node:module")).builtinModules.includes(specifier);\n}\nfunction getSyntheticModuleExports(moduleExports) {\n const namespaceObject = moduleExports && (typeof moduleExports === "object" || typeof moduleExports === "function") ? moduleExports : { default: moduleExports };\n const effectiveExports = { ...namespaceObject };\n if (!Object.prototype.hasOwnProperty.call(effectiveExports, "default")) effectiveExports.default = namespaceObject;\n return effectiveExports;\n}\nasync function createSyntheticModuleFromExports(identifier, moduleExports, vm) {\n if (typeof vm.SyntheticModule !== "function") throw new Error("vm.SyntheticModule is required to load Node.js built-in modules in ESM remote entries.");\n const effectiveExports = getSyntheticModuleExports(moduleExports);\n const exportNames = Object.keys(effectiveExports);\n const syntheticModule = new vm.SyntheticModule(exportNames, function setSyntheticModuleExports() {\n for (const name of exportNames) this.setExport(name, effectiveExports[name]);\n }, { identifier });\n esmModuleCache.set(identifier, syntheticModule);\n await syntheticModule.link(async () => {\n throw new Error(`Node.js built-in module "${identifier}" should not request child modules.`);\n });\n await syntheticModule.evaluate();\n return syntheticModule;\n}\nasync function loadNodeBuiltinModule(specifier, vm) {\n const cacheKey = `node-builtin:${specifier}`;\n if (esmModuleCache.has(cacheKey)) return esmModuleCache.get(cacheKey);\n return createSyntheticModuleFromExports(cacheKey, await importNodeModule(specifier), vm);\n}\nasync function loadResolvedModule(specifier, parentUrl, options) {\n if (await isNodeBuiltinSpecifier(specifier)) return loadNodeBuiltinModule(specifier, options.vm);\n if (isBareModuleSpecifier(specifier)) throw new Error(`Unsupported ESM module specifier "${specifier}". Only relative or absolute http(s) remote modules and Node.js built-in modules are supported.`);\n const resolvedUrl = new URL(specifier, parentUrl).href;\n if (!isFetchableRemoteModuleUrl(resolvedUrl)) throw new Error(`Unsupported ESM module specifier "${specifier}" resolved to "${resolvedUrl}". Only http(s) remote modules and Node.js built-in modules are supported.`);\n return loadModule(resolvedUrl, options);\n}\nasync function evaluateDynamicModule(module) {\n if (module.status === "linked") await module.evaluate();\n if (module.status === "errored") throw module.error;\n return module;\n}\nasync function loadModule(url, options) {\n if (esmModuleCache.has(url)) return esmModuleCache.get(url);\n const { fetch: fetch2, vm } = options;\n if (!isFetchableRemoteModuleUrl(url)) throw new Error(`Unsupported ESM module URL "${url}". Only http(s) remote modules and Node.js built-in modules are supported.`);\n const code = await (await fetch2(url)).text();\n const cwdFileUrl = (await importNodeModule("node:url")).pathToFileURL(process.cwd()).href;\n const sourceTextModule = new vm.SourceTextModule(code, {\n identifier: url,\n initializeImportMeta: (meta) => {\n meta.url = createImportMetaUrl(url, cwdFileUrl);\n },\n importModuleDynamically: async (specifier) => {\n return evaluateDynamicModule(await loadResolvedModule(specifier, url, options));\n }\n });\n esmModuleCache.set(url, sourceTextModule);\n await sourceTextModule.link(async (specifier) => {\n return loadResolvedModule(specifier, url, options);\n });\n return sourceTextModule;\n}\nconst dataFetchFunction = async function(options) {\n var _a, _b;\n const [id, data, downgrade] = options;\n logger.debug("==========call data fetch function!");\n if (data) {\n if (!id) {\n throw new Error("id is required!");\n }\n if (!getDataFetchMap()) {\n initDataFetchMap();\n }\n const dataFetchItem = getDataFetchItem(id);\n if (dataFetchItem) {\n (_b = (_a = dataFetchItem[1]) == null ? void 0 : _a[1]) == null ? void 0 : _b.call(_a, data);\n dataFetchItem[2] = MF_DATA_FETCH_STATUS.LOADED;\n return;\n }\n if (!dataFetchItem) {\n const dataFetchMap = getDataFetchMap();\n let res;\n let rej;\n const p = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n dataFetchMap[id] = [\n [\n async () => async () => {\n return "";\n },\n MF_DATA_FETCH_TYPE.FETCH_SERVER\n ],\n [p, res, rej],\n MF_DATA_FETCH_STATUS.LOADED\n ];\n res && res(data);\n return;\n }\n }\n if (downgrade) {\n const mfDowngrade2 = getDowngradeTag();\n if (!mfDowngrade2) {\n globalThis[DOWNGRADE_KEY] = id ? [id] : true;\n } else if (Array.isArray(mfDowngrade2) && id && !mfDowngrade2.includes(id)) {\n mfDowngrade2.push(id);\n }\n }\n const mfDowngrade = getDowngradeTag();\n if (typeof mfDowngrade === "boolean") {\n return callAllDowngrade();\n }\n if (Array.isArray(mfDowngrade)) {\n if (!id) {\n globalThis[DOWNGRADE_KEY] = true;\n return callAllDowngrade();\n }\n if (!mfDowngrade.includes(id)) {\n mfDowngrade.push(id);\n }\n return callDowngrade(id);\n }\n};\nfunction injectDataFetch() {\n var _a;\n globalThis[_a = DATA_FETCH_FUNCTION] || (globalThis[_a] = []);\n const dataFetch = globalThis[DATA_FETCH_FUNCTION];\n if (dataFetch.push === dataFetchFunction) {\n return;\n }\n if (typeof window === "undefined") {\n return;\n }\n globalThis[FS_HREF] = window.location.href;\n dataFetch.push = dataFetchFunction;\n}\nconst getDocsUrl = (errorCode) => {\n return `View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${errorCode.split("-")[0].toLowerCase()}#${errorCode.toLowerCase()}`;\n};\nconst getShortErrorMsg = (errorCode, errorDescMap, args, originalErrorMsg) => {\n const msg = [`${[errorDescMap[errorCode]]} #${errorCode}`];\n args && msg.push(`args: ${JSON.stringify(args)}`);\n msg.push(getDocsUrl(errorCode));\n originalErrorMsg && msg.push(`Original Error Message:\n ${originalErrorMsg}`);\n return msg.join("\\n");\n};\nfunction logAndReport(code, descMap, args, logger2, originalErrorMsg, context) {\n return logger2(getShortErrorMsg(code, descMap, args, originalErrorMsg));\n}\nconst LOG_CATEGORY = "[ Federation Runtime ]";\nfunction assert(condition, msgOrCode, descMap, args, context) {\n if (!condition) error(msgOrCode);\n}\nfunction error(msgOrCode, descMap, args, originalErrorMsg, context) {\n if (descMap !== void 0) return logAndReport(msgOrCode, descMap, args ?? {}, (msg2) => {\n throw new Error(`${LOG_CATEGORY}: ${msg2}`);\n }, originalErrorMsg);\n const msg = msgOrCode;\n if (msg instanceof Error) {\n if (!msg.message.startsWith(LOG_CATEGORY)) msg.message = `${LOG_CATEGORY}: ${msg.message}`;\n throw msg;\n }\n throw new Error(`${LOG_CATEGORY}: ${msg}`);\n}\nconst processModuleAlias = (name, subPath) => {\n let moduleName;\n if (name.endsWith("/")) moduleName = name.slice(0, -1);\n else moduleName = name;\n if (subPath.startsWith(".")) subPath = subPath.slice(1);\n moduleName = moduleName + subPath;\n return moduleName;\n};\nconst MAX_PRELOADED_ASSETS = 2e3;\nconst CurrentGlobal = typeof globalThis === "object" ? globalThis : window;\nconst nativeGlobal = (() => {\n try {\n return document.defaultView;\n } catch {\n return CurrentGlobal;\n }\n})();\nfunction definePropertyGlobalVal(target, key, val) {\n Object.defineProperty(target, key, {\n value: val,\n configurable: false,\n writable: true\n });\n}\nfunction includeOwnProperty(target, key) {\n return Object.hasOwnProperty.call(target, key);\n}\nif (!includeOwnProperty(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__")) definePropertyGlobalVal(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__", {});\nconst globalLoading = CurrentGlobal.__GLOBAL_LOADING_REMOTE_ENTRY__;\nfunction setGlobalDefaultVal(target) {\n var _a, _b, _c, _d, _e, _f, _g;\n if (includeOwnProperty(target, "__VMOK__") && !includeOwnProperty(target, "__FEDERATION__")) definePropertyGlobalVal(target, "__FEDERATION__", target.__VMOK__);\n if (!includeOwnProperty(target, "__FEDERATION__")) {\n definePropertyGlobalVal(target, "__FEDERATION__", {\n __GLOBAL_PLUGIN__: [],\n __INSTANCES__: [],\n moduleInfo: {},\n __SHARE__: {},\n __MANIFEST_LOADING__: {},\n __PRELOADED_MAP__: /* @__PURE__ */ new Map(),\n __PRELOADED_ASSETS__: /* @__PURE__ */ new Set()\n });\n definePropertyGlobalVal(target, "__VMOK__", target.__FEDERATION__);\n }\n (_a = target.__FEDERATION__).__GLOBAL_PLUGIN__ ?? (_a.__GLOBAL_PLUGIN__ = []);\n (_b = target.__FEDERATION__).__INSTANCES__ ?? (_b.__INSTANCES__ = []);\n (_c = target.__FEDERATION__).moduleInfo ?? (_c.moduleInfo = {});\n (_d = target.__FEDERATION__).__SHARE__ ?? (_d.__SHARE__ = {});\n (_e = target.__FEDERATION__).__MANIFEST_LOADING__ ?? (_e.__MANIFEST_LOADING__ = {});\n (_f = target.__FEDERATION__).__PRELOADED_MAP__ ?? (_f.__PRELOADED_MAP__ = /* @__PURE__ */ new Map());\n (_g = target.__FEDERATION__).__PRELOADED_ASSETS__ ?? (_g.__PRELOADED_ASSETS__ = /* @__PURE__ */ new Set());\n}\nsetGlobalDefaultVal(CurrentGlobal);\nsetGlobalDefaultVal(nativeGlobal);\nconst getRemoteEntryExports = (name, globalName) => {\n const remoteEntryKey = globalName || `__FEDERATION_${name}:custom__`;\n return {\n remoteEntryKey,\n entryExports: CurrentGlobal[remoteEntryKey]\n };\n};\nconst getPreloadedAsset = (url) => CurrentGlobal.__FEDERATION__.__PRELOADED_ASSETS__.has(url);\nconst setPreloadedAsset = (url) => {\n const preloadedAssets = CurrentGlobal.__FEDERATION__.__PRELOADED_ASSETS__;\n preloadedAssets.add(url);\n if (preloadedAssets.size > MAX_PRELOADED_ASSETS) {\n const oldestUrl = preloadedAssets.values().next().value;\n if (oldestUrl !== void 0) preloadedAssets.delete(oldestUrl);\n }\n};\nconst DEFAULT_SCOPE = "default";\nconst DEFAULT_REMOTE_TYPE = "global";\nfunction composeRemoteRequestId(remoteName, expose) {\n if (!expose || expose === ".") return remoteName;\n return `${remoteName}/${expose.replace(/^\\.\\//, "")}`;\n}\nfunction matchRemoteWithNameAndExpose(remotes, id) {\n for (const remote of remotes) {\n const isNameMatched = id.startsWith(remote.name);\n let expose = id.replace(remote.name, "");\n if (isNameMatched) {\n if (expose.startsWith("/")) {\n const pkgNameOrAlias = remote.name;\n expose = `.${expose}`;\n return {\n pkgNameOrAlias,\n expose,\n remote\n };\n } else if (expose === "") return {\n pkgNameOrAlias: remote.name,\n expose: ".",\n remote\n };\n }\n const isAliasMatched = remote.alias && id.startsWith(remote.alias);\n let exposeWithAlias = remote.alias && id.replace(remote.alias, "");\n if (remote.alias && isAliasMatched) {\n if (exposeWithAlias && exposeWithAlias.startsWith("/")) {\n const pkgNameOrAlias = remote.alias;\n exposeWithAlias = `.${exposeWithAlias}`;\n return {\n pkgNameOrAlias,\n expose: exposeWithAlias,\n remote\n };\n } else if (exposeWithAlias === "") return {\n pkgNameOrAlias: remote.alias,\n expose: ".",\n remote\n };\n }\n }\n}\nconst RUNTIME_001 = "RUNTIME-001";\nconst RUNTIME_002 = "RUNTIME-002";\nconst RUNTIME_003 = "RUNTIME-003";\nconst RUNTIME_004 = "RUNTIME-004";\nconst RUNTIME_005 = "RUNTIME-005";\nconst RUNTIME_006 = "RUNTIME-006";\nconst RUNTIME_007 = "RUNTIME-007";\nconst RUNTIME_008 = "RUNTIME-008";\nconst RUNTIME_009 = "RUNTIME-009";\nconst RUNTIME_010 = "RUNTIME-010";\nconst RUNTIME_011 = "RUNTIME-011";\nconst RUNTIME_012 = "RUNTIME-012";\nconst RUNTIME_013 = "RUNTIME-013";\nconst RUNTIME_014 = "RUNTIME-014";\nconst RUNTIME_015 = "RUNTIME-015";\nconst runtimeDescMap = {\n [RUNTIME_001]: "Failed to get remoteEntry exports.",\n [RUNTIME_002]: \'The remote entry interface does not contain "init"\',\n [RUNTIME_003]: "Failed to get manifest.",\n [RUNTIME_004]: "Failed to locate remote.",\n [RUNTIME_005]: "Invalid loadShareSync function call from bundler runtime",\n [RUNTIME_006]: "Invalid loadShareSync function call from runtime",\n [RUNTIME_007]: "Failed to get remote snapshot.",\n [RUNTIME_008]: "Failed to load script resources.",\n [RUNTIME_009]: "Please call createInstance first.",\n [RUNTIME_010]: \'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.\',\n [RUNTIME_011]: "The remoteEntry URL is missing from the remote snapshot.",\n [RUNTIME_012]: \'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.\',\n [RUNTIME_013]: "The manifest is not a valid Module Federation manifest.",\n [RUNTIME_014]: "The remote does not expose the requested module.",\n [RUNTIME_015]: "Remote container initialization failed."\n};\n({\n ...runtimeDescMap\n});\nconst importCallback = ".then(callbacks[0]).catch(callbacks[1])";\nconst remoteEntryLoadingOrigins = /* @__PURE__ */ new WeakMap();\nconst esmRemoteEntryLoadErrorMessages = [\n "Failed to fetch dynamically imported module",\n "Importing a module script failed",\n "error loading dynamically imported module"\n];\nfunction isEsmRemoteEntryLoadError(err) {\n if (!(err instanceof TypeError)) return false;\n return esmRemoteEntryLoadErrorMessages.some((loadErrorMessage) => err.message.includes(loadErrorMessage));\n}\nfunction isEsmRemoteType(type) {\n return type === "esm" || type === "module";\n}\nasync function loadEsmEntry({ entry, remoteEntryExports, name, getEntryUrl }) {\n return new Promise((resolve, reject) => {\n const rejectEntry = (loadError) => {\n if (isEsmRemoteEntryLoadError(loadError)) {\n const originalMsg = loadError instanceof Error ? loadError.message : String(loadError);\n try {\n error(RUNTIME_008, runtimeDescMap, {\n remoteName: name,\n resourceUrl: url\n }, originalMsg);\n } catch (runtimeError) {\n reject(runtimeError);\n return;\n }\n }\n reject(loadError);\n };\n const url = getEntryUrl ? getEntryUrl(entry) : entry;\n try {\n if (!remoteEntryExports) if (typeof FEDERATION_ALLOW_NEW_FUNCTION !== "undefined") new Function("callbacks", `import("${url}")${importCallback}`)([resolve, rejectEntry]);\n else import(\n /* webpackIgnore: true */\n /* @vite-ignore */\n url\n ).then(resolve).catch(rejectEntry);\n else resolve(remoteEntryExports);\n } catch (e) {\n error(`Failed to load ESM entry from "${url}". ${e instanceof Error ? e.message : String(e)}`);\n }\n });\n}\nasync function loadSystemJsEntry({ entry, remoteEntryExports }) {\n return new Promise((resolve, reject) => {\n try {\n if (!remoteEntryExports) if (typeof __system_context__ === "undefined") System.import(entry).then(resolve).catch(reject);\n else new Function("callbacks", `System.import("${entry}")${importCallback}`)([resolve, reject]);\n else resolve(remoteEntryExports);\n } catch (e) {\n error(`Failed to load SystemJS entry from "${entry}". ${e instanceof Error ? e.message : String(e)}`);\n }\n });\n}\nfunction handleRemoteEntryLoaded(name, globalName, entry) {\n const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);\n if (!entryExports) error(RUNTIME_001, runtimeDescMap, {\n remoteName: name,\n remoteEntryUrl: entry,\n remoteEntryKey\n });\n return entryExports;\n}\nasync function loadEntryScript({ name, globalName, entry, remoteInfo, loaderHook, getEntryUrl, resourceContext }) {\n const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);\n if (remoteEntryExports) return remoteEntryExports;\n const url = getEntryUrl ? getEntryUrl(entry) : entry;\n return loadScript(url, {\n attrs: {},\n createScriptHook: (url2, attrs) => {\n const res = loaderHook.lifecycle.createScript.emit({\n url: url2,\n attrs,\n remoteInfo,\n resourceContext: resourceContext ? {\n ...resourceContext,\n url: url2\n } : void 0\n });\n if (!res) return;\n if (res instanceof HTMLScriptElement) return res;\n if ("script" in res || "timeout" in res) return res;\n }\n }).then(() => {\n return handleRemoteEntryLoaded(name, globalName, entry);\n }, (loadError) => {\n const originalMsg = loadError instanceof Error ? loadError.message : String(loadError);\n error(RUNTIME_008, runtimeDescMap, {\n remoteName: name,\n resourceUrl: url\n }, originalMsg);\n });\n}\nasync function loadEntryDom({ remoteInfo, remoteEntryExports, loaderHook, getEntryUrl, resourceContext }) {\n const { entry, entryGlobalName: globalName, name, type } = remoteInfo;\n if (isEsmRemoteType(type)) return loadEsmEntry({\n entry,\n remoteEntryExports,\n name,\n getEntryUrl\n });\n if (type === "system") return loadSystemJsEntry({\n entry,\n remoteEntryExports\n });\n return loadEntryScript({\n entry,\n globalName,\n name,\n remoteInfo,\n loaderHook,\n getEntryUrl,\n resourceContext\n });\n}\nasync function loadEntryNode({ remoteInfo, loaderHook, resourceContext }) {\n const { entry, entryGlobalName: globalName, name, type } = remoteInfo;\n const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);\n if (remoteEntryExports) return remoteEntryExports;\n return loadScriptNode(entry, {\n attrs: {\n name,\n globalName,\n type\n },\n loaderHook: { createScriptHook: (url, attrs = {}) => {\n const res = loaderHook.lifecycle.createScript.emit({\n url,\n attrs,\n remoteInfo,\n resourceContext: resourceContext ? {\n ...resourceContext,\n url\n } : void 0\n });\n if (!res) return;\n if ("url" in res) return res;\n } }\n }).then(() => {\n return handleRemoteEntryLoaded(name, globalName, entry);\n }).catch((e) => {\n error(`Failed to load Node.js entry for remote "${name}" from "${entry}". ${e instanceof Error ? e.message : String(e)}`);\n });\n}\nfunction getRemoteEntryUniqueKey(remoteInfo) {\n const { entry, name } = remoteInfo;\n return composeKeyWithSeparator(name, entry);\n}\nasync function getRemoteEntry(params) {\n const { origin, remoteEntryExports, remoteInfo, getEntryUrl, resourceContext, _inErrorHandling = false } = params;\n const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);\n if (remoteEntryExports) {\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n remoteEntryExports,\n resourceContext,\n cached: true\n });\n return remoteEntryExports;\n }\n if (!globalLoading[uniqueKey]) {\n const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;\n const loaderHook = origin.loaderHook;\n const loading = loadEntryHook.emit({\n origin,\n loaderHook,\n remoteInfo,\n remoteEntryExports,\n resourceContext\n }).then((res) => {\n if (res) return res;\n return (typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : isBrowserEnvValue) ? loadEntryDom({\n remoteInfo,\n remoteEntryExports,\n loaderHook,\n getEntryUrl,\n resourceContext\n }) : loadEntryNode({\n remoteInfo,\n loaderHook,\n resourceContext\n });\n }).then(async (res) => {\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n remoteEntryExports: res,\n resourceContext\n });\n return res;\n }).catch(async (loadError) => {\n const isScriptExecutionError = loadError instanceof Error && loadError.message.includes("ScriptExecutionError");\n if (loadError instanceof Error && loadError.message.includes(RUNTIME_008) && !isScriptExecutionError && !_inErrorHandling) {\n const wrappedGetRemoteEntry = (params2) => {\n return getRemoteEntry({\n ...params2,\n _inErrorHandling: true\n });\n };\n const recoveredRemoteEntryExports = await origin.loaderHook.lifecycle.loadEntryError.emit({\n getRemoteEntry: wrappedGetRemoteEntry,\n origin,\n remoteInfo,\n remoteEntryExports,\n globalLoading,\n uniqueKey\n });\n if (recoveredRemoteEntryExports) {\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n remoteEntryExports: recoveredRemoteEntryExports,\n resourceContext,\n error: loadError,\n recovered: true\n });\n return recoveredRemoteEntryExports;\n }\n }\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n resourceContext,\n error: loadError\n });\n throw loadError;\n });\n globalLoading[uniqueKey] = loading;\n loading.then(void 0, () => {\n if (globalLoading[uniqueKey] === loading) delete globalLoading[uniqueKey];\n });\n remoteEntryLoadingOrigins.set(loading, origin);\n }\n const remoteEntryLoading = globalLoading[uniqueKey];\n if (remoteEntryLoadingOrigins.get(remoteEntryLoading) !== origin) try {\n const result = await remoteEntryLoading;\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n remoteEntryExports: result,\n resourceContext\n });\n return result;\n } catch (loadError) {\n await origin.loaderHook.lifecycle.afterLoadEntry.emit({\n origin,\n remoteInfo,\n resourceContext,\n error: loadError\n });\n throw loadError;\n }\n return remoteEntryLoading;\n}\nfunction getRemoteInfo(remote) {\n return {\n ...remote,\n entry: "entry" in remote ? remote.entry : "",\n type: remote.type || DEFAULT_REMOTE_TYPE,\n entryGlobalName: remote.entryGlobalName || remote.name,\n shareScope: remote.shareScope || DEFAULT_SCOPE\n };\n}\nfunction remoteToEntry(r) {\n return {\n name: r.name,\n alias: r.alias,\n entry: "entry" in r ? r.entry : void 0,\n version: "version" in r ? r.version : void 0,\n type: r.type,\n entryGlobalName: r.entryGlobalName,\n shareScope: r.shareScope\n };\n}\nfunction optionsToMFContext(options) {\n var _a, _b, _c, _d, _e, _f;\n const shared = {};\n for (const [pkgName, versions] of Object.entries(options.shared)) {\n const first = versions[0];\n if (first) shared[pkgName] = {\n version: first.version,\n singleton: (_a = first.shareConfig) == null ? void 0 : _a.singleton,\n requiredVersion: ((_b = first.shareConfig) == null ? void 0 : _b.requiredVersion) === false ? false : (_c = first.shareConfig) == null ? void 0 : _c.requiredVersion,\n eager: first.eager,\n strictVersion: (_d = first.shareConfig) == null ? void 0 : _d.strictVersion\n };\n }\n return {\n project: {\n name: options.name,\n mfRole: ((_e = options.remotes) == null ? void 0 : _e.length) > 0 ? "host" : "unknown"\n },\n mfConfig: {\n name: options.name,\n remotes: ((_f = options.remotes) == null ? void 0 : _f.map(remoteToEntry)) ?? [],\n shared\n }\n };\n}\nfunction isTimeoutError(error2) {\n if (!(error2 instanceof Error)) return false;\n return error2.message.includes("timed out") || error2.name.includes("Timeout");\n}\nfunction createAssetResult(context, url, status, error2) {\n return {\n url,\n status,\n resourceType: context.resourceType,\n initiator: context.initiator,\n id: context.id,\n error: error2\n };\n}\nfunction preloadAssetOnce(context, url, recordPreloadedAssets, preload) {\n if (!recordPreloadedAssets) return preload();\n if (getPreloadedAsset(url)) return Promise.resolve(createAssetResult(context, url, "cached"));\n setPreloadedAsset(url);\n return preload();\n}\nasync function waitForRemoteEntryPreload(host, remoteInfo, entryRemoteInfo, context) {\n const cachedRemote = host.moduleCache.get(entryRemoteInfo.name);\n const url = entryRemoteInfo.entry;\n if (cachedRemote == null ? void 0 : cachedRemote.remoteEntryExports) return createAssetResult(context, url, "cached");\n try {\n if (!await getRemoteEntry({\n origin: host,\n remoteInfo: entryRemoteInfo,\n remoteEntryExports: cachedRemote == null ? void 0 : cachedRemote.remoteEntryExports,\n resourceContext: {\n ...context,\n url\n }\n })) throw new Error(`Failed to load remoteEntry "${url}".`);\n return createAssetResult(context, url, "success");\n } catch (error2) {\n return createAssetResult(context, url, isTimeoutError(error2) ? "timeout" : "error", error2);\n }\n}\nfunction waitForLinkPreload({ host, remoteInfo, url, attrs, context, needDeleteLink }) {\n return new Promise((resolve) => {\n const { link, needAttach } = createLink({\n url,\n cb: () => {\n resolve(createAssetResult(context, url, needAttach ? "success" : "cached"));\n },\n onErrorCallback: (error2) => {\n resolve(createAssetResult(context, url, isTimeoutError(error2) ? "timeout" : "error", error2));\n },\n attrs,\n createLinkHook: (hookUrl, hookAttrs) => {\n const res = host.loaderHook.lifecycle.createLink.emit({\n url: hookUrl,\n attrs: hookAttrs,\n remoteInfo,\n resourceContext: {\n ...context,\n url: hookUrl\n }\n });\n if (res instanceof HTMLLinkElement) return res;\n return res;\n },\n needDeleteLink\n });\n needAttach && document.head.appendChild(link);\n });\n}\nfunction waitForScriptPreload({ host, remoteInfo, url, attrs, context }) {\n return new Promise((resolve) => {\n const { script, needAttach } = createScript({\n url,\n cb: () => {\n resolve(createAssetResult(context, url, needAttach ? "success" : "cached"));\n },\n onErrorCallback: (error2) => {\n resolve(createAssetResult(context, url, isTimeoutError(error2) ? "timeout" : "error", error2));\n },\n attrs,\n createScriptHook: (hookUrl, hookAttrs) => {\n const res = host.loaderHook.lifecycle.createScript.emit({\n url: hookUrl,\n attrs: hookAttrs,\n remoteInfo,\n resourceContext: {\n ...context,\n url: hookUrl\n }\n });\n if (res instanceof HTMLScriptElement) return res;\n return res;\n },\n needDeleteScript: true\n });\n needAttach && document.head.appendChild(script);\n });\n}\nfunction createResourceContext(baseContext, resourceType) {\n return {\n ...baseContext,\n resourceType\n };\n}\nfunction preloadAssets(remoteInfo, host, assets, useLinkPreload = true, baseContext = {\n initiator: "preloadRemote",\n id: remoteInfo.name\n}, recordPreloadedAssets = true) {\n const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;\n const results = [];\n if (host.options.inBrowser) {\n entryAssets.forEach((asset) => {\n const { moduleInfo: entryRemoteInfo } = asset;\n results.push(waitForRemoteEntryPreload(host, remoteInfo, entryRemoteInfo, createResourceContext(baseContext, "remoteEntry")));\n });\n if (useLinkPreload) {\n const defaultAttrs2 = {\n rel: "preload",\n as: "style"\n };\n cssAssets.forEach((cssUrl) => {\n const context = createResourceContext(baseContext, "css");\n results.push(preloadAssetOnce(context, cssUrl, recordPreloadedAssets, () => waitForLinkPreload({\n host,\n remoteInfo,\n url: cssUrl,\n attrs: defaultAttrs2,\n context\n })));\n });\n } else {\n const defaultAttrs2 = {\n rel: "stylesheet",\n type: "text/css"\n };\n cssAssets.forEach((cssUrl) => {\n const context = createResourceContext(baseContext, "css");\n results.push(preloadAssetOnce(context, cssUrl, recordPreloadedAssets, () => waitForLinkPreload({\n host,\n remoteInfo,\n url: cssUrl,\n attrs: defaultAttrs2,\n needDeleteLink: false,\n context\n })));\n });\n }\n let preloadJsAsset = waitForScriptPreload;\n let defaultAttrs = {\n fetchpriority: "high",\n type: "text/javascript"\n };\n if (useLinkPreload) {\n preloadJsAsset = waitForLinkPreload;\n defaultAttrs = {\n rel: "preload",\n as: "script"\n };\n } else if (isEsmRemoteType(remoteInfo.type)) {\n preloadJsAsset = waitForLinkPreload;\n defaultAttrs = {\n rel: "modulepreload",\n fetchpriority: "high"\n };\n }\n jsAssetsWithoutEntry.forEach((jsUrl) => {\n const context = createResourceContext(baseContext, "js");\n results.push(preloadAssetOnce(context, jsUrl, recordPreloadedAssets, () => preloadJsAsset({\n host,\n remoteInfo,\n url: jsUrl,\n attrs: defaultAttrs,\n context\n })));\n });\n }\n return Promise.all(results);\n}\nvar helpers_default = {\n utils: {\n matchRemoteWithNameAndExpose,\n preloadAssets,\n getRemoteInfo\n }\n};\nfunction getAvailableExposeNames(remoteSnapshot) {\n if (!remoteSnapshot || !("modules" in remoteSnapshot) || !Array.isArray(remoteSnapshot.modules)) return;\n const exposes = remoteSnapshot.modules.map((module) => module.moduleName).filter(Boolean);\n return exposes.length ? exposes.join(",") : void 0;\n}\nfunction createRemoteEntryInitOptions(remoteInfo, hostShareScopeMap, rawInitScope) {\n const localShareScopeMap = hostShareScopeMap;\n const shareScopeKeys = Array.isArray(remoteInfo.shareScope) ? remoteInfo.shareScope : [remoteInfo.shareScope];\n if (!shareScopeKeys.length) shareScopeKeys.push("default");\n shareScopeKeys.forEach((shareScopeKey) => {\n if (!localShareScopeMap[shareScopeKey]) localShareScopeMap[shareScopeKey] = {};\n });\n const remoteEntryInitOptions = {\n version: remoteInfo.version || "",\n shareScopeKeys: Array.isArray(remoteInfo.shareScope) ? shareScopeKeys : remoteInfo.shareScope || "default"\n };\n Object.defineProperty(remoteEntryInitOptions, "shareScopeMap", {\n value: localShareScopeMap,\n enumerable: false\n });\n return {\n remoteEntryInitOptions,\n shareScope: localShareScopeMap[shareScopeKeys[0]],\n initScope: rawInitScope ?? []\n };\n}\nvar Module$1 = class {\n constructor({ remoteInfo, host }) {\n this.inited = false;\n this.initing = false;\n this.lib = void 0;\n this.remoteInfo = remoteInfo;\n this.host = host;\n }\n async getEntry(expose, resourceContext) {\n const effectiveResourceContext = resourceContext || {\n initiator: "loadRemote",\n id: composeRemoteRequestId(this.remoteInfo.name, expose),\n resourceType: "remoteEntry",\n url: this.remoteInfo.entry,\n expose\n };\n const remoteEntryExports = await getRemoteEntry({\n origin: this.host,\n remoteInfo: this.remoteInfo,\n remoteEntryExports: this.remoteEntryExports,\n resourceContext: effectiveResourceContext\n });\n assert(remoteEntryExports, `remoteEntryExports is undefined \n ${safeToString(this.remoteInfo)}`);\n this.remoteEntryExports = remoteEntryExports;\n return this.remoteEntryExports;\n }\n async init(id, remoteSnapshot, rawInitScope, expose, resourceContext) {\n const remoteEntryExports = await this.getEntry(expose, resourceContext);\n if (this.inited) {\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n cached: true,\n origin: this.host\n });\n return remoteEntryExports;\n }\n if (this.initPromise) {\n try {\n await this.initPromise;\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n cached: true,\n origin: this.host\n });\n } catch (initError) {\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n error: initError,\n cached: true,\n origin: this.host\n });\n throw initError;\n }\n return remoteEntryExports;\n }\n this.initing = true;\n this.initPromise = (async () => {\n await this.host.loaderHook.lifecycle.beforeInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n origin: this.host\n });\n const { remoteEntryInitOptions, shareScope, initScope } = createRemoteEntryInitOptions(this.remoteInfo, this.host.shareScopeMap, rawInitScope);\n const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({\n shareScope,\n remoteEntryInitOptions,\n initScope,\n remoteInfo: this.remoteInfo,\n origin: this.host\n });\n if (typeof (remoteEntryExports == null ? void 0 : remoteEntryExports.init) === "undefined") error(RUNTIME_002, runtimeDescMap, {\n hostName: this.host.name,\n remoteName: this.remoteInfo.name,\n remoteEntryUrl: this.remoteInfo.entry,\n remoteEntryKey: this.remoteInfo.entryGlobalName\n }, void 0, optionsToMFContext(this.host.options));\n try {\n await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);\n } catch (initError) {\n error(RUNTIME_015, runtimeDescMap, {\n hostName: this.host.name,\n remoteName: this.remoteInfo.name,\n remoteEntryUrl: this.remoteInfo.entry,\n remoteEntryKey: this.remoteInfo.entryGlobalName,\n shareScope: this.remoteInfo.shareScope\n }, `${initError}`, optionsToMFContext(this.host.options));\n }\n await this.host.hooks.lifecycle.initContainer.emit({\n ...initContainerOptions,\n id,\n remoteSnapshot,\n remoteEntryExports\n });\n this.inited = true;\n })();\n try {\n await this.initPromise;\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n origin: this.host\n });\n } catch (initError) {\n await this.host.loaderHook.lifecycle.afterInitRemote.emit({\n id,\n remoteInfo: this.remoteInfo,\n remoteSnapshot,\n remoteEntryExports,\n error: initError,\n origin: this.host\n });\n throw initError;\n } finally {\n this.initing = false;\n this.initPromise = void 0;\n }\n return remoteEntryExports;\n }\n async get(id, expose, options, remoteSnapshot) {\n const { loadFactory = true } = options || { loadFactory: true };\n const remoteEntryExports = await this.init(id, remoteSnapshot, void 0, expose);\n this.lib = remoteEntryExports;\n await this.host.loaderHook.lifecycle.beforeGetExpose.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n remoteEntryExports,\n origin: this.host\n });\n let moduleFactory;\n try {\n const hookModuleFactory = await this.host.loaderHook.lifecycle.getModuleFactory.emit({\n remoteEntryExports,\n expose,\n moduleInfo: this.remoteInfo\n });\n moduleFactory = typeof hookModuleFactory === "function" ? hookModuleFactory : void 0;\n if (!moduleFactory) moduleFactory = await remoteEntryExports.get(expose);\n if (!moduleFactory) error(RUNTIME_014, runtimeDescMap, {\n hostName: this.host.name,\n remoteName: this.remoteInfo.name,\n remoteEntryUrl: this.remoteInfo.entry,\n expose,\n requestId: id,\n availableExposes: getAvailableExposeNames(remoteSnapshot)\n }, void 0, optionsToMFContext(this.host.options));\n await this.host.loaderHook.lifecycle.afterGetExpose.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n remoteEntryExports,\n moduleFactory,\n origin: this.host\n });\n } catch (getExposeError) {\n await this.host.loaderHook.lifecycle.afterGetExpose.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n remoteEntryExports,\n error: getExposeError,\n origin: this.host\n });\n throw getExposeError;\n }\n const symbolName = processModuleAlias(this.remoteInfo.name, expose);\n const wrapModuleFactory = this.wraperFactory(moduleFactory, symbolName);\n if (!loadFactory) return wrapModuleFactory;\n await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n loadFactory,\n origin: this.host\n });\n try {\n const exposeContent = await wrapModuleFactory();\n await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n loadFactory,\n exposeModule: exposeContent,\n origin: this.host\n });\n return exposeContent;\n } catch (executeFactoryError) {\n await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({\n id,\n expose,\n moduleInfo: this.remoteInfo,\n loadFactory,\n error: executeFactoryError,\n origin: this.host\n });\n throw executeFactoryError;\n }\n }\n wraperFactory(moduleFactory, id) {\n function defineModuleId(res, id2) {\n if (res && typeof res === "object" && Object.isExtensible(res) && !Object.getOwnPropertyDescriptor(res, Symbol.for("mf_module_id"))) Object.defineProperty(res, Symbol.for("mf_module_id"), {\n value: id2,\n enumerable: false\n });\n }\n return () => {\n const res = moduleFactory();\n if (res instanceof Promise) return res.then((asyncRes) => {\n defineModuleId(asyncRes, id);\n return asyncRes;\n });\n defineModuleId(res, id);\n return res;\n };\n }\n};\nconst REMOTE_DISABLED_MESSAGE = "Remote loading is disabled by experiments.optimization.disableRemote.";\nvar UnavailableRemoteModule = class {\n constructor() {\n throw new Error(REMOTE_DISABLED_MESSAGE);\n }\n};\ntypeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN === "boolean" ? !FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN : true;\ntypeof FEDERATION_OPTIMIZE_NO_REMOTE === "boolean" ? !FEDERATION_OPTIMIZE_NO_REMOTE : true;\ntypeof FEDERATION_OPTIMIZE_NO_SHARED === "boolean" ? !FEDERATION_OPTIMIZE_NO_SHARED : true;\nconst helpers = helpers_default;\ntypeof FEDERATION_OPTIMIZE_NO_REMOTE === "boolean" && FEDERATION_OPTIMIZE_NO_REMOTE ? UnavailableRemoteModule : Module$1;\nconst utils = helpers.utils;\nconst runtimeHelpers = {\n utils\n};\nasync function prefetch(options) {\n const { instance, id, dataFetchParams, preloadComponentResource } = options;\n if (!id) {\n logger.error("id is required for prefetch!");\n return;\n }\n if (!instance) {\n logger.error("instance is required for prefetch!");\n return;\n }\n const matchedRemoteInfo = runtimeHelpers.utils.matchRemoteWithNameAndExpose(\n instance.options.remotes,\n id\n );\n if (!matchedRemoteInfo) {\n logger.error(`Can not found \'${id}\' in instance.options.remotes!`);\n return;\n }\n const { remote, expose } = matchedRemoteInfo;\n const { remoteSnapshot, globalSnapshot } = await instance.snapshotHandler.loadRemoteSnapshotInfo({\n moduleInfo: remote,\n id\n });\n if (preloadComponentResource) {\n const remoteInfo = runtimeHelpers.utils.getRemoteInfo(remote);\n Promise.resolve(\n instance.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({\n origin: instance,\n preloadOptions: {\n remote,\n preloadConfig: {\n nameOrAlias: remote.name,\n exposes: [expose]\n }\n },\n remote,\n remoteInfo,\n globalSnapshot,\n remoteSnapshot\n })\n ).then((assets) => {\n if (assets) {\n runtimeHelpers.utils.preloadAssets(remoteInfo, instance, assets);\n }\n });\n }\n const dataFetchMap = getDataFetchMap();\n if (!dataFetchMap) {\n return;\n }\n const dataFetchInfo = getDataFetchInfo({\n name: remote.name,\n alias: remote.alias,\n id,\n remoteSnapshot\n });\n const dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {\n name: instance.name,\n version: instance.options.version\n });\n if (!dataFetchMapKey) {\n return;\n }\n const dataFetchItem = dataFetchMap[dataFetchMapKey];\n if (!dataFetchItem) {\n return;\n }\n const [getDataFetchGetter, _type, getDataFetchPromise] = dataFetchItem[0];\n let _getDataFetchPromise = getDataFetchPromise;\n if (!getDataFetchPromise) {\n if (!getDataFetchGetter) {\n return;\n }\n _getDataFetchPromise = getDataFetchGetter();\n }\n _getDataFetchPromise.then((dataFetchFn) => {\n return dataFetchFn({\n ...dataFetchParams,\n _id: dataFetchMapKey,\n isDowngrade: false\n });\n });\n}\nexport {\n dataFetchFunction as d,\n injectDataFetch as i,\n prefetch as p\n};\n',
|
|
213
|
+
"size-limited-cache.es.js": "var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nclass SizeLimitedCache {\n constructor(options) {\n __publicField(this, \"maxSize\");\n __publicField(this, \"entries\", /* @__PURE__ */ new Map());\n __publicField(this, \"sizeCalculation\");\n __publicField(this, \"currentSize\", 0);\n if (!Number.isInteger(options.maxSize) || options.maxSize <= 0) {\n throw new TypeError(\"maxSize must be a positive integer\");\n }\n this.maxSize = options.maxSize;\n this.sizeCalculation = options.sizeCalculation;\n }\n get size() {\n return this.entries.size;\n }\n get calculatedSize() {\n return this.currentSize;\n }\n get(key) {\n const entry = this.entries.get(key);\n if (!entry) {\n return void 0;\n }\n this.refresh(key, entry);\n return entry.value;\n }\n has(key) {\n const entry = this.entries.get(key);\n if (!entry) {\n return false;\n }\n this.refresh(key, entry);\n return true;\n }\n set(key, value, options = {}) {\n var _a;\n const entrySize = options.size ?? ((_a = this.sizeCalculation) == null ? void 0 : _a.call(this, value, key)) ?? 1;\n if (!Number.isInteger(entrySize) || entrySize <= 0) {\n throw new TypeError(\"entry size must be a positive integer\");\n }\n this.delete(key);\n if (entrySize > this.maxSize) {\n return this;\n }\n this.entries.set(key, { value, size: entrySize });\n this.currentSize += entrySize;\n this.evictUntilWithinLimit();\n return this;\n }\n delete(key) {\n const entry = this.entries.get(key);\n if (!entry) {\n return false;\n }\n this.currentSize -= entry.size;\n return this.entries.delete(key);\n }\n clear() {\n this.entries.clear();\n this.currentSize = 0;\n }\n refresh(key, entry) {\n this.entries.delete(key);\n this.entries.set(key, entry);\n }\n evictUntilWithinLimit() {\n while (this.currentSize > this.maxSize) {\n const oldest = this.entries.keys().next();\n if (oldest.done) {\n this.currentSize = 0;\n return;\n }\n this.delete(oldest.value);\n }\n }\n}\nexport {\n SizeLimitedCache\n};\n",
|
|
214
|
+
"utils-BBP3hEeV.mjs": "import { S as SEPARATOR, c as createLogger, i as isBrowserEnvValue } from \"./logger-DwWkXsWl.mjs\";\nimport { SizeLimitedCache } from \"./size-limited-cache.es.js\";\nconst LOG_CATEGORY = \"[ Federation Runtime ]\";\nconst composeKeyWithSeparator = function(...args) {\n if (!args.length) return \"\";\n return args.reduce((sum, cur) => {\n if (!cur) return sum;\n if (!sum) return cur;\n return `${sum}${SEPARATOR}${cur}`;\n }, \"\");\n};\nconst warn = (msg) => {\n console.warn(`${LOG_CATEGORY}: ${msg}`);\n};\nfunction safeToString(info) {\n try {\n return JSON.stringify(info, null, 2);\n } catch (e) {\n return \"\";\n }\n}\nconst PLUGIN_IDENTIFIER = \"[ Module Federation React ]\";\nconst DOWNGRADE_KEY = \"_mfSSRDowngrade\";\nconst DATA_FETCH_FUNCTION = \"_mfDataFetch\";\nconst FS_HREF = \"_mfFSHref\";\nconst ERROR_TYPE = {\n DATA_FETCH: 1,\n LOAD_REMOTE: 2,\n UNKNOWN: 3\n};\nconst WRAP_DATA_FETCH_ID_IDENTIFIER = \"wrap_dfip_identifier\";\nvar MF_DATA_FETCH_TYPE = /* @__PURE__ */ ((MF_DATA_FETCH_TYPE2) => {\n MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2[\"FETCH_SERVER\"] = 1] = \"FETCH_SERVER\";\n MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2[\"FETCH_CLIENT\"] = 2] = \"FETCH_CLIENT\";\n return MF_DATA_FETCH_TYPE2;\n})(MF_DATA_FETCH_TYPE || {});\nvar MF_DATA_FETCH_STATUS = /* @__PURE__ */ ((MF_DATA_FETCH_STATUS2) => {\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"LOADED\"] = 1] = \"LOADED\";\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"LOADING\"] = 2] = \"LOADING\";\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"AWAIT\"] = 0] = \"AWAIT\";\n MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2[\"ERROR\"] = 3] = \"ERROR\";\n return MF_DATA_FETCH_STATUS2;\n})(MF_DATA_FETCH_STATUS || {});\nconst DATA_FETCH_IDENTIFIER = \"data\";\nconst DATA_FETCH_CLIENT_SUFFIX = \".client\";\nconst DATA_FETCH_QUERY = \"x-mf-data-fetch\";\nconst DATA_FETCH_ERROR_PREFIX = \"caught the following error during dataFetch: \";\nconst LOAD_REMOTE_ERROR_PREFIX = \"caught the following error during loadRemote: \";\nconst logger = createLogger(PLUGIN_IDENTIFIER);\nconst CacheSize = {\n KB: 1024,\n MB: 1024 * 1024,\n GB: 1024 * 1024 * 1024\n};\nconst CacheTime = {\n SECOND: 1e3,\n MINUTE: 60 * 1e3,\n HOUR: 60 * 60 * 1e3,\n DAY: 24 * 60 * 60 * 1e3,\n WEEK: 7 * 24 * 60 * 60 * 1e3,\n MONTH: 30 * 24 * 60 * 60 * 1e3\n};\nfunction getTagKeyMap() {\n const dataFetchCache = getDataFetchCache();\n if (!dataFetchCache || !dataFetchCache.tagKeyMap) {\n const tagKeyMap = /* @__PURE__ */ new Map();\n globalThis.__MF_DATA_FETCH_CACHE__ || (globalThis.__MF_DATA_FETCH_CACHE__ = {});\n globalThis.__MF_DATA_FETCH_CACHE__.tagKeyMap = tagKeyMap;\n return tagKeyMap;\n }\n return dataFetchCache.tagKeyMap;\n}\nfunction addTagKeyRelation(tag, key) {\n const tagKeyMap = getTagKeyMap();\n let keys = tagKeyMap.get(tag);\n if (!keys) {\n keys = /* @__PURE__ */ new Set();\n tagKeyMap.set(tag, keys);\n }\n keys.add(key);\n}\nfunction getCacheConfig() {\n const dataFetchCache = getDataFetchCache();\n if (!dataFetchCache || !dataFetchCache.cacheConfig) {\n const cacheConfig = {\n maxSize: CacheSize.GB\n };\n globalThis.__MF_DATA_FETCH_CACHE__ || (globalThis.__MF_DATA_FETCH_CACHE__ = {});\n globalThis.__MF_DATA_FETCH_CACHE__.cacheConfig = cacheConfig;\n return cacheConfig;\n }\n return dataFetchCache.cacheConfig;\n}\nfunction configureCache(config) {\n const cacheConfig = getCacheConfig();\n Object.assign(cacheConfig, config);\n}\nfunction getSizeLimitedCache() {\n const dataFetchCache = getDataFetchCache();\n const cacheConfig = getCacheConfig();\n if (!dataFetchCache || !dataFetchCache.cacheStore) {\n const cacheStore = new SizeLimitedCache({\n maxSize: cacheConfig.maxSize ?? CacheSize.GB,\n sizeCalculation: (value) => {\n if (!value.size) {\n return 1;\n }\n let size = 0;\n for (const [k, item] of value.entries()) {\n size += k.length * 2;\n size += estimateObjectSize(item.data);\n size += 8;\n }\n return size;\n }\n });\n globalThis.__MF_DATA_FETCH_CACHE__ || (globalThis.__MF_DATA_FETCH_CACHE__ = {});\n globalThis.__MF_DATA_FETCH_CACHE__.cacheStore = cacheStore;\n return cacheStore;\n }\n return dataFetchCache.cacheStore;\n}\nfunction estimateObjectSize(data) {\n const type = typeof data;\n if (type === \"number\") return 8;\n if (type === \"boolean\") return 4;\n if (type === \"string\") return Math.max(data.length * 2, 1);\n if (data === null || data === void 0) return 1;\n if (ArrayBuffer.isView(data)) {\n return Math.max(data.byteLength, 1);\n }\n if (Array.isArray(data)) {\n return Math.max(\n data.reduce((acc, item) => acc + estimateObjectSize(item), 0),\n 1\n );\n }\n if (data instanceof Map || data instanceof Set) {\n return 1024;\n }\n if (data instanceof Date) {\n return 8;\n }\n if (type === \"object\") {\n return Math.max(\n Object.entries(data).reduce(\n (acc, [key, value]) => acc + key.length * 2 + estimateObjectSize(value),\n 0\n ),\n 1\n );\n }\n return 1;\n}\nfunction generateKey(dataFetchOptions) {\n return JSON.stringify(dataFetchOptions, (_, value) => {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return Object.keys(value).sort().reduce((result, key) => {\n result[key] = value[key];\n return result;\n }, {});\n }\n return value;\n });\n}\nfunction cache(fn, options) {\n const {\n tag = \"default\",\n maxAge = CacheTime.MINUTE * 5,\n revalidate = 0,\n onCache,\n getKey\n } = options || {};\n const tags = Array.isArray(tag) ? tag : [tag];\n return async (dataFetchOptions) => {\n if (dataFetchOptions.isDowngrade || !dataFetchOptions._id) {\n return fn(dataFetchOptions);\n }\n const store = getSizeLimitedCache();\n const now = Date.now();\n const storeKey = dataFetchOptions._id;\n const cacheKey = getKey ? getKey(dataFetchOptions) : generateKey(dataFetchOptions);\n tags.forEach((t) => addTagKeyRelation(t, cacheKey));\n let cacheStore = store.get(cacheKey);\n if (!cacheStore) {\n cacheStore = /* @__PURE__ */ new Map();\n }\n const cached = cacheStore.get(storeKey);\n if (cached) {\n const age = now - cached.timestamp;\n if (age < maxAge) {\n if (onCache) {\n const useCache = onCache({\n status: \"hit\",\n key: cacheKey,\n params: dataFetchOptions,\n result: cached.data\n });\n if (!useCache) {\n return fn(dataFetchOptions);\n }\n }\n return cached.data;\n }\n if (revalidate > 0 && age < maxAge + revalidate) {\n if (onCache) {\n onCache({\n status: \"stale\",\n key: cacheKey,\n params: dataFetchOptions,\n result: cached.data\n });\n }\n if (!cached.isRevalidating) {\n cached.isRevalidating = true;\n Promise.resolve().then(async () => {\n try {\n const newData = await fn(dataFetchOptions);\n cacheStore.set(storeKey, {\n data: newData,\n timestamp: Date.now(),\n isRevalidating: false\n });\n store.set(cacheKey, cacheStore);\n } catch (error) {\n cached.isRevalidating = false;\n console.error(\"Background revalidation failed:\", error);\n }\n });\n }\n return cached.data;\n }\n }\n const data = await fn(dataFetchOptions);\n cacheStore.set(storeKey, {\n data,\n timestamp: now,\n isRevalidating: false\n });\n store.set(cacheKey, cacheStore);\n if (onCache) {\n onCache({\n status: \"miss\",\n key: cacheKey,\n params: dataFetchOptions,\n result: data\n });\n }\n return data;\n };\n}\nfunction revalidateTag(tag) {\n const tagKeyMap = getTagKeyMap();\n const keys = tagKeyMap.get(tag);\n const cacheStore = getSizeLimitedCache();\n if (keys) {\n keys.forEach((key) => {\n cacheStore == null ? void 0 : cacheStore.delete(key);\n });\n }\n}\nfunction clearStore() {\n var _a;\n const cacheStore = getSizeLimitedCache();\n const tagKeyMap = getTagKeyMap();\n cacheStore == null ? void 0 : cacheStore.clear();\n (_a = globalThis.__MF_DATA_FETCH_CACHE__) == null ? true : delete _a.cacheStore;\n tagKeyMap.clear();\n}\nconst getDataFetchInfo = ({\n name,\n alias,\n id,\n remoteSnapshot\n}) => {\n if (!remoteSnapshot) {\n return;\n }\n if (!(\"modules\" in remoteSnapshot)) {\n return;\n }\n const regex = new RegExp(`^${name}(/[^/].*|)$`);\n const nameOrAlias = regex.test(id) ? name : alias || name;\n const expose = id.replace(nameOrAlias, \"\");\n let dataFetchName = \"\";\n let dataFetchId = \"\";\n let dataFetchKey = \"\";\n if (expose.startsWith(\"/\")) {\n dataFetchName = `${expose.slice(1)}.${DATA_FETCH_IDENTIFIER}`;\n dataFetchId = `${id}.${DATA_FETCH_IDENTIFIER}`;\n dataFetchKey = `${name}${expose}.${DATA_FETCH_IDENTIFIER}`;\n } else if (expose === \"\") {\n dataFetchName = DATA_FETCH_IDENTIFIER;\n dataFetchId = `${id}/${DATA_FETCH_IDENTIFIER}`;\n dataFetchKey = `${name}/${DATA_FETCH_IDENTIFIER}`;\n } else {\n return;\n }\n if (!dataFetchName || !dataFetchId || !dataFetchKey) {\n return;\n }\n if (!remoteSnapshot.modules.find(\n (module) => module.moduleName === dataFetchName\n )) {\n return;\n }\n return {\n dataFetchName,\n dataFetchId,\n dataFetchKey\n };\n};\nfunction initDataFetchMap() {\n globalThis.__MF_DATA_FETCH_MAP__ || (globalThis.__MF_DATA_FETCH_MAP__ = {});\n}\nfunction getDataFetchItem(id) {\n var _a;\n return (_a = globalThis.__MF_DATA_FETCH_MAP__) == null ? void 0 : _a[id];\n}\nfunction getDataFetchMap() {\n return globalThis.__MF_DATA_FETCH_MAP__;\n}\nfunction getDataFetchCache() {\n return globalThis.__MF_DATA_FETCH_CACHE__;\n}\nconst flushDataFetch = () => {\n globalThis.__MF_DATA_FETCH_MAP__ = {};\n globalThis[DOWNGRADE_KEY] = void 0;\n clearStore();\n};\nfunction setDataFetchItemLoadedStatus(id) {\n const dataFetchItem = getDataFetchItem(id);\n if (!dataFetchItem) {\n return;\n }\n dataFetchItem[2] = MF_DATA_FETCH_STATUS.LOADED;\n}\nconst wrapDataFetchId = (id) => {\n return `${WRAP_DATA_FETCH_ID_IDENTIFIER}${id}${WRAP_DATA_FETCH_ID_IDENTIFIER}`;\n};\nconst getDataFetchIdWithErrorMsgs = (errMsgs) => {\n const firstIdentifierIndex = errMsgs.indexOf(WRAP_DATA_FETCH_ID_IDENTIFIER);\n if (firstIdentifierIndex === -1) {\n return void 0;\n }\n const secondIdentifierIndex = errMsgs.indexOf(\n WRAP_DATA_FETCH_ID_IDENTIFIER,\n firstIdentifierIndex + WRAP_DATA_FETCH_ID_IDENTIFIER.length\n );\n if (secondIdentifierIndex === -1) {\n return void 0;\n }\n return errMsgs.substring(\n firstIdentifierIndex + WRAP_DATA_FETCH_ID_IDENTIFIER.length,\n secondIdentifierIndex\n );\n};\nasync function fetchData(id, params, remoteInfo) {\n var _a;\n const callFetchData = async () => {\n const item = getDataFetchItem(id);\n if (!item) {\n return;\n }\n const [fetchDataFnArr, ..._rest] = item;\n const fetchDataFn = await fetchDataFnArr[2];\n if (!fetchDataFn) {\n return;\n }\n return fetchDataFn({\n ...params,\n _id: id\n });\n };\n if (isBrowserEnvValue) {\n const dataFetchItem = getDataFetchItem(id);\n if (!dataFetchItem) {\n throw new Error(`dataFetchItem not found, id: ${id}`);\n }\n if ((_a = dataFetchItem[1]) == null ? void 0 : _a[0]) {\n return dataFetchItem[1][0];\n }\n if (isCSROnly()) {\n logger.debug(\"==========csr only!\");\n return callFetchData();\n }\n if (remoteInfo) {\n return callDowngrade(id, params, remoteInfo);\n }\n const mfDowngrade = getDowngradeTag();\n if (mfDowngrade && (typeof mfDowngrade === \"boolean\" || mfDowngrade.includes(id))) {\n return callDowngrade(id, { ...params, isDowngrade: true });\n }\n let res;\n let rej;\n const p = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n dataFetchItem[1] = [p, res, rej];\n dataFetchItem[2] = MF_DATA_FETCH_STATUS.AWAIT;\n return dataFetchItem[1][0];\n }\n return callFetchData();\n}\nfunction getDataFetchMapKey(dataFetchInfo, hostInfo) {\n if (!dataFetchInfo || !hostInfo) {\n return;\n }\n const { dataFetchKey } = dataFetchInfo;\n return composeKeyWithSeparator(dataFetchKey, hostInfo.name, hostInfo.version);\n}\nasync function loadDataFetchModule(instance, id) {\n return instance.loadRemote(id).then((m) => {\n if (m && typeof m === \"object\" && \"fetchData\" in m && typeof m.fetchData === \"function\") {\n return m.fetchData;\n }\n throw new Error(\n `fetchData not found in remote ${id}, ${JSON.stringify(m)}`\n );\n });\n}\nfunction isDataLoaderExpose(exposeKey) {\n return exposeKey.endsWith(DATA_FETCH_IDENTIFIER) || exposeKey.endsWith(DATA_FETCH_CLIENT_SUFFIX);\n}\nfunction getDowngradeTag() {\n return globalThis[DOWNGRADE_KEY];\n}\nfunction callAllDowngrade() {\n const dataFetchMap = getDataFetchMap();\n if (!dataFetchMap) {\n return;\n }\n Object.keys(dataFetchMap).forEach((key) => {\n callDowngrade(key);\n });\n}\nasync function callDowngrade(id, params, remoteInfo) {\n const dataFetchMap = getDataFetchMap();\n if (!dataFetchMap) {\n return;\n }\n const mfDataFetch = dataFetchMap[id];\n if ((mfDataFetch == null ? void 0 : mfDataFetch[2]) === MF_DATA_FETCH_STATUS.AWAIT) {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADING;\n let promise;\n let res;\n let rej;\n if (mfDataFetch[1]) {\n promise = mfDataFetch[1][0];\n res = mfDataFetch[1][1];\n rej = mfDataFetch[1][2];\n } else {\n promise = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n mfDataFetch[1] = [promise, res, rej];\n }\n const dataFetchType = mfDataFetch[0][1];\n if (dataFetchType === MF_DATA_FETCH_TYPE.FETCH_CLIENT) {\n try {\n mfDataFetch[0][0]().then(async (getDataFetchFn) => {\n return getDataFetchFn({\n ...params,\n isDowngrade: true,\n _id: id\n }).then((data) => {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADED;\n res && res(data);\n });\n });\n } catch (e) {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.ERROR;\n rej && rej(e);\n }\n } else if (dataFetchType === MF_DATA_FETCH_TYPE.FETCH_SERVER) {\n try {\n const currentUrl = new URL(window.location.href);\n currentUrl.searchParams.set(DATA_FETCH_QUERY, encodeURIComponent(id));\n if (params) {\n currentUrl.searchParams.set(\n \"params\",\n encodeURIComponent(JSON.stringify(params))\n );\n }\n if (remoteInfo) {\n currentUrl.searchParams.set(\n \"remoteInfo\",\n encodeURIComponent(JSON.stringify(remoteInfo))\n );\n }\n const fetchServerQuery = globalThis.FEDERATION_SERVER_QUERY;\n if (fetchServerQuery && typeof fetchServerQuery === \"object\") {\n Object.keys(fetchServerQuery).forEach((key) => {\n currentUrl.searchParams.set(\n key,\n JSON.stringify(fetchServerQuery[key])\n );\n });\n }\n const fetchUrl = currentUrl.toString();\n const data = await fetch(fetchUrl).then((res2) => res2.json());\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADED;\n res && res(data);\n } catch (e) {\n mfDataFetch[2] = MF_DATA_FETCH_STATUS.ERROR;\n rej && rej(e);\n }\n }\n return promise;\n }\n}\nfunction isCSROnly() {\n return window._SSR_DATA === void 0;\n}\nfunction isServerEnv() {\n return typeof window === \"undefined\";\n}\nfunction setSSREnv({\n fetchServerQuery\n}) {\n globalThis.FEDERATION_SSR = true;\n globalThis.FEDERATION_SERVER_QUERY = fetchServerQuery;\n}\nfunction getLoadedRemoteInfos(id, instance) {\n if (!instance) {\n return;\n }\n const { name, expose } = instance.remoteHandler.idToRemoteMap[id] || {};\n if (!name) {\n return;\n }\n const module = instance.moduleCache.get(name);\n if (!module) {\n return;\n }\n const { remoteSnapshot } = instance.snapshotHandler.getGlobalRemoteInfo(\n module.remoteInfo\n );\n return {\n ...module.remoteInfo,\n snapshot: remoteSnapshot,\n expose\n };\n}\nexport {\n setDataFetchItemLoadedStatus as A,\n warn as B,\n CacheSize as C,\n DATA_FETCH_QUERY as D,\n ERROR_TYPE as E,\n FS_HREF as F,\n DOWNGRADE_KEY as G,\n callAllDowngrade as H,\n callDowngrade as I,\n getDowngradeTag as J,\n composeKeyWithSeparator as K,\n LOAD_REMOTE_ERROR_PREFIX as L,\n MF_DATA_FETCH_STATUS as M,\n safeToString as N,\n getDataFetchCache as O,\n CacheTime as a,\n clearStore as b,\n cache as c,\n configureCache as d,\n getDataFetchMap as e,\n flushDataFetch as f,\n generateKey as g,\n fetchData as h,\n initDataFetchMap as i,\n loadDataFetchModule as j,\n isDataLoaderExpose as k,\n logger as l,\n getDataFetchInfo as m,\n getDataFetchMapKey as n,\n getDataFetchItem as o,\n DATA_FETCH_CLIENT_SUFFIX as p,\n MF_DATA_FETCH_TYPE as q,\n revalidateTag as r,\n setSSREnv as s,\n isCSROnly as t,\n isServerEnv as u,\n getDataFetchIdWithErrorMsgs as v,\n DATA_FETCH_ERROR_PREFIX as w,\n wrapDataFetchId as x,\n DATA_FETCH_FUNCTION as y,\n getLoadedRemoteInfos as z\n};\n"
|
|
215
|
+
};
|
|
216
|
+
const ENTRY_FILE = 'entry.ts';
|
|
217
|
+
const APP_FILE = 'app.tsx';
|
|
218
|
+
const BRIDGE_ROOT = 'bridge';
|
|
219
|
+
const BRIDGE_INDEX_FILE = `${BRIDGE_ROOT}/index.es.js`;
|
|
220
|
+
const BRIDGE_ROUTER_STUB_FILE = `${BRIDGE_ROOT}/react-router-dom-stub.js`;
|
|
221
|
+
const BRIDGE_ROUTER_STUB_SOURCE = `export function useLocation() {
|
|
206
222
|
throw new Error('react-router-dom is not available in playground bridge runtime.');
|
|
207
223
|
}
|
|
208
224
|
export const useRouteMatch = undefined;
|
|
@@ -211,7 +227,7 @@ export const useHref = undefined;
|
|
|
211
227
|
export const UNSAFE_RouteContext = undefined;
|
|
212
228
|
export default {};
|
|
213
229
|
`;
|
|
214
|
-
const BRIDGE_REACT_SHIM_SOURCE = `const React = window.React;
|
|
230
|
+
const BRIDGE_REACT_SHIM_SOURCE = `const React = window.React;
|
|
215
231
|
if (!React) {
|
|
216
232
|
throw new Error('React runtime is not available for bridge runtime.');
|
|
217
233
|
}
|
|
@@ -227,7 +243,7 @@ export const useEffect = React.useEffect;
|
|
|
227
243
|
export const useRef = React.useRef;
|
|
228
244
|
export const useState = React.useState;
|
|
229
245
|
`;
|
|
230
|
-
const BRIDGE_REACT_DOM_SHIM_SOURCE = `const ReactDOM = window.ReactDOM;
|
|
246
|
+
const BRIDGE_REACT_DOM_SHIM_SOURCE = `const ReactDOM = window.ReactDOM;
|
|
231
247
|
if (!ReactDOM) {
|
|
232
248
|
throw new Error('ReactDOM runtime is not available for bridge runtime.');
|
|
233
249
|
}
|
|
@@ -236,64 +252,64 @@ export const createRoot = ReactDOM.createRoot;
|
|
|
236
252
|
export const render = ReactDOM.render;
|
|
237
253
|
export const unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
|
|
238
254
|
`;
|
|
239
|
-
const BRIDGE_SHIM_MODULES = {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
};
|
|
244
|
-
function buildBridgeRuntimeFiles() {
|
|
245
|
-
return {
|
|
246
|
-
...Object.fromEntries(Object.entries(BRIDGE_RUNTIME_FILES).map(([filename, source])=>[
|
|
247
|
-
`${BRIDGE_ROOT}/${filename}`,
|
|
248
|
-
String(source).replace(/(["'])react-router-dom\1/g, '$1./react-router-dom-stub.js$1')
|
|
249
|
-
])),
|
|
250
|
-
[BRIDGE_ROUTER_STUB_FILE]: BRIDGE_ROUTER_STUB_SOURCE
|
|
255
|
+
const BRIDGE_SHIM_MODULES = {
|
|
256
|
+
react: BRIDGE_REACT_SHIM_SOURCE,
|
|
257
|
+
'react-dom': BRIDGE_REACT_DOM_SHIM_SOURCE,
|
|
258
|
+
'react-dom/client': BRIDGE_REACT_DOM_SHIM_SOURCE
|
|
251
259
|
};
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
260
|
+
function buildBridgeRuntimeFiles() {
|
|
261
|
+
return {
|
|
262
|
+
...Object.fromEntries(Object.entries(BRIDGE_RUNTIME_FILES).map(([filename, source])=>[
|
|
263
|
+
`${BRIDGE_ROOT}/${filename}`,
|
|
264
|
+
String(source).replace(/(["'])react-router-dom\1/g, '$1./react-router-dom-stub.js$1')
|
|
265
|
+
])),
|
|
266
|
+
[BRIDGE_ROUTER_STUB_FILE]: BRIDGE_ROUTER_STUB_SOURCE
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function transpileModule(ts, filename, source) {
|
|
270
|
+
const result = ts.transpileModule(source, {
|
|
271
|
+
fileName: filename,
|
|
272
|
+
compilerOptions: {
|
|
273
|
+
allowSyntheticDefaultImports: true,
|
|
274
|
+
esModuleInterop: true,
|
|
275
|
+
jsx: ts.JsxEmit.React,
|
|
276
|
+
module: ts.ModuleKind.CommonJS,
|
|
277
|
+
moduleResolution: ts.ModuleResolutionKind.NodeJs,
|
|
278
|
+
target: ts.ScriptTarget.ES2020
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
if (result.diagnostics?.length) {
|
|
282
|
+
const message = result.diagnostics.map((diagnostic)=>'string' == typeof diagnostic.messageText ? diagnostic.messageText : diagnostic.messageText.messageText).join('\n');
|
|
283
|
+
if (message) throw new Error(message);
|
|
263
284
|
}
|
|
264
|
-
|
|
265
|
-
if (result.diagnostics?.length) {
|
|
266
|
-
const message = result.diagnostics.map((diagnostic)=>'string' == typeof diagnostic.messageText ? diagnostic.messageText : diagnostic.messageText.messageText).join('\n');
|
|
267
|
-
if (message) throw new Error(message);
|
|
285
|
+
return result.outputText;
|
|
268
286
|
}
|
|
269
|
-
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
function createBridgeRuntimeBootstrap() {
|
|
296
|
-
return `
|
|
287
|
+
function createModuleFactory(ts, filename, source) {
|
|
288
|
+
return `${JSON.stringify(filename)}: function(require, module, exports) {\n${transpileModule(ts, filename, source)}\n}`;
|
|
289
|
+
}
|
|
290
|
+
function normalizeRuntimeFileName(value) {
|
|
291
|
+
const normalized = value.trim().replace(/^\.\/+/, '');
|
|
292
|
+
if (!normalized || normalized.includes('/') || normalized.includes('\\')) return 'mf.ts';
|
|
293
|
+
return normalized.endsWith('.ts') ? normalized : `${normalized}.ts`;
|
|
294
|
+
}
|
|
295
|
+
function getRuntimeFileBaseName(filename) {
|
|
296
|
+
return filename.replace(/\.ts$/, '');
|
|
297
|
+
}
|
|
298
|
+
function normalizeGlobalName(value) {
|
|
299
|
+
const normalized = value.trim().replace(/[^\w$]/g, '_');
|
|
300
|
+
if (!normalized || /^\d/.test(normalized)) return 'ModuleFederationRuntime';
|
|
301
|
+
return normalized;
|
|
302
|
+
}
|
|
303
|
+
function getRuntimeGlobalNames(primaryName) {
|
|
304
|
+
const names = [
|
|
305
|
+
primaryName.trim()
|
|
306
|
+
].filter(Boolean);
|
|
307
|
+
return [
|
|
308
|
+
...new Set(names)
|
|
309
|
+
];
|
|
310
|
+
}
|
|
311
|
+
function createBridgeRuntimeBootstrap() {
|
|
312
|
+
return `
|
|
297
313
|
var bridgeRuntimeFiles = ${JSON.stringify(buildBridgeRuntimeFiles())};
|
|
298
314
|
var bridgeShimModules = ${JSON.stringify(BRIDGE_SHIM_MODULES)};
|
|
299
315
|
var bridgeModuleUrlCache = {};
|
|
@@ -356,22 +372,23 @@ function createBridgeRuntimeBootstrap() {
|
|
|
356
372
|
return window.__MF_PLAYGROUND_BRIDGE__;
|
|
357
373
|
}
|
|
358
374
|
`;
|
|
359
|
-
}
|
|
360
|
-
async function compilePlaygroundApp(params) {
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
+
}
|
|
376
|
+
async function compilePlaygroundApp(params) {
|
|
377
|
+
const ts = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "typescript-compiler"));
|
|
378
|
+
params.rspackConfigCode;
|
|
379
|
+
const runtimeModuleUrl = params.runtimeModuleUrl.trim();
|
|
380
|
+
if (!runtimeModuleUrl) throw new Error('runtimeModuleUrl is required.');
|
|
381
|
+
const runtimeFileName = normalizeRuntimeFileName(params.runtimeFileName);
|
|
382
|
+
const runtimeFileBaseName = getRuntimeFileBaseName(runtimeFileName);
|
|
383
|
+
const runtimeGlobalName = normalizeGlobalName(params.runtimeGlobalName);
|
|
384
|
+
const runtimeGlobalNames = getRuntimeGlobalNames(runtimeGlobalName);
|
|
385
|
+
const runtimePackageName = params.runtimePackageName.trim() || '@module-federation/runtime';
|
|
386
|
+
const factories = [
|
|
387
|
+
createModuleFactory(ts, APP_FILE, params.appCode),
|
|
388
|
+
createModuleFactory(ts, runtimeFileName, params.mfCode),
|
|
389
|
+
createModuleFactory(ts, ENTRY_FILE, params.entryCode)
|
|
390
|
+
].join(',\n');
|
|
391
|
+
return `(async function() {
|
|
375
392
|
${createBridgeRuntimeBootstrap()}
|
|
376
393
|
var bridgeExports = await ensureBridgeRuntime();
|
|
377
394
|
var mfRuntimePromise = null;
|
|
@@ -462,146 +479,146 @@ ${factories}
|
|
|
462
479
|
await loadModuleFederationRuntime();
|
|
463
480
|
require(${JSON.stringify(ENTRY_FILE)});
|
|
464
481
|
})();`;
|
|
465
|
-
}
|
|
466
|
-
function guessRemoteName(manifest) {
|
|
467
|
-
return manifest.metaData?.name || manifest.name || manifest.id || '@module-federation/unknown-remote';
|
|
468
|
-
}
|
|
469
|
-
function normalizeExpose(expose) {
|
|
470
|
-
const normalizedExpose = expose.trim();
|
|
471
|
-
if (!normalizedExpose || '.' === normalizedExpose || './' === normalizedExpose || './.' === normalizedExpose) return '';
|
|
472
|
-
return normalizedExpose.replace(/^\.\//, '').replace(/^\//, '');
|
|
473
|
-
}
|
|
474
|
-
function formatLoadedTarget(remoteName, expose) {
|
|
475
|
-
return expose ? `${remoteName}/${expose}` : remoteName;
|
|
476
|
-
}
|
|
477
|
-
async function fetchJson(url) {
|
|
478
|
-
const response = await fetch(url);
|
|
479
|
-
if (!response.ok) throw new Error(`Fetch failed: ${response.status} ${response.statusText} (${url})`);
|
|
480
|
-
return await response.json();
|
|
481
|
-
}
|
|
482
|
-
async function fetchManifest(url) {
|
|
483
|
-
return fetchJson(url);
|
|
484
|
-
}
|
|
485
|
-
const cx = (...names)=>names.filter((name)=>Boolean(name)).map((name)=>App_module[name] || name).join(' ');
|
|
486
|
-
const MONACO_CDN_VS_URL = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
|
|
487
|
-
react_namespaceObject.loader.config({
|
|
488
|
-
paths: {
|
|
489
|
-
vs: MONACO_CDN_VS_URL
|
|
490
482
|
}
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
const DEFAULT_RUNTIME_MODULE_URL = 'https://esm.sh/@module-federation/runtime@2.6.0?bundle';
|
|
494
|
-
const DEFAULT_REACT_VERSION = '19.1.1';
|
|
495
|
-
const DEFAULT_LEFT_PANE_WIDTH = 50;
|
|
496
|
-
const MIN_LEFT_PANE_WIDTH = 28;
|
|
497
|
-
const MAX_LEFT_PANE_WIDTH = 72;
|
|
498
|
-
const MANIFEST_QUERY_KEYS = [
|
|
499
|
-
'url',
|
|
500
|
-
'manifestUrl',
|
|
501
|
-
'manifest',
|
|
502
|
-
'm'
|
|
503
|
-
];
|
|
504
|
-
const EXPOSE_QUERY_KEYS = [
|
|
505
|
-
'expose',
|
|
506
|
-
'e'
|
|
507
|
-
];
|
|
508
|
-
const EXPORT_QUERY_KEYS = [
|
|
509
|
-
'export',
|
|
510
|
-
'exportName'
|
|
511
|
-
];
|
|
512
|
-
const PREVIEW_ROUTE_QUERY_KEYS = [
|
|
513
|
-
'route',
|
|
514
|
-
'previewRoute'
|
|
515
|
-
];
|
|
516
|
-
const AUTO_RUN_QUERY_KEYS = [
|
|
517
|
-
...MANIFEST_QUERY_KEYS,
|
|
518
|
-
...EXPOSE_QUERY_KEYS,
|
|
519
|
-
...EXPORT_QUERY_KEYS,
|
|
520
|
-
...PREVIEW_ROUTE_QUERY_KEYS,
|
|
521
|
-
'run'
|
|
522
|
-
];
|
|
523
|
-
function normalizeIdentifier(value, fallback) {
|
|
524
|
-
const normalized = (value || '').trim().replace(/[^\w$]/g, '_');
|
|
525
|
-
if (!normalized || /^\d/.test(normalized)) return fallback;
|
|
526
|
-
return normalized;
|
|
527
|
-
}
|
|
528
|
-
function normalizeTemplateFileName(value, fallback) {
|
|
529
|
-
const normalized = (value || '').trim().replace(/^\.\/+/, '').replace(/[^\w$.-]/g, '_');
|
|
530
|
-
if (!normalized || normalized.includes('/') || normalized.includes('\\')) return fallback;
|
|
531
|
-
return normalized.endsWith('.ts') ? normalized : `${normalized}.ts`;
|
|
532
|
-
}
|
|
533
|
-
function getTemplateFileBaseName(fileName) {
|
|
534
|
-
return fileName.replace(/\.ts$/, '');
|
|
535
|
-
}
|
|
536
|
-
function getPlaygroundTemplate(props) {
|
|
537
|
-
const runtimeFileName = normalizeTemplateFileName(props.templateRuntimeFileName, 'mf.ts');
|
|
538
|
-
const runtimeImportName = normalizeIdentifier(props.templateRuntimeImportName, 'getModuleFederationInstance');
|
|
539
|
-
return {
|
|
540
|
-
bridgePackageName: '@module-federation/bridge-react',
|
|
541
|
-
playgroundName: props.templatePlaygroundName?.trim() || '@module-federation/playground',
|
|
542
|
-
playgroundPropsGlobalName: normalizeIdentifier(props.templatePlaygroundPropsGlobalName, '__MF_PLAYGROUND_PROPS__'),
|
|
543
|
-
playgroundTitle: props.templatePlaygroundTitle?.trim() || 'Module Federation Playground',
|
|
544
|
-
runtimeFileBaseName: getTemplateFileBaseName(runtimeFileName),
|
|
545
|
-
runtimeFileName,
|
|
546
|
-
runtimeGlobalName: normalizeIdentifier(props.templateRuntimeGlobalName, 'ModuleFederationRuntime'),
|
|
547
|
-
runtimeImportName,
|
|
548
|
-
runtimeInstanceName: normalizeIdentifier(props.templateRuntimeInstanceName, 'moduleFederationInstance'),
|
|
549
|
-
runtimePackageName: props.templateRuntimePackageName?.trim() || '@module-federation/runtime',
|
|
550
|
-
runtimeVariableName: normalizeIdentifier(props.templateRuntimeVariableName, 'moduleFederation')
|
|
551
|
-
};
|
|
552
|
-
}
|
|
553
|
-
function getPlaygroundDefaults(props) {
|
|
554
|
-
return {
|
|
555
|
-
autoRun: props.autoRun ?? false,
|
|
556
|
-
defaultExpose: props.defaultExpose ?? '',
|
|
557
|
-
defaultExportName: props.defaultExportName ?? 'default',
|
|
558
|
-
defaultManifestUrl: props.defaultManifestUrl ?? DEFAULT_MANIFEST_URL,
|
|
559
|
-
defaultPreviewRoute: props.defaultPreviewRoute ?? '/',
|
|
560
|
-
monacoVsUrl: props.monacoVsUrl ?? MONACO_CDN_VS_URL,
|
|
561
|
-
reactRuntimeUrls: props.reactRuntimeUrls ?? {},
|
|
562
|
-
runtimeModuleUrl: props.runtimeModuleUrl ?? DEFAULT_RUNTIME_MODULE_URL,
|
|
563
|
-
template: getPlaygroundTemplate(props)
|
|
564
|
-
};
|
|
565
|
-
}
|
|
566
|
-
function getReactRuntimeUrl(pkg, version, reactRuntimeUrls) {
|
|
567
|
-
if ('react' === pkg) return reactRuntimeUrls.react || `https://unpkg.com/react@${version}/umd/react.development.js`;
|
|
568
|
-
return reactRuntimeUrls.reactDom || `https://unpkg.com/react-dom@${version}/umd/react-dom.development.js`;
|
|
569
|
-
}
|
|
570
|
-
function normalizeDependencyVersion(version) {
|
|
571
|
-
return version.trim().replace(/^[~^<>=\s]+/, '').split(' ')[0] || version.trim();
|
|
572
|
-
}
|
|
573
|
-
function getFirstSearchParam(searchParams, keys) {
|
|
574
|
-
for (const key of keys){
|
|
575
|
-
const value = searchParams.get(key)?.trim();
|
|
576
|
-
if (value) return value;
|
|
483
|
+
function guessRemoteName(manifest) {
|
|
484
|
+
return manifest.metaData?.name || manifest.name || manifest.id || '@module-federation/unknown-remote';
|
|
577
485
|
}
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
}
|
|
583
|
-
function
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
const
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
const
|
|
486
|
+
function normalizeExpose(expose) {
|
|
487
|
+
const normalizedExpose = expose.trim();
|
|
488
|
+
if (!normalizedExpose || '.' === normalizedExpose || './' === normalizedExpose || './.' === normalizedExpose) return '';
|
|
489
|
+
return normalizedExpose.replace(/^\.\//, '').replace(/^\//, '');
|
|
490
|
+
}
|
|
491
|
+
function formatLoadedTarget(remoteName, expose) {
|
|
492
|
+
return expose ? `${remoteName}/${expose}` : remoteName;
|
|
493
|
+
}
|
|
494
|
+
async function fetchJson(url) {
|
|
495
|
+
const response = await fetch(url);
|
|
496
|
+
if (!response.ok) throw new Error(`Fetch failed: ${response.status} ${response.statusText} (${url})`);
|
|
497
|
+
return await response.json();
|
|
498
|
+
}
|
|
499
|
+
async function fetchManifest(url) {
|
|
500
|
+
return fetchJson(url);
|
|
501
|
+
}
|
|
502
|
+
const cx = (...names)=>names.filter((name)=>Boolean(name)).map((name)=>App_module[name] || name).join(' ');
|
|
503
|
+
const MONACO_CDN_VS_URL = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
|
|
504
|
+
react_namespaceObject.loader.config({
|
|
505
|
+
paths: {
|
|
506
|
+
vs: MONACO_CDN_VS_URL
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
const DEFAULT_MANIFEST_URL = 'https://unpkg.com/module-federation-rslib-provider@latest/dist/mf/mf-manifest.json';
|
|
510
|
+
const DEFAULT_RUNTIME_MODULE_URL = 'https://esm.sh/@module-federation/runtime@2.6.0?bundle';
|
|
511
|
+
const DEFAULT_REACT_VERSION = '19.1.1';
|
|
512
|
+
const DEFAULT_LEFT_PANE_WIDTH = 50;
|
|
513
|
+
const MIN_LEFT_PANE_WIDTH = 28;
|
|
514
|
+
const MAX_LEFT_PANE_WIDTH = 72;
|
|
515
|
+
const MANIFEST_QUERY_KEYS = [
|
|
516
|
+
'url',
|
|
517
|
+
'manifestUrl',
|
|
518
|
+
'manifest',
|
|
519
|
+
'm'
|
|
520
|
+
];
|
|
521
|
+
const EXPOSE_QUERY_KEYS = [
|
|
522
|
+
'expose',
|
|
523
|
+
'e'
|
|
524
|
+
];
|
|
525
|
+
const EXPORT_QUERY_KEYS = [
|
|
526
|
+
'export',
|
|
527
|
+
'exportName'
|
|
528
|
+
];
|
|
529
|
+
const PREVIEW_ROUTE_QUERY_KEYS = [
|
|
530
|
+
'route',
|
|
531
|
+
'previewRoute'
|
|
532
|
+
];
|
|
533
|
+
const AUTO_RUN_QUERY_KEYS = [
|
|
534
|
+
...MANIFEST_QUERY_KEYS,
|
|
535
|
+
...EXPOSE_QUERY_KEYS,
|
|
536
|
+
...EXPORT_QUERY_KEYS,
|
|
537
|
+
...PREVIEW_ROUTE_QUERY_KEYS,
|
|
538
|
+
'run'
|
|
539
|
+
];
|
|
540
|
+
function normalizeIdentifier(value, fallback) {
|
|
541
|
+
const normalized = (value || '').trim().replace(/[^\w$]/g, '_');
|
|
542
|
+
if (!normalized || /^\d/.test(normalized)) return fallback;
|
|
543
|
+
return normalized;
|
|
544
|
+
}
|
|
545
|
+
function normalizeTemplateFileName(value, fallback) {
|
|
546
|
+
const normalized = (value || '').trim().replace(/^\.\/+/, '').replace(/[^\w$.-]/g, '_');
|
|
547
|
+
if (!normalized || normalized.includes('/') || normalized.includes('\\')) return fallback;
|
|
548
|
+
return normalized.endsWith('.ts') ? normalized : `${normalized}.ts`;
|
|
549
|
+
}
|
|
550
|
+
function getTemplateFileBaseName(fileName) {
|
|
551
|
+
return fileName.replace(/\.ts$/, '');
|
|
552
|
+
}
|
|
553
|
+
function getPlaygroundTemplate(props) {
|
|
554
|
+
const runtimeFileName = normalizeTemplateFileName(props.templateRuntimeFileName, 'mf.ts');
|
|
555
|
+
const runtimeImportName = normalizeIdentifier(props.templateRuntimeImportName, 'getModuleFederationInstance');
|
|
556
|
+
return {
|
|
557
|
+
bridgePackageName: '@module-federation/bridge-react',
|
|
558
|
+
playgroundName: props.templatePlaygroundName?.trim() || '@module-federation/playground',
|
|
559
|
+
playgroundPropsGlobalName: normalizeIdentifier(props.templatePlaygroundPropsGlobalName, '__MF_PLAYGROUND_PROPS__'),
|
|
560
|
+
playgroundTitle: props.templatePlaygroundTitle?.trim() || 'Module Federation Playground',
|
|
561
|
+
runtimeFileBaseName: getTemplateFileBaseName(runtimeFileName),
|
|
562
|
+
runtimeFileName,
|
|
563
|
+
runtimeGlobalName: normalizeIdentifier(props.templateRuntimeGlobalName, 'ModuleFederationRuntime'),
|
|
564
|
+
runtimeImportName,
|
|
565
|
+
runtimeInstanceName: normalizeIdentifier(props.templateRuntimeInstanceName, 'moduleFederationInstance'),
|
|
566
|
+
runtimePackageName: props.templateRuntimePackageName?.trim() || '@module-federation/runtime',
|
|
567
|
+
runtimeVariableName: normalizeIdentifier(props.templateRuntimeVariableName, 'moduleFederation')
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
function getPlaygroundDefaults(props) {
|
|
571
|
+
return {
|
|
572
|
+
autoRun: props.autoRun ?? false,
|
|
573
|
+
defaultExpose: props.defaultExpose ?? '',
|
|
574
|
+
defaultExportName: props.defaultExportName ?? 'default',
|
|
575
|
+
defaultManifestUrl: props.defaultManifestUrl ?? DEFAULT_MANIFEST_URL,
|
|
576
|
+
defaultPreviewRoute: props.defaultPreviewRoute ?? '/',
|
|
577
|
+
monacoVsUrl: props.monacoVsUrl ?? MONACO_CDN_VS_URL,
|
|
578
|
+
reactRuntimeUrls: props.reactRuntimeUrls ?? {},
|
|
579
|
+
runtimeModuleUrl: props.runtimeModuleUrl ?? DEFAULT_RUNTIME_MODULE_URL,
|
|
580
|
+
template: getPlaygroundTemplate(props)
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
function getReactRuntimeUrl(pkg, version, reactRuntimeUrls) {
|
|
584
|
+
if ('react' === pkg) return reactRuntimeUrls.react || `https://unpkg.com/react@${version}/umd/react.development.js`;
|
|
585
|
+
return reactRuntimeUrls.reactDom || `https://unpkg.com/react-dom@${version}/umd/react-dom.development.js`;
|
|
586
|
+
}
|
|
587
|
+
function normalizeDependencyVersion(version) {
|
|
588
|
+
return version.trim().replace(/^[~^<>=\s]+/, '').split(' ')[0] || version.trim();
|
|
589
|
+
}
|
|
590
|
+
function getFirstSearchParam(searchParams, keys) {
|
|
591
|
+
for (const key of keys){
|
|
592
|
+
const value = searchParams.get(key)?.trim();
|
|
593
|
+
if (value) return value;
|
|
594
|
+
}
|
|
595
|
+
return '';
|
|
596
|
+
}
|
|
597
|
+
function hasSearchParam(searchParams, keys) {
|
|
598
|
+
return keys.some((key)=>searchParams.has(key));
|
|
599
|
+
}
|
|
600
|
+
function getInitialQueryConfig(defaults) {
|
|
601
|
+
if ('undefined' == typeof window) return {
|
|
602
|
+
autoRun: defaults.autoRun,
|
|
603
|
+
expose: defaults.defaultExpose,
|
|
604
|
+
exportName: defaults.defaultExportName,
|
|
605
|
+
manifestUrl: defaults.defaultManifestUrl,
|
|
606
|
+
previewRoute: defaults.defaultPreviewRoute
|
|
607
|
+
};
|
|
608
|
+
const searchParams = new URLSearchParams(window.location.search);
|
|
609
|
+
const manifestFromQuery = getFirstSearchParam(searchParams, MANIFEST_QUERY_KEYS);
|
|
610
|
+
const exposeFromQuery = getFirstSearchParam(searchParams, EXPOSE_QUERY_KEYS);
|
|
611
|
+
const exportFromQuery = getFirstSearchParam(searchParams, EXPORT_QUERY_KEYS);
|
|
612
|
+
const previewRouteFromQuery = getFirstSearchParam(searchParams, PREVIEW_ROUTE_QUERY_KEYS);
|
|
613
|
+
return {
|
|
614
|
+
autoRun: hasSearchParam(searchParams, AUTO_RUN_QUERY_KEYS) || defaults.autoRun,
|
|
615
|
+
expose: exposeFromQuery || defaults.defaultExpose,
|
|
616
|
+
exportName: exportFromQuery || defaults.defaultExportName,
|
|
617
|
+
manifestUrl: manifestFromQuery || defaults.defaultManifestUrl,
|
|
618
|
+
previewRoute: previewRouteFromQuery || defaults.defaultPreviewRoute
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
const DEFAULT_ENTRY_CODE = `import App from './app';
|
|
605
622
|
import React from 'react';
|
|
606
623
|
import { createRoot } from 'react-dom/client';
|
|
607
624
|
|
|
@@ -615,24 +632,24 @@ createRoot(container).render(
|
|
|
615
632
|
React.createElement(App),
|
|
616
633
|
);
|
|
617
634
|
`;
|
|
618
|
-
const APP_LOADED_TARGET_PLACEHOLDER = '__LOADED_TARGET__';
|
|
619
|
-
function getReactMajor(version) {
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
}
|
|
623
|
-
function getBridgeProviderImportPath(reactVersion) {
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
}
|
|
629
|
-
function isBridgeAppExpose(expose) {
|
|
630
|
-
|
|
631
|
-
}
|
|
632
|
-
function buildDefaultComponentAppCode(loadedTarget, exportName, template) {
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
635
|
+
const APP_LOADED_TARGET_PLACEHOLDER = '__LOADED_TARGET__';
|
|
636
|
+
function getReactMajor(version) {
|
|
637
|
+
const match = version.trim().match(/^(\d+)/);
|
|
638
|
+
return match ? Number(match[1]) : 19;
|
|
639
|
+
}
|
|
640
|
+
function getBridgeProviderImportPath(reactVersion) {
|
|
641
|
+
const major = getReactMajor(reactVersion);
|
|
642
|
+
if (major >= 19) return '@module-federation/bridge-react/v19';
|
|
643
|
+
if (major >= 18) return '@module-federation/bridge-react/v18';
|
|
644
|
+
return '@module-federation/bridge-react';
|
|
645
|
+
}
|
|
646
|
+
function isBridgeAppExpose(expose) {
|
|
647
|
+
return 'export-app' === normalizeExpose(expose);
|
|
648
|
+
}
|
|
649
|
+
function buildDefaultComponentAppCode(loadedTarget, exportName, template) {
|
|
650
|
+
const safeLoadedTarget = loadedTarget.trim() || APP_LOADED_TARGET_PLACEHOLDER;
|
|
651
|
+
const safeExportName = exportName.trim() || 'default';
|
|
652
|
+
return `import React from 'react';
|
|
636
653
|
import { ${template.runtimeImportName} } from './${template.runtimeFileBaseName}';
|
|
637
654
|
|
|
638
655
|
const loadedTargetLabel = ${JSON.stringify(safeLoadedTarget)};
|
|
@@ -659,11 +676,11 @@ export default function App() {
|
|
|
659
676
|
);
|
|
660
677
|
}
|
|
661
678
|
`;
|
|
662
|
-
}
|
|
663
|
-
function buildDefaultBridgeAppCode(loadedTarget, exportName, template) {
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
679
|
+
}
|
|
680
|
+
function buildDefaultBridgeAppCode(loadedTarget, exportName, template) {
|
|
681
|
+
const safeLoadedTarget = loadedTarget.trim() || APP_LOADED_TARGET_PLACEHOLDER;
|
|
682
|
+
const safeExportName = exportName.trim() || 'default';
|
|
683
|
+
return `import React from 'react';
|
|
667
684
|
import { createRemoteAppComponent, ${template.runtimeImportName} } from './${template.runtimeFileBaseName}';
|
|
668
685
|
|
|
669
686
|
const loadedTargetLabel = ${JSON.stringify(safeLoadedTarget)};
|
|
@@ -703,20 +720,20 @@ export default function App() {
|
|
|
703
720
|
);
|
|
704
721
|
}
|
|
705
722
|
`;
|
|
706
|
-
}
|
|
707
|
-
function buildDefaultAppCode(loadedTarget, exportName, expose, _reactVersion, template) {
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
}
|
|
711
|
-
const MF_MANIFEST_PLACEHOLDER = '__MANIFEST_URL__';
|
|
712
|
-
const MF_REMOTE_NAME_PLACEHOLDER = '__REMOTE_NAME__';
|
|
713
|
-
function buildDefaultMfCode(manifestUrl, remoteName, reactVersions, template) {
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
723
|
+
}
|
|
724
|
+
function buildDefaultAppCode(loadedTarget, exportName, expose, _reactVersion, template) {
|
|
725
|
+
if (isBridgeAppExpose(expose)) return buildDefaultBridgeAppCode(loadedTarget, exportName, template);
|
|
726
|
+
return buildDefaultComponentAppCode(loadedTarget, exportName, template);
|
|
727
|
+
}
|
|
728
|
+
const MF_MANIFEST_PLACEHOLDER = '__MANIFEST_URL__';
|
|
729
|
+
const MF_REMOTE_NAME_PLACEHOLDER = '__REMOTE_NAME__';
|
|
730
|
+
function buildDefaultMfCode(manifestUrl, remoteName, reactVersions, template) {
|
|
731
|
+
const safeManifestUrl = manifestUrl.trim() || MF_MANIFEST_PLACEHOLDER;
|
|
732
|
+
const safeRemoteName = remoteName.trim() || MF_REMOTE_NAME_PLACEHOLDER;
|
|
733
|
+
const safeReactVersion = reactVersions.react?.trim() || DEFAULT_REACT_VERSION;
|
|
734
|
+
const safeReactDomClientVersion = reactVersions['react-dom/client']?.trim() || reactVersions['react-dom']?.trim() || safeReactVersion;
|
|
735
|
+
const bridgeProviderImportPath = getBridgeProviderImportPath(safeReactVersion);
|
|
736
|
+
return `import React from 'react';
|
|
720
737
|
import * as ReactDOMClient from 'react-dom/client';
|
|
721
738
|
import { createInstance } from ${JSON.stringify(template.runtimePackageName)};
|
|
722
739
|
|
|
@@ -838,9 +855,9 @@ export async function ${template.runtimeImportName}() {
|
|
|
838
855
|
return ${template.runtimeInstanceName};
|
|
839
856
|
}
|
|
840
857
|
`;
|
|
841
|
-
}
|
|
842
|
-
function buildDefaultRspackConfigCode(template) {
|
|
843
|
-
|
|
858
|
+
}
|
|
859
|
+
function buildDefaultRspackConfigCode(template) {
|
|
860
|
+
return `// Only used to show the browser sandbox shape. Configure your real bundler as needed.
|
|
844
861
|
export default {
|
|
845
862
|
mode: 'development',
|
|
846
863
|
entry: './entry.ts',
|
|
@@ -910,115 +927,115 @@ export default {
|
|
|
910
927
|
],
|
|
911
928
|
};
|
|
912
929
|
`;
|
|
913
|
-
}
|
|
914
|
-
const FILE_TABS = [
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
];
|
|
940
|
-
function getFileTabs(template) {
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
}
|
|
948
|
-
function getEditorLanguage(file) {
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
}
|
|
954
|
-
function EditorLoadingState() {
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
});
|
|
962
|
-
}
|
|
963
|
-
function getEditorTheme() {
|
|
964
|
-
if ('undefined' == typeof document) return 'vs-dark';
|
|
965
|
-
const root = document.documentElement;
|
|
966
|
-
return root.classList.contains('dark') || root.classList.contains('rp-dark') ? 'vs-dark' : 'vs';
|
|
967
|
-
}
|
|
968
|
-
function getDocumentLocale() {
|
|
969
|
-
if ('undefined' == typeof document) return 'zh';
|
|
970
|
-
const lang = document.documentElement.lang || ('undefined' != typeof navigator ? navigator.language : '') || 'zh';
|
|
971
|
-
return lang.toLowerCase().startsWith('en') ? 'en' : 'zh';
|
|
972
|
-
}
|
|
973
|
-
function useEditorTheme() {
|
|
974
|
-
const [theme, setTheme] = (0, external_react_namespaceObject.useState)(getEditorTheme);
|
|
975
|
-
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
976
|
-
if ('undefined' == typeof document) return;
|
|
977
|
-
const root = document.documentElement;
|
|
978
|
-
const observer = new MutationObserver(()=>{
|
|
979
|
-
setTheme(getEditorTheme());
|
|
980
|
-
});
|
|
981
|
-
observer.observe(root, {
|
|
982
|
-
attributeFilter: [
|
|
983
|
-
'class'
|
|
984
|
-
],
|
|
985
|
-
attributes: true
|
|
986
|
-
});
|
|
987
|
-
return ()=>observer.disconnect();
|
|
988
|
-
}, []);
|
|
989
|
-
return theme;
|
|
990
|
-
}
|
|
991
|
-
function useLocale() {
|
|
992
|
-
const [locale, setLocale] = (0, external_react_namespaceObject.useState)(getDocumentLocale);
|
|
993
|
-
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
994
|
-
if ('undefined' == typeof document) return;
|
|
995
|
-
const observer = new MutationObserver(()=>{
|
|
996
|
-
setLocale(getDocumentLocale());
|
|
997
|
-
});
|
|
998
|
-
observer.observe(document.documentElement, {
|
|
999
|
-
attributeFilter: [
|
|
1000
|
-
'lang'
|
|
1001
|
-
],
|
|
1002
|
-
attributes: true
|
|
930
|
+
}
|
|
931
|
+
const FILE_TABS = [
|
|
932
|
+
{
|
|
933
|
+
key: 'app.tsx',
|
|
934
|
+
copyKey: 'app-code',
|
|
935
|
+
copyMessage: '已复制 app.tsx 到剪贴板',
|
|
936
|
+
placeholder: 'export default function App(...) { ... }'
|
|
937
|
+
},
|
|
938
|
+
{
|
|
939
|
+
key: 'entry.ts',
|
|
940
|
+
copyKey: 'entry-code',
|
|
941
|
+
copyMessage: '已复制 entry.ts 到剪贴板',
|
|
942
|
+
placeholder: "import App from './app';"
|
|
943
|
+
},
|
|
944
|
+
{
|
|
945
|
+
key: 'runtime',
|
|
946
|
+
copyKey: 'runtime-code',
|
|
947
|
+
copyMessage: '已复制 runtime.ts 到剪贴板',
|
|
948
|
+
placeholder: 'export async function getRuntimeInstance(...) { ... }'
|
|
949
|
+
},
|
|
950
|
+
{
|
|
951
|
+
key: 'rspack.config.mjs',
|
|
952
|
+
copyKey: 'rspack-config',
|
|
953
|
+
copyMessage: '已复制 rspack.config.mjs 到剪贴板',
|
|
954
|
+
placeholder: 'export default { ... }'
|
|
955
|
+
}
|
|
956
|
+
];
|
|
957
|
+
function getFileTabs(template) {
|
|
958
|
+
return FILE_TABS.map((item)=>'runtime' === item.key ? {
|
|
959
|
+
...item,
|
|
960
|
+
copyMessage: `已复制 ${template.runtimeFileName} 到剪贴板`,
|
|
961
|
+
label: template.runtimeFileName,
|
|
962
|
+
placeholder: `export async function ${template.runtimeImportName}(...) { ... }`
|
|
963
|
+
} : item);
|
|
964
|
+
}
|
|
965
|
+
function getEditorLanguage(file) {
|
|
966
|
+
if ('app.tsx' === file) return "typescript";
|
|
967
|
+
if ('entry.ts' === file || 'runtime' === file) return "typescript";
|
|
968
|
+
if (file.endsWith('.mjs')) return "javascript";
|
|
969
|
+
return 'plaintext';
|
|
970
|
+
}
|
|
971
|
+
function EditorLoadingState() {
|
|
972
|
+
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
973
|
+
className: cx('vp-loadingSimple'),
|
|
974
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
975
|
+
className: cx('vp-loadingSpinner'),
|
|
976
|
+
"aria-hidden": "true"
|
|
977
|
+
})
|
|
1003
978
|
});
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
979
|
+
}
|
|
980
|
+
function getEditorTheme() {
|
|
981
|
+
if ('undefined' == typeof document) return 'vs-dark';
|
|
982
|
+
const root = document.documentElement;
|
|
983
|
+
return root.classList.contains('dark') || root.classList.contains('rp-dark') ? 'vs-dark' : 'vs';
|
|
984
|
+
}
|
|
985
|
+
function getDocumentLocale() {
|
|
986
|
+
if ('undefined' == typeof document) return 'zh';
|
|
987
|
+
const lang = document.documentElement.lang || ('undefined' != typeof navigator ? navigator.language : '') || 'zh';
|
|
988
|
+
return lang.toLowerCase().startsWith('en') ? 'en' : 'zh';
|
|
989
|
+
}
|
|
990
|
+
function useEditorTheme() {
|
|
991
|
+
const [theme, setTheme] = (0, external_react_namespaceObject.useState)(getEditorTheme);
|
|
992
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
993
|
+
if ('undefined' == typeof document) return;
|
|
994
|
+
const root = document.documentElement;
|
|
995
|
+
const observer = new MutationObserver(()=>{
|
|
996
|
+
setTheme(getEditorTheme());
|
|
997
|
+
});
|
|
998
|
+
observer.observe(root, {
|
|
999
|
+
attributeFilter: [
|
|
1000
|
+
'class'
|
|
1001
|
+
],
|
|
1002
|
+
attributes: true
|
|
1003
|
+
});
|
|
1004
|
+
return ()=>observer.disconnect();
|
|
1005
|
+
}, []);
|
|
1006
|
+
return theme;
|
|
1007
|
+
}
|
|
1008
|
+
function useLocale() {
|
|
1009
|
+
const [locale, setLocale] = (0, external_react_namespaceObject.useState)(getDocumentLocale);
|
|
1010
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1011
|
+
if ('undefined' == typeof document) return;
|
|
1012
|
+
const observer = new MutationObserver(()=>{
|
|
1013
|
+
setLocale(getDocumentLocale());
|
|
1014
|
+
});
|
|
1015
|
+
observer.observe(document.documentElement, {
|
|
1016
|
+
attributeFilter: [
|
|
1017
|
+
'lang'
|
|
1018
|
+
],
|
|
1019
|
+
attributes: true
|
|
1020
|
+
});
|
|
1021
|
+
return ()=>observer.disconnect();
|
|
1022
|
+
}, []);
|
|
1023
|
+
return locale;
|
|
1024
|
+
}
|
|
1025
|
+
function getEditorPath(file, template) {
|
|
1026
|
+
if ('rspack.config.mjs' === file) return `file:///${file}`;
|
|
1027
|
+
if ('runtime' === file) return `file:///src/${template.runtimeFileName}`;
|
|
1028
|
+
return `file:///src/${file}`;
|
|
1029
|
+
}
|
|
1030
|
+
function configureEditor(monaco, template) {
|
|
1031
|
+
const localTypes = {
|
|
1032
|
+
'file:///node_modules/@types/react/index.d.ts': `
|
|
1016
1033
|
declare module 'react' {
|
|
1017
1034
|
const React: any;
|
|
1018
1035
|
export default React;
|
|
1019
1036
|
}
|
|
1020
1037
|
`,
|
|
1021
|
-
|
|
1038
|
+
'file:///node_modules/@types/react-dom/client.d.ts': `
|
|
1022
1039
|
declare module 'react-dom/client' {
|
|
1023
1040
|
export function createRoot(container: Element | DocumentFragment): {
|
|
1024
1041
|
render(children: any): void;
|
|
@@ -1026,7 +1043,7 @@ declare module 'react-dom/client' {
|
|
|
1026
1043
|
};
|
|
1027
1044
|
}
|
|
1028
1045
|
`,
|
|
1029
|
-
|
|
1046
|
+
[`file:///src/${template.runtimeFileBaseName}.d.ts`]: `
|
|
1030
1047
|
export function createRemoteAppComponent(options: {
|
|
1031
1048
|
export?: string;
|
|
1032
1049
|
fallback?: (context: { error?: Error | null }) => any;
|
|
@@ -1037,11 +1054,11 @@ export function ${template.runtimeImportName}(): Promise<{
|
|
|
1037
1054
|
loadRemote(request: string): Promise<any>;
|
|
1038
1055
|
}>;
|
|
1039
1056
|
`,
|
|
1040
|
-
|
|
1057
|
+
'file:///src/app.d.ts': `
|
|
1041
1058
|
const App: any;
|
|
1042
1059
|
export default App;
|
|
1043
1060
|
`,
|
|
1044
|
-
|
|
1061
|
+
'file:///src/globals.d.ts': `
|
|
1045
1062
|
declare global {
|
|
1046
1063
|
interface Window {
|
|
1047
1064
|
${template.playgroundPropsGlobalName}?: any;
|
|
@@ -1055,122 +1072,122 @@ declare global {
|
|
|
1055
1072
|
}
|
|
1056
1073
|
export {};
|
|
1057
1074
|
`
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
}
|
|
1075
|
-
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
|
|
1076
|
-
noSemanticValidation: false,
|
|
1077
|
-
noSyntaxValidation: false
|
|
1078
|
-
});
|
|
1079
|
-
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
|
1080
|
-
noSemanticValidation: false,
|
|
1081
|
-
noSyntaxValidation: false
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
function syncEditorModels(monaco, files, template) {
|
|
1085
|
-
for (const [file, value] of Object.entries(files)){
|
|
1086
|
-
const uri = monaco.Uri.parse(getEditorPath(file, template));
|
|
1087
|
-
const model = monaco.editor.getModel(uri);
|
|
1088
|
-
if (model) {
|
|
1089
|
-
if (model.getValue() !== value) model.setValue(value);
|
|
1090
|
-
continue;
|
|
1075
|
+
};
|
|
1076
|
+
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
|
|
1077
|
+
allowJs: true,
|
|
1078
|
+
allowNonTsExtensions: true,
|
|
1079
|
+
esModuleInterop: true,
|
|
1080
|
+
jsx: monaco.languages.typescript.JsxEmit.React,
|
|
1081
|
+
module: monaco.languages.typescript.ModuleKind.ESNext,
|
|
1082
|
+
moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
|
|
1083
|
+
noImplicitAny: false,
|
|
1084
|
+
noEmit: true,
|
|
1085
|
+
strict: false,
|
|
1086
|
+
target: monaco.languages.typescript.ScriptTarget.ES2020
|
|
1087
|
+
});
|
|
1088
|
+
for (const [path, content] of Object.entries(localTypes)){
|
|
1089
|
+
monaco.languages.typescript.typescriptDefaults.addExtraLib(content, path);
|
|
1090
|
+
monaco.languages.typescript.javascriptDefaults.addExtraLib(content, path);
|
|
1091
1091
|
}
|
|
1092
|
-
monaco.
|
|
1092
|
+
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
|
|
1093
|
+
noSemanticValidation: false,
|
|
1094
|
+
noSyntaxValidation: false
|
|
1095
|
+
});
|
|
1096
|
+
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
|
1097
|
+
noSemanticValidation: false,
|
|
1098
|
+
noSyntaxValidation: false
|
|
1099
|
+
});
|
|
1093
1100
|
}
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
return acc;
|
|
1104
|
-
}, {});
|
|
1105
|
-
if ('object' == typeof shared) return Object.entries(shared).reduce((acc, [name, value])=>{
|
|
1106
|
-
if (value && 'object' == typeof value) {
|
|
1107
|
-
const resolvedVersion = ('version' in value && 'string' == typeof value.version ? value.version : 'requiredVersion' in value && 'string' == typeof value.requiredVersion ? normalizeDependencyVersion(value.requiredVersion) : '') || '';
|
|
1108
|
-
if (resolvedVersion) acc[name] = resolvedVersion;
|
|
1101
|
+
function syncEditorModels(monaco, files, template) {
|
|
1102
|
+
for (const [file, value] of Object.entries(files)){
|
|
1103
|
+
const uri = monaco.Uri.parse(getEditorPath(file, template));
|
|
1104
|
+
const model = monaco.editor.getModel(uri);
|
|
1105
|
+
if (model) {
|
|
1106
|
+
if (model.getValue() !== value) model.setValue(value);
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
monaco.editor.createModel(value, getEditorLanguage(file), uri);
|
|
1109
1110
|
}
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
}
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
'
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
}
|
|
1152
|
-
function
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1111
|
+
}
|
|
1112
|
+
function extractSharedDependencyVersions(manifest) {
|
|
1113
|
+
const shared = manifest.shared;
|
|
1114
|
+
if (!shared) return {};
|
|
1115
|
+
if (Array.isArray(shared)) return shared.reduce((acc, item)=>{
|
|
1116
|
+
if (item && 'object' == typeof item && 'name' in item && 'string' == typeof item.name) {
|
|
1117
|
+
const resolvedVersion = ('version' in item && 'string' == typeof item.version ? item.version : 'requiredVersion' in item && 'string' == typeof item.requiredVersion ? normalizeDependencyVersion(item.requiredVersion) : '') || '';
|
|
1118
|
+
if (resolvedVersion) acc[item.name] = resolvedVersion;
|
|
1119
|
+
}
|
|
1120
|
+
return acc;
|
|
1121
|
+
}, {});
|
|
1122
|
+
if ('object' == typeof shared) return Object.entries(shared).reduce((acc, [name, value])=>{
|
|
1123
|
+
if (value && 'object' == typeof value) {
|
|
1124
|
+
const resolvedVersion = ('version' in value && 'string' == typeof value.version ? value.version : 'requiredVersion' in value && 'string' == typeof value.requiredVersion ? normalizeDependencyVersion(value.requiredVersion) : '') || '';
|
|
1125
|
+
if (resolvedVersion) acc[name] = resolvedVersion;
|
|
1126
|
+
}
|
|
1127
|
+
return acc;
|
|
1128
|
+
}, {});
|
|
1129
|
+
return {};
|
|
1130
|
+
}
|
|
1131
|
+
function extractReactDependencyVersions(manifest) {
|
|
1132
|
+
const sharedVersions = extractSharedDependencyVersions(manifest);
|
|
1133
|
+
const reactVersion = sharedVersions.react || sharedVersions['react/'] || DEFAULT_REACT_VERSION;
|
|
1134
|
+
const reactDomVersion = sharedVersions['react-dom'] || reactVersion;
|
|
1135
|
+
const reactDomClientVersion = sharedVersions['react-dom/client'] || reactDomVersion || reactVersion;
|
|
1136
|
+
return {
|
|
1137
|
+
react: reactVersion,
|
|
1138
|
+
'react-dom/client': reactDomClientVersion
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
function updateDependencyVersionsInRspackConfig(configCode, _versions) {
|
|
1142
|
+
return configCode;
|
|
1143
|
+
}
|
|
1144
|
+
function getDefaultReactDependencyVersions() {
|
|
1145
|
+
return {
|
|
1146
|
+
react: DEFAULT_REACT_VERSION,
|
|
1147
|
+
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
function escapeInlineScript(source) {
|
|
1151
|
+
return source.replace(/<\/script/gi, "<\\/script");
|
|
1152
|
+
}
|
|
1153
|
+
function normalizePreviewRoute(route) {
|
|
1154
|
+
const trimmedRoute = route.trim();
|
|
1155
|
+
if (!trimmedRoute) return '/';
|
|
1156
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(trimmedRoute)) return '/';
|
|
1157
|
+
return trimmedRoute.startsWith('/') ? trimmedRoute : `/${trimmedRoute}`;
|
|
1158
|
+
}
|
|
1159
|
+
function resolveExposeFromOptions(exposeOptions, requestedExpose) {
|
|
1160
|
+
const trimmedExpose = requestedExpose.trim();
|
|
1161
|
+
if (!trimmedExpose) return exposeOptions[0] || '';
|
|
1162
|
+
const exactMatch = exposeOptions.find((item)=>item === trimmedExpose);
|
|
1163
|
+
if (exactMatch) return exactMatch;
|
|
1164
|
+
const normalizedRequestedExpose = normalizeExpose(trimmedExpose);
|
|
1165
|
+
const normalizedMatch = exposeOptions.find((item)=>normalizeExpose(item) === normalizedRequestedExpose);
|
|
1166
|
+
if (normalizedMatch) return normalizedMatch;
|
|
1167
|
+
return trimmedExpose;
|
|
1168
|
+
}
|
|
1169
|
+
function normalizeTerminalLevel(level) {
|
|
1170
|
+
if ('warn' === level || 'info' === level) return level;
|
|
1171
|
+
return 'error';
|
|
1172
|
+
}
|
|
1173
|
+
function formatErrorForTerminal(error) {
|
|
1174
|
+
return error instanceof Error ? error.stack || error.message : String(error);
|
|
1175
|
+
}
|
|
1176
|
+
function buildPreviewDocument(previewState, defaults) {
|
|
1177
|
+
const reactDependencyVersions = previewState.manifest ? extractReactDependencyVersions(previewState.manifest) : getDefaultReactDependencyVersions();
|
|
1178
|
+
const reactVersion = reactDependencyVersions.react || DEFAULT_REACT_VERSION;
|
|
1179
|
+
const reactDomVersion = reactDependencyVersions['react-dom/client'] || reactDependencyVersions['react-dom'] || reactVersion;
|
|
1180
|
+
const reactMajor = getReactMajor(reactVersion);
|
|
1181
|
+
const previewRoute = normalizePreviewRoute(previewState.previewRoute);
|
|
1182
|
+
const props = JSON.stringify({
|
|
1183
|
+
expose: previewState.expose,
|
|
1184
|
+
loadedTarget: previewState.loadedTarget,
|
|
1185
|
+
manifest: previewState.manifest,
|
|
1186
|
+
manifestUrl: previewState.manifestUrl,
|
|
1187
|
+
previewRoute
|
|
1188
|
+
});
|
|
1189
|
+
const bundle = escapeInlineScript(previewState.bundle);
|
|
1190
|
+
const dependencyInjection = reactMajor >= 19 ? `<script>
|
|
1174
1191
|
if (!window.parent?.__MF_PLAYGROUND_HOST_REACT__ || !window.parent?.__MF_PLAYGROUND_HOST_REACT_DOM__) {
|
|
1175
1192
|
throw new Error('Host React runtime is not available.');
|
|
1176
1193
|
}
|
|
@@ -1178,7 +1195,7 @@ function buildPreviewDocument(previewState, defaults) {
|
|
|
1178
1195
|
window.ReactDOM = window.parent.__MF_PLAYGROUND_HOST_REACT_DOM__;
|
|
1179
1196
|
</script>` : `<script src="${getReactRuntimeUrl('react', reactVersion, defaults.reactRuntimeUrls)}"></script>
|
|
1180
1197
|
<script src="${getReactRuntimeUrl('react-dom', reactDomVersion, defaults.reactRuntimeUrls)}"></script>`;
|
|
1181
|
-
|
|
1198
|
+
return `<!doctype html>
|
|
1182
1199
|
<html>
|
|
1183
1200
|
<head>
|
|
1184
1201
|
<meta charset="utf-8" />
|
|
@@ -1378,919 +1395,920 @@ function buildPreviewDocument(previewState, defaults) {
|
|
|
1378
1395
|
<script>${bundle}</script>
|
|
1379
1396
|
</body>
|
|
1380
1397
|
</html>`;
|
|
1381
|
-
}
|
|
1382
|
-
class RenderErrorBoundary extends external_react_namespaceObject.Component {
|
|
1383
|
-
static getDerivedStateFromError(error) {
|
|
1384
|
-
return {
|
|
1385
|
-
error: {
|
|
1386
|
-
message: error.message
|
|
1387
|
-
}
|
|
1388
|
-
};
|
|
1389
1398
|
}
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1399
|
+
class RenderErrorBoundary extends external_react_namespaceObject.Component {
|
|
1400
|
+
static getDerivedStateFromError(error) {
|
|
1401
|
+
return {
|
|
1402
|
+
error: {
|
|
1403
|
+
message: error.message
|
|
1404
|
+
}
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
componentDidCatch(error, info) {
|
|
1408
|
+
this.props.onError?.({
|
|
1409
|
+
message: error.message,
|
|
1410
|
+
componentStack: info.componentStack
|
|
1411
|
+
});
|
|
1412
|
+
}
|
|
1413
|
+
render() {
|
|
1414
|
+
if (this.state.error) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1415
|
+
className: cx('vp-errorPanel'),
|
|
1416
|
+
children: [
|
|
1417
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1418
|
+
className: cx('vp-errorTitle'),
|
|
1419
|
+
children: "Render Error"
|
|
1420
|
+
}),
|
|
1421
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("pre", {
|
|
1422
|
+
className: cx('vp-codeBlock'),
|
|
1423
|
+
children: this.state.error.message
|
|
1424
|
+
})
|
|
1425
|
+
]
|
|
1426
|
+
});
|
|
1427
|
+
return this.props.children;
|
|
1428
|
+
}
|
|
1429
|
+
constructor(...args){
|
|
1430
|
+
super(...args), this.state = {
|
|
1431
|
+
error: null
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1395
1434
|
}
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1435
|
+
function AppInner(props) {
|
|
1436
|
+
const { defaults } = props;
|
|
1437
|
+
const initialQueryConfig = (0, external_react_namespaceObject.useMemo)(()=>getInitialQueryConfig(defaults), [
|
|
1438
|
+
defaults
|
|
1439
|
+
]);
|
|
1440
|
+
const template = defaults.template;
|
|
1441
|
+
const initialGeneratedAppCode = (0, external_react_namespaceObject.useMemo)(()=>buildDefaultAppCode('', 'default', '', DEFAULT_REACT_VERSION, template), [
|
|
1442
|
+
template
|
|
1443
|
+
]);
|
|
1444
|
+
const initialGeneratedMfCode = (0, external_react_namespaceObject.useMemo)(()=>buildDefaultMfCode('', '', {
|
|
1445
|
+
react: DEFAULT_REACT_VERSION,
|
|
1446
|
+
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1447
|
+
}, template), [
|
|
1448
|
+
template
|
|
1449
|
+
]);
|
|
1450
|
+
const [manifestUrl, setManifestUrl] = (0, external_react_namespaceObject.useState)(initialQueryConfig.manifestUrl);
|
|
1451
|
+
const [exposeOptions, setExposeOptions] = (0, external_react_namespaceObject.useState)([]);
|
|
1452
|
+
const [expose, setExpose] = (0, external_react_namespaceObject.useState)(initialQueryConfig.expose);
|
|
1453
|
+
const [exportName, setExportName] = (0, external_react_namespaceObject.useState)(initialQueryConfig.exportName);
|
|
1454
|
+
const [previewRoute, setPreviewRoute] = (0, external_react_namespaceObject.useState)(initialQueryConfig.previewRoute);
|
|
1455
|
+
const [entryCode, setEntryCode] = (0, external_react_namespaceObject.useState)(DEFAULT_ENTRY_CODE);
|
|
1456
|
+
const [appCode, setAppCode] = (0, external_react_namespaceObject.useState)(initialGeneratedAppCode);
|
|
1457
|
+
const [lastGeneratedAppCode, setLastGeneratedAppCode] = (0, external_react_namespaceObject.useState)(initialGeneratedAppCode);
|
|
1458
|
+
const [mfCode, setMfCode] = (0, external_react_namespaceObject.useState)(initialGeneratedMfCode);
|
|
1459
|
+
const [lastGeneratedMfCode, setLastGeneratedMfCode] = (0, external_react_namespaceObject.useState)(initialGeneratedMfCode);
|
|
1460
|
+
const [rspackConfigCode, setRspackConfigCode] = (0, external_react_namespaceObject.useState)(()=>buildDefaultRspackConfigCode(template));
|
|
1461
|
+
const [openPanels, setOpenPanels] = (0, external_react_namespaceObject.useState)({
|
|
1462
|
+
control: true,
|
|
1463
|
+
code: false
|
|
1409
1464
|
});
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
const initialGeneratedAppCode = (0, external_react_namespaceObject.useMemo)(()=>buildDefaultAppCode('', 'default', '', DEFAULT_REACT_VERSION, template), [
|
|
1425
|
-
template
|
|
1426
|
-
]);
|
|
1427
|
-
const initialGeneratedMfCode = (0, external_react_namespaceObject.useMemo)(()=>buildDefaultMfCode('', '', {
|
|
1428
|
-
react: DEFAULT_REACT_VERSION,
|
|
1429
|
-
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1430
|
-
}, template), [
|
|
1431
|
-
template
|
|
1432
|
-
]);
|
|
1433
|
-
const [manifestUrl, setManifestUrl] = (0, external_react_namespaceObject.useState)(initialQueryConfig.manifestUrl);
|
|
1434
|
-
const [exposeOptions, setExposeOptions] = (0, external_react_namespaceObject.useState)([]);
|
|
1435
|
-
const [expose, setExpose] = (0, external_react_namespaceObject.useState)(initialQueryConfig.expose);
|
|
1436
|
-
const [exportName, setExportName] = (0, external_react_namespaceObject.useState)(initialQueryConfig.exportName);
|
|
1437
|
-
const [previewRoute, setPreviewRoute] = (0, external_react_namespaceObject.useState)(initialQueryConfig.previewRoute);
|
|
1438
|
-
const [entryCode, setEntryCode] = (0, external_react_namespaceObject.useState)(DEFAULT_ENTRY_CODE);
|
|
1439
|
-
const [appCode, setAppCode] = (0, external_react_namespaceObject.useState)(initialGeneratedAppCode);
|
|
1440
|
-
const [lastGeneratedAppCode, setLastGeneratedAppCode] = (0, external_react_namespaceObject.useState)(initialGeneratedAppCode);
|
|
1441
|
-
const [mfCode, setMfCode] = (0, external_react_namespaceObject.useState)(initialGeneratedMfCode);
|
|
1442
|
-
const [lastGeneratedMfCode, setLastGeneratedMfCode] = (0, external_react_namespaceObject.useState)(initialGeneratedMfCode);
|
|
1443
|
-
const [rspackConfigCode, setRspackConfigCode] = (0, external_react_namespaceObject.useState)(()=>buildDefaultRspackConfigCode(template));
|
|
1444
|
-
const [openPanels, setOpenPanels] = (0, external_react_namespaceObject.useState)({
|
|
1445
|
-
control: true,
|
|
1446
|
-
code: false
|
|
1447
|
-
});
|
|
1448
|
-
const [leftPaneWidth, setLeftPaneWidth] = (0, external_react_namespaceObject.useState)(DEFAULT_LEFT_PANE_WIDTH);
|
|
1449
|
-
const [isDesktopLayout, setIsDesktopLayout] = (0, external_react_namespaceObject.useState)(()=>'undefined' == typeof window || window.innerWidth > 980);
|
|
1450
|
-
const [activeFile, setActiveFile] = (0, external_react_namespaceObject.useState)('app.tsx');
|
|
1451
|
-
const [status, setStatus] = (0, external_react_namespaceObject.useState)('');
|
|
1452
|
-
const [isResolvingExpose, setIsResolvingExpose] = (0, external_react_namespaceObject.useState)(false);
|
|
1453
|
-
const [copiedKey, setCopiedKey] = (0, external_react_namespaceObject.useState)('');
|
|
1454
|
-
const [resolvedManifest, setResolvedManifest] = (0, external_react_namespaceObject.useState)(null);
|
|
1455
|
-
const [previewState, setPreviewState] = (0, external_react_namespaceObject.useState)(null);
|
|
1456
|
-
const [renderError, setRenderError] = (0, external_react_namespaceObject.useState)(null);
|
|
1457
|
-
const [terminalLines, setTerminalLines] = (0, external_react_namespaceObject.useState)([
|
|
1458
|
-
{
|
|
1459
|
-
id: 0,
|
|
1460
|
-
level: 'info',
|
|
1461
|
-
message: 'Terminal ready. Compile and runtime errors will appear here after Run Sandbox.'
|
|
1462
|
-
}
|
|
1463
|
-
]);
|
|
1464
|
-
const [runId, setRunId] = (0, external_react_namespaceObject.useState)(0);
|
|
1465
|
-
const runIdRef = (0, external_react_namespaceObject.useRef)(runId);
|
|
1466
|
-
const autoRunStartedRef = (0, external_react_namespaceObject.useRef)(false);
|
|
1467
|
-
const onRunRef = (0, external_react_namespaceObject.useRef)(null);
|
|
1468
|
-
const monacoRef = (0, external_react_namespaceObject.useRef)(null);
|
|
1469
|
-
const resizeStateRef = (0, external_react_namespaceObject.useRef)(null);
|
|
1470
|
-
const editorFiles = (0, external_react_namespaceObject.useMemo)(()=>({
|
|
1471
|
-
'app.tsx': appCode,
|
|
1472
|
-
'entry.ts': entryCode,
|
|
1473
|
-
runtime: mfCode,
|
|
1474
|
-
'rspack.config.mjs': rspackConfigCode
|
|
1475
|
-
}), [
|
|
1476
|
-
appCode,
|
|
1477
|
-
entryCode,
|
|
1478
|
-
mfCode,
|
|
1479
|
-
rspackConfigCode
|
|
1480
|
-
]);
|
|
1481
|
-
const fileTabs = (0, external_react_namespaceObject.useMemo)(()=>getFileTabs(template), [
|
|
1482
|
-
template
|
|
1483
|
-
]);
|
|
1484
|
-
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1485
|
-
react_namespaceObject.loader.config({
|
|
1486
|
-
paths: {
|
|
1487
|
-
vs: defaults.monacoVsUrl
|
|
1465
|
+
const [leftPaneWidth, setLeftPaneWidth] = (0, external_react_namespaceObject.useState)(DEFAULT_LEFT_PANE_WIDTH);
|
|
1466
|
+
const [isDesktopLayout, setIsDesktopLayout] = (0, external_react_namespaceObject.useState)(()=>'undefined' == typeof window || window.innerWidth > 980);
|
|
1467
|
+
const [activeFile, setActiveFile] = (0, external_react_namespaceObject.useState)('app.tsx');
|
|
1468
|
+
const [status, setStatus] = (0, external_react_namespaceObject.useState)('');
|
|
1469
|
+
const [isResolvingExpose, setIsResolvingExpose] = (0, external_react_namespaceObject.useState)(false);
|
|
1470
|
+
const [copiedKey, setCopiedKey] = (0, external_react_namespaceObject.useState)('');
|
|
1471
|
+
const [resolvedManifest, setResolvedManifest] = (0, external_react_namespaceObject.useState)(null);
|
|
1472
|
+
const [previewState, setPreviewState] = (0, external_react_namespaceObject.useState)(null);
|
|
1473
|
+
const [renderError, setRenderError] = (0, external_react_namespaceObject.useState)(null);
|
|
1474
|
+
const [terminalLines, setTerminalLines] = (0, external_react_namespaceObject.useState)([
|
|
1475
|
+
{
|
|
1476
|
+
id: 0,
|
|
1477
|
+
level: 'info',
|
|
1478
|
+
message: 'Terminal ready. Compile and runtime errors will appear here after Run Sandbox.'
|
|
1488
1479
|
}
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
editorFiles,
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1480
|
+
]);
|
|
1481
|
+
const [runId, setRunId] = (0, external_react_namespaceObject.useState)(0);
|
|
1482
|
+
const runIdRef = (0, external_react_namespaceObject.useRef)(runId);
|
|
1483
|
+
const autoRunStartedRef = (0, external_react_namespaceObject.useRef)(false);
|
|
1484
|
+
const onRunRef = (0, external_react_namespaceObject.useRef)(null);
|
|
1485
|
+
const monacoRef = (0, external_react_namespaceObject.useRef)(null);
|
|
1486
|
+
const resizeStateRef = (0, external_react_namespaceObject.useRef)(null);
|
|
1487
|
+
const editorFiles = (0, external_react_namespaceObject.useMemo)(()=>({
|
|
1488
|
+
'app.tsx': appCode,
|
|
1489
|
+
'entry.ts': entryCode,
|
|
1490
|
+
runtime: mfCode,
|
|
1491
|
+
'rspack.config.mjs': rspackConfigCode
|
|
1492
|
+
}), [
|
|
1493
|
+
appCode,
|
|
1494
|
+
entryCode,
|
|
1495
|
+
mfCode,
|
|
1496
|
+
rspackConfigCode
|
|
1497
|
+
]);
|
|
1498
|
+
const fileTabs = (0, external_react_namespaceObject.useMemo)(()=>getFileTabs(template), [
|
|
1499
|
+
template
|
|
1500
|
+
]);
|
|
1501
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1502
|
+
react_namespaceObject.loader.config({
|
|
1503
|
+
paths: {
|
|
1504
|
+
vs: defaults.monacoVsUrl
|
|
1505
|
+
}
|
|
1506
|
+
});
|
|
1507
|
+
}, [
|
|
1508
|
+
defaults.monacoVsUrl
|
|
1509
|
+
]);
|
|
1510
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1511
|
+
if (monacoRef.current) syncEditorModels(monacoRef.current, editorFiles, template);
|
|
1512
|
+
}, [
|
|
1513
|
+
editorFiles,
|
|
1514
|
+
template
|
|
1515
|
+
]);
|
|
1516
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1517
|
+
runIdRef.current = runId;
|
|
1518
|
+
}, [
|
|
1519
|
+
runId
|
|
1520
|
+
]);
|
|
1521
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1522
|
+
if ('undefined' == typeof window) return;
|
|
1523
|
+
const handleResize = ()=>{
|
|
1524
|
+
const nextIsDesktop = window.innerWidth > 980;
|
|
1525
|
+
setIsDesktopLayout(nextIsDesktop);
|
|
1526
|
+
if (!nextIsDesktop) {
|
|
1527
|
+
resizeStateRef.current = null;
|
|
1528
|
+
setLeftPaneWidth(DEFAULT_LEFT_PANE_WIDTH);
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
handleResize();
|
|
1532
|
+
window.addEventListener('resize', handleResize);
|
|
1533
|
+
return ()=>window.removeEventListener('resize', handleResize);
|
|
1534
|
+
}, []);
|
|
1535
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1536
|
+
if ('undefined' == typeof window) return;
|
|
1537
|
+
window.__MF_PLAYGROUND_HOST_REACT__ = external_react_namespaceObject;
|
|
1538
|
+
window.__MF_PLAYGROUND_HOST_REACT_DOM__ = {
|
|
1539
|
+
...external_react_dom_namespaceObject,
|
|
1540
|
+
...client_namespaceObject
|
|
1541
|
+
};
|
|
1542
|
+
}, []);
|
|
1543
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1544
|
+
if (!isDesktopLayout || 'undefined' == typeof window) return;
|
|
1545
|
+
const handleMouseMove = (event)=>{
|
|
1546
|
+
const resizeState = resizeStateRef.current;
|
|
1547
|
+
if (!resizeState) return;
|
|
1548
|
+
const viewportWidth = window.innerWidth || 1;
|
|
1549
|
+
const deltaRatio = (event.clientX - resizeState.startX) / viewportWidth * 100;
|
|
1550
|
+
const nextWidth = Math.min(MAX_LEFT_PANE_WIDTH, Math.max(MIN_LEFT_PANE_WIDTH, resizeState.startWidth + deltaRatio));
|
|
1551
|
+
setLeftPaneWidth(nextWidth);
|
|
1552
|
+
};
|
|
1553
|
+
const handleMouseUp = ()=>{
|
|
1510
1554
|
resizeStateRef.current = null;
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
};
|
|
1539
|
-
window.addEventListener('mousemove', handleMouseMove);
|
|
1540
|
-
window.addEventListener('mouseup', handleMouseUp);
|
|
1541
|
-
return ()=>{
|
|
1542
|
-
window.removeEventListener('mousemove', handleMouseMove);
|
|
1543
|
-
window.removeEventListener('mouseup', handleMouseUp);
|
|
1544
|
-
};
|
|
1545
|
-
}, [
|
|
1546
|
-
isDesktopLayout
|
|
1547
|
-
]);
|
|
1548
|
-
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1549
|
-
const onMessage = (event)=>{
|
|
1550
|
-
const data = event.data;
|
|
1551
|
-
if (!data || 'mf-playground-terminal' !== data.type || data.runId !== runIdRef.current) return;
|
|
1555
|
+
};
|
|
1556
|
+
window.addEventListener('mousemove', handleMouseMove);
|
|
1557
|
+
window.addEventListener('mouseup', handleMouseUp);
|
|
1558
|
+
return ()=>{
|
|
1559
|
+
window.removeEventListener('mousemove', handleMouseMove);
|
|
1560
|
+
window.removeEventListener('mouseup', handleMouseUp);
|
|
1561
|
+
};
|
|
1562
|
+
}, [
|
|
1563
|
+
isDesktopLayout
|
|
1564
|
+
]);
|
|
1565
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1566
|
+
const onMessage = (event)=>{
|
|
1567
|
+
const data = event.data;
|
|
1568
|
+
if (!data || 'mf-playground-terminal' !== data.type || data.runId !== runIdRef.current) return;
|
|
1569
|
+
setTerminalLines((currentLines)=>[
|
|
1570
|
+
...currentLines,
|
|
1571
|
+
{
|
|
1572
|
+
id: Date.now() + Math.random(),
|
|
1573
|
+
level: normalizeTerminalLevel(data.level),
|
|
1574
|
+
message: String(data.message || '')
|
|
1575
|
+
}
|
|
1576
|
+
].slice(-120));
|
|
1577
|
+
};
|
|
1578
|
+
window.addEventListener('message', onMessage);
|
|
1579
|
+
return ()=>window.removeEventListener('message', onMessage);
|
|
1580
|
+
}, []);
|
|
1581
|
+
const appendTerminalLine = (level, message)=>{
|
|
1552
1582
|
setTerminalLines((currentLines)=>[
|
|
1553
1583
|
...currentLines,
|
|
1554
1584
|
{
|
|
1555
1585
|
id: Date.now() + Math.random(),
|
|
1556
|
-
level
|
|
1557
|
-
message
|
|
1586
|
+
level,
|
|
1587
|
+
message
|
|
1558
1588
|
}
|
|
1559
1589
|
].slice(-120));
|
|
1560
1590
|
};
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1591
|
+
const manifestName = (0, external_react_namespaceObject.useMemo)(()=>{
|
|
1592
|
+
if (!resolvedManifest) return '';
|
|
1593
|
+
return resolvedManifest.metaData?.name || resolvedManifest.name || resolvedManifest.id || '';
|
|
1594
|
+
}, [
|
|
1595
|
+
resolvedManifest
|
|
1596
|
+
]);
|
|
1597
|
+
const syncGeneratedAppCode = (nextManifest, nextExpose, nextExportName)=>{
|
|
1598
|
+
const reactVersion = nextManifest ? extractReactDependencyVersions(nextManifest).react : DEFAULT_REACT_VERSION;
|
|
1599
|
+
if (!nextManifest) {
|
|
1600
|
+
const placeholderCode = buildDefaultAppCode('', nextExportName, nextExpose, reactVersion, template);
|
|
1601
|
+
setAppCode((currentCode)=>currentCode === lastGeneratedAppCode ? placeholderCode : currentCode);
|
|
1602
|
+
setLastGeneratedAppCode(placeholderCode);
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
const resolvedRemoteName = guessRemoteName(nextManifest).trim();
|
|
1606
|
+
const nextLoadedTarget = formatLoadedTarget(resolvedRemoteName, normalizeExpose(nextExpose));
|
|
1607
|
+
const nextCode = buildDefaultAppCode(nextLoadedTarget, nextExportName, nextExpose, reactVersion, template);
|
|
1608
|
+
setAppCode((currentCode)=>currentCode === lastGeneratedAppCode ? nextCode : currentCode);
|
|
1609
|
+
setLastGeneratedAppCode(nextCode);
|
|
1610
|
+
};
|
|
1611
|
+
const syncGeneratedMfCode = (nextManifestUrl, nextManifest)=>{
|
|
1612
|
+
if (!nextManifest) return;
|
|
1613
|
+
const resolvedRemoteName = guessRemoteName(nextManifest).trim();
|
|
1614
|
+
const reactDependencyVersions = extractReactDependencyVersions(nextManifest);
|
|
1615
|
+
const nextCode = buildDefaultMfCode(nextManifestUrl, resolvedRemoteName, reactDependencyVersions, template);
|
|
1616
|
+
setMfCode((currentCode)=>currentCode === lastGeneratedMfCode ? nextCode : currentCode);
|
|
1617
|
+
setLastGeneratedMfCode(nextCode);
|
|
1618
|
+
};
|
|
1619
|
+
const syncGeneratedMfPlaceholder = ()=>{
|
|
1620
|
+
const nextCode = buildDefaultMfCode('', '', {
|
|
1621
|
+
react: DEFAULT_REACT_VERSION,
|
|
1622
|
+
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1623
|
+
}, template);
|
|
1624
|
+
setMfCode((currentCode)=>currentCode === lastGeneratedMfCode ? nextCode : currentCode);
|
|
1625
|
+
setLastGeneratedMfCode(nextCode);
|
|
1626
|
+
};
|
|
1627
|
+
const onManifestReady = async (options)=>{
|
|
1628
|
+
const appendTerminal = options?.appendTerminal ?? true;
|
|
1629
|
+
const silentStatus = options?.silentStatus ?? false;
|
|
1630
|
+
const nextManifestUrl = manifestUrl.trim();
|
|
1631
|
+
if (!nextManifestUrl) {
|
|
1632
|
+
setResolvedManifest(null);
|
|
1633
|
+
setExposeOptions([]);
|
|
1634
|
+
setExpose('');
|
|
1635
|
+
setOpenPanels((current)=>({
|
|
1636
|
+
...current,
|
|
1637
|
+
code: false
|
|
1638
|
+
}));
|
|
1639
|
+
syncGeneratedAppCode(null, '', exportName);
|
|
1640
|
+
syncGeneratedMfPlaceholder();
|
|
1641
|
+
throw new Error(isEn ? 'Manifest URL is required before running the sandbox.' : '运行前请先填写 Manifest URL。');
|
|
1642
|
+
}
|
|
1643
|
+
setIsResolvingExpose(true);
|
|
1644
|
+
if (!silentStatus) setStatus(isEn ? 'Resolving manifest...' : '解析 Manifest 中...');
|
|
1645
|
+
if (appendTerminal) appendTerminalLine('info', `Resolving manifest: ${nextManifestUrl}`);
|
|
1646
|
+
try {
|
|
1647
|
+
const manifest = await fetchManifest(nextManifestUrl);
|
|
1648
|
+
const options = manifest.exposes?.map((item)=>item?.name?.trim()).filter((item)=>Boolean(item)) || [];
|
|
1649
|
+
const effectiveExpose = resolveExposeFromOptions(options, expose);
|
|
1650
|
+
setResolvedManifest(manifest);
|
|
1651
|
+
setExposeOptions(options);
|
|
1652
|
+
const reactDependencyVersions = extractReactDependencyVersions(manifest);
|
|
1653
|
+
const dependencyVersions = {
|
|
1654
|
+
...reactDependencyVersions
|
|
1655
|
+
};
|
|
1656
|
+
setRspackConfigCode((currentCode)=>updateDependencyVersionsInRspackConfig(currentCode, dependencyVersions));
|
|
1657
|
+
syncGeneratedAppCode(manifest, effectiveExpose, exportName);
|
|
1658
|
+
syncGeneratedMfCode(nextManifestUrl, manifest);
|
|
1659
|
+
setExpose(effectiveExpose);
|
|
1660
|
+
setOpenPanels((current)=>({
|
|
1661
|
+
...current,
|
|
1662
|
+
code: true
|
|
1663
|
+
}));
|
|
1664
|
+
if (!silentStatus) setStatus(options.length > 0 ? isEn ? `Loaded ${options.length} expose entries` : `已加载 ${options.length} 个 expose` : isEn ? 'No exposes found in manifest' : 'Manifest 未提供 expose');
|
|
1665
|
+
return manifest;
|
|
1666
|
+
} catch (error) {
|
|
1667
|
+
const message = formatErrorForTerminal(error);
|
|
1668
|
+
setResolvedManifest(null);
|
|
1669
|
+
setExposeOptions([]);
|
|
1670
|
+
setExpose('');
|
|
1671
|
+
setOpenPanels((current)=>({
|
|
1672
|
+
...current,
|
|
1673
|
+
code: false
|
|
1674
|
+
}));
|
|
1675
|
+
setStatus(error instanceof Error ? error.message : String(error));
|
|
1676
|
+
syncGeneratedAppCode(null, '', exportName);
|
|
1677
|
+
syncGeneratedMfPlaceholder();
|
|
1678
|
+
if (appendTerminal) appendTerminalLine('error', `Resolve manifest failed:\n${message}`);
|
|
1679
|
+
throw error;
|
|
1680
|
+
} finally{
|
|
1681
|
+
setIsResolvingExpose(false);
|
|
1682
|
+
}
|
|
1683
|
+
};
|
|
1684
|
+
const onRun = async ()=>{
|
|
1685
|
+
setPreviewState(null);
|
|
1686
|
+
setRenderError(null);
|
|
1687
|
+
setStatus('编译中...');
|
|
1688
|
+
setTerminalLines([
|
|
1567
1689
|
{
|
|
1568
|
-
id: Date.now()
|
|
1569
|
-
level,
|
|
1570
|
-
message
|
|
1690
|
+
id: Date.now(),
|
|
1691
|
+
level: 'info',
|
|
1692
|
+
message: 'Compiling sandbox...'
|
|
1571
1693
|
}
|
|
1572
|
-
]
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
if (!silentStatus) setStatus(isEn ? 'Resolving manifest...' : '解析 Manifest 中...');
|
|
1628
|
-
if (appendTerminal) appendTerminalLine('info', `Resolving manifest: ${nextManifestUrl}`);
|
|
1629
|
-
try {
|
|
1630
|
-
const manifest = await fetchManifest(nextManifestUrl);
|
|
1631
|
-
const options = manifest.exposes?.map((item)=>item?.name?.trim()).filter((item)=>Boolean(item)) || [];
|
|
1632
|
-
const effectiveExpose = resolveExposeFromOptions(options, expose);
|
|
1633
|
-
setResolvedManifest(manifest);
|
|
1634
|
-
setExposeOptions(options);
|
|
1635
|
-
const reactDependencyVersions = extractReactDependencyVersions(manifest);
|
|
1636
|
-
const dependencyVersions = {
|
|
1637
|
-
...reactDependencyVersions
|
|
1638
|
-
};
|
|
1639
|
-
setRspackConfigCode((currentCode)=>updateDependencyVersionsInRspackConfig(currentCode, dependencyVersions));
|
|
1640
|
-
syncGeneratedAppCode(manifest, effectiveExpose, exportName);
|
|
1641
|
-
syncGeneratedMfCode(nextManifestUrl, manifest);
|
|
1642
|
-
setExpose(effectiveExpose);
|
|
1643
|
-
setOpenPanels((current)=>({
|
|
1644
|
-
...current,
|
|
1645
|
-
code: true
|
|
1646
|
-
}));
|
|
1647
|
-
if (!silentStatus) setStatus(options.length > 0 ? isEn ? `Loaded ${options.length} expose entries` : `已加载 ${options.length} 个 expose` : isEn ? 'No exposes found in manifest' : 'Manifest 未提供 expose');
|
|
1648
|
-
return manifest;
|
|
1649
|
-
} catch (error) {
|
|
1650
|
-
const message = formatErrorForTerminal(error);
|
|
1651
|
-
setResolvedManifest(null);
|
|
1652
|
-
setExposeOptions([]);
|
|
1653
|
-
setExpose('');
|
|
1654
|
-
setOpenPanels((current)=>({
|
|
1655
|
-
...current,
|
|
1656
|
-
code: false
|
|
1657
|
-
}));
|
|
1658
|
-
setStatus(error instanceof Error ? error.message : String(error));
|
|
1659
|
-
syncGeneratedAppCode(null, '', exportName);
|
|
1660
|
-
syncGeneratedMfPlaceholder();
|
|
1661
|
-
if (appendTerminal) appendTerminalLine('error', `Resolve manifest failed:\n${message}`);
|
|
1662
|
-
throw error;
|
|
1663
|
-
} finally{
|
|
1664
|
-
setIsResolvingExpose(false);
|
|
1665
|
-
}
|
|
1666
|
-
};
|
|
1667
|
-
const onRun = async ()=>{
|
|
1668
|
-
setPreviewState(null);
|
|
1669
|
-
setRenderError(null);
|
|
1670
|
-
setStatus('编译中...');
|
|
1671
|
-
setTerminalLines([
|
|
1672
|
-
{
|
|
1673
|
-
id: Date.now(),
|
|
1674
|
-
level: 'info',
|
|
1675
|
-
message: 'Compiling sandbox...'
|
|
1694
|
+
]);
|
|
1695
|
+
try {
|
|
1696
|
+
const normalizedManifestUrl = manifestUrl.trim();
|
|
1697
|
+
const manifestForRun = await onManifestReady({
|
|
1698
|
+
appendTerminal: false,
|
|
1699
|
+
silentStatus: true
|
|
1700
|
+
});
|
|
1701
|
+
const reactDependencyVersions = manifestForRun ? extractReactDependencyVersions(manifestForRun) : getDefaultReactDependencyVersions();
|
|
1702
|
+
const dependencyVersions = {
|
|
1703
|
+
...reactDependencyVersions
|
|
1704
|
+
};
|
|
1705
|
+
const nextRspackConfigCode = updateDependencyVersionsInRspackConfig(rspackConfigCode, dependencyVersions);
|
|
1706
|
+
if (nextRspackConfigCode !== rspackConfigCode) setRspackConfigCode(nextRspackConfigCode);
|
|
1707
|
+
const remoteNameForRun = manifestForRun ? guessRemoteName(manifestForRun) : manifestName || normalizedManifestUrl || 'remote';
|
|
1708
|
+
const nextExposeForRun = normalizeExpose(expose || manifestForRun?.exposes?.[0]?.name || '');
|
|
1709
|
+
const nextGeneratedAppCode = buildDefaultAppCode(formatLoadedTarget(remoteNameForRun, nextExposeForRun), exportName, nextExposeForRun, reactDependencyVersions.react, template);
|
|
1710
|
+
const nextGeneratedMfCode = buildDefaultMfCode(normalizedManifestUrl, remoteNameForRun, reactDependencyVersions, template);
|
|
1711
|
+
const nextAppCode = appCode === lastGeneratedAppCode ? nextGeneratedAppCode : appCode;
|
|
1712
|
+
const nextMfCode = mfCode === lastGeneratedMfCode ? nextGeneratedMfCode : mfCode;
|
|
1713
|
+
if (nextGeneratedAppCode !== lastGeneratedAppCode) setLastGeneratedAppCode(nextGeneratedAppCode);
|
|
1714
|
+
if (nextAppCode !== appCode) setAppCode(nextAppCode);
|
|
1715
|
+
if (nextGeneratedMfCode !== lastGeneratedMfCode) setLastGeneratedMfCode(nextGeneratedMfCode);
|
|
1716
|
+
if (nextMfCode !== mfCode) setMfCode(nextMfCode);
|
|
1717
|
+
const bundle = await compilePlaygroundApp({
|
|
1718
|
+
appCode: nextAppCode,
|
|
1719
|
+
entryCode,
|
|
1720
|
+
mfCode: nextMfCode,
|
|
1721
|
+
runtimeModuleUrl: defaults.runtimeModuleUrl,
|
|
1722
|
+
runtimeFileName: template.runtimeFileName,
|
|
1723
|
+
runtimeGlobalName: template.runtimeGlobalName,
|
|
1724
|
+
runtimePackageName: template.runtimePackageName,
|
|
1725
|
+
rspackConfigCode: nextRspackConfigCode
|
|
1726
|
+
});
|
|
1727
|
+
const normalizedCurrentExpose = nextExposeForRun;
|
|
1728
|
+
const loadedTarget = formatLoadedTarget(remoteNameForRun, normalizedCurrentExpose);
|
|
1729
|
+
const nextRunId = runId + 1;
|
|
1730
|
+
runIdRef.current = nextRunId;
|
|
1731
|
+
setRunId(nextRunId);
|
|
1732
|
+
setPreviewState({
|
|
1733
|
+
kind: 'consumer',
|
|
1734
|
+
bundle,
|
|
1735
|
+
loadedTarget,
|
|
1736
|
+
manifest: manifestForRun,
|
|
1737
|
+
manifestUrl: normalizedManifestUrl,
|
|
1738
|
+
expose: normalizedCurrentExpose,
|
|
1739
|
+
previewRoute: normalizePreviewRoute(previewRoute),
|
|
1740
|
+
runtimeModuleUrl: defaults.runtimeModuleUrl,
|
|
1741
|
+
runId: nextRunId
|
|
1742
|
+
});
|
|
1743
|
+
setStatus('完成');
|
|
1744
|
+
appendTerminalLine('info', 'Sandbox bundle compiled. Preview is running.');
|
|
1745
|
+
} catch (error) {
|
|
1746
|
+
const message = formatErrorForTerminal(error);
|
|
1747
|
+
setStatus(error instanceof Error ? error.message : String(error));
|
|
1748
|
+
appendTerminalLine('error', `Run Sandbox failed:\n${message}`);
|
|
1676
1749
|
}
|
|
1750
|
+
};
|
|
1751
|
+
onRunRef.current = onRun;
|
|
1752
|
+
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1753
|
+
if (!initialQueryConfig.autoRun || autoRunStartedRef.current) return;
|
|
1754
|
+
autoRunStartedRef.current = true;
|
|
1755
|
+
onRunRef.current?.();
|
|
1756
|
+
}, [
|
|
1757
|
+
initialQueryConfig.autoRun
|
|
1677
1758
|
]);
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
const
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1759
|
+
const copyText = async (key, text, okMsg)=>{
|
|
1760
|
+
try {
|
|
1761
|
+
await navigator.clipboard.writeText(text);
|
|
1762
|
+
setCopiedKey(key);
|
|
1763
|
+
setStatus(okMsg);
|
|
1764
|
+
window.setTimeout(()=>setCopiedKey(''), 1000);
|
|
1765
|
+
} catch {
|
|
1766
|
+
setStatus('复制失败:浏览器不支持 clipboard API(可手动复制)');
|
|
1767
|
+
}
|
|
1768
|
+
};
|
|
1769
|
+
const CopyButton = (props)=>{
|
|
1770
|
+
const { copyKey, label, okMsg, text } = props;
|
|
1771
|
+
const done = copiedKey === copyKey;
|
|
1772
|
+
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("button", {
|
|
1773
|
+
type: "button",
|
|
1774
|
+
className: cx('vp-copyBtn'),
|
|
1775
|
+
onClick: ()=>void copyText(copyKey, text, okMsg),
|
|
1776
|
+
title: done ? 'Copied' : 'Copy',
|
|
1777
|
+
children: [
|
|
1778
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("svg", {
|
|
1779
|
+
"aria-hidden": "true",
|
|
1780
|
+
className: cx('vp-copyIcon'),
|
|
1781
|
+
viewBox: "0 0 24 24",
|
|
1782
|
+
fill: "none",
|
|
1783
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
1784
|
+
children: [
|
|
1785
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("path", {
|
|
1786
|
+
d: "M8 7.5C8 6.119 9.119 5 10.5 5H18c1.381 0 2.5 1.119 2.5 2.5V15c0 1.381-1.119 2.5-2.5 2.5h-7.5C9.119 17.5 8 16.381 8 15V7.5Z",
|
|
1787
|
+
stroke: "currentColor",
|
|
1788
|
+
strokeWidth: "1.6"
|
|
1789
|
+
}),
|
|
1790
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("path", {
|
|
1791
|
+
d: "M5 9.5C5 8.119 6.119 7 7.5 7H8",
|
|
1792
|
+
stroke: "currentColor",
|
|
1793
|
+
strokeWidth: "1.6",
|
|
1794
|
+
strokeLinecap: "round"
|
|
1795
|
+
}),
|
|
1796
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("path", {
|
|
1797
|
+
d: "M5 18.5C5 19.881 6.119 21 7.5 21H15c1.381 0 2.5-1.119 2.5-2.5V18",
|
|
1798
|
+
stroke: "currentColor",
|
|
1799
|
+
strokeWidth: "1.6",
|
|
1800
|
+
strokeLinecap: "round"
|
|
1801
|
+
})
|
|
1802
|
+
]
|
|
1803
|
+
}),
|
|
1804
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
1805
|
+
children: done ? 'Copied' : label || 'Copy'
|
|
1806
|
+
})
|
|
1807
|
+
]
|
|
1709
1808
|
});
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1809
|
+
};
|
|
1810
|
+
const renderPreview = ()=>{
|
|
1811
|
+
if (!previewState) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1812
|
+
className: cx('vp-empty'),
|
|
1813
|
+
children: [
|
|
1814
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1815
|
+
className: cx('vp-emptyTitle'),
|
|
1816
|
+
children: "Ready."
|
|
1817
|
+
}),
|
|
1818
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1819
|
+
children: isEn ? '1. Fill in the Manifest URL first.' : '1. 先填写 Manifest URL。'
|
|
1820
|
+
}),
|
|
1821
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1822
|
+
children: isEn ? '2. Click Run Sandbox. It resolves the manifest first, then starts the preview if everything is valid.' : '2. 点击 Run Sandbox。它会先解析 Manifest,没问题再启动右侧预览。'
|
|
1823
|
+
}),
|
|
1824
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1825
|
+
children: isEn ? '3. If manifest parsing fails, check the terminal below for the exact error.' : '3. 如果 Manifest 解析失败,直接看下方 Terminal 里的具体报错。'
|
|
1826
|
+
}),
|
|
1827
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1828
|
+
children: isEn ? '4. If you still need to adjust how the producer is loaded, edit the consumer code in the Code panel on the left. The Code panel only appears and loads after the first successful Manifest resolve.' : '4. 如果还需要调整加载方式,再去修改左侧 Code 里的消费者代码。Code 只有在第一次解析 Manifest 成功后才会出现并加载。'
|
|
1829
|
+
})
|
|
1830
|
+
]
|
|
1725
1831
|
});
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
const message = formatErrorForTerminal(error);
|
|
1730
|
-
setStatus(error instanceof Error ? error.message : String(error));
|
|
1731
|
-
appendTerminalLine('error', `Run Sandbox failed:\n${message}`);
|
|
1732
|
-
}
|
|
1733
|
-
};
|
|
1734
|
-
onRunRef.current = onRun;
|
|
1735
|
-
(0, external_react_namespaceObject.useEffect)(()=>{
|
|
1736
|
-
if (!initialQueryConfig.autoRun || autoRunStartedRef.current) return;
|
|
1737
|
-
autoRunStartedRef.current = true;
|
|
1738
|
-
onRunRef.current?.();
|
|
1739
|
-
}, [
|
|
1740
|
-
initialQueryConfig.autoRun
|
|
1741
|
-
]);
|
|
1742
|
-
const copyText = async (key, text, okMsg)=>{
|
|
1743
|
-
try {
|
|
1744
|
-
await navigator.clipboard.writeText(text);
|
|
1745
|
-
setCopiedKey(key);
|
|
1746
|
-
setStatus(okMsg);
|
|
1747
|
-
window.setTimeout(()=>setCopiedKey(''), 1000);
|
|
1748
|
-
} catch {
|
|
1749
|
-
setStatus('复制失败:浏览器不支持 clipboard API(可手动复制)');
|
|
1750
|
-
}
|
|
1751
|
-
};
|
|
1752
|
-
const CopyButton = (props)=>{
|
|
1753
|
-
const { copyKey, label, okMsg, text } = props;
|
|
1754
|
-
const done = copiedKey === copyKey;
|
|
1755
|
-
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("button", {
|
|
1756
|
-
type: "button",
|
|
1757
|
-
className: cx('vp-copyBtn'),
|
|
1758
|
-
onClick: ()=>void copyText(copyKey, text, okMsg),
|
|
1759
|
-
title: done ? 'Copied' : 'Copy',
|
|
1760
|
-
children: [
|
|
1761
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("svg", {
|
|
1762
|
-
"aria-hidden": "true",
|
|
1763
|
-
className: cx('vp-copyIcon'),
|
|
1764
|
-
viewBox: "0 0 24 24",
|
|
1765
|
-
fill: "none",
|
|
1766
|
-
xmlns: "http://www.w3.org/2000/svg",
|
|
1832
|
+
if ('consumer' === previewState.kind) {
|
|
1833
|
+
const { expose: currentExpose, runId: currentRunId } = previewState;
|
|
1834
|
+
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1767
1835
|
children: [
|
|
1768
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1836
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1837
|
+
className: cx('vp-kv'),
|
|
1838
|
+
children: [
|
|
1839
|
+
"Target:",
|
|
1840
|
+
' ',
|
|
1841
|
+
formatLoadedTarget(manifestName || 'remote', currentExpose)
|
|
1842
|
+
]
|
|
1772
1843
|
}),
|
|
1773
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
d: "M5 18.5C5 19.881 6.119 21 7.5 21H15c1.381 0 2.5-1.119 2.5-2.5V18",
|
|
1781
|
-
stroke: "currentColor",
|
|
1782
|
-
strokeWidth: "1.6",
|
|
1783
|
-
strokeLinecap: "round"
|
|
1844
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1845
|
+
className: cx('vp-renderArea'),
|
|
1846
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("iframe", {
|
|
1847
|
+
className: cx('vp-previewFrame'),
|
|
1848
|
+
title: "Sandbox Preview",
|
|
1849
|
+
srcDoc: buildPreviewDocument(previewState, defaults)
|
|
1850
|
+
}, currentRunId)
|
|
1784
1851
|
})
|
|
1785
1852
|
]
|
|
1786
|
-
})
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
};
|
|
1793
|
-
const renderPreview = ()=>{
|
|
1794
|
-
if (!previewState) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1795
|
-
className: cx('vp-empty'),
|
|
1796
|
-
children: [
|
|
1797
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1798
|
-
className: cx('vp-emptyTitle'),
|
|
1799
|
-
children: "Ready."
|
|
1800
|
-
}),
|
|
1801
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1802
|
-
children: isEn ? '1. Fill in the Manifest URL first.' : '1. 先填写 Manifest URL。'
|
|
1803
|
-
}),
|
|
1804
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1805
|
-
children: isEn ? '2. Click Run Sandbox. It resolves the manifest first, then starts the preview if everything is valid.' : '2. 点击 Run Sandbox。它会先解析 Manifest,没问题再启动右侧预览。'
|
|
1806
|
-
}),
|
|
1807
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1808
|
-
children: isEn ? '3. If manifest parsing fails, check the terminal below for the exact error.' : '3. 如果 Manifest 解析失败,直接看下方 Terminal 里的具体报错。'
|
|
1809
|
-
}),
|
|
1810
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1811
|
-
children: isEn ? '4. If you still need to adjust how the producer is loaded, edit the consumer code in the Code panel on the left. The Code panel only appears and loads after the first successful Manifest resolve.' : '4. 如果还需要调整加载方式,再去修改左侧 Code 里的消费者代码。Code 只有在第一次解析 Manifest 成功后才会出现并加载。'
|
|
1812
|
-
})
|
|
1813
|
-
]
|
|
1814
|
-
});
|
|
1815
|
-
if ('consumer' === previewState.kind) {
|
|
1816
|
-
const { expose: currentExpose, runId: currentRunId } = previewState;
|
|
1817
|
-
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
return null;
|
|
1856
|
+
};
|
|
1857
|
+
const renderTerminal = ()=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1858
|
+
className: cx('vp-terminal'),
|
|
1818
1859
|
children: [
|
|
1819
1860
|
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1820
|
-
className: cx('vp-
|
|
1861
|
+
className: cx('vp-terminalHeader'),
|
|
1821
1862
|
children: [
|
|
1822
|
-
"
|
|
1823
|
-
|
|
1824
|
-
|
|
1863
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
1864
|
+
children: "Terminal"
|
|
1865
|
+
}),
|
|
1866
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("button", {
|
|
1867
|
+
type: "button",
|
|
1868
|
+
className: cx('vp-terminalClear'),
|
|
1869
|
+
onClick: ()=>setTerminalLines([]),
|
|
1870
|
+
children: "Clear"
|
|
1871
|
+
})
|
|
1825
1872
|
]
|
|
1826
1873
|
}),
|
|
1827
1874
|
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1828
|
-
className: cx('vp-
|
|
1829
|
-
children:
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1875
|
+
className: cx('vp-terminalBody'),
|
|
1876
|
+
children: terminalLines.length > 0 ? terminalLines.map((line)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("pre", {
|
|
1877
|
+
className: cx('vp-terminalLine', 'error' === line.level && 'vp-terminalLineError', 'warn' === line.level && 'vp-terminalLineWarn'),
|
|
1878
|
+
children: line.message
|
|
1879
|
+
}, line.id)) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1880
|
+
className: cx('vp-terminalEmpty'),
|
|
1881
|
+
children: "No output."
|
|
1882
|
+
})
|
|
1834
1883
|
})
|
|
1835
1884
|
]
|
|
1836
1885
|
});
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
const moduleNameText = previewState?.kind === 'consumer' ? formatLoadedTarget(manifestName || 'remote', previewState.expose) : 'editor mode';
|
|
1900
|
-
const mainStyle = isDesktopLayout ? {
|
|
1901
|
-
gridTemplateColumns: `minmax(0, ${leftPaneWidth}fr) 10px minmax(0, ${100 - leftPaneWidth}fr)`
|
|
1902
|
-
} : void 0;
|
|
1903
|
-
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1904
|
-
className: cx('vp-root'),
|
|
1905
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("main", {
|
|
1906
|
-
className: cx('vp-main'),
|
|
1907
|
-
style: mainStyle,
|
|
1908
|
-
children: [
|
|
1909
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("section", {
|
|
1910
|
-
className: cx('vp-left'),
|
|
1911
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1912
|
-
className: cx('vp-card'),
|
|
1913
|
-
children: [
|
|
1914
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1915
|
-
className: cx('vp-cardHeader'),
|
|
1916
|
-
children: [
|
|
1917
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1918
|
-
className: cx('vp-cardTitle'),
|
|
1919
|
-
children: "Workspace"
|
|
1920
|
-
}),
|
|
1921
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1922
|
-
className: cx('vp-paneActions'),
|
|
1923
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("button", {
|
|
1924
|
-
type: "button",
|
|
1925
|
-
className: cx('vp-button', 'vp-buttonPrimary'),
|
|
1926
|
-
onClick: onRun,
|
|
1927
|
-
title: "Run Sandbox",
|
|
1928
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
1929
|
-
children: "Run Sandbox"
|
|
1886
|
+
const fileState = {
|
|
1887
|
+
'app.tsx': {
|
|
1888
|
+
value: appCode,
|
|
1889
|
+
onChange: setAppCode
|
|
1890
|
+
},
|
|
1891
|
+
'entry.ts': {
|
|
1892
|
+
value: entryCode,
|
|
1893
|
+
onChange: setEntryCode
|
|
1894
|
+
},
|
|
1895
|
+
runtime: {
|
|
1896
|
+
value: mfCode,
|
|
1897
|
+
onChange: setMfCode
|
|
1898
|
+
},
|
|
1899
|
+
'rspack.config.mjs': {
|
|
1900
|
+
value: rspackConfigCode,
|
|
1901
|
+
onChange: setRspackConfigCode
|
|
1902
|
+
}
|
|
1903
|
+
};
|
|
1904
|
+
const activeTab = fileTabs.find((item)=>item.key === activeFile) || fileTabs[0];
|
|
1905
|
+
const activeEditor = fileState[activeTab.key];
|
|
1906
|
+
const editorPath = getEditorPath(activeTab.key, template);
|
|
1907
|
+
const editorTheme = useEditorTheme();
|
|
1908
|
+
const locale = useLocale();
|
|
1909
|
+
const isEn = 'en' === locale;
|
|
1910
|
+
const canShowCodePanel = Boolean(resolvedManifest);
|
|
1911
|
+
const displayStatus = renderError?.message || status || 'Idle';
|
|
1912
|
+
const visibleExposeOptions = expose && !exposeOptions.includes(expose) ? [
|
|
1913
|
+
expose,
|
|
1914
|
+
...exposeOptions
|
|
1915
|
+
] : exposeOptions;
|
|
1916
|
+
const moduleNameText = previewState?.kind === 'consumer' ? formatLoadedTarget(manifestName || 'remote', previewState.expose) : 'editor mode';
|
|
1917
|
+
const mainStyle = isDesktopLayout ? {
|
|
1918
|
+
gridTemplateColumns: `minmax(0, ${leftPaneWidth}fr) 10px minmax(0, ${100 - leftPaneWidth}fr)`
|
|
1919
|
+
} : void 0;
|
|
1920
|
+
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1921
|
+
className: cx('vp-root'),
|
|
1922
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("main", {
|
|
1923
|
+
className: cx('vp-main'),
|
|
1924
|
+
style: mainStyle,
|
|
1925
|
+
children: [
|
|
1926
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("section", {
|
|
1927
|
+
className: cx('vp-left'),
|
|
1928
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1929
|
+
className: cx('vp-card'),
|
|
1930
|
+
children: [
|
|
1931
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1932
|
+
className: cx('vp-cardHeader'),
|
|
1933
|
+
children: [
|
|
1934
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1935
|
+
className: cx('vp-cardTitle'),
|
|
1936
|
+
children: "Workspace"
|
|
1937
|
+
}),
|
|
1938
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1939
|
+
className: cx('vp-paneActions'),
|
|
1940
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("button", {
|
|
1941
|
+
type: "button",
|
|
1942
|
+
className: cx('vp-button', 'vp-buttonPrimary'),
|
|
1943
|
+
onClick: onRun,
|
|
1944
|
+
title: "Run Sandbox",
|
|
1945
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
1946
|
+
children: "Run Sandbox"
|
|
1947
|
+
})
|
|
1930
1948
|
})
|
|
1931
1949
|
})
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1950
|
+
]
|
|
1951
|
+
}),
|
|
1952
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1953
|
+
className: cx('vp-cardBody'),
|
|
1954
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1955
|
+
className: cx('vp-collapse'),
|
|
1956
|
+
children: [
|
|
1957
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1958
|
+
className: cx('vp-collapseItem'),
|
|
1959
|
+
children: [
|
|
1960
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("button", {
|
|
1961
|
+
type: "button",
|
|
1962
|
+
className: cx('vp-collapseHeader', openPanels.control && 'vp-collapseHeaderActive'),
|
|
1963
|
+
onClick: ()=>setOpenPanels((current)=>({
|
|
1964
|
+
...current,
|
|
1965
|
+
control: !current.control
|
|
1966
|
+
})),
|
|
1967
|
+
"aria-expanded": openPanels.control,
|
|
1968
|
+
children: [
|
|
1969
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
1970
|
+
className: cx('vp-collapseLabel'),
|
|
1971
|
+
children: "Control Panel"
|
|
1972
|
+
}),
|
|
1973
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
1974
|
+
className: cx('vp-collapseArrow', openPanels.control && 'vp-collapseArrowOpen'),
|
|
1975
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("svg", {
|
|
1976
|
+
viewBox: "0 0 16 16",
|
|
1977
|
+
fill: "none",
|
|
1978
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
1979
|
+
"aria-hidden": "true",
|
|
1980
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("path", {
|
|
1981
|
+
d: "M4.5 6.5L8 10L11.5 6.5",
|
|
1982
|
+
stroke: "currentColor",
|
|
1983
|
+
strokeWidth: "1.6",
|
|
1984
|
+
strokeLinecap: "round",
|
|
1985
|
+
strokeLinejoin: "round"
|
|
1986
|
+
})
|
|
1969
1987
|
})
|
|
1970
1988
|
})
|
|
1989
|
+
]
|
|
1990
|
+
}),
|
|
1991
|
+
openPanels.control ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1992
|
+
className: cx('vp-collapseBody'),
|
|
1993
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1994
|
+
className: cx('vp-form'),
|
|
1995
|
+
children: [
|
|
1996
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1997
|
+
className: cx('vp-field'),
|
|
1998
|
+
children: [
|
|
1999
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2000
|
+
className: cx('vp-labelRow'),
|
|
2001
|
+
children: [
|
|
2002
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2003
|
+
className: cx('vp-label'),
|
|
2004
|
+
children: "Manifest URL"
|
|
2005
|
+
}),
|
|
2006
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2007
|
+
className: cx('vp-hint'),
|
|
2008
|
+
children: isEn ? 'Run Sandbox resolves this automatically' : '点击 Run Sandbox 时自动解析'
|
|
2009
|
+
})
|
|
2010
|
+
]
|
|
2011
|
+
}),
|
|
2012
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("input", {
|
|
2013
|
+
className: cx('vp-input'),
|
|
2014
|
+
value: manifestUrl,
|
|
2015
|
+
onChange: (event)=>{
|
|
2016
|
+
setManifestUrl(event.target.value);
|
|
2017
|
+
setResolvedManifest(null);
|
|
2018
|
+
setExposeOptions([]);
|
|
2019
|
+
setExpose('');
|
|
2020
|
+
setOpenPanels((current)=>({
|
|
2021
|
+
...current,
|
|
2022
|
+
code: false
|
|
2023
|
+
}));
|
|
2024
|
+
syncGeneratedAppCode(null, '', exportName);
|
|
2025
|
+
syncGeneratedMfPlaceholder();
|
|
2026
|
+
},
|
|
2027
|
+
placeholder: "https://.../mf-manifest.json"
|
|
2028
|
+
})
|
|
2029
|
+
]
|
|
2030
|
+
}),
|
|
2031
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2032
|
+
className: cx('vp-fieldGrid'),
|
|
2033
|
+
children: [
|
|
2034
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2035
|
+
className: cx('vp-field'),
|
|
2036
|
+
children: [
|
|
2037
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2038
|
+
className: cx('vp-labelRow'),
|
|
2039
|
+
children: [
|
|
2040
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2041
|
+
className: cx('vp-label'),
|
|
2042
|
+
children: "Expose"
|
|
2043
|
+
}),
|
|
2044
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2045
|
+
className: cx('vp-hint'),
|
|
2046
|
+
children: manifestName ? `Remote: ${manifestName}` : isEn ? 'Auto read from manifest' : '从 manifest 自动读取'
|
|
2047
|
+
})
|
|
2048
|
+
]
|
|
2049
|
+
}),
|
|
2050
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("select", {
|
|
2051
|
+
className: cx('vp-select'),
|
|
2052
|
+
value: expose,
|
|
2053
|
+
onChange: (event)=>{
|
|
2054
|
+
const nextExpose = event.target.value;
|
|
2055
|
+
setExpose(nextExpose);
|
|
2056
|
+
syncGeneratedAppCode(resolvedManifest, nextExpose, exportName);
|
|
2057
|
+
syncGeneratedMfCode(manifestUrl.trim(), resolvedManifest);
|
|
2058
|
+
},
|
|
2059
|
+
disabled: isResolvingExpose,
|
|
2060
|
+
children: visibleExposeOptions.length > 0 ? visibleExposeOptions.map((item)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("option", {
|
|
2061
|
+
value: item,
|
|
2062
|
+
children: item
|
|
2063
|
+
}, item)) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("option", {
|
|
2064
|
+
value: "",
|
|
2065
|
+
children: isEn ? 'Run Sandbox to load expose options' : '点击 Run Sandbox 后加载 expose'
|
|
2066
|
+
})
|
|
2067
|
+
})
|
|
2068
|
+
]
|
|
2069
|
+
}),
|
|
2070
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2071
|
+
className: cx('vp-field'),
|
|
2072
|
+
children: [
|
|
2073
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2074
|
+
className: cx('vp-labelRow'),
|
|
2075
|
+
children: [
|
|
2076
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2077
|
+
className: cx('vp-label'),
|
|
2078
|
+
children: "Export"
|
|
2079
|
+
}),
|
|
2080
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2081
|
+
className: cx('vp-hint'),
|
|
2082
|
+
children: isEn ? 'Default is default; you can switch to a named export' : '默认 default,可改成具名导出'
|
|
2083
|
+
})
|
|
2084
|
+
]
|
|
2085
|
+
}),
|
|
2086
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("input", {
|
|
2087
|
+
className: cx('vp-input'),
|
|
2088
|
+
value: exportName,
|
|
2089
|
+
onChange: (event)=>{
|
|
2090
|
+
const nextExportName = event.target.value;
|
|
2091
|
+
setExportName(nextExportName);
|
|
2092
|
+
syncGeneratedAppCode(resolvedManifest, expose, nextExportName);
|
|
2093
|
+
syncGeneratedMfCode(manifestUrl.trim(), resolvedManifest);
|
|
2094
|
+
},
|
|
2095
|
+
placeholder: "default"
|
|
2096
|
+
})
|
|
2097
|
+
]
|
|
2098
|
+
})
|
|
2099
|
+
]
|
|
2100
|
+
}),
|
|
2101
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2102
|
+
className: cx('vp-field'),
|
|
2103
|
+
children: [
|
|
2104
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2105
|
+
className: cx('vp-labelRow'),
|
|
2106
|
+
children: [
|
|
2107
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2108
|
+
className: cx('vp-label'),
|
|
2109
|
+
children: "Preview Route"
|
|
2110
|
+
}),
|
|
2111
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2112
|
+
className: cx('vp-hint'),
|
|
2113
|
+
children: isEn ? 'Match the basename used by export-app' : '和 export-app 的 basename 保持一致'
|
|
2114
|
+
})
|
|
2115
|
+
]
|
|
2116
|
+
}),
|
|
2117
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("input", {
|
|
2118
|
+
className: cx('vp-input'),
|
|
2119
|
+
value: previewRoute,
|
|
2120
|
+
onChange: (event)=>{
|
|
2121
|
+
setPreviewRoute(event.target.value);
|
|
2122
|
+
},
|
|
2123
|
+
placeholder: "/"
|
|
2124
|
+
})
|
|
2125
|
+
]
|
|
2126
|
+
})
|
|
2127
|
+
]
|
|
1971
2128
|
})
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
2129
|
+
}) : null
|
|
2130
|
+
]
|
|
2131
|
+
}),
|
|
2132
|
+
canShowCodePanel ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2133
|
+
className: cx('vp-collapseItem'),
|
|
2134
|
+
children: [
|
|
2135
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("button", {
|
|
2136
|
+
type: "button",
|
|
2137
|
+
className: cx('vp-collapseHeader', openPanels.code && 'vp-collapseHeaderActive'),
|
|
2138
|
+
onClick: ()=>setOpenPanels((current)=>({
|
|
2139
|
+
...current,
|
|
2140
|
+
code: !current.code
|
|
2141
|
+
})),
|
|
2142
|
+
"aria-expanded": openPanels.code,
|
|
1978
2143
|
children: [
|
|
1979
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.
|
|
1980
|
-
className: cx('vp-
|
|
1981
|
-
children:
|
|
1982
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
1983
|
-
className: cx('vp-labelRow'),
|
|
1984
|
-
children: [
|
|
1985
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1986
|
-
className: cx('vp-label'),
|
|
1987
|
-
children: "Manifest URL"
|
|
1988
|
-
}),
|
|
1989
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
1990
|
-
className: cx('vp-hint'),
|
|
1991
|
-
children: isEn ? 'Run Sandbox resolves this automatically' : '点击 Run Sandbox 时自动解析'
|
|
1992
|
-
})
|
|
1993
|
-
]
|
|
1994
|
-
}),
|
|
1995
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("input", {
|
|
1996
|
-
className: cx('vp-input'),
|
|
1997
|
-
value: manifestUrl,
|
|
1998
|
-
onChange: (event)=>{
|
|
1999
|
-
setManifestUrl(event.target.value);
|
|
2000
|
-
setResolvedManifest(null);
|
|
2001
|
-
setExposeOptions([]);
|
|
2002
|
-
setExpose('');
|
|
2003
|
-
setOpenPanels((current)=>({
|
|
2004
|
-
...current,
|
|
2005
|
-
code: false
|
|
2006
|
-
}));
|
|
2007
|
-
syncGeneratedAppCode(null, '', exportName);
|
|
2008
|
-
syncGeneratedMfPlaceholder();
|
|
2009
|
-
},
|
|
2010
|
-
placeholder: "https://.../mf-manifest.json"
|
|
2011
|
-
})
|
|
2012
|
-
]
|
|
2144
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2145
|
+
className: cx('vp-collapseLabel'),
|
|
2146
|
+
children: "Code"
|
|
2013
2147
|
}),
|
|
2148
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2149
|
+
className: cx('vp-collapseArrow', openPanels.code && 'vp-collapseArrowOpen'),
|
|
2150
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("svg", {
|
|
2151
|
+
viewBox: "0 0 16 16",
|
|
2152
|
+
fill: "none",
|
|
2153
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2154
|
+
"aria-hidden": "true",
|
|
2155
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("path", {
|
|
2156
|
+
d: "M4.5 6.5L8 10L11.5 6.5",
|
|
2157
|
+
stroke: "currentColor",
|
|
2158
|
+
strokeWidth: "1.6",
|
|
2159
|
+
strokeLinecap: "round",
|
|
2160
|
+
strokeLinejoin: "round"
|
|
2161
|
+
})
|
|
2162
|
+
})
|
|
2163
|
+
})
|
|
2164
|
+
]
|
|
2165
|
+
}),
|
|
2166
|
+
openPanels.code ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2167
|
+
className: cx('vp-collapseBody', 'vp-collapseBodyCode'),
|
|
2168
|
+
children: [
|
|
2014
2169
|
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2015
|
-
className: cx('vp-
|
|
2170
|
+
className: cx('vp-editorToolbar'),
|
|
2016
2171
|
children: [
|
|
2017
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.
|
|
2018
|
-
className: cx('vp-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2028
|
-
className: cx('vp-hint'),
|
|
2029
|
-
children: manifestName ? `Remote: ${manifestName}` : isEn ? 'Auto read from manifest' : '从 manifest 自动读取'
|
|
2030
|
-
})
|
|
2031
|
-
]
|
|
2032
|
-
}),
|
|
2033
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("select", {
|
|
2034
|
-
className: cx('vp-select'),
|
|
2035
|
-
value: expose,
|
|
2036
|
-
onChange: (event)=>{
|
|
2037
|
-
const nextExpose = event.target.value;
|
|
2038
|
-
setExpose(nextExpose);
|
|
2039
|
-
syncGeneratedAppCode(resolvedManifest, nextExpose, exportName);
|
|
2040
|
-
syncGeneratedMfCode(manifestUrl.trim(), resolvedManifest);
|
|
2041
|
-
},
|
|
2042
|
-
disabled: isResolvingExpose,
|
|
2043
|
-
children: visibleExposeOptions.length > 0 ? visibleExposeOptions.map((item)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("option", {
|
|
2044
|
-
value: item,
|
|
2045
|
-
children: item
|
|
2046
|
-
}, item)) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("option", {
|
|
2047
|
-
value: "",
|
|
2048
|
-
children: isEn ? 'Run Sandbox to load expose options' : '点击 Run Sandbox 后加载 expose'
|
|
2049
|
-
})
|
|
2050
|
-
})
|
|
2051
|
-
]
|
|
2172
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2173
|
+
className: cx('vp-editorTabs'),
|
|
2174
|
+
role: "tablist",
|
|
2175
|
+
"aria-label": "Files",
|
|
2176
|
+
children: fileTabs.map((item)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("button", {
|
|
2177
|
+
type: "button",
|
|
2178
|
+
className: item.key === activeTab.key ? cx('vp-editorTab', 'vp-editorTabActive') : cx('vp-editorTab'),
|
|
2179
|
+
onClick: ()=>setActiveFile(item.key),
|
|
2180
|
+
children: item.label || item.key
|
|
2181
|
+
}, item.key))
|
|
2052
2182
|
}),
|
|
2053
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
children: [
|
|
2059
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2060
|
-
className: cx('vp-label'),
|
|
2061
|
-
children: "Export"
|
|
2062
|
-
}),
|
|
2063
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2064
|
-
className: cx('vp-hint'),
|
|
2065
|
-
children: isEn ? 'Default is default; you can switch to a named export' : '默认 default,可改成具名导出'
|
|
2066
|
-
})
|
|
2067
|
-
]
|
|
2068
|
-
}),
|
|
2069
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("input", {
|
|
2070
|
-
className: cx('vp-input'),
|
|
2071
|
-
value: exportName,
|
|
2072
|
-
onChange: (event)=>{
|
|
2073
|
-
const nextExportName = event.target.value;
|
|
2074
|
-
setExportName(nextExportName);
|
|
2075
|
-
syncGeneratedAppCode(resolvedManifest, expose, nextExportName);
|
|
2076
|
-
syncGeneratedMfCode(manifestUrl.trim(), resolvedManifest);
|
|
2077
|
-
},
|
|
2078
|
-
placeholder: "default"
|
|
2079
|
-
})
|
|
2080
|
-
]
|
|
2183
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(CopyButton, {
|
|
2184
|
+
copyKey: activeTab.copyKey,
|
|
2185
|
+
label: "Copy",
|
|
2186
|
+
okMsg: activeTab.copyMessage,
|
|
2187
|
+
text: activeEditor.value
|
|
2081
2188
|
})
|
|
2082
2189
|
]
|
|
2083
2190
|
}),
|
|
2084
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.
|
|
2085
|
-
className: cx('vp-
|
|
2086
|
-
children:
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("input", {
|
|
2101
|
-
className: cx('vp-input'),
|
|
2102
|
-
value: previewRoute,
|
|
2103
|
-
onChange: (event)=>{
|
|
2104
|
-
setPreviewRoute(event.target.value);
|
|
2191
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2192
|
+
className: cx('vp-codeEditor'),
|
|
2193
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(react_default(), {
|
|
2194
|
+
height: "100%",
|
|
2195
|
+
language: getEditorLanguage(activeTab.key),
|
|
2196
|
+
path: editorPath,
|
|
2197
|
+
theme: editorTheme,
|
|
2198
|
+
value: activeEditor.value,
|
|
2199
|
+
loading: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(EditorLoadingState, {}),
|
|
2200
|
+
options: {
|
|
2201
|
+
automaticLayout: true,
|
|
2202
|
+
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
|
2203
|
+
fontSize: 13,
|
|
2204
|
+
lineHeight: 21,
|
|
2205
|
+
minimap: {
|
|
2206
|
+
enabled: false
|
|
2105
2207
|
},
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2208
|
+
padding: {
|
|
2209
|
+
top: 12,
|
|
2210
|
+
bottom: 12
|
|
2211
|
+
},
|
|
2212
|
+
scrollBeyondLastLine: false,
|
|
2213
|
+
tabSize: 2,
|
|
2214
|
+
wordWrap: 'on'
|
|
2215
|
+
},
|
|
2216
|
+
beforeMount: (monaco)=>configureEditor(monaco, template),
|
|
2217
|
+
onMount: (_, monaco)=>{
|
|
2218
|
+
monacoRef.current = monaco;
|
|
2219
|
+
syncEditorModels(monaco, editorFiles, template);
|
|
2220
|
+
},
|
|
2221
|
+
onChange: (value)=>activeEditor.onChange(value || '')
|
|
2222
|
+
}, editorPath)
|
|
2109
2223
|
})
|
|
2110
2224
|
]
|
|
2111
|
-
})
|
|
2112
|
-
|
|
2225
|
+
}) : null
|
|
2226
|
+
]
|
|
2227
|
+
}) : null
|
|
2228
|
+
]
|
|
2229
|
+
})
|
|
2230
|
+
})
|
|
2231
|
+
]
|
|
2232
|
+
})
|
|
2233
|
+
}),
|
|
2234
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2235
|
+
className: cx('vp-splitter'),
|
|
2236
|
+
"aria-hidden": "true",
|
|
2237
|
+
onMouseDown: isDesktopLayout ? (event)=>{
|
|
2238
|
+
resizeStateRef.current = {
|
|
2239
|
+
startWidth: leftPaneWidth,
|
|
2240
|
+
startX: event.clientX
|
|
2241
|
+
};
|
|
2242
|
+
} : void 0
|
|
2243
|
+
}),
|
|
2244
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("section", {
|
|
2245
|
+
className: cx('vp-right'),
|
|
2246
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2247
|
+
className: cx('vp-ide'),
|
|
2248
|
+
children: [
|
|
2249
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2250
|
+
className: cx('vp-ideTitlebar'),
|
|
2251
|
+
children: [
|
|
2252
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2253
|
+
className: cx('vp-ideDots'),
|
|
2254
|
+
children: [
|
|
2255
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2256
|
+
className: cx('vp-dot', 'vp-dotRed')
|
|
2257
|
+
}),
|
|
2258
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2259
|
+
className: cx('vp-dot', 'vp-dotYellow')
|
|
2260
|
+
}),
|
|
2261
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2262
|
+
className: cx('vp-dot', 'vp-dotGreen')
|
|
2263
|
+
})
|
|
2113
2264
|
]
|
|
2114
2265
|
}),
|
|
2115
|
-
|
|
2116
|
-
className: cx('vp-
|
|
2266
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2267
|
+
className: cx('vp-ideTitle'),
|
|
2268
|
+
children: "Sandbox Preview"
|
|
2269
|
+
}),
|
|
2270
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2271
|
+
className: cx('vp-ideMeta'),
|
|
2117
2272
|
children: [
|
|
2118
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
...current,
|
|
2123
|
-
code: !current.code
|
|
2124
|
-
})),
|
|
2125
|
-
"aria-expanded": openPanels.code,
|
|
2126
|
-
children: [
|
|
2127
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2128
|
-
className: cx('vp-collapseLabel'),
|
|
2129
|
-
children: "Code"
|
|
2130
|
-
}),
|
|
2131
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2132
|
-
className: cx('vp-collapseArrow', openPanels.code && 'vp-collapseArrowOpen'),
|
|
2133
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("svg", {
|
|
2134
|
-
viewBox: "0 0 16 16",
|
|
2135
|
-
fill: "none",
|
|
2136
|
-
xmlns: "http://www.w3.org/2000/svg",
|
|
2137
|
-
"aria-hidden": "true",
|
|
2138
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("path", {
|
|
2139
|
-
d: "M4.5 6.5L8 10L11.5 6.5",
|
|
2140
|
-
stroke: "currentColor",
|
|
2141
|
-
strokeWidth: "1.6",
|
|
2142
|
-
strokeLinecap: "round",
|
|
2143
|
-
strokeLinejoin: "round"
|
|
2144
|
-
})
|
|
2145
|
-
})
|
|
2146
|
-
})
|
|
2147
|
-
]
|
|
2273
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2274
|
+
className: cx('vp-ideMetaText'),
|
|
2275
|
+
title: moduleNameText,
|
|
2276
|
+
children: moduleNameText
|
|
2148
2277
|
}),
|
|
2149
|
-
|
|
2150
|
-
className: cx('vp-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
children: [
|
|
2155
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2156
|
-
className: cx('vp-editorTabs'),
|
|
2157
|
-
role: "tablist",
|
|
2158
|
-
"aria-label": "Files",
|
|
2159
|
-
children: fileTabs.map((item)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("button", {
|
|
2160
|
-
type: "button",
|
|
2161
|
-
className: item.key === activeTab.key ? cx('vp-editorTab', 'vp-editorTabActive') : cx('vp-editorTab'),
|
|
2162
|
-
onClick: ()=>setActiveFile(item.key),
|
|
2163
|
-
children: item.label || item.key
|
|
2164
|
-
}, item.key))
|
|
2165
|
-
}),
|
|
2166
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(CopyButton, {
|
|
2167
|
-
copyKey: activeTab.copyKey,
|
|
2168
|
-
label: "Copy",
|
|
2169
|
-
okMsg: activeTab.copyMessage,
|
|
2170
|
-
text: activeEditor.value
|
|
2171
|
-
})
|
|
2172
|
-
]
|
|
2173
|
-
}),
|
|
2174
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2175
|
-
className: cx('vp-codeEditor'),
|
|
2176
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(react_default(), {
|
|
2177
|
-
height: "100%",
|
|
2178
|
-
language: getEditorLanguage(activeTab.key),
|
|
2179
|
-
path: editorPath,
|
|
2180
|
-
theme: editorTheme,
|
|
2181
|
-
value: activeEditor.value,
|
|
2182
|
-
loading: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(EditorLoadingState, {}),
|
|
2183
|
-
options: {
|
|
2184
|
-
automaticLayout: true,
|
|
2185
|
-
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
|
2186
|
-
fontSize: 13,
|
|
2187
|
-
lineHeight: 21,
|
|
2188
|
-
minimap: {
|
|
2189
|
-
enabled: false
|
|
2190
|
-
},
|
|
2191
|
-
padding: {
|
|
2192
|
-
top: 12,
|
|
2193
|
-
bottom: 12
|
|
2194
|
-
},
|
|
2195
|
-
scrollBeyondLastLine: false,
|
|
2196
|
-
tabSize: 2,
|
|
2197
|
-
wordWrap: 'on'
|
|
2198
|
-
},
|
|
2199
|
-
beforeMount: (monaco)=>configureEditor(monaco, template),
|
|
2200
|
-
onMount: (_, monaco)=>{
|
|
2201
|
-
monacoRef.current = monaco;
|
|
2202
|
-
syncEditorModels(monaco, editorFiles, template);
|
|
2203
|
-
},
|
|
2204
|
-
onChange: (value)=>activeEditor.onChange(value || '')
|
|
2205
|
-
}, editorPath)
|
|
2206
|
-
})
|
|
2207
|
-
]
|
|
2208
|
-
}) : null
|
|
2278
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2279
|
+
className: cx('vp-ideStatus'),
|
|
2280
|
+
title: displayStatus,
|
|
2281
|
+
children: displayStatus
|
|
2282
|
+
})
|
|
2209
2283
|
]
|
|
2210
|
-
})
|
|
2284
|
+
})
|
|
2285
|
+
]
|
|
2286
|
+
}),
|
|
2287
|
+
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2288
|
+
className: cx('vp-ideBody'),
|
|
2289
|
+
children: [
|
|
2290
|
+
renderPreview(),
|
|
2291
|
+
renderTerminal()
|
|
2211
2292
|
]
|
|
2212
2293
|
})
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
})
|
|
2216
|
-
}),
|
|
2217
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2218
|
-
className: cx('vp-splitter'),
|
|
2219
|
-
"aria-hidden": "true",
|
|
2220
|
-
onMouseDown: isDesktopLayout ? (event)=>{
|
|
2221
|
-
resizeStateRef.current = {
|
|
2222
|
-
startWidth: leftPaneWidth,
|
|
2223
|
-
startX: event.clientX
|
|
2224
|
-
};
|
|
2225
|
-
} : void 0
|
|
2226
|
-
}),
|
|
2227
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("section", {
|
|
2228
|
-
className: cx('vp-right'),
|
|
2229
|
-
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2230
|
-
className: cx('vp-ide'),
|
|
2231
|
-
children: [
|
|
2232
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2233
|
-
className: cx('vp-ideTitlebar'),
|
|
2234
|
-
children: [
|
|
2235
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2236
|
-
className: cx('vp-ideDots'),
|
|
2237
|
-
children: [
|
|
2238
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2239
|
-
className: cx('vp-dot', 'vp-dotRed')
|
|
2240
|
-
}),
|
|
2241
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2242
|
-
className: cx('vp-dot', 'vp-dotYellow')
|
|
2243
|
-
}),
|
|
2244
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2245
|
-
className: cx('vp-dot', 'vp-dotGreen')
|
|
2246
|
-
})
|
|
2247
|
-
]
|
|
2248
|
-
}),
|
|
2249
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
|
|
2250
|
-
className: cx('vp-ideTitle'),
|
|
2251
|
-
children: "Sandbox Preview"
|
|
2252
|
-
}),
|
|
2253
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2254
|
-
className: cx('vp-ideMeta'),
|
|
2255
|
-
children: [
|
|
2256
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2257
|
-
className: cx('vp-ideMetaText'),
|
|
2258
|
-
title: moduleNameText,
|
|
2259
|
-
children: moduleNameText
|
|
2260
|
-
}),
|
|
2261
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
|
|
2262
|
-
className: cx('vp-ideStatus'),
|
|
2263
|
-
title: displayStatus,
|
|
2264
|
-
children: displayStatus
|
|
2265
|
-
})
|
|
2266
|
-
]
|
|
2267
|
-
})
|
|
2268
|
-
]
|
|
2269
|
-
}),
|
|
2270
|
-
/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
|
|
2271
|
-
className: cx('vp-ideBody'),
|
|
2272
|
-
children: [
|
|
2273
|
-
renderPreview(),
|
|
2274
|
-
renderTerminal()
|
|
2275
|
-
]
|
|
2276
|
-
})
|
|
2277
|
-
]
|
|
2294
|
+
]
|
|
2295
|
+
})
|
|
2278
2296
|
})
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
})
|
|
2282
|
-
}
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
})
|
|
2292
|
-
}
|
|
2293
|
-
}
|
|
2297
|
+
]
|
|
2298
|
+
})
|
|
2299
|
+
});
|
|
2300
|
+
}
|
|
2301
|
+
function App(props) {
|
|
2302
|
+
const defaults = (0, external_react_namespaceObject.useMemo)(()=>getPlaygroundDefaults(props), [
|
|
2303
|
+
props
|
|
2304
|
+
]);
|
|
2305
|
+
return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(RenderErrorBoundary, {
|
|
2306
|
+
children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(AppInner, {
|
|
2307
|
+
defaults: defaults
|
|
2308
|
+
})
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
})();
|
|
2294
2312
|
exports.ModuleFederationPlayground = __webpack_exports__.ModuleFederationPlayground;
|
|
2295
2313
|
exports["default"] = __webpack_exports__["default"];
|
|
2296
2314
|
for(var __webpack_i__ in __webpack_exports__)if (-1 === [
|