@module-federation/playground 0.0.0-feat-ts7-20260709074021
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.d.ts +34 -0
- package/dist/cjs/index.js +2302 -0
- package/dist/esm/index.d.ts +34 -0
- package/dist/esm/index.mjs +2254 -0
- package/dist/mf/117.js +10 -0
- package/dist/mf/117.js.LICENSE.txt +9 -0
- package/dist/mf/395.js +381 -0
- package/dist/mf/395.js.LICENSE.txt +14 -0
- package/dist/mf/427.js +10 -0
- package/dist/mf/427.js.LICENSE.txt +9 -0
- package/dist/mf/776.js +381 -0
- package/dist/mf/776.js.LICENSE.txt +14 -0
- package/dist/mf/844.js +18 -0
- package/dist/mf/844.js.LICENSE.txt +19 -0
- package/dist/mf/97.js +10 -0
- package/dist/mf/97.js.LICENSE.txt +9 -0
- package/dist/mf/__federation_expose_default_export.css +701 -0
- package/dist/mf/__federation_expose_default_export.js +700 -0
- package/dist/mf/__federation_expose_demo.js +1 -0
- package/dist/mf/index.css +701 -0
- package/dist/mf/index.d.ts +34 -0
- package/dist/mf/index.html +11 -0
- package/dist/mf/index.js +527 -0
- package/dist/mf/mf-manifest.json +151 -0
- package/dist/mf/mf-stats.json +185 -0
- package/dist/mf/remoteEntry.js +7 -0
- package/dist/mf/ssr/105mf_playground.js +10 -0
- package/dist/mf/ssr/105mf_playground.js.LICENSE.txt +9 -0
- package/dist/mf/ssr/315mf_playground.js +10 -0
- package/dist/mf/ssr/315mf_playground.js.LICENSE.txt +9 -0
- package/dist/mf/ssr/349mf_playground.js +10 -0
- package/dist/mf/ssr/349mf_playground.js.LICENSE.txt +9 -0
- package/dist/mf/ssr/503mf_playground.js +18 -0
- package/dist/mf/ssr/503mf_playground.js.LICENSE.txt +19 -0
- package/dist/mf/ssr/884mf_playground.js +18 -0
- package/dist/mf/ssr/884mf_playground.js.LICENSE.txt +19 -0
- package/dist/mf/ssr/__federation_expose_default_exportmf_playground.js +1080 -0
- package/dist/mf/ssr/__federation_expose_default_exportmf_playground.js.LICENSE.txt +14 -0
- package/dist/mf/ssr/__federation_expose_demomf_playground.js +1 -0
- package/dist/mf/ssr/index.js +1089 -0
- package/dist/mf/ssr/index.js.LICENSE.txt +14 -0
- package/dist/mf/ssr/mf-manifest.json +144 -0
- package/dist/mf/ssr/mf-stats.json +178 -0
- package/dist/mf/ssr/remoteEntry.js +10 -0
- package/package.json +61 -0
|
@@ -0,0 +1,2254 @@
|
|
|
1
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
2
|
+
import react, { loader } from "@monaco-editor/react";
|
|
3
|
+
import typescript from "typescript";
|
|
4
|
+
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
|
|
5
|
+
import * as __WEBPACK_EXTERNAL_MODULE_react_dom_7136dc57__ from "react-dom";
|
|
6
|
+
import * as __WEBPACK_EXTERNAL_MODULE_react_dom_client_76b1397c__ from "react-dom/client";
|
|
7
|
+
const App_module = {
|
|
8
|
+
"vp-root": "vp-root-o94tBV",
|
|
9
|
+
vpRoot: "vp-root-o94tBV",
|
|
10
|
+
"vp-main": "vp-main-ukILls",
|
|
11
|
+
vpMain: "vp-main-ukILls",
|
|
12
|
+
"vp-left": "vp-left-wWIJZj",
|
|
13
|
+
vpLeft: "vp-left-wWIJZj",
|
|
14
|
+
"vp-splitter": "vp-splitter-C3LUiw",
|
|
15
|
+
vpSplitter: "vp-splitter-C3LUiw",
|
|
16
|
+
"vp-card": "vp-card-OxIN8P",
|
|
17
|
+
vpCard: "vp-card-OxIN8P",
|
|
18
|
+
"vp-cardHeader": "vp-cardHeader-yl8bmF",
|
|
19
|
+
vpCardHeader: "vp-cardHeader-yl8bmF",
|
|
20
|
+
"vp-cardTitle": "vp-cardTitle-iRjbB2",
|
|
21
|
+
vpCardTitle: "vp-cardTitle-iRjbB2",
|
|
22
|
+
"vp-editorTabs": "vp-editorTabs-P8EPHu",
|
|
23
|
+
vpEditorTabs: "vp-editorTabs-P8EPHu",
|
|
24
|
+
"vp-editorTab": "vp-editorTab-en3Nbi",
|
|
25
|
+
vpEditorTab: "vp-editorTab-en3Nbi",
|
|
26
|
+
"vp-editorTabActive": "vp-editorTabActive-j1OAlc",
|
|
27
|
+
vpEditorTabActive: "vp-editorTabActive-j1OAlc",
|
|
28
|
+
"vp-cardBody": "vp-cardBody-UdVf2N",
|
|
29
|
+
vpCardBody: "vp-cardBody-UdVf2N",
|
|
30
|
+
"vp-paneActions": "vp-paneActions-l5K74Q",
|
|
31
|
+
vpPaneActions: "vp-paneActions-l5K74Q",
|
|
32
|
+
"vp-collapse": "vp-collapse-VViOM4",
|
|
33
|
+
vpCollapse: "vp-collapse-VViOM4",
|
|
34
|
+
"vp-collapseItem": "vp-collapseItem-MtDnlb",
|
|
35
|
+
vpCollapseItem: "vp-collapseItem-MtDnlb",
|
|
36
|
+
"vp-collapseHeader": "vp-collapseHeader-Y1drUL",
|
|
37
|
+
vpCollapseHeader: "vp-collapseHeader-Y1drUL",
|
|
38
|
+
"vp-collapseHeaderActive": "vp-collapseHeaderActive-d5oo1z",
|
|
39
|
+
vpCollapseHeaderActive: "vp-collapseHeaderActive-d5oo1z",
|
|
40
|
+
"vp-collapseLabel": "vp-collapseLabel-SYefMk",
|
|
41
|
+
vpCollapseLabel: "vp-collapseLabel-SYefMk",
|
|
42
|
+
"vp-collapseArrow": "vp-collapseArrow-s7319m",
|
|
43
|
+
vpCollapseArrow: "vp-collapseArrow-s7319m",
|
|
44
|
+
"vp-collapseArrowOpen": "vp-collapseArrowOpen-NQp4Jq",
|
|
45
|
+
vpCollapseArrowOpen: "vp-collapseArrowOpen-NQp4Jq",
|
|
46
|
+
"vp-collapseBody": "vp-collapseBody-ig7Trn",
|
|
47
|
+
vpCollapseBody: "vp-collapseBody-ig7Trn",
|
|
48
|
+
"vp-collapseBodyCode": "vp-collapseBodyCode-ACBnWh",
|
|
49
|
+
vpCollapseBodyCode: "vp-collapseBodyCode-ACBnWh",
|
|
50
|
+
"vp-form": "vp-form-pITn1W",
|
|
51
|
+
vpForm: "vp-form-pITn1W",
|
|
52
|
+
"vp-fieldGrid": "vp-fieldGrid-SR9eJh",
|
|
53
|
+
vpFieldGrid: "vp-fieldGrid-SR9eJh",
|
|
54
|
+
"vp-field": "vp-field-NzMT8s",
|
|
55
|
+
vpField: "vp-field-NzMT8s",
|
|
56
|
+
"vp-labelRow": "vp-labelRow-DlcEeA",
|
|
57
|
+
vpLabelRow: "vp-labelRow-DlcEeA",
|
|
58
|
+
"vp-label": "vp-label-KGpsbl",
|
|
59
|
+
vpLabel: "vp-label-KGpsbl",
|
|
60
|
+
"vp-hint": "vp-hint-fYzOU2",
|
|
61
|
+
vpHint: "vp-hint-fYzOU2",
|
|
62
|
+
"vp-input": "vp-input-UHKU2F",
|
|
63
|
+
vpInput: "vp-input-UHKU2F",
|
|
64
|
+
"vp-select": "vp-select-Tk6IhF",
|
|
65
|
+
vpSelect: "vp-select-Tk6IhF",
|
|
66
|
+
"vp-codeEditor": "vp-codeEditor-bXbNn1",
|
|
67
|
+
vpCodeEditor: "vp-codeEditor-bXbNn1",
|
|
68
|
+
"vp-editorToolbar": "vp-editorToolbar-SVglCq",
|
|
69
|
+
vpEditorToolbar: "vp-editorToolbar-SVglCq",
|
|
70
|
+
"vp-loadingSimple": "vp-loadingSimple-t3py2h",
|
|
71
|
+
vpLoadingSimple: "vp-loadingSimple-t3py2h",
|
|
72
|
+
"vp-loadingSpinner": "vp-loadingSpinner-YRww21",
|
|
73
|
+
vpLoadingSpinner: "vp-loadingSpinner-YRww21",
|
|
74
|
+
"vp-spin": "vp-spin-vqXwPJ",
|
|
75
|
+
vpSpin: "vp-spin-vqXwPJ",
|
|
76
|
+
"vp-previewFrame": "vp-previewFrame-K_cT99",
|
|
77
|
+
vpPreviewFrame: "vp-previewFrame-K_cT99",
|
|
78
|
+
"vp-actions": "vp-actions-kW_pM2",
|
|
79
|
+
vpActions: "vp-actions-kW_pM2",
|
|
80
|
+
"vp-button": "vp-button-jQtwaB",
|
|
81
|
+
vpButton: "vp-button-jQtwaB",
|
|
82
|
+
"vp-buttonGhost": "vp-buttonGhost-wKOfIf",
|
|
83
|
+
vpButtonGhost: "vp-buttonGhost-wKOfIf",
|
|
84
|
+
"vp-buttonPrimary": "vp-buttonPrimary-SYnJ9I",
|
|
85
|
+
vpButtonPrimary: "vp-buttonPrimary-SYnJ9I",
|
|
86
|
+
vpShimmer: "vpShimmer-XeNYGG",
|
|
87
|
+
"vp-codeBlock": "vp-codeBlock-CMSobd",
|
|
88
|
+
vpCodeBlock: "vp-codeBlock-CMSobd",
|
|
89
|
+
"vp-emptyTitle": "vp-emptyTitle-LUdxhN",
|
|
90
|
+
vpEmptyTitle: "vp-emptyTitle-LUdxhN",
|
|
91
|
+
"vp-copyBtn": "vp-copyBtn-rEbuE6",
|
|
92
|
+
vpCopyBtn: "vp-copyBtn-rEbuE6",
|
|
93
|
+
"vp-copyIcon": "vp-copyIcon-C8ndDr",
|
|
94
|
+
vpCopyIcon: "vp-copyIcon-C8ndDr",
|
|
95
|
+
"vp-right": "vp-right-Pdn7k6",
|
|
96
|
+
vpRight: "vp-right-Pdn7k6",
|
|
97
|
+
"vp-ide": "vp-ide-MCK1rq",
|
|
98
|
+
vpIde: "vp-ide-MCK1rq",
|
|
99
|
+
"vp-ideTitlebar": "vp-ideTitlebar-xV_SLu",
|
|
100
|
+
vpIdeTitlebar: "vp-ideTitlebar-xV_SLu",
|
|
101
|
+
"vp-ideDots": "vp-ideDots-rmPPqM",
|
|
102
|
+
vpIdeDots: "vp-ideDots-rmPPqM",
|
|
103
|
+
"vp-dot": "vp-dot-QAY3S7",
|
|
104
|
+
vpDot: "vp-dot-QAY3S7",
|
|
105
|
+
"vp-dotRed": "vp-dotRed-qBSHb4",
|
|
106
|
+
vpDotRed: "vp-dotRed-qBSHb4",
|
|
107
|
+
"vp-dotYellow": "vp-dotYellow-JiMbQd",
|
|
108
|
+
vpDotYellow: "vp-dotYellow-JiMbQd",
|
|
109
|
+
"vp-dotGreen": "vp-dotGreen-p1oJVa",
|
|
110
|
+
vpDotGreen: "vp-dotGreen-p1oJVa",
|
|
111
|
+
"vp-ideTitle": "vp-ideTitle-pyBOAZ",
|
|
112
|
+
vpIdeTitle: "vp-ideTitle-pyBOAZ",
|
|
113
|
+
"vp-ideMeta": "vp-ideMeta-IwLWqJ",
|
|
114
|
+
vpIdeMeta: "vp-ideMeta-IwLWqJ",
|
|
115
|
+
"vp-ideMetaText": "vp-ideMetaText-hM7Yjo",
|
|
116
|
+
vpIdeMetaText: "vp-ideMetaText-hM7Yjo",
|
|
117
|
+
"vp-ideStatus": "vp-ideStatus-CNZYH6",
|
|
118
|
+
vpIdeStatus: "vp-ideStatus-CNZYH6",
|
|
119
|
+
"vp-ideBody": "vp-ideBody-iRMqXK",
|
|
120
|
+
vpIdeBody: "vp-ideBody-iRMqXK",
|
|
121
|
+
"vp-empty": "vp-empty-WMX1Vp",
|
|
122
|
+
vpEmpty: "vp-empty-WMX1Vp",
|
|
123
|
+
"vp-kv": "vp-kv-HhceUA",
|
|
124
|
+
vpKv: "vp-kv-HhceUA",
|
|
125
|
+
"vp-renderArea": "vp-renderArea-UsEDCB",
|
|
126
|
+
vpRenderArea: "vp-renderArea-UsEDCB",
|
|
127
|
+
"vp-terminal": "vp-terminal-F6_CEQ",
|
|
128
|
+
vpTerminal: "vp-terminal-F6_CEQ",
|
|
129
|
+
"vp-terminalHeader": "vp-terminalHeader-BG3x8z",
|
|
130
|
+
vpTerminalHeader: "vp-terminalHeader-BG3x8z",
|
|
131
|
+
"vp-terminalClear": "vp-terminalClear-N0wY3l",
|
|
132
|
+
vpTerminalClear: "vp-terminalClear-N0wY3l",
|
|
133
|
+
"vp-terminalBody": "vp-terminalBody-Fn12Co",
|
|
134
|
+
vpTerminalBody: "vp-terminalBody-Fn12Co",
|
|
135
|
+
"vp-terminalLine": "vp-terminalLine-V8_M04",
|
|
136
|
+
vpTerminalLine: "vp-terminalLine-V8_M04",
|
|
137
|
+
"vp-terminalLineError": "vp-terminalLineError-puKD3j",
|
|
138
|
+
vpTerminalLineError: "vp-terminalLineError-puKD3j",
|
|
139
|
+
"vp-terminalLineWarn": "vp-terminalLineWarn-BIZDl_",
|
|
140
|
+
vpTerminalLineWarn: "vp-terminalLineWarn-BIZDl_",
|
|
141
|
+
"vp-terminalEmpty": "vp-terminalEmpty-pYP34A",
|
|
142
|
+
vpTerminalEmpty: "vp-terminalEmpty-pYP34A",
|
|
143
|
+
"vp-errorPanel": "vp-errorPanel-zDWm6k",
|
|
144
|
+
vpErrorPanel: "vp-errorPanel-zDWm6k",
|
|
145
|
+
"vp-errorTitle": "vp-errorTitle-ykARVb",
|
|
146
|
+
vpErrorTitle: "vp-errorTitle-ykARVb"
|
|
147
|
+
};
|
|
148
|
+
const BRIDGE_RUNTIME_FILES = {
|
|
149
|
+
"bridge-base-CIOXqUYV.mjs": "import * as React from \"react\";\nimport { Component, createElement, createContext } from \"react\";\nimport { L as LoggerInstance, R as RouterContext } from \"./index-Bs2NxD2z.mjs\";\nimport { federationRuntime } from \"./plugin.es.js\";\nconst ErrorBoundaryContext = createContext(null);\nconst initialState = {\n didCatch: false,\n error: null\n};\nclass ErrorBoundary extends Component {\n constructor(props) {\n super(props);\n this.resetErrorBoundary = this.resetErrorBoundary.bind(this);\n this.state = initialState;\n }\n static getDerivedStateFromError(error) {\n return {\n didCatch: true,\n error\n };\n }\n resetErrorBoundary() {\n const {\n error\n } = this.state;\n if (error !== null) {\n var _this$props$onReset, _this$props;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n (_this$props$onReset = (_this$props = this.props).onReset) === null || _this$props$onReset === void 0 ? void 0 : _this$props$onReset.call(_this$props, {\n args,\n reason: \"imperative-api\"\n });\n this.setState(initialState);\n }\n }\n componentDidCatch(error, info) {\n var _this$props$onError, _this$props2;\n (_this$props$onError = (_this$props2 = this.props).onError) === null || _this$props$onError === void 0 ? void 0 : _this$props$onError.call(_this$props2, error, info);\n }\n componentDidUpdate(prevProps, prevState) {\n const {\n didCatch\n } = this.state;\n const {\n resetKeys\n } = this.props;\n if (didCatch && prevState.error !== null && hasArrayChanged(prevProps.resetKeys, resetKeys)) {\n var _this$props$onReset2, _this$props3;\n (_this$props$onReset2 = (_this$props3 = this.props).onReset) === null || _this$props$onReset2 === void 0 ? void 0 : _this$props$onReset2.call(_this$props3, {\n next: resetKeys,\n prev: prevProps.resetKeys,\n reason: \"keys\"\n });\n this.setState(initialState);\n }\n }\n render() {\n const {\n children,\n fallbackRender,\n FallbackComponent,\n fallback\n } = this.props;\n const {\n didCatch,\n error\n } = this.state;\n let childToRender = children;\n if (didCatch) {\n const props = {\n error,\n resetErrorBoundary: this.resetErrorBoundary\n };\n if (typeof fallbackRender === \"function\") {\n childToRender = fallbackRender(props);\n } else if (FallbackComponent) {\n childToRender = createElement(FallbackComponent, props);\n } else if (fallback !== void 0) {\n childToRender = fallback;\n } else {\n throw error;\n }\n }\n return createElement(ErrorBoundaryContext.Provider, {\n value: {\n didCatch,\n error,\n resetErrorBoundary: this.resetErrorBoundary\n }\n }, childToRender);\n }\n}\nfunction hasArrayChanged() {\n let a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];\n let b = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];\n return a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]));\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.message));\n const ErrorBoundaryComponent = ErrorBoundary;\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(ErrorBoundaryComponent, { 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 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(info)) || {};\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 await Promise.resolve(\n bridgeInfo.render(rootComponentWithErrorBoundary, dom)\n ).then((root) => 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 },\n destroy(info) {\n var _a, _b, _c;\n const { dom } = info;\n LoggerInstance.debug(`createBridgeComponent destroy Info`, info);\n const root = rootMap.get(dom);\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 (_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.afterBridgeDestroy) == null ? void 0 : _c.emit(info);\n }\n };\n };\n}\nexport {\n ErrorBoundary as E,\n createBaseBridgeComponent as c\n};\n",
|
|
150
|
+
"createHelpers-BY5Uj9_Z.mjs": "import { c as createBaseBridgeComponent, E as ErrorBoundary } from \"./bridge-base-CIOXqUYV.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, _h;\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 (_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 moduleName,\n dom: renderDom.current,\n basename,\n memoryRoute,\n fallback,\n ...resProps\n });\n (_e = providerInfoRef.current) == null ? void 0 : _e.destroy({\n moduleName,\n dom: renderDom.current\n });\n (_h = (_g = (_f = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _f.lifecycle) == null ? void 0 : _g.afterBridgeDestroy) == null ? void 0 : _h.emit({\n moduleName,\n dom: renderDom.current,\n basename,\n memoryRoute,\n fallback,\n ...resProps\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 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(renderProps)) || {};\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 }, [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 ErrorBoundaryComponent = ErrorBoundary;\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 ErrorBoundaryComponent,\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",
|
|
151
|
+
"data-fetch-utils.es.js": "import { y as DATA_FETCH_FUNCTION } from \"./utils-DGS4pYp8.mjs\";\nimport { C, a, c, b, d, g, r } from \"./utils-DGS4pYp8.mjs\";\nimport { d as dataFetchFunction } from \"./prefetch-BwRDb4SJ.mjs\";\nimport { i, p } from \"./prefetch-BwRDb4SJ.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",
|
|
152
|
+
"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",
|
|
153
|
+
"index.es.js": "import { R as RemoteAppWrapper, c as createRemoteAppComponentFactory, a as createDeprecatedRemoteComponentFactory } from \"./createHelpers-BY5Uj9_Z.mjs\";\nimport { b } from \"./createHelpers-BY5Uj9_Z.mjs\";\nimport { a, c, b as b2, l } from \"./lazy-load-component-plugin-aj97Vt-4.mjs\";\nimport { C, a as a2, E, c as c2, b as b3, d, g, r, s } from \"./utils-DGS4pYp8.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 { p } from \"./prefetch-BwRDb4SJ.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 if (pathname !== \"\" && pathname !== location.pathname) {\n LoggerInstance.debug(\n `createRemoteAppComponent dispatchPopstateEnv >>>`,\n {\n name: props.name,\n pathname: location.pathname\n }\n );\n e();\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",
|
|
154
|
+
"lazy-load-component-plugin-aj97Vt-4.mjs": 'import { i as injectDataFetch, p as prefetch } from "./prefetch-BwRDb4SJ.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-DGS4pYp8.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',
|
|
155
|
+
"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",
|
|
156
|
+
"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",
|
|
157
|
+
"prefetch-BwRDb4SJ.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, m as getDataFetchInfo, n as getDataFetchMapKey } from "./utils-DGS4pYp8.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 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 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 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])";\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 switch (type) {\n case "esm":\n case "module":\n return loadEsmEntry({\n entry,\n remoteEntryExports\n });\n case "system":\n return loadSystemJsEntry({\n entry,\n remoteEntryExports\n });\n default:\n return loadEntryScript({\n entry,\n globalName,\n name,\n remoteInfo,\n loaderHook,\n getEntryUrl,\n resourceContext\n });\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 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 defaultAttrs = {\n rel: "preload",\n as: "style"\n };\n cssAssets.forEach((cssUrl) => {\n results.push(waitForLinkPreload({\n host,\n remoteInfo,\n url: cssUrl,\n attrs: defaultAttrs,\n context: createResourceContext(baseContext, "css")\n }));\n });\n } else {\n const defaultAttrs = {\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: defaultAttrs,\n needDeleteLink: false,\n context: createResourceContext(baseContext, "css")\n }));\n });\n }\n if (useLinkPreload) {\n const defaultAttrs = {\n rel: "preload",\n as: "script"\n };\n jsAssetsWithoutEntry.forEach((jsUrl) => {\n results.push(waitForLinkPreload({\n host,\n remoteInfo,\n url: jsUrl,\n attrs: defaultAttrs,\n context: createResourceContext(baseContext, "js")\n }));\n });\n } else {\n const defaultAttrs = {\n fetchpriority: "high",\n type: (remoteInfo == null ? void 0 : remoteInfo.type) === "module" ? "module" : "text/javascript"\n };\n jsAssetsWithoutEntry.forEach((jsUrl) => {\n results.push(waitForScriptPreload({\n host,\n remoteInfo,\n url: jsUrl,\n attrs: defaultAttrs,\n context: createResourceContext(baseContext, "js")\n }));\n });\n }\n }\n return Promise.all(results);\n}\nvar helpers_default = {\n utils: {\n matchRemoteWithNameAndExpose,\n preloadAssets,\n getRemoteInfo\n }\n};\ntypeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN === "boolean" ? !FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN : true;\nconst helpers = helpers_default;\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',
|
|
158
|
+
"utils-DGS4pYp8.mjs": 'var __defProp = Object.defineProperty;\nvar __typeError = (msg) => {\n throw TypeError(msg);\n};\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);\nvar __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);\nvar __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));\nvar __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);\nvar __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);\nvar __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);\nvar __privateWrapper = (obj, member, setter, getter) => ({\n set _(value) {\n __privateSet(obj, member, value, setter);\n },\n get _() {\n return __privateGet(obj, member, getter);\n }\n});\nvar _a, _constructing, _b, _c, _max, _maxSize, _dispose, _disposeAfter, _fetchMethod, _memoMethod, _size, _calculatedSize, _keyMap, _keyList, _valList, _next, _prev, _head, _tail, _free, _disposed, _sizes, _starts, _ttls, _hasDispose, _hasFetchMethod, _hasDisposeAfter, _LRUCache_instances, initializeTTLTracking_fn, _updateItemAge, _statusTTL, _setItemTTL, _isStale, initializeSizeTracking_fn, _removeItemSize, _addItemSize, _requireSize, indexes_fn, rindexes_fn, isValidIndex_fn, evict_fn, backgroundFetch_fn, isBackgroundFetch_fn, connect_fn, moveToTail_fn, delete_fn, clear_fn;\nimport { S as SEPARATOR, c as createLogger, i as isBrowserEnvValue } from "./logger-DwWkXsWl.mjs";\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};\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 perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;\nconst warned = /* @__PURE__ */ new Set();\nconst PROCESS = typeof process === "object" && !!process ? process : {};\nconst emitWarning = (msg, type, code, fn) => {\n typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);\n};\nlet AC = globalThis.AbortController;\nlet AS = globalThis.AbortSignal;\nif (typeof AC === "undefined") {\n AS = class AbortSignal {\n constructor() {\n __publicField(this, "onabort");\n __publicField(this, "_onabort", []);\n __publicField(this, "reason");\n __publicField(this, "aborted", false);\n }\n addEventListener(_, fn) {\n this._onabort.push(fn);\n }\n };\n AC = class AbortController {\n constructor() {\n __publicField(this, "signal", new AS());\n warnACPolyfill();\n }\n abort(reason) {\n var _a2, _b2;\n if (this.signal.aborted)\n return;\n this.signal.reason = reason;\n this.signal.aborted = true;\n for (const fn of this.signal._onabort) {\n fn(reason);\n }\n (_b2 = (_a2 = this.signal).onabort) == null ? void 0 : _b2.call(_a2, reason);\n }\n };\n let printACPolyfillWarning = ((_a = PROCESS.env) == null ? void 0 : _a.LRU_CACHE_IGNORE_AC_WARNING) !== "1";\n const warnACPolyfill = () => {\n if (!printACPolyfillWarning)\n return;\n printACPolyfillWarning = false;\n emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);\n };\n}\nconst shouldWarn = (code) => !warned.has(code);\nconst isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);\nconst getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;\nclass ZeroArray extends Array {\n constructor(size) {\n super(size);\n this.fill(0);\n }\n}\nconst _Stack = class _Stack {\n constructor(max, HeapCls) {\n __publicField(this, "heap");\n __publicField(this, "length");\n if (!__privateGet(_Stack, _constructing)) {\n throw new TypeError("instantiate Stack using Stack.create(n)");\n }\n this.heap = new HeapCls(max);\n this.length = 0;\n }\n static create(max) {\n const HeapCls = getUintArray(max);\n if (!HeapCls)\n return [];\n __privateSet(_Stack, _constructing, true);\n const s = new _Stack(max, HeapCls);\n __privateSet(_Stack, _constructing, false);\n return s;\n }\n push(n) {\n this.heap[this.length++] = n;\n }\n pop() {\n return this.heap[--this.length];\n }\n};\n_constructing = new WeakMap();\n// private constructor\n__privateAdd(_Stack, _constructing, false);\nlet Stack = _Stack;\nconst _LRUCache = class _LRUCache {\n constructor(options) {\n __privateAdd(this, _LRUCache_instances);\n // options that cannot be changed without disaster\n __privateAdd(this, _max);\n __privateAdd(this, _maxSize);\n __privateAdd(this, _dispose);\n __privateAdd(this, _disposeAfter);\n __privateAdd(this, _fetchMethod);\n __privateAdd(this, _memoMethod);\n /**\n * {@link LRUCache.OptionsBase.ttl}\n */\n __publicField(this, "ttl");\n /**\n * {@link LRUCache.OptionsBase.ttlResolution}\n */\n __publicField(this, "ttlResolution");\n /**\n * {@link LRUCache.OptionsBase.ttlAutopurge}\n */\n __publicField(this, "ttlAutopurge");\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnGet}\n */\n __publicField(this, "updateAgeOnGet");\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnHas}\n */\n __publicField(this, "updateAgeOnHas");\n /**\n * {@link LRUCache.OptionsBase.allowStale}\n */\n __publicField(this, "allowStale");\n /**\n * {@link LRUCache.OptionsBase.noDisposeOnSet}\n */\n __publicField(this, "noDisposeOnSet");\n /**\n * {@link LRUCache.OptionsBase.noUpdateTTL}\n */\n __publicField(this, "noUpdateTTL");\n /**\n * {@link LRUCache.OptionsBase.maxEntrySize}\n */\n __publicField(this, "maxEntrySize");\n /**\n * {@link LRUCache.OptionsBase.sizeCalculation}\n */\n __publicField(this, "sizeCalculation");\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n */\n __publicField(this, "noDeleteOnFetchRejection");\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n */\n __publicField(this, "noDeleteOnStaleGet");\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n */\n __publicField(this, "allowStaleOnFetchAbort");\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n */\n __publicField(this, "allowStaleOnFetchRejection");\n /**\n * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n */\n __publicField(this, "ignoreFetchAbort");\n // computed properties\n __privateAdd(this, _size);\n __privateAdd(this, _calculatedSize);\n __privateAdd(this, _keyMap);\n __privateAdd(this, _keyList);\n __privateAdd(this, _valList);\n __privateAdd(this, _next);\n __privateAdd(this, _prev);\n __privateAdd(this, _head);\n __privateAdd(this, _tail);\n __privateAdd(this, _free);\n __privateAdd(this, _disposed);\n __privateAdd(this, _sizes);\n __privateAdd(this, _starts);\n __privateAdd(this, _ttls);\n __privateAdd(this, _hasDispose);\n __privateAdd(this, _hasFetchMethod);\n __privateAdd(this, _hasDisposeAfter);\n // conditionally set private methods related to TTL\n __privateAdd(this, _updateItemAge, () => {\n });\n __privateAdd(this, _statusTTL, () => {\n });\n __privateAdd(this, _setItemTTL, () => {\n });\n /* c8 ignore stop */\n __privateAdd(this, _isStale, () => false);\n __privateAdd(this, _removeItemSize, (_i) => {\n });\n __privateAdd(this, _addItemSize, (_i, _s, _st) => {\n });\n __privateAdd(this, _requireSize, (_k, _v, size, sizeCalculation) => {\n if (size || sizeCalculation) {\n throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");\n }\n return 0;\n });\n /**\n * A String value that is used in the creation of the default string\n * description of an object. Called by the built-in method\n * `Object.prototype.toString`.\n */\n __publicField(this, _b, "LRUCache");\n const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;\n if (max !== 0 && !isPosInt(max)) {\n throw new TypeError("max option must be a nonnegative integer");\n }\n const UintArray = max ? getUintArray(max) : Array;\n if (!UintArray) {\n throw new Error("invalid max value: " + max);\n }\n __privateSet(this, _max, max);\n __privateSet(this, _maxSize, maxSize);\n this.maxEntrySize = maxEntrySize || __privateGet(this, _maxSize);\n this.sizeCalculation = sizeCalculation;\n if (this.sizeCalculation) {\n if (!__privateGet(this, _maxSize) && !this.maxEntrySize) {\n throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");\n }\n if (typeof this.sizeCalculation !== "function") {\n throw new TypeError("sizeCalculation set to non-function");\n }\n }\n if (memoMethod !== void 0 && typeof memoMethod !== "function") {\n throw new TypeError("memoMethod must be a function if defined");\n }\n __privateSet(this, _memoMethod, memoMethod);\n if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {\n throw new TypeError("fetchMethod must be a function if specified");\n }\n __privateSet(this, _fetchMethod, fetchMethod);\n __privateSet(this, _hasFetchMethod, !!fetchMethod);\n __privateSet(this, _keyMap, /* @__PURE__ */ new Map());\n __privateSet(this, _keyList, new Array(max).fill(void 0));\n __privateSet(this, _valList, new Array(max).fill(void 0));\n __privateSet(this, _next, new UintArray(max));\n __privateSet(this, _prev, new UintArray(max));\n __privateSet(this, _head, 0);\n __privateSet(this, _tail, 0);\n __privateSet(this, _free, Stack.create(max));\n __privateSet(this, _size, 0);\n __privateSet(this, _calculatedSize, 0);\n if (typeof dispose === "function") {\n __privateSet(this, _dispose, dispose);\n }\n if (typeof disposeAfter === "function") {\n __privateSet(this, _disposeAfter, disposeAfter);\n __privateSet(this, _disposed, []);\n } else {\n __privateSet(this, _disposeAfter, void 0);\n __privateSet(this, _disposed, void 0);\n }\n __privateSet(this, _hasDispose, !!__privateGet(this, _dispose));\n __privateSet(this, _hasDisposeAfter, !!__privateGet(this, _disposeAfter));\n this.noDisposeOnSet = !!noDisposeOnSet;\n this.noUpdateTTL = !!noUpdateTTL;\n this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;\n this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;\n this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;\n this.ignoreFetchAbort = !!ignoreFetchAbort;\n if (this.maxEntrySize !== 0) {\n if (__privateGet(this, _maxSize) !== 0) {\n if (!isPosInt(__privateGet(this, _maxSize))) {\n throw new TypeError("maxSize must be a positive integer if specified");\n }\n }\n if (!isPosInt(this.maxEntrySize)) {\n throw new TypeError("maxEntrySize must be a positive integer if specified");\n }\n __privateMethod(this, _LRUCache_instances, initializeSizeTracking_fn).call(this);\n }\n this.allowStale = !!allowStale;\n this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;\n this.updateAgeOnGet = !!updateAgeOnGet;\n this.updateAgeOnHas = !!updateAgeOnHas;\n this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;\n this.ttlAutopurge = !!ttlAutopurge;\n this.ttl = ttl || 0;\n if (this.ttl) {\n if (!isPosInt(this.ttl)) {\n throw new TypeError("ttl must be a positive integer if specified");\n }\n __privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this);\n }\n if (__privateGet(this, _max) === 0 && this.ttl === 0 && __privateGet(this, _maxSize) === 0) {\n throw new TypeError("At least one of max, maxSize, or ttl is required");\n }\n if (!this.ttlAutopurge && !__privateGet(this, _max) && !__privateGet(this, _maxSize)) {\n const code = "LRU_CACHE_UNBOUNDED";\n if (shouldWarn(code)) {\n warned.add(code);\n const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";\n emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);\n }\n }\n }\n /**\n * Do not call this method unless you need to inspect the\n * inner workings of the cache. If anything returned by this\n * object is modified in any way, strange breakage may occur.\n *\n * These fields are private for a reason!\n *\n * @internal\n */\n static unsafeExposeInternals(c) {\n return {\n // properties\n starts: __privateGet(c, _starts),\n ttls: __privateGet(c, _ttls),\n sizes: __privateGet(c, _sizes),\n keyMap: __privateGet(c, _keyMap),\n keyList: __privateGet(c, _keyList),\n valList: __privateGet(c, _valList),\n next: __privateGet(c, _next),\n prev: __privateGet(c, _prev),\n get head() {\n return __privateGet(c, _head);\n },\n get tail() {\n return __privateGet(c, _tail);\n },\n free: __privateGet(c, _free),\n // methods\n isBackgroundFetch: (p) => {\n var _a2;\n return __privateMethod(_a2 = c, _LRUCache_instances, isBackgroundFetch_fn).call(_a2, p);\n },\n backgroundFetch: (k, index, options, context) => {\n var _a2;\n return __privateMethod(_a2 = c, _LRUCache_instances, backgroundFetch_fn).call(_a2, k, index, options, context);\n },\n moveToTail: (index) => {\n var _a2;\n return __privateMethod(_a2 = c, _LRUCache_instances, moveToTail_fn).call(_a2, index);\n },\n indexes: (options) => {\n var _a2;\n return __privateMethod(_a2 = c, _LRUCache_instances, indexes_fn).call(_a2, options);\n },\n rindexes: (options) => {\n var _a2;\n return __privateMethod(_a2 = c, _LRUCache_instances, rindexes_fn).call(_a2, options);\n },\n isStale: (index) => {\n var _a2;\n return __privateGet(_a2 = c, _isStale).call(_a2, index);\n }\n };\n }\n // Protected read-only members\n /**\n * {@link LRUCache.OptionsBase.max} (read-only)\n */\n get max() {\n return __privateGet(this, _max);\n }\n /**\n * {@link LRUCache.OptionsBase.maxSize} (read-only)\n */\n get maxSize() {\n return __privateGet(this, _maxSize);\n }\n /**\n * The total computed size of items in the cache (read-only)\n */\n get calculatedSize() {\n return __privateGet(this, _calculatedSize);\n }\n /**\n * The number of items stored in the cache (read-only)\n */\n get size() {\n return __privateGet(this, _size);\n }\n /**\n * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n */\n get fetchMethod() {\n return __privateGet(this, _fetchMethod);\n }\n get memoMethod() {\n return __privateGet(this, _memoMethod);\n }\n /**\n * {@link LRUCache.OptionsBase.dispose} (read-only)\n */\n get dispose() {\n return __privateGet(this, _dispose);\n }\n /**\n * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n */\n get disposeAfter() {\n return __privateGet(this, _disposeAfter);\n }\n /**\n * Return the number of ms left in the item\'s TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n */\n getRemainingTTL(key) {\n return __privateGet(this, _keyMap).has(key) ? Infinity : 0;\n }\n /**\n * Return a generator yielding `[key, value]` pairs,\n * in order from most recently used to least recently used.\n */\n *entries() {\n for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {\n if (__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {\n yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]];\n }\n }\n }\n /**\n * Inverse order version of {@link LRUCache.entries}\n *\n * Return a generator yielding `[key, value]` pairs,\n * in order from least recently used to most recently used.\n */\n *rentries() {\n for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {\n if (__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {\n yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]];\n }\n }\n }\n /**\n * Return a generator yielding the keys in the cache,\n * in order from most recently used to least recently used.\n */\n *keys() {\n for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {\n const k = __privateGet(this, _keyList)[i];\n if (k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {\n yield k;\n }\n }\n }\n /**\n * Inverse order version of {@link LRUCache.keys}\n *\n * Return a generator yielding the keys in the cache,\n * in order from least recently used to most recently used.\n */\n *rkeys() {\n for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {\n const k = __privateGet(this, _keyList)[i];\n if (k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {\n yield k;\n }\n }\n }\n /**\n * Return a generator yielding the values in the cache,\n * in order from most recently used to least recently used.\n */\n *values() {\n for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {\n const v = __privateGet(this, _valList)[i];\n if (v !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {\n yield __privateGet(this, _valList)[i];\n }\n }\n }\n /**\n * Inverse order version of {@link LRUCache.values}\n *\n * Return a generator yielding the values in the cache,\n * in order from least recently used to most recently used.\n */\n *rvalues() {\n for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {\n const v = __privateGet(this, _valList)[i];\n if (v !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {\n yield __privateGet(this, _valList)[i];\n }\n }\n }\n /**\n * Iterating over the cache itself yields the same results as\n * {@link LRUCache.entries}\n */\n [(_c = Symbol.iterator, _b = Symbol.toStringTag, _c)]() {\n return this.entries();\n }\n /**\n * Find a value for which the supplied fn method returns a truthy value,\n * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n */\n find(fn, getOptions = {}) {\n for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {\n const v = __privateGet(this, _valList)[i];\n const value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;\n if (value === void 0)\n continue;\n if (fn(value, __privateGet(this, _keyList)[i], this)) {\n return this.get(__privateGet(this, _keyList)[i], getOptions);\n }\n }\n }\n /**\n * Call the supplied function on each item in the cache, in order from most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or iterate over stale values.\n */\n forEach(fn, thisp = this) {\n for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {\n const v = __privateGet(this, _valList)[i];\n const value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;\n if (value === void 0)\n continue;\n fn.call(thisp, value, __privateGet(this, _keyList)[i], this);\n }\n }\n /**\n * The same as {@link LRUCache.forEach} but items are iterated over in\n * reverse order. (ie, less recently used items are iterated over first.)\n */\n rforEach(fn, thisp = this) {\n for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {\n const v = __privateGet(this, _valList)[i];\n const value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;\n if (value === void 0)\n continue;\n fn.call(thisp, value, __privateGet(this, _keyList)[i], this);\n }\n }\n /**\n * Delete any stale entries. Returns true if anything was removed,\n * false otherwise.\n */\n purgeStale() {\n let deleted = false;\n for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: true })) {\n if (__privateGet(this, _isStale).call(this, i)) {\n __privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[i], "expire");\n deleted = true;\n }\n }\n return deleted;\n }\n /**\n * Get the extended info about a given entry, to get its value, size, and\n * TTL info simultaneously. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * if relevant.\n */\n info(key) {\n const i = __privateGet(this, _keyMap).get(key);\n if (i === void 0)\n return void 0;\n const v = __privateGet(this, _valList)[i];\n const value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;\n if (value === void 0)\n return void 0;\n const entry = { value };\n if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {\n const ttl = __privateGet(this, _ttls)[i];\n const start = __privateGet(this, _starts)[i];\n if (ttl && start) {\n const remain = ttl - (perf.now() - start);\n entry.ttl = remain;\n entry.start = Date.now();\n }\n }\n if (__privateGet(this, _sizes)) {\n entry.size = __privateGet(this, _sizes)[i];\n }\n return entry;\n }\n /**\n * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n * passed to {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\n */\n dump() {\n const arr = [];\n for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this, { allowStale: true })) {\n const key = __privateGet(this, _keyList)[i];\n const v = __privateGet(this, _valList)[i];\n const value = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;\n if (value === void 0 || key === void 0)\n continue;\n const entry = { value };\n if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {\n entry.ttl = __privateGet(this, _ttls)[i];\n const age = perf.now() - __privateGet(this, _starts)[i];\n entry.start = Math.floor(Date.now() - age);\n }\n if (__privateGet(this, _sizes)) {\n entry.size = __privateGet(this, _sizes)[i];\n }\n arr.unshift([key, entry]);\n }\n return arr;\n }\n /**\n * Reset the cache and load in the items in entries in the order listed.\n *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\n */\n load(arr) {\n this.clear();\n for (const [key, entry] of arr) {\n if (entry.start) {\n const age = Date.now() - entry.start;\n entry.start = perf.now() - age;\n }\n this.set(key, entry.value, entry);\n }\n }\n /**\n * Add a value to the cache.\n *\n * Note: if `undefined` is specified as a value, this is an alias for\n * {@link LRUCache#delete}\n *\n * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\n */\n set(k, v, setOptions = {}) {\n var _a2, _b2, _c2, _d, _e;\n if (v === void 0) {\n this.delete(k);\n return this;\n }\n const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;\n let { noUpdateTTL = this.noUpdateTTL } = setOptions;\n const size = __privateGet(this, _requireSize).call(this, k, v, setOptions.size || 0, sizeCalculation);\n if (this.maxEntrySize && size > this.maxEntrySize) {\n if (status) {\n status.set = "miss";\n status.maxEntrySizeExceeded = true;\n }\n __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "set");\n return this;\n }\n let index = __privateGet(this, _size) === 0 ? void 0 : __privateGet(this, _keyMap).get(k);\n if (index === void 0) {\n index = __privateGet(this, _size) === 0 ? __privateGet(this, _tail) : __privateGet(this, _free).length !== 0 ? __privateGet(this, _free).pop() : __privateGet(this, _size) === __privateGet(this, _max) ? __privateMethod(this, _LRUCache_instances, evict_fn).call(this, false) : __privateGet(this, _size);\n __privateGet(this, _keyList)[index] = k;\n __privateGet(this, _valList)[index] = v;\n __privateGet(this, _keyMap).set(k, index);\n __privateGet(this, _next)[__privateGet(this, _tail)] = index;\n __privateGet(this, _prev)[index] = __privateGet(this, _tail);\n __privateSet(this, _tail, index);\n __privateWrapper(this, _size)._++;\n __privateGet(this, _addItemSize).call(this, index, size, status);\n if (status)\n status.set = "add";\n noUpdateTTL = false;\n } else {\n __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);\n const oldVal = __privateGet(this, _valList)[index];\n if (v !== oldVal) {\n if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal)) {\n oldVal.__abortController.abort(new Error("replaced"));\n const { __staleWhileFetching: s } = oldVal;\n if (s !== void 0 && !noDisposeOnSet) {\n if (__privateGet(this, _hasDispose)) {\n (_a2 = __privateGet(this, _dispose)) == null ? void 0 : _a2.call(this, s, k, "set");\n }\n if (__privateGet(this, _hasDisposeAfter)) {\n (_b2 = __privateGet(this, _disposed)) == null ? void 0 : _b2.push([s, k, "set"]);\n }\n }\n } else if (!noDisposeOnSet) {\n if (__privateGet(this, _hasDispose)) {\n (_c2 = __privateGet(this, _dispose)) == null ? void 0 : _c2.call(this, oldVal, k, "set");\n }\n if (__privateGet(this, _hasDisposeAfter)) {\n (_d = __privateGet(this, _disposed)) == null ? void 0 : _d.push([oldVal, k, "set"]);\n }\n }\n __privateGet(this, _removeItemSize).call(this, index);\n __privateGet(this, _addItemSize).call(this, index, size, status);\n __privateGet(this, _valList)[index] = v;\n if (status) {\n status.set = "replace";\n const oldValue = oldVal && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal) ? oldVal.__staleWhileFetching : oldVal;\n if (oldValue !== void 0)\n status.oldValue = oldValue;\n }\n } else if (status) {\n status.set = "update";\n }\n }\n if (ttl !== 0 && !__privateGet(this, _ttls)) {\n __privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this);\n }\n if (__privateGet(this, _ttls)) {\n if (!noUpdateTTL) {\n __privateGet(this, _setItemTTL).call(this, index, ttl, start);\n }\n if (status)\n __privateGet(this, _statusTTL).call(this, status, index);\n }\n if (!noDisposeOnSet && __privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {\n const dt = __privateGet(this, _disposed);\n let task;\n while (task = dt == null ? void 0 : dt.shift()) {\n (_e = __privateGet(this, _disposeAfter)) == null ? void 0 : _e.call(this, ...task);\n }\n }\n return this;\n }\n /**\n * Evict the least recently used item, returning its value or\n * `undefined` if cache is empty.\n */\n pop() {\n var _a2;\n try {\n while (__privateGet(this, _size)) {\n const val = __privateGet(this, _valList)[__privateGet(this, _head)];\n __privateMethod(this, _LRUCache_instances, evict_fn).call(this, true);\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, val)) {\n if (val.__staleWhileFetching) {\n return val.__staleWhileFetching;\n }\n } else if (val !== void 0) {\n return val;\n }\n }\n } finally {\n if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {\n const dt = __privateGet(this, _disposed);\n let task;\n while (task = dt == null ? void 0 : dt.shift()) {\n (_a2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _a2.call(this, ...task);\n }\n }\n }\n }\n /**\n * Check if a key is in the cache, without updating the recency of use.\n * Will return false if the item is stale, even though it is technically\n * in the cache.\n *\n * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\n *\n * Will not update item age unless\n * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n */\n has(k, hasOptions = {}) {\n const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;\n const index = __privateGet(this, _keyMap).get(k);\n if (index !== void 0) {\n const v = __privateGet(this, _valList)[index];\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) && v.__staleWhileFetching === void 0) {\n return false;\n }\n if (!__privateGet(this, _isStale).call(this, index)) {\n if (updateAgeOnHas) {\n __privateGet(this, _updateItemAge).call(this, index);\n }\n if (status) {\n status.has = "hit";\n __privateGet(this, _statusTTL).call(this, status, index);\n }\n return true;\n } else if (status) {\n status.has = "stale";\n __privateGet(this, _statusTTL).call(this, status, index);\n }\n } else if (status) {\n status.has = "miss";\n }\n return false;\n }\n /**\n * Like {@link LRUCache#get} but doesn\'t update recency or delete stale\n * items.\n *\n * Returns `undefined` if the item is stale, unless\n * {@link LRUCache.OptionsBase.allowStale} is set.\n */\n peek(k, peekOptions = {}) {\n const { allowStale = this.allowStale } = peekOptions;\n const index = __privateGet(this, _keyMap).get(k);\n if (index === void 0 || !allowStale && __privateGet(this, _isStale).call(this, index)) {\n return;\n }\n const v = __privateGet(this, _valList)[index];\n return __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;\n }\n async fetch(k, fetchOptions = {}) {\n const {\n // get options\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n // set options\n ttl = this.ttl,\n noDisposeOnSet = this.noDisposeOnSet,\n size = 0,\n sizeCalculation = this.sizeCalculation,\n noUpdateTTL = this.noUpdateTTL,\n // fetch exclusive options\n noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n ignoreFetchAbort = this.ignoreFetchAbort,\n allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n context,\n forceRefresh = false,\n status,\n signal\n } = fetchOptions;\n if (!__privateGet(this, _hasFetchMethod)) {\n if (status)\n status.fetch = "get";\n return this.get(k, {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n status\n });\n }\n const options = {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n ttl,\n noDisposeOnSet,\n size,\n sizeCalculation,\n noUpdateTTL,\n noDeleteOnFetchRejection,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n status,\n signal\n };\n let index = __privateGet(this, _keyMap).get(k);\n if (index === void 0) {\n if (status)\n status.fetch = "miss";\n const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options, context);\n return p.__returned = p;\n } else {\n const v = __privateGet(this, _valList)[index];\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {\n const stale = allowStale && v.__staleWhileFetching !== void 0;\n if (status) {\n status.fetch = "inflight";\n if (stale)\n status.returnedStale = true;\n }\n return stale ? v.__staleWhileFetching : v.__returned = v;\n }\n const isStale = __privateGet(this, _isStale).call(this, index);\n if (!forceRefresh && !isStale) {\n if (status)\n status.fetch = "hit";\n __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);\n if (updateAgeOnGet) {\n __privateGet(this, _updateItemAge).call(this, index);\n }\n if (status)\n __privateGet(this, _statusTTL).call(this, status, index);\n return v;\n }\n const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options, context);\n const hasStale = p.__staleWhileFetching !== void 0;\n const staleVal = hasStale && allowStale;\n if (status) {\n status.fetch = isStale ? "stale" : "refresh";\n if (staleVal && isStale)\n status.returnedStale = true;\n }\n return staleVal ? p.__staleWhileFetching : p.__returned = p;\n }\n }\n async forceFetch(k, fetchOptions = {}) {\n const v = await this.fetch(k, fetchOptions);\n if (v === void 0)\n throw new Error("fetch() returned undefined");\n return v;\n }\n memo(k, memoOptions = {}) {\n const memoMethod = __privateGet(this, _memoMethod);\n if (!memoMethod) {\n throw new Error("no memoMethod provided to constructor");\n }\n const { context, forceRefresh, ...options } = memoOptions;\n const v = this.get(k, options);\n if (!forceRefresh && v !== void 0)\n return v;\n const vv = memoMethod(k, v, {\n options,\n context\n });\n this.set(k, vv, options);\n return vv;\n }\n /**\n * Return a value from the cache. Will update the recency of the cache\n * entry found.\n *\n * If the key is not found, get() will return `undefined`.\n */\n get(k, getOptions = {}) {\n const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;\n const index = __privateGet(this, _keyMap).get(k);\n if (index !== void 0) {\n const value = __privateGet(this, _valList)[index];\n const fetching = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, value);\n if (status)\n __privateGet(this, _statusTTL).call(this, status, index);\n if (__privateGet(this, _isStale).call(this, index)) {\n if (status)\n status.get = "stale";\n if (!fetching) {\n if (!noDeleteOnStaleGet) {\n __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "expire");\n }\n if (status && allowStale)\n status.returnedStale = true;\n return allowStale ? value : void 0;\n } else {\n if (status && allowStale && value.__staleWhileFetching !== void 0) {\n status.returnedStale = true;\n }\n return allowStale ? value.__staleWhileFetching : void 0;\n }\n } else {\n if (status)\n status.get = "hit";\n if (fetching) {\n return value.__staleWhileFetching;\n }\n __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);\n if (updateAgeOnGet) {\n __privateGet(this, _updateItemAge).call(this, index);\n }\n return value;\n }\n } else if (status) {\n status.get = "miss";\n }\n }\n /**\n * Deletes a key out of the cache.\n *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k) {\n return __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "delete");\n }\n /**\n * Clear the cache entirely, throwing away all values.\n */\n clear() {\n return __privateMethod(this, _LRUCache_instances, clear_fn).call(this, "delete");\n }\n};\n_max = new WeakMap();\n_maxSize = new WeakMap();\n_dispose = new WeakMap();\n_disposeAfter = new WeakMap();\n_fetchMethod = new WeakMap();\n_memoMethod = new WeakMap();\n_size = new WeakMap();\n_calculatedSize = new WeakMap();\n_keyMap = new WeakMap();\n_keyList = new WeakMap();\n_valList = new WeakMap();\n_next = new WeakMap();\n_prev = new WeakMap();\n_head = new WeakMap();\n_tail = new WeakMap();\n_free = new WeakMap();\n_disposed = new WeakMap();\n_sizes = new WeakMap();\n_starts = new WeakMap();\n_ttls = new WeakMap();\n_hasDispose = new WeakMap();\n_hasFetchMethod = new WeakMap();\n_hasDisposeAfter = new WeakMap();\n_LRUCache_instances = new WeakSet();\ninitializeTTLTracking_fn = function() {\n const ttls = new ZeroArray(__privateGet(this, _max));\n const starts = new ZeroArray(__privateGet(this, _max));\n __privateSet(this, _ttls, ttls);\n __privateSet(this, _starts, starts);\n __privateSet(this, _setItemTTL, (index, ttl, start = perf.now()) => {\n starts[index] = ttl !== 0 ? start : 0;\n ttls[index] = ttl;\n if (ttl !== 0 && this.ttlAutopurge) {\n const t = setTimeout(() => {\n if (__privateGet(this, _isStale).call(this, index)) {\n __privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[index], "expire");\n }\n }, ttl + 1);\n if (t.unref) {\n t.unref();\n }\n }\n });\n __privateSet(this, _updateItemAge, (index) => {\n starts[index] = ttls[index] !== 0 ? perf.now() : 0;\n });\n __privateSet(this, _statusTTL, (status, index) => {\n if (ttls[index]) {\n const ttl = ttls[index];\n const start = starts[index];\n if (!ttl || !start)\n return;\n status.ttl = ttl;\n status.start = start;\n status.now = cachedNow || getNow();\n const age = status.now - start;\n status.remainingTTL = ttl - age;\n }\n });\n let cachedNow = 0;\n const getNow = () => {\n const n = perf.now();\n if (this.ttlResolution > 0) {\n cachedNow = n;\n const t = setTimeout(() => cachedNow = 0, this.ttlResolution);\n if (t.unref) {\n t.unref();\n }\n }\n return n;\n };\n this.getRemainingTTL = (key) => {\n const index = __privateGet(this, _keyMap).get(key);\n if (index === void 0) {\n return 0;\n }\n const ttl = ttls[index];\n const start = starts[index];\n if (!ttl || !start) {\n return Infinity;\n }\n const age = (cachedNow || getNow()) - start;\n return ttl - age;\n };\n __privateSet(this, _isStale, (index) => {\n const s = starts[index];\n const t = ttls[index];\n return !!t && !!s && (cachedNow || getNow()) - s > t;\n });\n};\n_updateItemAge = new WeakMap();\n_statusTTL = new WeakMap();\n_setItemTTL = new WeakMap();\n_isStale = new WeakMap();\ninitializeSizeTracking_fn = function() {\n const sizes = new ZeroArray(__privateGet(this, _max));\n __privateSet(this, _calculatedSize, 0);\n __privateSet(this, _sizes, sizes);\n __privateSet(this, _removeItemSize, (index) => {\n __privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) - sizes[index]);\n sizes[index] = 0;\n });\n __privateSet(this, _requireSize, (k, v, size, sizeCalculation) => {\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {\n return 0;\n }\n if (!isPosInt(size)) {\n if (sizeCalculation) {\n if (typeof sizeCalculation !== "function") {\n throw new TypeError("sizeCalculation must be a function");\n }\n size = sizeCalculation(v, k);\n if (!isPosInt(size)) {\n throw new TypeError("sizeCalculation return invalid (expect positive integer)");\n }\n } else {\n throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");\n }\n }\n return size;\n });\n __privateSet(this, _addItemSize, (index, size, status) => {\n sizes[index] = size;\n if (__privateGet(this, _maxSize)) {\n const maxSize = __privateGet(this, _maxSize) - sizes[index];\n while (__privateGet(this, _calculatedSize) > maxSize) {\n __privateMethod(this, _LRUCache_instances, evict_fn).call(this, true);\n }\n }\n __privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) + sizes[index]);\n if (status) {\n status.entrySize = size;\n status.totalCalculatedSize = __privateGet(this, _calculatedSize);\n }\n });\n};\n_removeItemSize = new WeakMap();\n_addItemSize = new WeakMap();\n_requireSize = new WeakMap();\nindexes_fn = function* ({ allowStale = this.allowStale } = {}) {\n if (__privateGet(this, _size)) {\n for (let i = __privateGet(this, _tail); true; ) {\n if (!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i)) {\n break;\n }\n if (allowStale || !__privateGet(this, _isStale).call(this, i)) {\n yield i;\n }\n if (i === __privateGet(this, _head)) {\n break;\n } else {\n i = __privateGet(this, _prev)[i];\n }\n }\n }\n};\nrindexes_fn = function* ({ allowStale = this.allowStale } = {}) {\n if (__privateGet(this, _size)) {\n for (let i = __privateGet(this, _head); true; ) {\n if (!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i)) {\n break;\n }\n if (allowStale || !__privateGet(this, _isStale).call(this, i)) {\n yield i;\n }\n if (i === __privateGet(this, _tail)) {\n break;\n } else {\n i = __privateGet(this, _next)[i];\n }\n }\n }\n};\nisValidIndex_fn = function(index) {\n return index !== void 0 && __privateGet(this, _keyMap).get(__privateGet(this, _keyList)[index]) === index;\n};\nevict_fn = function(free) {\n var _a2, _b2;\n const head = __privateGet(this, _head);\n const k = __privateGet(this, _keyList)[head];\n const v = __privateGet(this, _valList)[head];\n if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {\n v.__abortController.abort(new Error("evicted"));\n } else if (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) {\n if (__privateGet(this, _hasDispose)) {\n (_a2 = __privateGet(this, _dispose)) == null ? void 0 : _a2.call(this, v, k, "evict");\n }\n if (__privateGet(this, _hasDisposeAfter)) {\n (_b2 = __privateGet(this, _disposed)) == null ? void 0 : _b2.push([v, k, "evict"]);\n }\n }\n __privateGet(this, _removeItemSize).call(this, head);\n if (free) {\n __privateGet(this, _keyList)[head] = void 0;\n __privateGet(this, _valList)[head] = void 0;\n __privateGet(this, _free).push(head);\n }\n if (__privateGet(this, _size) === 1) {\n __privateSet(this, _head, __privateSet(this, _tail, 0));\n __privateGet(this, _free).length = 0;\n } else {\n __privateSet(this, _head, __privateGet(this, _next)[head]);\n }\n __privateGet(this, _keyMap).delete(k);\n __privateWrapper(this, _size)._--;\n return head;\n};\nbackgroundFetch_fn = function(k, index, options, context) {\n const v = index === void 0 ? void 0 : __privateGet(this, _valList)[index];\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {\n return v;\n }\n const ac = new AC();\n const { signal } = options;\n signal == null ? void 0 : signal.addEventListener("abort", () => ac.abort(signal.reason), {\n signal: ac.signal\n });\n const fetchOpts = {\n signal: ac.signal,\n options,\n context\n };\n const cb = (v2, updateCache = false) => {\n const { aborted } = ac.signal;\n const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;\n if (options.status) {\n if (aborted && !updateCache) {\n options.status.fetchAborted = true;\n options.status.fetchError = ac.signal.reason;\n if (ignoreAbort)\n options.status.fetchAbortIgnored = true;\n } else {\n options.status.fetchResolved = true;\n }\n }\n if (aborted && !ignoreAbort && !updateCache) {\n return fetchFail(ac.signal.reason);\n }\n const bf2 = p;\n if (__privateGet(this, _valList)[index] === p) {\n if (v2 === void 0) {\n if (bf2.__staleWhileFetching) {\n __privateGet(this, _valList)[index] = bf2.__staleWhileFetching;\n } else {\n __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch");\n }\n } else {\n if (options.status)\n options.status.fetchUpdated = true;\n this.set(k, v2, fetchOpts.options);\n }\n }\n return v2;\n };\n const eb = (er) => {\n if (options.status) {\n options.status.fetchRejected = true;\n options.status.fetchError = er;\n }\n return fetchFail(er);\n };\n const fetchFail = (er) => {\n const { aborted } = ac.signal;\n const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;\n const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;\n const noDelete = allowStale || options.noDeleteOnFetchRejection;\n const bf2 = p;\n if (__privateGet(this, _valList)[index] === p) {\n const del = !noDelete || bf2.__staleWhileFetching === void 0;\n if (del) {\n __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch");\n } else if (!allowStaleAborted) {\n __privateGet(this, _valList)[index] = bf2.__staleWhileFetching;\n }\n }\n if (allowStale) {\n if (options.status && bf2.__staleWhileFetching !== void 0) {\n options.status.returnedStale = true;\n }\n return bf2.__staleWhileFetching;\n } else if (bf2.__returned === bf2) {\n throw er;\n }\n };\n const pcall = (res, rej) => {\n var _a2;\n const fmp = (_a2 = __privateGet(this, _fetchMethod)) == null ? void 0 : _a2.call(this, k, v, fetchOpts);\n if (fmp && fmp instanceof Promise) {\n fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);\n }\n ac.signal.addEventListener("abort", () => {\n if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {\n res(void 0);\n if (options.allowStaleOnFetchAbort) {\n res = (v2) => cb(v2, true);\n }\n }\n });\n };\n if (options.status)\n options.status.fetchDispatched = true;\n const p = new Promise(pcall).then(cb, eb);\n const bf = Object.assign(p, {\n __abortController: ac,\n __staleWhileFetching: v,\n __returned: void 0\n });\n if (index === void 0) {\n this.set(k, bf, { ...fetchOpts.options, status: void 0 });\n index = __privateGet(this, _keyMap).get(k);\n } else {\n __privateGet(this, _valList)[index] = bf;\n }\n return bf;\n};\nisBackgroundFetch_fn = function(p) {\n if (!__privateGet(this, _hasFetchMethod))\n return false;\n const b = p;\n return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;\n};\nconnect_fn = function(p, n) {\n __privateGet(this, _prev)[n] = p;\n __privateGet(this, _next)[p] = n;\n};\nmoveToTail_fn = function(index) {\n if (index !== __privateGet(this, _tail)) {\n if (index === __privateGet(this, _head)) {\n __privateSet(this, _head, __privateGet(this, _next)[index]);\n } else {\n __privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _prev)[index], __privateGet(this, _next)[index]);\n }\n __privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _tail), index);\n __privateSet(this, _tail, index);\n }\n};\ndelete_fn = function(k, reason) {\n var _a2, _b2, _c2, _d;\n let deleted = false;\n if (__privateGet(this, _size) !== 0) {\n const index = __privateGet(this, _keyMap).get(k);\n if (index !== void 0) {\n deleted = true;\n if (__privateGet(this, _size) === 1) {\n __privateMethod(this, _LRUCache_instances, clear_fn).call(this, reason);\n } else {\n __privateGet(this, _removeItemSize).call(this, index);\n const v = __privateGet(this, _valList)[index];\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {\n v.__abortController.abort(new Error("deleted"));\n } else if (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) {\n if (__privateGet(this, _hasDispose)) {\n (_a2 = __privateGet(this, _dispose)) == null ? void 0 : _a2.call(this, v, k, reason);\n }\n if (__privateGet(this, _hasDisposeAfter)) {\n (_b2 = __privateGet(this, _disposed)) == null ? void 0 : _b2.push([v, k, reason]);\n }\n }\n __privateGet(this, _keyMap).delete(k);\n __privateGet(this, _keyList)[index] = void 0;\n __privateGet(this, _valList)[index] = void 0;\n if (index === __privateGet(this, _tail)) {\n __privateSet(this, _tail, __privateGet(this, _prev)[index]);\n } else if (index === __privateGet(this, _head)) {\n __privateSet(this, _head, __privateGet(this, _next)[index]);\n } else {\n const pi = __privateGet(this, _prev)[index];\n __privateGet(this, _next)[pi] = __privateGet(this, _next)[index];\n const ni = __privateGet(this, _next)[index];\n __privateGet(this, _prev)[ni] = __privateGet(this, _prev)[index];\n }\n __privateWrapper(this, _size)._--;\n __privateGet(this, _free).push(index);\n }\n }\n }\n if (__privateGet(this, _hasDisposeAfter) && ((_c2 = __privateGet(this, _disposed)) == null ? void 0 : _c2.length)) {\n const dt = __privateGet(this, _disposed);\n let task;\n while (task = dt == null ? void 0 : dt.shift()) {\n (_d = __privateGet(this, _disposeAfter)) == null ? void 0 : _d.call(this, ...task);\n }\n }\n return deleted;\n};\nclear_fn = function(reason) {\n var _a2, _b2, _c2;\n for (const index of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: true })) {\n const v = __privateGet(this, _valList)[index];\n if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {\n v.__abortController.abort(new Error("deleted"));\n } else {\n const k = __privateGet(this, _keyList)[index];\n if (__privateGet(this, _hasDispose)) {\n (_a2 = __privateGet(this, _dispose)) == null ? void 0 : _a2.call(this, v, k, reason);\n }\n if (__privateGet(this, _hasDisposeAfter)) {\n (_b2 = __privateGet(this, _disposed)) == null ? void 0 : _b2.push([v, k, reason]);\n }\n }\n }\n __privateGet(this, _keyMap).clear();\n __privateGet(this, _valList).fill(void 0);\n __privateGet(this, _keyList).fill(void 0);\n if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {\n __privateGet(this, _ttls).fill(0);\n __privateGet(this, _starts).fill(0);\n }\n if (__privateGet(this, _sizes)) {\n __privateGet(this, _sizes).fill(0);\n }\n __privateSet(this, _head, 0);\n __privateSet(this, _tail, 0);\n __privateGet(this, _free).length = 0;\n __privateSet(this, _calculatedSize, 0);\n __privateSet(this, _size, 0);\n if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {\n const dt = __privateGet(this, _disposed);\n let task;\n while (task = dt == null ? void 0 : dt.shift()) {\n (_c2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _c2.call(this, ...task);\n }\n }\n};\nlet LRUCache = _LRUCache;\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 getLRUCache() {\n const dataFetchCache = getDataFetchCache();\n const cacheConfig = getCacheConfig();\n if (!dataFetchCache || !dataFetchCache.cacheStore) {\n const cacheStore = new LRUCache({\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 updateAgeOnGet: true,\n updateAgeOnHas: true\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 = getLRUCache();\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 lruCache = getLRUCache();\n if (keys) {\n keys.forEach((key) => {\n lruCache == null ? void 0 : lruCache.delete(key);\n });\n }\n}\nfunction clearStore() {\n var _a2;\n const lruCache = getLRUCache();\n const tagKeyMap = getTagKeyMap();\n lruCache == null ? void 0 : lruCache.clear();\n (_a2 = globalThis.__MF_DATA_FETCH_CACHE__) == null ? true : delete _a2.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 _a2;\n return (_a2 = globalThis.__MF_DATA_FETCH_MAP__) == null ? void 0 : _a2[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 _a2;\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 ((_a2 = dataFetchItem[1]) == null ? void 0 : _a2[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 getDataFetchCache as N,\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'
|
|
159
|
+
};
|
|
160
|
+
const ENTRY_FILE = 'entry.ts';
|
|
161
|
+
const APP_FILE = 'app.tsx';
|
|
162
|
+
const BRIDGE_ROOT = 'bridge';
|
|
163
|
+
const BRIDGE_INDEX_FILE = `${BRIDGE_ROOT}/index.es.js`;
|
|
164
|
+
const BRIDGE_ROUTER_STUB_FILE = `${BRIDGE_ROOT}/react-router-dom-stub.js`;
|
|
165
|
+
const BRIDGE_ROUTER_STUB_SOURCE = `export function useLocation() {
|
|
166
|
+
throw new Error('react-router-dom is not available in playground bridge runtime.');
|
|
167
|
+
}
|
|
168
|
+
export const useRouteMatch = undefined;
|
|
169
|
+
export const useHistory = undefined;
|
|
170
|
+
export const useHref = undefined;
|
|
171
|
+
export const UNSAFE_RouteContext = undefined;
|
|
172
|
+
export default {};
|
|
173
|
+
`;
|
|
174
|
+
const BRIDGE_REACT_SHIM_SOURCE = `const React = window.React;
|
|
175
|
+
if (!React) {
|
|
176
|
+
throw new Error('React runtime is not available for bridge runtime.');
|
|
177
|
+
}
|
|
178
|
+
export default React;
|
|
179
|
+
export const Component = React.Component;
|
|
180
|
+
export const Suspense = React.Suspense;
|
|
181
|
+
export const createContext = React.createContext;
|
|
182
|
+
export const createElement = React.createElement;
|
|
183
|
+
export const forwardRef = React.forwardRef;
|
|
184
|
+
export const lazy = React.lazy;
|
|
185
|
+
export const useContext = React.useContext;
|
|
186
|
+
export const useEffect = React.useEffect;
|
|
187
|
+
export const useRef = React.useRef;
|
|
188
|
+
export const useState = React.useState;
|
|
189
|
+
`;
|
|
190
|
+
const BRIDGE_REACT_DOM_SHIM_SOURCE = `const ReactDOM = window.ReactDOM;
|
|
191
|
+
if (!ReactDOM) {
|
|
192
|
+
throw new Error('ReactDOM runtime is not available for bridge runtime.');
|
|
193
|
+
}
|
|
194
|
+
export default ReactDOM;
|
|
195
|
+
export const createRoot = ReactDOM.createRoot;
|
|
196
|
+
export const render = ReactDOM.render;
|
|
197
|
+
export const unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
|
|
198
|
+
`;
|
|
199
|
+
const BRIDGE_SHIM_MODULES = {
|
|
200
|
+
react: BRIDGE_REACT_SHIM_SOURCE,
|
|
201
|
+
'react-dom': BRIDGE_REACT_DOM_SHIM_SOURCE,
|
|
202
|
+
'react-dom/client': BRIDGE_REACT_DOM_SHIM_SOURCE
|
|
203
|
+
};
|
|
204
|
+
function buildBridgeRuntimeFiles() {
|
|
205
|
+
return {
|
|
206
|
+
...Object.fromEntries(Object.entries(BRIDGE_RUNTIME_FILES).map(([filename, source])=>[
|
|
207
|
+
`${BRIDGE_ROOT}/${filename}`,
|
|
208
|
+
String(source).replace(/(["'])react-router-dom\1/g, '$1./react-router-dom-stub.js$1')
|
|
209
|
+
])),
|
|
210
|
+
[BRIDGE_ROUTER_STUB_FILE]: BRIDGE_ROUTER_STUB_SOURCE
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
function transpileModule(filename, source) {
|
|
214
|
+
const result = typescript.transpileModule(source, {
|
|
215
|
+
fileName: filename,
|
|
216
|
+
compilerOptions: {
|
|
217
|
+
allowSyntheticDefaultImports: true,
|
|
218
|
+
esModuleInterop: true,
|
|
219
|
+
jsx: typescript.JsxEmit.React,
|
|
220
|
+
module: typescript.ModuleKind.CommonJS,
|
|
221
|
+
moduleResolution: typescript.ModuleResolutionKind.NodeJs,
|
|
222
|
+
target: typescript.ScriptTarget.ES2020
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
if (result.diagnostics?.length) {
|
|
226
|
+
const message = result.diagnostics.map((diagnostic)=>'string' == typeof diagnostic.messageText ? diagnostic.messageText : diagnostic.messageText.messageText).join('\n');
|
|
227
|
+
if (message) throw new Error(message);
|
|
228
|
+
}
|
|
229
|
+
return result.outputText;
|
|
230
|
+
}
|
|
231
|
+
function createModuleFactory(filename, source) {
|
|
232
|
+
return `${JSON.stringify(filename)}: function(require, module, exports) {\n${transpileModule(filename, source)}\n}`;
|
|
233
|
+
}
|
|
234
|
+
function normalizeRuntimeFileName(value) {
|
|
235
|
+
const normalized = value.trim().replace(/^\.\/+/, '');
|
|
236
|
+
if (!normalized || normalized.includes('/') || normalized.includes('\\')) return 'mf.ts';
|
|
237
|
+
return normalized.endsWith('.ts') ? normalized : `${normalized}.ts`;
|
|
238
|
+
}
|
|
239
|
+
function getRuntimeFileBaseName(filename) {
|
|
240
|
+
return filename.replace(/\.ts$/, '');
|
|
241
|
+
}
|
|
242
|
+
function normalizeGlobalName(value) {
|
|
243
|
+
const normalized = value.trim().replace(/[^\w$]/g, '_');
|
|
244
|
+
if (!normalized || /^\d/.test(normalized)) return 'ModuleFederationRuntime';
|
|
245
|
+
return normalized;
|
|
246
|
+
}
|
|
247
|
+
function getRuntimeGlobalNames(primaryName) {
|
|
248
|
+
const names = [
|
|
249
|
+
primaryName.trim()
|
|
250
|
+
].filter(Boolean);
|
|
251
|
+
return [
|
|
252
|
+
...new Set(names)
|
|
253
|
+
];
|
|
254
|
+
}
|
|
255
|
+
function createBridgeRuntimeBootstrap() {
|
|
256
|
+
return `
|
|
257
|
+
var bridgeRuntimeFiles = ${JSON.stringify(buildBridgeRuntimeFiles())};
|
|
258
|
+
var bridgeShimModules = ${JSON.stringify(BRIDGE_SHIM_MODULES)};
|
|
259
|
+
var bridgeModuleUrlCache = {};
|
|
260
|
+
var bridgeShimUrlCache = {};
|
|
261
|
+
function createBridgeDataUrl(source) {
|
|
262
|
+
return URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));
|
|
263
|
+
}
|
|
264
|
+
function createBridgeShimUrl(request) {
|
|
265
|
+
if (!bridgeShimModules[request]) {
|
|
266
|
+
throw new Error('Unsupported bridge runtime dependency: ' + request);
|
|
267
|
+
}
|
|
268
|
+
if (!bridgeShimUrlCache[request]) {
|
|
269
|
+
bridgeShimUrlCache[request] = createBridgeDataUrl(bridgeShimModules[request]);
|
|
270
|
+
}
|
|
271
|
+
return bridgeShimUrlCache[request];
|
|
272
|
+
}
|
|
273
|
+
function resolveBridgeModulePath(from, request) {
|
|
274
|
+
if (request.indexOf('./') !== 0) {
|
|
275
|
+
return request;
|
|
276
|
+
}
|
|
277
|
+
var parts = from.split('/');
|
|
278
|
+
parts.pop();
|
|
279
|
+
request.slice(2).split('/').forEach(function(part) {
|
|
280
|
+
if (!part || part === '.') {
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (part === '..') {
|
|
284
|
+
parts.pop();
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
parts.push(part);
|
|
288
|
+
});
|
|
289
|
+
return parts.join('/');
|
|
290
|
+
}
|
|
291
|
+
function createBridgeModuleUrl(filename) {
|
|
292
|
+
if (bridgeModuleUrlCache[filename]) {
|
|
293
|
+
return bridgeModuleUrlCache[filename];
|
|
294
|
+
}
|
|
295
|
+
var source = bridgeRuntimeFiles[filename];
|
|
296
|
+
if (!source) {
|
|
297
|
+
throw new Error('Bridge runtime source not found: ' + filename);
|
|
298
|
+
}
|
|
299
|
+
source = source.replace(/from\\s+["']([^"']+)["']/g, function(full, request) {
|
|
300
|
+
if (request.indexOf('./') === 0) {
|
|
301
|
+
return 'from ' + JSON.stringify(createBridgeModuleUrl(resolveBridgeModulePath(filename, request)));
|
|
302
|
+
}
|
|
303
|
+
if (bridgeShimModules[request]) {
|
|
304
|
+
return 'from ' + JSON.stringify(createBridgeShimUrl(request));
|
|
305
|
+
}
|
|
306
|
+
return full;
|
|
307
|
+
});
|
|
308
|
+
bridgeModuleUrlCache[filename] = createBridgeDataUrl(source);
|
|
309
|
+
return bridgeModuleUrlCache[filename];
|
|
310
|
+
}
|
|
311
|
+
async function ensureBridgeRuntime() {
|
|
312
|
+
if (window.__MF_PLAYGROUND_BRIDGE__) {
|
|
313
|
+
return window.__MF_PLAYGROUND_BRIDGE__;
|
|
314
|
+
}
|
|
315
|
+
window.__MF_PLAYGROUND_BRIDGE__ = await import(createBridgeModuleUrl(${JSON.stringify(BRIDGE_INDEX_FILE)}));
|
|
316
|
+
return window.__MF_PLAYGROUND_BRIDGE__;
|
|
317
|
+
}
|
|
318
|
+
`;
|
|
319
|
+
}
|
|
320
|
+
async function compilePlaygroundApp(params) {
|
|
321
|
+
params.rspackConfigCode;
|
|
322
|
+
const runtimeModuleUrl = params.runtimeModuleUrl.trim();
|
|
323
|
+
if (!runtimeModuleUrl) throw new Error('runtimeModuleUrl is required.');
|
|
324
|
+
const runtimeFileName = normalizeRuntimeFileName(params.runtimeFileName);
|
|
325
|
+
const runtimeFileBaseName = getRuntimeFileBaseName(runtimeFileName);
|
|
326
|
+
const runtimeGlobalName = normalizeGlobalName(params.runtimeGlobalName);
|
|
327
|
+
const runtimeGlobalNames = getRuntimeGlobalNames(runtimeGlobalName);
|
|
328
|
+
const runtimePackageName = params.runtimePackageName.trim() || '@module-federation/runtime';
|
|
329
|
+
const factories = [
|
|
330
|
+
createModuleFactory(APP_FILE, params.appCode),
|
|
331
|
+
createModuleFactory(runtimeFileName, params.mfCode),
|
|
332
|
+
createModuleFactory(ENTRY_FILE, params.entryCode)
|
|
333
|
+
].join(',\n');
|
|
334
|
+
return `(async function() {
|
|
335
|
+
${createBridgeRuntimeBootstrap()}
|
|
336
|
+
var bridgeExports = await ensureBridgeRuntime();
|
|
337
|
+
var mfRuntimePromise = null;
|
|
338
|
+
var runtimeGlobalName = ${JSON.stringify(runtimeGlobalName)};
|
|
339
|
+
var runtimeGlobalNames = ${JSON.stringify(runtimeGlobalNames)};
|
|
340
|
+
var runtimePackageName = ${JSON.stringify(runtimePackageName)};
|
|
341
|
+
function getRuntimeFromWindow() {
|
|
342
|
+
for (var i = 0; i < runtimeGlobalNames.length; i++) {
|
|
343
|
+
var name = runtimeGlobalNames[i];
|
|
344
|
+
var runtime = window[name];
|
|
345
|
+
if (runtime && runtime.createInstance) {
|
|
346
|
+
window[runtimeGlobalName] = runtime;
|
|
347
|
+
return runtime;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
function loadClassicRuntimeScript() {
|
|
353
|
+
return new Promise(function(resolve, reject) {
|
|
354
|
+
var existingRuntime = getRuntimeFromWindow();
|
|
355
|
+
if (existingRuntime) {
|
|
356
|
+
resolve(existingRuntime);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
var script = document.createElement('script');
|
|
360
|
+
script.src = ${JSON.stringify(runtimeModuleUrl)};
|
|
361
|
+
script.async = true;
|
|
362
|
+
script.onload = function() {
|
|
363
|
+
var runtime = getRuntimeFromWindow();
|
|
364
|
+
if (runtime) {
|
|
365
|
+
resolve(runtime);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
reject(new Error('Runtime script loaded but no runtime global was found.'));
|
|
369
|
+
};
|
|
370
|
+
script.onerror = function() {
|
|
371
|
+
reject(new Error('Failed to load runtime script: ' + ${JSON.stringify(runtimeModuleUrl)}));
|
|
372
|
+
};
|
|
373
|
+
document.head.appendChild(script);
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
function loadModuleFederationRuntime() {
|
|
377
|
+
var existingRuntime = getRuntimeFromWindow();
|
|
378
|
+
if (existingRuntime) return Promise.resolve(existingRuntime);
|
|
379
|
+
if (!mfRuntimePromise) {
|
|
380
|
+
mfRuntimePromise = import(${JSON.stringify(runtimeModuleUrl)}).then(function(runtime) {
|
|
381
|
+
var runtimeCandidate = runtime && runtime.createInstance ? runtime : getRuntimeFromWindow();
|
|
382
|
+
if (runtimeCandidate) {
|
|
383
|
+
window[runtimeGlobalName] = runtimeCandidate;
|
|
384
|
+
return runtimeCandidate;
|
|
385
|
+
}
|
|
386
|
+
return loadClassicRuntimeScript();
|
|
387
|
+
}).catch(loadClassicRuntimeScript);
|
|
388
|
+
}
|
|
389
|
+
return mfRuntimePromise;
|
|
390
|
+
}
|
|
391
|
+
var modules = {
|
|
392
|
+
${factories}
|
|
393
|
+
};
|
|
394
|
+
var cache = {};
|
|
395
|
+
var aliases = {
|
|
396
|
+
'./app': 'app.tsx',
|
|
397
|
+
'./app.tsx': 'app.tsx',
|
|
398
|
+
${JSON.stringify(`./${runtimeFileBaseName}`)}: ${JSON.stringify(runtimeFileName)},
|
|
399
|
+
${JSON.stringify(`./${runtimeFileName}`)}: ${JSON.stringify(runtimeFileName)}
|
|
400
|
+
};
|
|
401
|
+
function require(request) {
|
|
402
|
+
var id = aliases[request] || request;
|
|
403
|
+
if (request === 'react') return window.React;
|
|
404
|
+
if (request === 'react-dom' || request === 'react-dom/client') return window.ReactDOM;
|
|
405
|
+
if (
|
|
406
|
+
request === runtimePackageName ||
|
|
407
|
+
request === '@module-federation/runtime'
|
|
408
|
+
) {
|
|
409
|
+
return getRuntimeFromWindow();
|
|
410
|
+
}
|
|
411
|
+
if (request === './bridge/index.es.js') return bridgeExports;
|
|
412
|
+
if (request.indexOf('@module-federation/bridge-react') === 0) return bridgeExports;
|
|
413
|
+
if (!modules[id]) {
|
|
414
|
+
throw new Error('Module not found in playground bundle: ' + request);
|
|
415
|
+
}
|
|
416
|
+
if (cache[id]) return cache[id].exports;
|
|
417
|
+
var module = { exports: {} };
|
|
418
|
+
cache[id] = module;
|
|
419
|
+
modules[id](require, module, module.exports);
|
|
420
|
+
return module.exports;
|
|
421
|
+
}
|
|
422
|
+
await loadModuleFederationRuntime();
|
|
423
|
+
require(${JSON.stringify(ENTRY_FILE)});
|
|
424
|
+
})();`;
|
|
425
|
+
}
|
|
426
|
+
function guessRemoteName(manifest) {
|
|
427
|
+
return manifest.metaData?.name || manifest.name || manifest.id || '@module-federation/unknown-remote';
|
|
428
|
+
}
|
|
429
|
+
function normalizeExpose(expose) {
|
|
430
|
+
const normalizedExpose = expose.trim();
|
|
431
|
+
if (!normalizedExpose || '.' === normalizedExpose || './' === normalizedExpose || './.' === normalizedExpose) return '';
|
|
432
|
+
return normalizedExpose.replace(/^\.\//, '').replace(/^\//, '');
|
|
433
|
+
}
|
|
434
|
+
function formatLoadedTarget(remoteName, expose) {
|
|
435
|
+
return expose ? `${remoteName}/${expose}` : remoteName;
|
|
436
|
+
}
|
|
437
|
+
async function fetchJson(url) {
|
|
438
|
+
const response = await fetch(url);
|
|
439
|
+
if (!response.ok) throw new Error(`Fetch failed: ${response.status} ${response.statusText} (${url})`);
|
|
440
|
+
return await response.json();
|
|
441
|
+
}
|
|
442
|
+
async function fetchManifest(url) {
|
|
443
|
+
return fetchJson(url);
|
|
444
|
+
}
|
|
445
|
+
const cx = (...names)=>names.filter((name)=>Boolean(name)).map((name)=>App_module[name] || name).join(' ');
|
|
446
|
+
const MONACO_CDN_VS_URL = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
|
|
447
|
+
loader.config({
|
|
448
|
+
paths: {
|
|
449
|
+
vs: MONACO_CDN_VS_URL
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
const DEFAULT_MANIFEST_URL = 'https://unpkg.com/module-federation-rslib-provider@latest/dist/mf/mf-manifest.json';
|
|
453
|
+
const DEFAULT_RUNTIME_MODULE_URL = 'https://esm.sh/@module-federation/runtime@2.6.0?bundle';
|
|
454
|
+
const DEFAULT_REACT_VERSION = '19.1.1';
|
|
455
|
+
const DEFAULT_LEFT_PANE_WIDTH = 50;
|
|
456
|
+
const MIN_LEFT_PANE_WIDTH = 28;
|
|
457
|
+
const MAX_LEFT_PANE_WIDTH = 72;
|
|
458
|
+
const MANIFEST_QUERY_KEYS = [
|
|
459
|
+
'url',
|
|
460
|
+
'manifestUrl',
|
|
461
|
+
'manifest',
|
|
462
|
+
'm'
|
|
463
|
+
];
|
|
464
|
+
const EXPOSE_QUERY_KEYS = [
|
|
465
|
+
'expose',
|
|
466
|
+
'e'
|
|
467
|
+
];
|
|
468
|
+
const EXPORT_QUERY_KEYS = [
|
|
469
|
+
'export',
|
|
470
|
+
'exportName'
|
|
471
|
+
];
|
|
472
|
+
const PREVIEW_ROUTE_QUERY_KEYS = [
|
|
473
|
+
'route',
|
|
474
|
+
'previewRoute'
|
|
475
|
+
];
|
|
476
|
+
const AUTO_RUN_QUERY_KEYS = [
|
|
477
|
+
...MANIFEST_QUERY_KEYS,
|
|
478
|
+
...EXPOSE_QUERY_KEYS,
|
|
479
|
+
...EXPORT_QUERY_KEYS,
|
|
480
|
+
...PREVIEW_ROUTE_QUERY_KEYS,
|
|
481
|
+
'run'
|
|
482
|
+
];
|
|
483
|
+
function normalizeIdentifier(value, fallback) {
|
|
484
|
+
const normalized = (value || '').trim().replace(/[^\w$]/g, '_');
|
|
485
|
+
if (!normalized || /^\d/.test(normalized)) return fallback;
|
|
486
|
+
return normalized;
|
|
487
|
+
}
|
|
488
|
+
function normalizeTemplateFileName(value, fallback) {
|
|
489
|
+
const normalized = (value || '').trim().replace(/^\.\/+/, '').replace(/[^\w$.-]/g, '_');
|
|
490
|
+
if (!normalized || normalized.includes('/') || normalized.includes('\\')) return fallback;
|
|
491
|
+
return normalized.endsWith('.ts') ? normalized : `${normalized}.ts`;
|
|
492
|
+
}
|
|
493
|
+
function getTemplateFileBaseName(fileName) {
|
|
494
|
+
return fileName.replace(/\.ts$/, '');
|
|
495
|
+
}
|
|
496
|
+
function getPlaygroundTemplate(props) {
|
|
497
|
+
const runtimeFileName = normalizeTemplateFileName(props.templateRuntimeFileName, 'mf.ts');
|
|
498
|
+
const runtimeImportName = normalizeIdentifier(props.templateRuntimeImportName, 'getModuleFederationInstance');
|
|
499
|
+
return {
|
|
500
|
+
bridgePackageName: '@module-federation/bridge-react',
|
|
501
|
+
playgroundName: props.templatePlaygroundName?.trim() || '@module-federation/playground',
|
|
502
|
+
playgroundPropsGlobalName: normalizeIdentifier(props.templatePlaygroundPropsGlobalName, '__MF_PLAYGROUND_PROPS__'),
|
|
503
|
+
playgroundTitle: props.templatePlaygroundTitle?.trim() || 'Module Federation Playground',
|
|
504
|
+
runtimeFileBaseName: getTemplateFileBaseName(runtimeFileName),
|
|
505
|
+
runtimeFileName,
|
|
506
|
+
runtimeGlobalName: normalizeIdentifier(props.templateRuntimeGlobalName, 'ModuleFederationRuntime'),
|
|
507
|
+
runtimeImportName,
|
|
508
|
+
runtimeInstanceName: normalizeIdentifier(props.templateRuntimeInstanceName, 'moduleFederationInstance'),
|
|
509
|
+
runtimePackageName: props.templateRuntimePackageName?.trim() || '@module-federation/runtime',
|
|
510
|
+
runtimeVariableName: normalizeIdentifier(props.templateRuntimeVariableName, 'moduleFederation')
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
function getPlaygroundDefaults(props) {
|
|
514
|
+
return {
|
|
515
|
+
autoRun: props.autoRun ?? false,
|
|
516
|
+
defaultExpose: props.defaultExpose ?? '',
|
|
517
|
+
defaultExportName: props.defaultExportName ?? 'default',
|
|
518
|
+
defaultManifestUrl: props.defaultManifestUrl ?? DEFAULT_MANIFEST_URL,
|
|
519
|
+
defaultPreviewRoute: props.defaultPreviewRoute ?? '/',
|
|
520
|
+
monacoVsUrl: props.monacoVsUrl ?? MONACO_CDN_VS_URL,
|
|
521
|
+
reactRuntimeUrls: props.reactRuntimeUrls ?? {},
|
|
522
|
+
runtimeModuleUrl: props.runtimeModuleUrl ?? DEFAULT_RUNTIME_MODULE_URL,
|
|
523
|
+
template: getPlaygroundTemplate(props)
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function getReactRuntimeUrl(pkg, version, reactRuntimeUrls) {
|
|
527
|
+
if ('react' === pkg) return reactRuntimeUrls.react || `https://unpkg.com/react@${version}/umd/react.development.js`;
|
|
528
|
+
return reactRuntimeUrls.reactDom || `https://unpkg.com/react-dom@${version}/umd/react-dom.development.js`;
|
|
529
|
+
}
|
|
530
|
+
function normalizeDependencyVersion(version) {
|
|
531
|
+
return version.trim().replace(/^[~^<>=\s]+/, '').split(' ')[0] || version.trim();
|
|
532
|
+
}
|
|
533
|
+
function getFirstSearchParam(searchParams, keys) {
|
|
534
|
+
for (const key of keys){
|
|
535
|
+
const value = searchParams.get(key)?.trim();
|
|
536
|
+
if (value) return value;
|
|
537
|
+
}
|
|
538
|
+
return '';
|
|
539
|
+
}
|
|
540
|
+
function hasSearchParam(searchParams, keys) {
|
|
541
|
+
return keys.some((key)=>searchParams.has(key));
|
|
542
|
+
}
|
|
543
|
+
function getInitialQueryConfig(defaults) {
|
|
544
|
+
if ('undefined' == typeof window) return {
|
|
545
|
+
autoRun: defaults.autoRun,
|
|
546
|
+
expose: defaults.defaultExpose,
|
|
547
|
+
exportName: defaults.defaultExportName,
|
|
548
|
+
manifestUrl: defaults.defaultManifestUrl,
|
|
549
|
+
previewRoute: defaults.defaultPreviewRoute
|
|
550
|
+
};
|
|
551
|
+
const searchParams = new URLSearchParams(window.location.search);
|
|
552
|
+
const manifestFromQuery = getFirstSearchParam(searchParams, MANIFEST_QUERY_KEYS);
|
|
553
|
+
const exposeFromQuery = getFirstSearchParam(searchParams, EXPOSE_QUERY_KEYS);
|
|
554
|
+
const exportFromQuery = getFirstSearchParam(searchParams, EXPORT_QUERY_KEYS);
|
|
555
|
+
const previewRouteFromQuery = getFirstSearchParam(searchParams, PREVIEW_ROUTE_QUERY_KEYS);
|
|
556
|
+
return {
|
|
557
|
+
autoRun: hasSearchParam(searchParams, AUTO_RUN_QUERY_KEYS) || defaults.autoRun,
|
|
558
|
+
expose: exposeFromQuery || defaults.defaultExpose,
|
|
559
|
+
exportName: exportFromQuery || defaults.defaultExportName,
|
|
560
|
+
manifestUrl: manifestFromQuery || defaults.defaultManifestUrl,
|
|
561
|
+
previewRoute: previewRouteFromQuery || defaults.defaultPreviewRoute
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
const DEFAULT_ENTRY_CODE = `import App from './app';
|
|
565
|
+
import React from 'react';
|
|
566
|
+
import { createRoot } from 'react-dom/client';
|
|
567
|
+
|
|
568
|
+
const container = document.getElementById('root');
|
|
569
|
+
|
|
570
|
+
if (!container) {
|
|
571
|
+
throw new Error('Preview root not found.');
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
createRoot(container).render(
|
|
575
|
+
React.createElement(App),
|
|
576
|
+
);
|
|
577
|
+
`;
|
|
578
|
+
const APP_LOADED_TARGET_PLACEHOLDER = '__LOADED_TARGET__';
|
|
579
|
+
function getReactMajor(version) {
|
|
580
|
+
const match = version.trim().match(/^(\d+)/);
|
|
581
|
+
return match ? Number(match[1]) : 19;
|
|
582
|
+
}
|
|
583
|
+
function getBridgeProviderImportPath(reactVersion) {
|
|
584
|
+
const major = getReactMajor(reactVersion);
|
|
585
|
+
if (major >= 19) return '@module-federation/bridge-react/v19';
|
|
586
|
+
if (major >= 18) return '@module-federation/bridge-react/v18';
|
|
587
|
+
return '@module-federation/bridge-react';
|
|
588
|
+
}
|
|
589
|
+
function isBridgeAppExpose(expose) {
|
|
590
|
+
return 'export-app' === normalizeExpose(expose);
|
|
591
|
+
}
|
|
592
|
+
function buildDefaultComponentAppCode(loadedTarget, exportName, template) {
|
|
593
|
+
const safeLoadedTarget = loadedTarget.trim() || APP_LOADED_TARGET_PLACEHOLDER;
|
|
594
|
+
const safeExportName = exportName.trim() || 'default';
|
|
595
|
+
return `import React from 'react';
|
|
596
|
+
import { ${template.runtimeImportName} } from './${template.runtimeFileBaseName}';
|
|
597
|
+
|
|
598
|
+
const loadedTargetLabel = ${JSON.stringify(safeLoadedTarget)};
|
|
599
|
+
|
|
600
|
+
export default function App() {
|
|
601
|
+
const RemoteComponent = React.useMemo(
|
|
602
|
+
() =>
|
|
603
|
+
React.lazy(async () => {
|
|
604
|
+
const ${template.runtimeVariableName} = await ${template.runtimeImportName}();
|
|
605
|
+
const module = await ${template.runtimeVariableName}.loadRemote(${JSON.stringify(safeLoadedTarget)});
|
|
606
|
+
return { default: module?.[${JSON.stringify(safeExportName)}] };
|
|
607
|
+
}),
|
|
608
|
+
[],
|
|
609
|
+
);
|
|
610
|
+
|
|
611
|
+
return (
|
|
612
|
+
<div style={{ display: 'grid', gap: 16 }}>
|
|
613
|
+
<React.Suspense fallback={<div>Loading remote module...</div>}>
|
|
614
|
+
<RemoteComponent
|
|
615
|
+
title=${JSON.stringify(template.playgroundTitle)}
|
|
616
|
+
/>
|
|
617
|
+
</React.Suspense>
|
|
618
|
+
</div>
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
`;
|
|
622
|
+
}
|
|
623
|
+
function buildDefaultBridgeAppCode(loadedTarget, exportName, template) {
|
|
624
|
+
const safeLoadedTarget = loadedTarget.trim() || APP_LOADED_TARGET_PLACEHOLDER;
|
|
625
|
+
const safeExportName = exportName.trim() || 'default';
|
|
626
|
+
return `import React from 'react';
|
|
627
|
+
import { createRemoteAppComponent, ${template.runtimeImportName} } from './${template.runtimeFileBaseName}';
|
|
628
|
+
|
|
629
|
+
const loadedTargetLabel = ${JSON.stringify(safeLoadedTarget)};
|
|
630
|
+
|
|
631
|
+
const RemoteApp = createRemoteAppComponent({
|
|
632
|
+
loader: async () => {
|
|
633
|
+
const ${template.runtimeVariableName} = await ${template.runtimeImportName}();
|
|
634
|
+
return ${template.runtimeVariableName}.loadRemote(${JSON.stringify(safeLoadedTarget)});
|
|
635
|
+
},
|
|
636
|
+
export: ${JSON.stringify(safeExportName)},
|
|
637
|
+
loading: (
|
|
638
|
+
<div style={{ padding: 16, fontSize: 13, opacity: 0.72 }}>
|
|
639
|
+
Loading remote app...
|
|
640
|
+
</div>
|
|
641
|
+
),
|
|
642
|
+
fallback: ({ error }) => (
|
|
643
|
+
<div
|
|
644
|
+
style={{
|
|
645
|
+
padding: 16,
|
|
646
|
+
borderRadius: 12,
|
|
647
|
+
border: '1px solid rgba(255, 90, 90, 0.24)',
|
|
648
|
+
background: 'rgba(255, 90, 90, 0.08)',
|
|
649
|
+
color: '#c53b3b',
|
|
650
|
+
fontSize: 13,
|
|
651
|
+
}}
|
|
652
|
+
>
|
|
653
|
+
{error?.message || 'Failed to load remote app.'}
|
|
654
|
+
</div>
|
|
655
|
+
),
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
export default function App() {
|
|
659
|
+
return (
|
|
660
|
+
<div style={{ display: 'grid', gap: 16 }}>
|
|
661
|
+
<RemoteApp basename="/" />
|
|
662
|
+
</div>
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
`;
|
|
666
|
+
}
|
|
667
|
+
function buildDefaultAppCode(loadedTarget, exportName, expose, _reactVersion, template) {
|
|
668
|
+
if (isBridgeAppExpose(expose)) return buildDefaultBridgeAppCode(loadedTarget, exportName, template);
|
|
669
|
+
return buildDefaultComponentAppCode(loadedTarget, exportName, template);
|
|
670
|
+
}
|
|
671
|
+
const MF_MANIFEST_PLACEHOLDER = '__MANIFEST_URL__';
|
|
672
|
+
const MF_REMOTE_NAME_PLACEHOLDER = '__REMOTE_NAME__';
|
|
673
|
+
function buildDefaultMfCode(manifestUrl, remoteName, reactVersions, template) {
|
|
674
|
+
const safeManifestUrl = manifestUrl.trim() || MF_MANIFEST_PLACEHOLDER;
|
|
675
|
+
const safeRemoteName = remoteName.trim() || MF_REMOTE_NAME_PLACEHOLDER;
|
|
676
|
+
const safeReactVersion = reactVersions.react?.trim() || DEFAULT_REACT_VERSION;
|
|
677
|
+
const safeReactDomClientVersion = reactVersions['react-dom/client']?.trim() || reactVersions['react-dom']?.trim() || safeReactVersion;
|
|
678
|
+
const bridgeProviderImportPath = getBridgeProviderImportPath(safeReactVersion);
|
|
679
|
+
return `import React from 'react';
|
|
680
|
+
import * as ReactDOMClient from 'react-dom/client';
|
|
681
|
+
import { createInstance } from ${JSON.stringify(template.runtimePackageName)};
|
|
682
|
+
|
|
683
|
+
const PLAYGROUND_NAME = ${JSON.stringify(template.playgroundName)};
|
|
684
|
+
const manifestUrl = ${JSON.stringify(safeManifestUrl)};
|
|
685
|
+
const remoteName = ${JSON.stringify(safeRemoteName)};
|
|
686
|
+
const reactVersion = ${JSON.stringify(safeReactVersion)};
|
|
687
|
+
const reactDomClientVersion = ${JSON.stringify(safeReactDomClientVersion)};
|
|
688
|
+
|
|
689
|
+
let ${template.runtimeInstanceName} = null;
|
|
690
|
+
|
|
691
|
+
// The playground bundles the bridge runtime into the sandbox.
|
|
692
|
+
// In a real host, import createRemoteAppComponent from '${template.bridgePackageName}'.
|
|
693
|
+
// React version differences mainly affect the producer-side createBridgeComponent import:
|
|
694
|
+
// current react version: ${safeReactVersion}
|
|
695
|
+
// producer-side import: ${bridgeProviderImportPath}
|
|
696
|
+
import { createRemoteAppComponent as createBridgeRemoteAppComponent } from './bridge/index.es.js';
|
|
697
|
+
|
|
698
|
+
function normalizePlaygroundRoute(route) {
|
|
699
|
+
const normalizedRoute = typeof route === 'string' ? route.trim() : '';
|
|
700
|
+
|
|
701
|
+
if (!normalizedRoute || /^[a-z][a-z\\d+.-]*:/i.test(normalizedRoute)) {
|
|
702
|
+
return '/';
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
return normalizedRoute.startsWith('/') ? normalizedRoute : \`/\${normalizedRoute}\`;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function getPlaygroundRoute() {
|
|
709
|
+
return normalizePlaygroundRoute(window[${JSON.stringify(template.playgroundPropsGlobalName)}]?.previewRoute);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export function createRemoteAppComponent(options) {
|
|
713
|
+
const RemoteApp = createBridgeRemoteAppComponent(options);
|
|
714
|
+
|
|
715
|
+
return React.forwardRef((props, ref) => {
|
|
716
|
+
const previewRoute = getPlaygroundRoute();
|
|
717
|
+
const propsWithRoute = {
|
|
718
|
+
...props,
|
|
719
|
+
ref,
|
|
720
|
+
basename:
|
|
721
|
+
props?.basename && props.basename !== '/' ? props.basename : previewRoute,
|
|
722
|
+
memoryRoute: props?.memoryRoute || { entryPath: previewRoute },
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
return React.createElement(RemoteApp, propsWithRoute);
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function createShared() {
|
|
730
|
+
return {
|
|
731
|
+
react: {
|
|
732
|
+
version: reactVersion,
|
|
733
|
+
scope: 'default',
|
|
734
|
+
lib: () => React,
|
|
735
|
+
shareConfig: {
|
|
736
|
+
singleton: true,
|
|
737
|
+
requiredVersion: reactVersion,
|
|
738
|
+
fixedDependencies: false,
|
|
739
|
+
},
|
|
740
|
+
},
|
|
741
|
+
'react/': {
|
|
742
|
+
version: reactVersion,
|
|
743
|
+
scope: 'default',
|
|
744
|
+
lib: () => React,
|
|
745
|
+
shareConfig: {
|
|
746
|
+
singleton: true,
|
|
747
|
+
requiredVersion: reactVersion,
|
|
748
|
+
fixedDependencies: false,
|
|
749
|
+
},
|
|
750
|
+
},
|
|
751
|
+
'react-dom/client': {
|
|
752
|
+
version: reactDomClientVersion,
|
|
753
|
+
scope: 'default',
|
|
754
|
+
lib: () => ReactDOMClient,
|
|
755
|
+
shareConfig: {
|
|
756
|
+
singleton: true,
|
|
757
|
+
requiredVersion: reactDomClientVersion,
|
|
758
|
+
fixedDependencies: false,
|
|
759
|
+
},
|
|
760
|
+
},
|
|
761
|
+
'react-dom': {
|
|
762
|
+
version: reactDomClientVersion,
|
|
763
|
+
scope: 'default',
|
|
764
|
+
lib: () => ReactDOMClient,
|
|
765
|
+
shareConfig: {
|
|
766
|
+
singleton: true,
|
|
767
|
+
requiredVersion: reactDomClientVersion,
|
|
768
|
+
fixedDependencies: false,
|
|
769
|
+
},
|
|
770
|
+
},
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
export async function ${template.runtimeImportName}() {
|
|
775
|
+
if (manifestUrl === ${JSON.stringify(MF_MANIFEST_PLACEHOLDER)}) {
|
|
776
|
+
throw new Error('manifestUrl is not resolved yet. Run Sandbox first.');
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
if (remoteName === ${JSON.stringify(MF_REMOTE_NAME_PLACEHOLDER)}) {
|
|
780
|
+
throw new Error('remoteName is not resolved yet. Run Sandbox first.');
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
if (${template.runtimeInstanceName}) {
|
|
784
|
+
return ${template.runtimeInstanceName};
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
${template.runtimeInstanceName} = createInstance({
|
|
788
|
+
name: PLAYGROUND_NAME,
|
|
789
|
+
remotes: [
|
|
790
|
+
{
|
|
791
|
+
name: remoteName,
|
|
792
|
+
entry: manifestUrl,
|
|
793
|
+
},
|
|
794
|
+
],
|
|
795
|
+
shared: createShared(),
|
|
796
|
+
});
|
|
797
|
+
|
|
798
|
+
return ${template.runtimeInstanceName};
|
|
799
|
+
}
|
|
800
|
+
`;
|
|
801
|
+
}
|
|
802
|
+
function buildDefaultRspackConfigCode(template) {
|
|
803
|
+
return `// Only used to show the browser sandbox shape. Configure your real bundler as needed.
|
|
804
|
+
export default {
|
|
805
|
+
mode: 'development',
|
|
806
|
+
entry: './entry.ts',
|
|
807
|
+
devtool: false,
|
|
808
|
+
externalsType: 'window',
|
|
809
|
+
lazyCompilation: false,
|
|
810
|
+
externals: {
|
|
811
|
+
react: 'React',
|
|
812
|
+
'react-dom': 'ReactDOM',
|
|
813
|
+
'react-dom/client': 'ReactDOM',
|
|
814
|
+
${JSON.stringify(template.runtimePackageName)}: ${JSON.stringify(template.runtimeGlobalName)},
|
|
815
|
+
},
|
|
816
|
+
target: ['web', 'es2020'],
|
|
817
|
+
output: {
|
|
818
|
+
path: '/dist',
|
|
819
|
+
filename: 'app.js',
|
|
820
|
+
},
|
|
821
|
+
resolve: {
|
|
822
|
+
extensions: ['.tsx', '.ts', '.jsx', '.js'],
|
|
823
|
+
},
|
|
824
|
+
module: {
|
|
825
|
+
rules: [
|
|
826
|
+
{
|
|
827
|
+
test: /\\.[jt]sx?$/,
|
|
828
|
+
type: 'javascript/auto',
|
|
829
|
+
use: {
|
|
830
|
+
loader: 'builtin:swc-loader',
|
|
831
|
+
options: {
|
|
832
|
+
jsc: {
|
|
833
|
+
parser: {
|
|
834
|
+
syntax: 'typescript',
|
|
835
|
+
tsx: true,
|
|
836
|
+
},
|
|
837
|
+
transform: {
|
|
838
|
+
react: {
|
|
839
|
+
runtime: 'classic',
|
|
840
|
+
},
|
|
841
|
+
},
|
|
842
|
+
},
|
|
843
|
+
},
|
|
844
|
+
},
|
|
845
|
+
},
|
|
846
|
+
],
|
|
847
|
+
},
|
|
848
|
+
experiments: {
|
|
849
|
+
buildHttp: {
|
|
850
|
+
allowedUris: ['https://'],
|
|
851
|
+
},
|
|
852
|
+
useInputFileSystem: [/.*/],
|
|
853
|
+
},
|
|
854
|
+
plugins: [
|
|
855
|
+
new BrowserHttpImportEsmPlugin({
|
|
856
|
+
domain: 'https://esm.sh',
|
|
857
|
+
dependencyVersions: {},
|
|
858
|
+
postprocess: (request) => {
|
|
859
|
+
if (
|
|
860
|
+
request.packageName === 'react' ||
|
|
861
|
+
request.packageName === 'react-dom' ||
|
|
862
|
+
request.packageName === 'react-dom/client' ||
|
|
863
|
+
request.packageName === ${JSON.stringify(template.runtimePackageName)}
|
|
864
|
+
) {
|
|
865
|
+
return null;
|
|
866
|
+
}
|
|
867
|
+
return request;
|
|
868
|
+
}
|
|
869
|
+
}),
|
|
870
|
+
],
|
|
871
|
+
};
|
|
872
|
+
`;
|
|
873
|
+
}
|
|
874
|
+
const FILE_TABS = [
|
|
875
|
+
{
|
|
876
|
+
key: 'app.tsx',
|
|
877
|
+
copyKey: 'app-code',
|
|
878
|
+
copyMessage: '已复制 app.tsx 到剪贴板',
|
|
879
|
+
placeholder: 'export default function App(...) { ... }'
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
key: 'entry.ts',
|
|
883
|
+
copyKey: 'entry-code',
|
|
884
|
+
copyMessage: '已复制 entry.ts 到剪贴板',
|
|
885
|
+
placeholder: "import App from './app';"
|
|
886
|
+
},
|
|
887
|
+
{
|
|
888
|
+
key: 'runtime',
|
|
889
|
+
copyKey: 'runtime-code',
|
|
890
|
+
copyMessage: '已复制 runtime.ts 到剪贴板',
|
|
891
|
+
placeholder: 'export async function getRuntimeInstance(...) { ... }'
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
key: 'rspack.config.mjs',
|
|
895
|
+
copyKey: 'rspack-config',
|
|
896
|
+
copyMessage: '已复制 rspack.config.mjs 到剪贴板',
|
|
897
|
+
placeholder: 'export default { ... }'
|
|
898
|
+
}
|
|
899
|
+
];
|
|
900
|
+
function getFileTabs(template) {
|
|
901
|
+
return FILE_TABS.map((item)=>'runtime' === item.key ? {
|
|
902
|
+
...item,
|
|
903
|
+
copyMessage: `已复制 ${template.runtimeFileName} 到剪贴板`,
|
|
904
|
+
label: template.runtimeFileName,
|
|
905
|
+
placeholder: `export async function ${template.runtimeImportName}(...) { ... }`
|
|
906
|
+
} : item);
|
|
907
|
+
}
|
|
908
|
+
function getEditorLanguage(file) {
|
|
909
|
+
if ('app.tsx' === file) return "typescript";
|
|
910
|
+
if ('entry.ts' === file || 'runtime' === file) return "typescript";
|
|
911
|
+
if (file.endsWith('.mjs')) return "javascript";
|
|
912
|
+
return 'plaintext';
|
|
913
|
+
}
|
|
914
|
+
function EditorLoadingState() {
|
|
915
|
+
return /*#__PURE__*/ jsx("div", {
|
|
916
|
+
className: cx('vp-loadingSimple'),
|
|
917
|
+
children: /*#__PURE__*/ jsx("span", {
|
|
918
|
+
className: cx('vp-loadingSpinner'),
|
|
919
|
+
"aria-hidden": "true"
|
|
920
|
+
})
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
function getEditorTheme() {
|
|
924
|
+
if ('undefined' == typeof document) return 'vs-dark';
|
|
925
|
+
const root = document.documentElement;
|
|
926
|
+
return root.classList.contains('dark') || root.classList.contains('rp-dark') ? 'vs-dark' : 'vs';
|
|
927
|
+
}
|
|
928
|
+
function getDocumentLocale() {
|
|
929
|
+
if ('undefined' == typeof document) return 'zh';
|
|
930
|
+
const lang = document.documentElement.lang || ('undefined' != typeof navigator ? navigator.language : '') || 'zh';
|
|
931
|
+
return lang.toLowerCase().startsWith('en') ? 'en' : 'zh';
|
|
932
|
+
}
|
|
933
|
+
function useEditorTheme() {
|
|
934
|
+
const [theme, setTheme] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(getEditorTheme);
|
|
935
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
936
|
+
if ('undefined' == typeof document) return;
|
|
937
|
+
const root = document.documentElement;
|
|
938
|
+
const observer = new MutationObserver(()=>{
|
|
939
|
+
setTheme(getEditorTheme());
|
|
940
|
+
});
|
|
941
|
+
observer.observe(root, {
|
|
942
|
+
attributeFilter: [
|
|
943
|
+
'class'
|
|
944
|
+
],
|
|
945
|
+
attributes: true
|
|
946
|
+
});
|
|
947
|
+
return ()=>observer.disconnect();
|
|
948
|
+
}, []);
|
|
949
|
+
return theme;
|
|
950
|
+
}
|
|
951
|
+
function useLocale() {
|
|
952
|
+
const [locale, setLocale] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(getDocumentLocale);
|
|
953
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
954
|
+
if ('undefined' == typeof document) return;
|
|
955
|
+
const observer = new MutationObserver(()=>{
|
|
956
|
+
setLocale(getDocumentLocale());
|
|
957
|
+
});
|
|
958
|
+
observer.observe(document.documentElement, {
|
|
959
|
+
attributeFilter: [
|
|
960
|
+
'lang'
|
|
961
|
+
],
|
|
962
|
+
attributes: true
|
|
963
|
+
});
|
|
964
|
+
return ()=>observer.disconnect();
|
|
965
|
+
}, []);
|
|
966
|
+
return locale;
|
|
967
|
+
}
|
|
968
|
+
function getEditorPath(file, template) {
|
|
969
|
+
if ('rspack.config.mjs' === file) return `file:///${file}`;
|
|
970
|
+
if ('runtime' === file) return `file:///src/${template.runtimeFileName}`;
|
|
971
|
+
return `file:///src/${file}`;
|
|
972
|
+
}
|
|
973
|
+
function configureEditor(monaco, template) {
|
|
974
|
+
const localTypes = {
|
|
975
|
+
'file:///node_modules/@types/react/index.d.ts': `
|
|
976
|
+
declare module 'react' {
|
|
977
|
+
const React: any;
|
|
978
|
+
export default React;
|
|
979
|
+
}
|
|
980
|
+
`,
|
|
981
|
+
'file:///node_modules/@types/react-dom/client.d.ts': `
|
|
982
|
+
declare module 'react-dom/client' {
|
|
983
|
+
export function createRoot(container: Element | DocumentFragment): {
|
|
984
|
+
render(children: any): void;
|
|
985
|
+
unmount(): void;
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
`,
|
|
989
|
+
[`file:///src/${template.runtimeFileBaseName}.d.ts`]: `
|
|
990
|
+
export function createRemoteAppComponent(options: {
|
|
991
|
+
export?: string;
|
|
992
|
+
fallback?: (context: { error?: Error | null }) => any;
|
|
993
|
+
loader: () => Promise<any>;
|
|
994
|
+
loading?: any;
|
|
995
|
+
}): any;
|
|
996
|
+
export function ${template.runtimeImportName}(): Promise<{
|
|
997
|
+
loadRemote(request: string): Promise<any>;
|
|
998
|
+
}>;
|
|
999
|
+
`,
|
|
1000
|
+
'file:///src/app.d.ts': `
|
|
1001
|
+
const App: any;
|
|
1002
|
+
export default App;
|
|
1003
|
+
`,
|
|
1004
|
+
'file:///src/globals.d.ts': `
|
|
1005
|
+
declare global {
|
|
1006
|
+
interface Window {
|
|
1007
|
+
${template.playgroundPropsGlobalName}?: any;
|
|
1008
|
+
${template.runtimeGlobalName}?: {
|
|
1009
|
+
createInstance?: (...args: any[]) => any;
|
|
1010
|
+
};
|
|
1011
|
+
ModuleFederationRuntime?: {
|
|
1012
|
+
createInstance?: (...args: any[]) => any;
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
export {};
|
|
1017
|
+
`
|
|
1018
|
+
};
|
|
1019
|
+
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
|
|
1020
|
+
allowJs: true,
|
|
1021
|
+
allowNonTsExtensions: true,
|
|
1022
|
+
esModuleInterop: true,
|
|
1023
|
+
jsx: monaco.languages.typescript.JsxEmit.React,
|
|
1024
|
+
module: monaco.languages.typescript.ModuleKind.ESNext,
|
|
1025
|
+
moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
|
|
1026
|
+
noImplicitAny: false,
|
|
1027
|
+
noEmit: true,
|
|
1028
|
+
strict: false,
|
|
1029
|
+
target: monaco.languages.typescript.ScriptTarget.ES2020
|
|
1030
|
+
});
|
|
1031
|
+
for (const [path, content] of Object.entries(localTypes)){
|
|
1032
|
+
monaco.languages.typescript.typescriptDefaults.addExtraLib(content, path);
|
|
1033
|
+
monaco.languages.typescript.javascriptDefaults.addExtraLib(content, path);
|
|
1034
|
+
}
|
|
1035
|
+
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
|
|
1036
|
+
noSemanticValidation: false,
|
|
1037
|
+
noSyntaxValidation: false
|
|
1038
|
+
});
|
|
1039
|
+
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
|
1040
|
+
noSemanticValidation: false,
|
|
1041
|
+
noSyntaxValidation: false
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
function syncEditorModels(monaco, files, template) {
|
|
1045
|
+
for (const [file, value] of Object.entries(files)){
|
|
1046
|
+
const uri = monaco.Uri.parse(getEditorPath(file, template));
|
|
1047
|
+
const model = monaco.editor.getModel(uri);
|
|
1048
|
+
if (model) {
|
|
1049
|
+
if (model.getValue() !== value) model.setValue(value);
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
monaco.editor.createModel(value, getEditorLanguage(file), uri);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
function extractSharedDependencyVersions(manifest) {
|
|
1056
|
+
const shared = manifest.shared;
|
|
1057
|
+
if (!shared) return {};
|
|
1058
|
+
if (Array.isArray(shared)) return shared.reduce((acc, item)=>{
|
|
1059
|
+
if (item && 'object' == typeof item && 'name' in item && 'string' == typeof item.name) {
|
|
1060
|
+
const resolvedVersion = ('version' in item && 'string' == typeof item.version ? item.version : 'requiredVersion' in item && 'string' == typeof item.requiredVersion ? normalizeDependencyVersion(item.requiredVersion) : '') || '';
|
|
1061
|
+
if (resolvedVersion) acc[item.name] = resolvedVersion;
|
|
1062
|
+
}
|
|
1063
|
+
return acc;
|
|
1064
|
+
}, {});
|
|
1065
|
+
if ('object' == typeof shared) return Object.entries(shared).reduce((acc, [name, value])=>{
|
|
1066
|
+
if (value && 'object' == typeof value) {
|
|
1067
|
+
const resolvedVersion = ('version' in value && 'string' == typeof value.version ? value.version : 'requiredVersion' in value && 'string' == typeof value.requiredVersion ? normalizeDependencyVersion(value.requiredVersion) : '') || '';
|
|
1068
|
+
if (resolvedVersion) acc[name] = resolvedVersion;
|
|
1069
|
+
}
|
|
1070
|
+
return acc;
|
|
1071
|
+
}, {});
|
|
1072
|
+
return {};
|
|
1073
|
+
}
|
|
1074
|
+
function extractReactDependencyVersions(manifest) {
|
|
1075
|
+
const sharedVersions = extractSharedDependencyVersions(manifest);
|
|
1076
|
+
const reactVersion = sharedVersions.react || sharedVersions['react/'] || DEFAULT_REACT_VERSION;
|
|
1077
|
+
const reactDomVersion = sharedVersions['react-dom'] || reactVersion;
|
|
1078
|
+
const reactDomClientVersion = sharedVersions['react-dom/client'] || reactDomVersion || reactVersion;
|
|
1079
|
+
return {
|
|
1080
|
+
react: reactVersion,
|
|
1081
|
+
'react-dom/client': reactDomClientVersion
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
function updateDependencyVersionsInRspackConfig(configCode, _versions) {
|
|
1085
|
+
return configCode;
|
|
1086
|
+
}
|
|
1087
|
+
function getDefaultReactDependencyVersions() {
|
|
1088
|
+
return {
|
|
1089
|
+
react: DEFAULT_REACT_VERSION,
|
|
1090
|
+
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
function escapeInlineScript(source) {
|
|
1094
|
+
return source.replace(/<\/script/gi, "<\\/script");
|
|
1095
|
+
}
|
|
1096
|
+
function normalizePreviewRoute(route) {
|
|
1097
|
+
const trimmedRoute = route.trim();
|
|
1098
|
+
if (!trimmedRoute) return '/';
|
|
1099
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(trimmedRoute)) return '/';
|
|
1100
|
+
return trimmedRoute.startsWith('/') ? trimmedRoute : `/${trimmedRoute}`;
|
|
1101
|
+
}
|
|
1102
|
+
function resolveExposeFromOptions(exposeOptions, requestedExpose) {
|
|
1103
|
+
const trimmedExpose = requestedExpose.trim();
|
|
1104
|
+
if (!trimmedExpose) return exposeOptions[0] || '';
|
|
1105
|
+
const exactMatch = exposeOptions.find((item)=>item === trimmedExpose);
|
|
1106
|
+
if (exactMatch) return exactMatch;
|
|
1107
|
+
const normalizedRequestedExpose = normalizeExpose(trimmedExpose);
|
|
1108
|
+
const normalizedMatch = exposeOptions.find((item)=>normalizeExpose(item) === normalizedRequestedExpose);
|
|
1109
|
+
if (normalizedMatch) return normalizedMatch;
|
|
1110
|
+
return trimmedExpose;
|
|
1111
|
+
}
|
|
1112
|
+
function normalizeTerminalLevel(level) {
|
|
1113
|
+
if ('warn' === level || 'info' === level) return level;
|
|
1114
|
+
return 'error';
|
|
1115
|
+
}
|
|
1116
|
+
function formatErrorForTerminal(error) {
|
|
1117
|
+
return error instanceof Error ? error.stack || error.message : String(error);
|
|
1118
|
+
}
|
|
1119
|
+
function buildPreviewDocument(previewState, defaults) {
|
|
1120
|
+
const reactDependencyVersions = previewState.manifest ? extractReactDependencyVersions(previewState.manifest) : getDefaultReactDependencyVersions();
|
|
1121
|
+
const reactVersion = reactDependencyVersions.react || DEFAULT_REACT_VERSION;
|
|
1122
|
+
const reactDomVersion = reactDependencyVersions['react-dom/client'] || reactDependencyVersions['react-dom'] || reactVersion;
|
|
1123
|
+
const reactMajor = getReactMajor(reactVersion);
|
|
1124
|
+
const previewRoute = normalizePreviewRoute(previewState.previewRoute);
|
|
1125
|
+
const props = JSON.stringify({
|
|
1126
|
+
expose: previewState.expose,
|
|
1127
|
+
loadedTarget: previewState.loadedTarget,
|
|
1128
|
+
manifest: previewState.manifest,
|
|
1129
|
+
manifestUrl: previewState.manifestUrl,
|
|
1130
|
+
previewRoute
|
|
1131
|
+
});
|
|
1132
|
+
const bundle = escapeInlineScript(previewState.bundle);
|
|
1133
|
+
const dependencyInjection = reactMajor >= 19 ? `<script>
|
|
1134
|
+
if (!window.parent?.__MF_PLAYGROUND_HOST_REACT__ || !window.parent?.__MF_PLAYGROUND_HOST_REACT_DOM__) {
|
|
1135
|
+
throw new Error('Host React runtime is not available.');
|
|
1136
|
+
}
|
|
1137
|
+
window.React = window.parent.__MF_PLAYGROUND_HOST_REACT__;
|
|
1138
|
+
window.ReactDOM = window.parent.__MF_PLAYGROUND_HOST_REACT_DOM__;
|
|
1139
|
+
</script>` : `<script src="${getReactRuntimeUrl('react', reactVersion, defaults.reactRuntimeUrls)}"></script>
|
|
1140
|
+
<script src="${getReactRuntimeUrl('react-dom', reactDomVersion, defaults.reactRuntimeUrls)}"></script>`;
|
|
1141
|
+
return `<!doctype html>
|
|
1142
|
+
<html>
|
|
1143
|
+
<head>
|
|
1144
|
+
<meta charset="utf-8" />
|
|
1145
|
+
<style>
|
|
1146
|
+
html, body, #root {
|
|
1147
|
+
height: 100%;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
html {
|
|
1151
|
+
background: var(--mf-preview-bg, transparent) !important;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
body {
|
|
1155
|
+
margin: 0;
|
|
1156
|
+
padding: 12px;
|
|
1157
|
+
box-sizing: border-box;
|
|
1158
|
+
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
1159
|
+
background: var(--mf-preview-bg, transparent) !important;
|
|
1160
|
+
color: var(--mf-preview-text, #e5eef7);
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
#root {
|
|
1164
|
+
background: transparent !important;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
pre {
|
|
1168
|
+
white-space: pre-wrap;
|
|
1169
|
+
word-break: break-word;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
#mf-error {
|
|
1173
|
+
display: none;
|
|
1174
|
+
margin-bottom: 12px;
|
|
1175
|
+
padding: 12px;
|
|
1176
|
+
border-radius: 12px;
|
|
1177
|
+
background: rgba(255, 90, 90, 0.12);
|
|
1178
|
+
border: 1px solid rgba(255, 90, 90, 0.24);
|
|
1179
|
+
color: #ffd7d7;
|
|
1180
|
+
font-size: 12px;
|
|
1181
|
+
}
|
|
1182
|
+
</style>
|
|
1183
|
+
</head>
|
|
1184
|
+
<body>
|
|
1185
|
+
<div id="mf-error"></div>
|
|
1186
|
+
<div id="root"></div>
|
|
1187
|
+
${dependencyInjection}
|
|
1188
|
+
<script>
|
|
1189
|
+
window.__MF_PLAYGROUND_PROPS__ = ${props};
|
|
1190
|
+
const parentStyles = window.parent?.getComputedStyle?.(window.parent.document.body);
|
|
1191
|
+
if (parentStyles) {
|
|
1192
|
+
document.documentElement.style.setProperty('--mf-preview-bg', parentStyles.background);
|
|
1193
|
+
document.documentElement.style.setProperty('--mf-preview-text', parentStyles.color);
|
|
1194
|
+
}
|
|
1195
|
+
const postTerminal = (level, message) => {
|
|
1196
|
+
window.parent?.postMessage({
|
|
1197
|
+
type: 'mf-playground-terminal',
|
|
1198
|
+
runId: ${previewState.runId},
|
|
1199
|
+
level,
|
|
1200
|
+
message: String(message || ''),
|
|
1201
|
+
}, '*');
|
|
1202
|
+
};
|
|
1203
|
+
const patchPreviewRouterSource = (source) => {
|
|
1204
|
+
const previewEntry = 'window.__MF_PLAYGROUND_PROPS__?.previewRoute || "/"';
|
|
1205
|
+
return source
|
|
1206
|
+
.replace(
|
|
1207
|
+
/history: createBrowserHistory\\(\\{\\s*window: opts === null \\|\\| opts === void 0 \\? void 0 : opts\\.window\\s*\\}\\),/g,
|
|
1208
|
+
\`history: createMemoryHistory({
|
|
1209
|
+
initialEntries: [\${previewEntry}],
|
|
1210
|
+
v5Compat: true
|
|
1211
|
+
}),\`
|
|
1212
|
+
)
|
|
1213
|
+
.replace(
|
|
1214
|
+
/historyRef\\.current = createBrowserHistory\\(\\{\\s*window: window2,\\s*v5Compat: true\\s*\\}\\);/g,
|
|
1215
|
+
\`historyRef.current = createMemoryHistory({
|
|
1216
|
+
initialEntries: [\${previewEntry}],
|
|
1217
|
+
v5Compat: true
|
|
1218
|
+
});\`
|
|
1219
|
+
);
|
|
1220
|
+
};
|
|
1221
|
+
const installPreviewRouterPatch = () => {
|
|
1222
|
+
const originalAppendChild = HTMLHeadElement.prototype.appendChild;
|
|
1223
|
+
|
|
1224
|
+
HTMLHeadElement.prototype.appendChild = function appendChildWithRouterPatch(node) {
|
|
1225
|
+
if (
|
|
1226
|
+
node instanceof HTMLScriptElement &&
|
|
1227
|
+
node.src &&
|
|
1228
|
+
!node.src.startsWith('blob:')
|
|
1229
|
+
) {
|
|
1230
|
+
const originalSrc = node.src;
|
|
1231
|
+
|
|
1232
|
+
fetch(originalSrc)
|
|
1233
|
+
.then((response) => {
|
|
1234
|
+
if (!response.ok) {
|
|
1235
|
+
throw new Error(\`HTTP \${response.status}\`);
|
|
1236
|
+
}
|
|
1237
|
+
return response.text();
|
|
1238
|
+
})
|
|
1239
|
+
.then((source) => {
|
|
1240
|
+
const patchedSource = patchPreviewRouterSource(source);
|
|
1241
|
+
if (patchedSource === source) {
|
|
1242
|
+
node.src = originalSrc;
|
|
1243
|
+
} else {
|
|
1244
|
+
node.src = URL.createObjectURL(
|
|
1245
|
+
new Blob([patchedSource], { type: 'text/javascript' })
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
originalAppendChild.call(this, node);
|
|
1249
|
+
})
|
|
1250
|
+
.catch((error) => {
|
|
1251
|
+
node.src = originalSrc;
|
|
1252
|
+
originalAppendChild.call(this, node);
|
|
1253
|
+
postTerminal(
|
|
1254
|
+
'warn',
|
|
1255
|
+
\`Preview router patch skipped for \${originalSrc}: \${error?.message || String(error)}\`
|
|
1256
|
+
);
|
|
1257
|
+
});
|
|
1258
|
+
|
|
1259
|
+
return node;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
return originalAppendChild.call(this, node);
|
|
1263
|
+
};
|
|
1264
|
+
};
|
|
1265
|
+
const patchHistoryForSrcdoc = () => {
|
|
1266
|
+
if (window.location.protocol !== 'about:') {
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
const wrap = (method) => {
|
|
1271
|
+
const original = window.history[method].bind(window.history);
|
|
1272
|
+
window.history[method] = (state, unused, url) => {
|
|
1273
|
+
try {
|
|
1274
|
+
return original(state, unused, url);
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
if (!(error instanceof DOMException) || error.name !== 'SecurityError') {
|
|
1277
|
+
throw error;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
const fallbackState =
|
|
1281
|
+
url == null
|
|
1282
|
+
? state
|
|
1283
|
+
: {
|
|
1284
|
+
...(state && typeof state === 'object' ? state : {}),
|
|
1285
|
+
__mfPreviewUrl: String(url),
|
|
1286
|
+
};
|
|
1287
|
+
|
|
1288
|
+
postTerminal(
|
|
1289
|
+
'warn',
|
|
1290
|
+
\`Preview router fallback applied for \${method}: \${String(url || '')}\`
|
|
1291
|
+
);
|
|
1292
|
+
|
|
1293
|
+
return original(fallbackState, unused, window.location.href);
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
};
|
|
1297
|
+
|
|
1298
|
+
wrap('pushState');
|
|
1299
|
+
wrap('replaceState');
|
|
1300
|
+
};
|
|
1301
|
+
installPreviewRouterPatch();
|
|
1302
|
+
patchHistoryForSrcdoc();
|
|
1303
|
+
const formatTerminalValue = (value) => {
|
|
1304
|
+
if (value instanceof Error) {
|
|
1305
|
+
return value.stack || value.message;
|
|
1306
|
+
}
|
|
1307
|
+
if (typeof value === 'object' && value !== null) {
|
|
1308
|
+
try {
|
|
1309
|
+
return JSON.stringify(value, null, 2);
|
|
1310
|
+
} catch {
|
|
1311
|
+
return String(value);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
return String(value);
|
|
1315
|
+
};
|
|
1316
|
+
for (const method of ['error', 'warn']) {
|
|
1317
|
+
const original = console[method];
|
|
1318
|
+
console[method] = (...args) => {
|
|
1319
|
+
postTerminal(method, args.map(formatTerminalValue).join(' '));
|
|
1320
|
+
original.apply(console, args);
|
|
1321
|
+
};
|
|
1322
|
+
}
|
|
1323
|
+
const errorBox = document.getElementById('mf-error');
|
|
1324
|
+
const showError = (value) => {
|
|
1325
|
+
if (!errorBox) return;
|
|
1326
|
+
errorBox.style.display = 'block';
|
|
1327
|
+
errorBox.textContent = value;
|
|
1328
|
+
postTerminal('error', value);
|
|
1329
|
+
};
|
|
1330
|
+
window.addEventListener('error', (event) => {
|
|
1331
|
+
showError(event.error?.stack || event.message || String(event.error));
|
|
1332
|
+
});
|
|
1333
|
+
window.addEventListener('unhandledrejection', (event) => {
|
|
1334
|
+
const reason = event.reason;
|
|
1335
|
+
showError(reason?.stack || reason?.message || String(reason));
|
|
1336
|
+
});
|
|
1337
|
+
</script>
|
|
1338
|
+
<script>${bundle}</script>
|
|
1339
|
+
</body>
|
|
1340
|
+
</html>`;
|
|
1341
|
+
}
|
|
1342
|
+
class RenderErrorBoundary extends __WEBPACK_EXTERNAL_MODULE_react__.Component {
|
|
1343
|
+
static getDerivedStateFromError(error) {
|
|
1344
|
+
return {
|
|
1345
|
+
error: {
|
|
1346
|
+
message: error.message
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
componentDidCatch(error, info) {
|
|
1351
|
+
this.props.onError?.({
|
|
1352
|
+
message: error.message,
|
|
1353
|
+
componentStack: info.componentStack
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
render() {
|
|
1357
|
+
if (this.state.error) return /*#__PURE__*/ jsxs("div", {
|
|
1358
|
+
className: cx('vp-errorPanel'),
|
|
1359
|
+
children: [
|
|
1360
|
+
/*#__PURE__*/ jsx("div", {
|
|
1361
|
+
className: cx('vp-errorTitle'),
|
|
1362
|
+
children: "Render Error"
|
|
1363
|
+
}),
|
|
1364
|
+
/*#__PURE__*/ jsx("pre", {
|
|
1365
|
+
className: cx('vp-codeBlock'),
|
|
1366
|
+
children: this.state.error.message
|
|
1367
|
+
})
|
|
1368
|
+
]
|
|
1369
|
+
});
|
|
1370
|
+
return this.props.children;
|
|
1371
|
+
}
|
|
1372
|
+
constructor(...args){
|
|
1373
|
+
super(...args), this.state = {
|
|
1374
|
+
error: null
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
function AppInner(props) {
|
|
1379
|
+
const { defaults } = props;
|
|
1380
|
+
const initialQueryConfig = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>getInitialQueryConfig(defaults), [
|
|
1381
|
+
defaults
|
|
1382
|
+
]);
|
|
1383
|
+
const template = defaults.template;
|
|
1384
|
+
const initialGeneratedAppCode = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>buildDefaultAppCode('', 'default', '', DEFAULT_REACT_VERSION, template), [
|
|
1385
|
+
template
|
|
1386
|
+
]);
|
|
1387
|
+
const initialGeneratedMfCode = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>buildDefaultMfCode('', '', {
|
|
1388
|
+
react: DEFAULT_REACT_VERSION,
|
|
1389
|
+
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1390
|
+
}, template), [
|
|
1391
|
+
template
|
|
1392
|
+
]);
|
|
1393
|
+
const [manifestUrl, setManifestUrl] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialQueryConfig.manifestUrl);
|
|
1394
|
+
const [exposeOptions, setExposeOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
|
|
1395
|
+
const [expose, setExpose] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialQueryConfig.expose);
|
|
1396
|
+
const [exportName, setExportName] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialQueryConfig.exportName);
|
|
1397
|
+
const [previewRoute, setPreviewRoute] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialQueryConfig.previewRoute);
|
|
1398
|
+
const [entryCode, setEntryCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(DEFAULT_ENTRY_CODE);
|
|
1399
|
+
const [appCode, setAppCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialGeneratedAppCode);
|
|
1400
|
+
const [lastGeneratedAppCode, setLastGeneratedAppCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialGeneratedAppCode);
|
|
1401
|
+
const [mfCode, setMfCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialGeneratedMfCode);
|
|
1402
|
+
const [lastGeneratedMfCode, setLastGeneratedMfCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(initialGeneratedMfCode);
|
|
1403
|
+
const [rspackConfigCode, setRspackConfigCode] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(()=>buildDefaultRspackConfigCode(template));
|
|
1404
|
+
const [openPanels, setOpenPanels] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({
|
|
1405
|
+
control: true,
|
|
1406
|
+
code: false
|
|
1407
|
+
});
|
|
1408
|
+
const [leftPaneWidth, setLeftPaneWidth] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(DEFAULT_LEFT_PANE_WIDTH);
|
|
1409
|
+
const [isDesktopLayout, setIsDesktopLayout] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(()=>'undefined' == typeof window || window.innerWidth > 980);
|
|
1410
|
+
const [activeFile, setActiveFile] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)('app.tsx');
|
|
1411
|
+
const [status, setStatus] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)('');
|
|
1412
|
+
const [isResolvingExpose, setIsResolvingExpose] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
|
|
1413
|
+
const [copiedKey, setCopiedKey] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)('');
|
|
1414
|
+
const [resolvedManifest, setResolvedManifest] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(null);
|
|
1415
|
+
const [previewState, setPreviewState] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(null);
|
|
1416
|
+
const [renderError, setRenderError] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(null);
|
|
1417
|
+
const [terminalLines, setTerminalLines] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([
|
|
1418
|
+
{
|
|
1419
|
+
id: 0,
|
|
1420
|
+
level: 'info',
|
|
1421
|
+
message: 'Terminal ready. Compile and runtime errors will appear here after Run Sandbox.'
|
|
1422
|
+
}
|
|
1423
|
+
]);
|
|
1424
|
+
const [runId, setRunId] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(0);
|
|
1425
|
+
const runIdRef = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(runId);
|
|
1426
|
+
const autoRunStartedRef = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(false);
|
|
1427
|
+
const onRunRef = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(null);
|
|
1428
|
+
const monacoRef = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(null);
|
|
1429
|
+
const resizeStateRef = (0, __WEBPACK_EXTERNAL_MODULE_react__.useRef)(null);
|
|
1430
|
+
const editorFiles = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>({
|
|
1431
|
+
'app.tsx': appCode,
|
|
1432
|
+
'entry.ts': entryCode,
|
|
1433
|
+
runtime: mfCode,
|
|
1434
|
+
'rspack.config.mjs': rspackConfigCode
|
|
1435
|
+
}), [
|
|
1436
|
+
appCode,
|
|
1437
|
+
entryCode,
|
|
1438
|
+
mfCode,
|
|
1439
|
+
rspackConfigCode
|
|
1440
|
+
]);
|
|
1441
|
+
const fileTabs = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>getFileTabs(template), [
|
|
1442
|
+
template
|
|
1443
|
+
]);
|
|
1444
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1445
|
+
loader.config({
|
|
1446
|
+
paths: {
|
|
1447
|
+
vs: defaults.monacoVsUrl
|
|
1448
|
+
}
|
|
1449
|
+
});
|
|
1450
|
+
}, [
|
|
1451
|
+
defaults.monacoVsUrl
|
|
1452
|
+
]);
|
|
1453
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1454
|
+
if (monacoRef.current) syncEditorModels(monacoRef.current, editorFiles, template);
|
|
1455
|
+
}, [
|
|
1456
|
+
editorFiles,
|
|
1457
|
+
template
|
|
1458
|
+
]);
|
|
1459
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1460
|
+
runIdRef.current = runId;
|
|
1461
|
+
}, [
|
|
1462
|
+
runId
|
|
1463
|
+
]);
|
|
1464
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1465
|
+
if ('undefined' == typeof window) return;
|
|
1466
|
+
const handleResize = ()=>{
|
|
1467
|
+
const nextIsDesktop = window.innerWidth > 980;
|
|
1468
|
+
setIsDesktopLayout(nextIsDesktop);
|
|
1469
|
+
if (!nextIsDesktop) {
|
|
1470
|
+
resizeStateRef.current = null;
|
|
1471
|
+
setLeftPaneWidth(DEFAULT_LEFT_PANE_WIDTH);
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
handleResize();
|
|
1475
|
+
window.addEventListener('resize', handleResize);
|
|
1476
|
+
return ()=>window.removeEventListener('resize', handleResize);
|
|
1477
|
+
}, []);
|
|
1478
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1479
|
+
if ('undefined' == typeof window) return;
|
|
1480
|
+
window.__MF_PLAYGROUND_HOST_REACT__ = __WEBPACK_EXTERNAL_MODULE_react__;
|
|
1481
|
+
window.__MF_PLAYGROUND_HOST_REACT_DOM__ = {
|
|
1482
|
+
...__WEBPACK_EXTERNAL_MODULE_react_dom_7136dc57__,
|
|
1483
|
+
...__WEBPACK_EXTERNAL_MODULE_react_dom_client_76b1397c__
|
|
1484
|
+
};
|
|
1485
|
+
}, []);
|
|
1486
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1487
|
+
if (!isDesktopLayout || 'undefined' == typeof window) return;
|
|
1488
|
+
const handleMouseMove = (event)=>{
|
|
1489
|
+
const resizeState = resizeStateRef.current;
|
|
1490
|
+
if (!resizeState) return;
|
|
1491
|
+
const viewportWidth = window.innerWidth || 1;
|
|
1492
|
+
const deltaRatio = (event.clientX - resizeState.startX) / viewportWidth * 100;
|
|
1493
|
+
const nextWidth = Math.min(MAX_LEFT_PANE_WIDTH, Math.max(MIN_LEFT_PANE_WIDTH, resizeState.startWidth + deltaRatio));
|
|
1494
|
+
setLeftPaneWidth(nextWidth);
|
|
1495
|
+
};
|
|
1496
|
+
const handleMouseUp = ()=>{
|
|
1497
|
+
resizeStateRef.current = null;
|
|
1498
|
+
};
|
|
1499
|
+
window.addEventListener('mousemove', handleMouseMove);
|
|
1500
|
+
window.addEventListener('mouseup', handleMouseUp);
|
|
1501
|
+
return ()=>{
|
|
1502
|
+
window.removeEventListener('mousemove', handleMouseMove);
|
|
1503
|
+
window.removeEventListener('mouseup', handleMouseUp);
|
|
1504
|
+
};
|
|
1505
|
+
}, [
|
|
1506
|
+
isDesktopLayout
|
|
1507
|
+
]);
|
|
1508
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1509
|
+
const onMessage = (event)=>{
|
|
1510
|
+
const data = event.data;
|
|
1511
|
+
if (!data || 'mf-playground-terminal' !== data.type || data.runId !== runIdRef.current) return;
|
|
1512
|
+
setTerminalLines((currentLines)=>[
|
|
1513
|
+
...currentLines,
|
|
1514
|
+
{
|
|
1515
|
+
id: Date.now() + Math.random(),
|
|
1516
|
+
level: normalizeTerminalLevel(data.level),
|
|
1517
|
+
message: String(data.message || '')
|
|
1518
|
+
}
|
|
1519
|
+
].slice(-120));
|
|
1520
|
+
};
|
|
1521
|
+
window.addEventListener('message', onMessage);
|
|
1522
|
+
return ()=>window.removeEventListener('message', onMessage);
|
|
1523
|
+
}, []);
|
|
1524
|
+
const appendTerminalLine = (level, message)=>{
|
|
1525
|
+
setTerminalLines((currentLines)=>[
|
|
1526
|
+
...currentLines,
|
|
1527
|
+
{
|
|
1528
|
+
id: Date.now() + Math.random(),
|
|
1529
|
+
level,
|
|
1530
|
+
message
|
|
1531
|
+
}
|
|
1532
|
+
].slice(-120));
|
|
1533
|
+
};
|
|
1534
|
+
const manifestName = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
|
|
1535
|
+
if (!resolvedManifest) return '';
|
|
1536
|
+
return resolvedManifest.metaData?.name || resolvedManifest.name || resolvedManifest.id || '';
|
|
1537
|
+
}, [
|
|
1538
|
+
resolvedManifest
|
|
1539
|
+
]);
|
|
1540
|
+
const syncGeneratedAppCode = (nextManifest, nextExpose, nextExportName)=>{
|
|
1541
|
+
const reactVersion = nextManifest ? extractReactDependencyVersions(nextManifest).react : DEFAULT_REACT_VERSION;
|
|
1542
|
+
if (!nextManifest) {
|
|
1543
|
+
const placeholderCode = buildDefaultAppCode('', nextExportName, nextExpose, reactVersion, template);
|
|
1544
|
+
setAppCode((currentCode)=>currentCode === lastGeneratedAppCode ? placeholderCode : currentCode);
|
|
1545
|
+
setLastGeneratedAppCode(placeholderCode);
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
const resolvedRemoteName = guessRemoteName(nextManifest).trim();
|
|
1549
|
+
const nextLoadedTarget = formatLoadedTarget(resolvedRemoteName, normalizeExpose(nextExpose));
|
|
1550
|
+
const nextCode = buildDefaultAppCode(nextLoadedTarget, nextExportName, nextExpose, reactVersion, template);
|
|
1551
|
+
setAppCode((currentCode)=>currentCode === lastGeneratedAppCode ? nextCode : currentCode);
|
|
1552
|
+
setLastGeneratedAppCode(nextCode);
|
|
1553
|
+
};
|
|
1554
|
+
const syncGeneratedMfCode = (nextManifestUrl, nextManifest)=>{
|
|
1555
|
+
if (!nextManifest) return;
|
|
1556
|
+
const resolvedRemoteName = guessRemoteName(nextManifest).trim();
|
|
1557
|
+
const reactDependencyVersions = extractReactDependencyVersions(nextManifest);
|
|
1558
|
+
const nextCode = buildDefaultMfCode(nextManifestUrl, resolvedRemoteName, reactDependencyVersions, template);
|
|
1559
|
+
setMfCode((currentCode)=>currentCode === lastGeneratedMfCode ? nextCode : currentCode);
|
|
1560
|
+
setLastGeneratedMfCode(nextCode);
|
|
1561
|
+
};
|
|
1562
|
+
const syncGeneratedMfPlaceholder = ()=>{
|
|
1563
|
+
const nextCode = buildDefaultMfCode('', '', {
|
|
1564
|
+
react: DEFAULT_REACT_VERSION,
|
|
1565
|
+
'react-dom/client': DEFAULT_REACT_VERSION
|
|
1566
|
+
}, template);
|
|
1567
|
+
setMfCode((currentCode)=>currentCode === lastGeneratedMfCode ? nextCode : currentCode);
|
|
1568
|
+
setLastGeneratedMfCode(nextCode);
|
|
1569
|
+
};
|
|
1570
|
+
const onManifestReady = async (options)=>{
|
|
1571
|
+
const appendTerminal = options?.appendTerminal ?? true;
|
|
1572
|
+
const silentStatus = options?.silentStatus ?? false;
|
|
1573
|
+
const nextManifestUrl = manifestUrl.trim();
|
|
1574
|
+
if (!nextManifestUrl) {
|
|
1575
|
+
setResolvedManifest(null);
|
|
1576
|
+
setExposeOptions([]);
|
|
1577
|
+
setExpose('');
|
|
1578
|
+
setOpenPanels((current)=>({
|
|
1579
|
+
...current,
|
|
1580
|
+
code: false
|
|
1581
|
+
}));
|
|
1582
|
+
syncGeneratedAppCode(null, '', exportName);
|
|
1583
|
+
syncGeneratedMfPlaceholder();
|
|
1584
|
+
throw new Error(isEn ? 'Manifest URL is required before running the sandbox.' : '运行前请先填写 Manifest URL。');
|
|
1585
|
+
}
|
|
1586
|
+
setIsResolvingExpose(true);
|
|
1587
|
+
if (!silentStatus) setStatus(isEn ? 'Resolving manifest...' : '解析 Manifest 中...');
|
|
1588
|
+
if (appendTerminal) appendTerminalLine('info', `Resolving manifest: ${nextManifestUrl}`);
|
|
1589
|
+
try {
|
|
1590
|
+
const manifest = await fetchManifest(nextManifestUrl);
|
|
1591
|
+
const options = manifest.exposes?.map((item)=>item?.name?.trim()).filter((item)=>Boolean(item)) || [];
|
|
1592
|
+
const effectiveExpose = resolveExposeFromOptions(options, expose);
|
|
1593
|
+
setResolvedManifest(manifest);
|
|
1594
|
+
setExposeOptions(options);
|
|
1595
|
+
const reactDependencyVersions = extractReactDependencyVersions(manifest);
|
|
1596
|
+
const dependencyVersions = {
|
|
1597
|
+
...reactDependencyVersions
|
|
1598
|
+
};
|
|
1599
|
+
setRspackConfigCode((currentCode)=>updateDependencyVersionsInRspackConfig(currentCode, dependencyVersions));
|
|
1600
|
+
syncGeneratedAppCode(manifest, effectiveExpose, exportName);
|
|
1601
|
+
syncGeneratedMfCode(nextManifestUrl, manifest);
|
|
1602
|
+
setExpose(effectiveExpose);
|
|
1603
|
+
setOpenPanels((current)=>({
|
|
1604
|
+
...current,
|
|
1605
|
+
code: true
|
|
1606
|
+
}));
|
|
1607
|
+
if (!silentStatus) setStatus(options.length > 0 ? isEn ? `Loaded ${options.length} expose entries` : `已加载 ${options.length} 个 expose` : isEn ? 'No exposes found in manifest' : 'Manifest 未提供 expose');
|
|
1608
|
+
return manifest;
|
|
1609
|
+
} catch (error) {
|
|
1610
|
+
const message = formatErrorForTerminal(error);
|
|
1611
|
+
setResolvedManifest(null);
|
|
1612
|
+
setExposeOptions([]);
|
|
1613
|
+
setExpose('');
|
|
1614
|
+
setOpenPanels((current)=>({
|
|
1615
|
+
...current,
|
|
1616
|
+
code: false
|
|
1617
|
+
}));
|
|
1618
|
+
setStatus(error instanceof Error ? error.message : String(error));
|
|
1619
|
+
syncGeneratedAppCode(null, '', exportName);
|
|
1620
|
+
syncGeneratedMfPlaceholder();
|
|
1621
|
+
if (appendTerminal) appendTerminalLine('error', `Resolve manifest failed:\n${message}`);
|
|
1622
|
+
throw error;
|
|
1623
|
+
} finally{
|
|
1624
|
+
setIsResolvingExpose(false);
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
const onRun = async ()=>{
|
|
1628
|
+
setPreviewState(null);
|
|
1629
|
+
setRenderError(null);
|
|
1630
|
+
setStatus('编译中...');
|
|
1631
|
+
setTerminalLines([
|
|
1632
|
+
{
|
|
1633
|
+
id: Date.now(),
|
|
1634
|
+
level: 'info',
|
|
1635
|
+
message: 'Compiling sandbox...'
|
|
1636
|
+
}
|
|
1637
|
+
]);
|
|
1638
|
+
try {
|
|
1639
|
+
const normalizedManifestUrl = manifestUrl.trim();
|
|
1640
|
+
const manifestForRun = await onManifestReady({
|
|
1641
|
+
appendTerminal: false,
|
|
1642
|
+
silentStatus: true
|
|
1643
|
+
});
|
|
1644
|
+
const reactDependencyVersions = manifestForRun ? extractReactDependencyVersions(manifestForRun) : getDefaultReactDependencyVersions();
|
|
1645
|
+
const dependencyVersions = {
|
|
1646
|
+
...reactDependencyVersions
|
|
1647
|
+
};
|
|
1648
|
+
const nextRspackConfigCode = updateDependencyVersionsInRspackConfig(rspackConfigCode, dependencyVersions);
|
|
1649
|
+
if (nextRspackConfigCode !== rspackConfigCode) setRspackConfigCode(nextRspackConfigCode);
|
|
1650
|
+
const remoteNameForRun = manifestForRun ? guessRemoteName(manifestForRun) : manifestName || normalizedManifestUrl || 'remote';
|
|
1651
|
+
const nextExposeForRun = normalizeExpose(expose || manifestForRun?.exposes?.[0]?.name || '');
|
|
1652
|
+
const nextGeneratedAppCode = buildDefaultAppCode(formatLoadedTarget(remoteNameForRun, nextExposeForRun), exportName, nextExposeForRun, reactDependencyVersions.react, template);
|
|
1653
|
+
const nextGeneratedMfCode = buildDefaultMfCode(normalizedManifestUrl, remoteNameForRun, reactDependencyVersions, template);
|
|
1654
|
+
const nextAppCode = appCode === lastGeneratedAppCode ? nextGeneratedAppCode : appCode;
|
|
1655
|
+
const nextMfCode = mfCode === lastGeneratedMfCode ? nextGeneratedMfCode : mfCode;
|
|
1656
|
+
if (nextGeneratedAppCode !== lastGeneratedAppCode) setLastGeneratedAppCode(nextGeneratedAppCode);
|
|
1657
|
+
if (nextAppCode !== appCode) setAppCode(nextAppCode);
|
|
1658
|
+
if (nextGeneratedMfCode !== lastGeneratedMfCode) setLastGeneratedMfCode(nextGeneratedMfCode);
|
|
1659
|
+
if (nextMfCode !== mfCode) setMfCode(nextMfCode);
|
|
1660
|
+
const bundle = await compilePlaygroundApp({
|
|
1661
|
+
appCode: nextAppCode,
|
|
1662
|
+
entryCode,
|
|
1663
|
+
mfCode: nextMfCode,
|
|
1664
|
+
runtimeModuleUrl: defaults.runtimeModuleUrl,
|
|
1665
|
+
runtimeFileName: template.runtimeFileName,
|
|
1666
|
+
runtimeGlobalName: template.runtimeGlobalName,
|
|
1667
|
+
runtimePackageName: template.runtimePackageName,
|
|
1668
|
+
rspackConfigCode: nextRspackConfigCode
|
|
1669
|
+
});
|
|
1670
|
+
const normalizedCurrentExpose = nextExposeForRun;
|
|
1671
|
+
const loadedTarget = formatLoadedTarget(remoteNameForRun, normalizedCurrentExpose);
|
|
1672
|
+
const nextRunId = runId + 1;
|
|
1673
|
+
runIdRef.current = nextRunId;
|
|
1674
|
+
setRunId(nextRunId);
|
|
1675
|
+
setPreviewState({
|
|
1676
|
+
kind: 'consumer',
|
|
1677
|
+
bundle,
|
|
1678
|
+
loadedTarget,
|
|
1679
|
+
manifest: manifestForRun,
|
|
1680
|
+
manifestUrl: normalizedManifestUrl,
|
|
1681
|
+
expose: normalizedCurrentExpose,
|
|
1682
|
+
previewRoute: normalizePreviewRoute(previewRoute),
|
|
1683
|
+
runtimeModuleUrl: defaults.runtimeModuleUrl,
|
|
1684
|
+
runId: nextRunId
|
|
1685
|
+
});
|
|
1686
|
+
setStatus('完成');
|
|
1687
|
+
appendTerminalLine('info', 'Sandbox bundle compiled. Preview is running.');
|
|
1688
|
+
} catch (error) {
|
|
1689
|
+
const message = formatErrorForTerminal(error);
|
|
1690
|
+
setStatus(error instanceof Error ? error.message : String(error));
|
|
1691
|
+
appendTerminalLine('error', `Run Sandbox failed:\n${message}`);
|
|
1692
|
+
}
|
|
1693
|
+
};
|
|
1694
|
+
onRunRef.current = onRun;
|
|
1695
|
+
(0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
|
|
1696
|
+
if (!initialQueryConfig.autoRun || autoRunStartedRef.current) return;
|
|
1697
|
+
autoRunStartedRef.current = true;
|
|
1698
|
+
onRunRef.current?.();
|
|
1699
|
+
}, [
|
|
1700
|
+
initialQueryConfig.autoRun
|
|
1701
|
+
]);
|
|
1702
|
+
const copyText = async (key, text, okMsg)=>{
|
|
1703
|
+
try {
|
|
1704
|
+
await navigator.clipboard.writeText(text);
|
|
1705
|
+
setCopiedKey(key);
|
|
1706
|
+
setStatus(okMsg);
|
|
1707
|
+
window.setTimeout(()=>setCopiedKey(''), 1000);
|
|
1708
|
+
} catch {
|
|
1709
|
+
setStatus('复制失败:浏览器不支持 clipboard API(可手动复制)');
|
|
1710
|
+
}
|
|
1711
|
+
};
|
|
1712
|
+
const CopyButton = (props)=>{
|
|
1713
|
+
const { copyKey, label, okMsg, text } = props;
|
|
1714
|
+
const done = copiedKey === copyKey;
|
|
1715
|
+
return /*#__PURE__*/ jsxs("button", {
|
|
1716
|
+
type: "button",
|
|
1717
|
+
className: cx('vp-copyBtn'),
|
|
1718
|
+
onClick: ()=>void copyText(copyKey, text, okMsg),
|
|
1719
|
+
title: done ? 'Copied' : 'Copy',
|
|
1720
|
+
children: [
|
|
1721
|
+
/*#__PURE__*/ jsxs("svg", {
|
|
1722
|
+
"aria-hidden": "true",
|
|
1723
|
+
className: cx('vp-copyIcon'),
|
|
1724
|
+
viewBox: "0 0 24 24",
|
|
1725
|
+
fill: "none",
|
|
1726
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
1727
|
+
children: [
|
|
1728
|
+
/*#__PURE__*/ jsx("path", {
|
|
1729
|
+
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",
|
|
1730
|
+
stroke: "currentColor",
|
|
1731
|
+
strokeWidth: "1.6"
|
|
1732
|
+
}),
|
|
1733
|
+
/*#__PURE__*/ jsx("path", {
|
|
1734
|
+
d: "M5 9.5C5 8.119 6.119 7 7.5 7H8",
|
|
1735
|
+
stroke: "currentColor",
|
|
1736
|
+
strokeWidth: "1.6",
|
|
1737
|
+
strokeLinecap: "round"
|
|
1738
|
+
}),
|
|
1739
|
+
/*#__PURE__*/ jsx("path", {
|
|
1740
|
+
d: "M5 18.5C5 19.881 6.119 21 7.5 21H15c1.381 0 2.5-1.119 2.5-2.5V18",
|
|
1741
|
+
stroke: "currentColor",
|
|
1742
|
+
strokeWidth: "1.6",
|
|
1743
|
+
strokeLinecap: "round"
|
|
1744
|
+
})
|
|
1745
|
+
]
|
|
1746
|
+
}),
|
|
1747
|
+
/*#__PURE__*/ jsx("span", {
|
|
1748
|
+
children: done ? 'Copied' : label || 'Copy'
|
|
1749
|
+
})
|
|
1750
|
+
]
|
|
1751
|
+
});
|
|
1752
|
+
};
|
|
1753
|
+
const renderPreview = ()=>{
|
|
1754
|
+
if (!previewState) return /*#__PURE__*/ jsxs("div", {
|
|
1755
|
+
className: cx('vp-empty'),
|
|
1756
|
+
children: [
|
|
1757
|
+
/*#__PURE__*/ jsx("div", {
|
|
1758
|
+
className: cx('vp-emptyTitle'),
|
|
1759
|
+
children: "Ready."
|
|
1760
|
+
}),
|
|
1761
|
+
/*#__PURE__*/ jsx("div", {
|
|
1762
|
+
children: isEn ? '1. Fill in the Manifest URL first.' : '1. 先填写 Manifest URL。'
|
|
1763
|
+
}),
|
|
1764
|
+
/*#__PURE__*/ jsx("div", {
|
|
1765
|
+
children: isEn ? '2. Click Run Sandbox. It resolves the manifest first, then starts the preview if everything is valid.' : '2. 点击 Run Sandbox。它会先解析 Manifest,没问题再启动右侧预览。'
|
|
1766
|
+
}),
|
|
1767
|
+
/*#__PURE__*/ jsx("div", {
|
|
1768
|
+
children: isEn ? '3. If manifest parsing fails, check the terminal below for the exact error.' : '3. 如果 Manifest 解析失败,直接看下方 Terminal 里的具体报错。'
|
|
1769
|
+
}),
|
|
1770
|
+
/*#__PURE__*/ jsx("div", {
|
|
1771
|
+
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 成功后才会出现并加载。'
|
|
1772
|
+
})
|
|
1773
|
+
]
|
|
1774
|
+
});
|
|
1775
|
+
if ('consumer' === previewState.kind) {
|
|
1776
|
+
const { expose: currentExpose, runId: currentRunId } = previewState;
|
|
1777
|
+
return /*#__PURE__*/ jsxs("div", {
|
|
1778
|
+
children: [
|
|
1779
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1780
|
+
className: cx('vp-kv'),
|
|
1781
|
+
children: [
|
|
1782
|
+
"Target:",
|
|
1783
|
+
' ',
|
|
1784
|
+
formatLoadedTarget(manifestName || 'remote', currentExpose)
|
|
1785
|
+
]
|
|
1786
|
+
}),
|
|
1787
|
+
/*#__PURE__*/ jsx("div", {
|
|
1788
|
+
className: cx('vp-renderArea'),
|
|
1789
|
+
children: /*#__PURE__*/ jsx("iframe", {
|
|
1790
|
+
className: cx('vp-previewFrame'),
|
|
1791
|
+
title: "Sandbox Preview",
|
|
1792
|
+
srcDoc: buildPreviewDocument(previewState, defaults)
|
|
1793
|
+
}, currentRunId)
|
|
1794
|
+
})
|
|
1795
|
+
]
|
|
1796
|
+
});
|
|
1797
|
+
}
|
|
1798
|
+
return null;
|
|
1799
|
+
};
|
|
1800
|
+
const renderTerminal = ()=>/*#__PURE__*/ jsxs("div", {
|
|
1801
|
+
className: cx('vp-terminal'),
|
|
1802
|
+
children: [
|
|
1803
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1804
|
+
className: cx('vp-terminalHeader'),
|
|
1805
|
+
children: [
|
|
1806
|
+
/*#__PURE__*/ jsx("span", {
|
|
1807
|
+
children: "Terminal"
|
|
1808
|
+
}),
|
|
1809
|
+
/*#__PURE__*/ jsx("button", {
|
|
1810
|
+
type: "button",
|
|
1811
|
+
className: cx('vp-terminalClear'),
|
|
1812
|
+
onClick: ()=>setTerminalLines([]),
|
|
1813
|
+
children: "Clear"
|
|
1814
|
+
})
|
|
1815
|
+
]
|
|
1816
|
+
}),
|
|
1817
|
+
/*#__PURE__*/ jsx("div", {
|
|
1818
|
+
className: cx('vp-terminalBody'),
|
|
1819
|
+
children: terminalLines.length > 0 ? terminalLines.map((line)=>/*#__PURE__*/ jsx("pre", {
|
|
1820
|
+
className: cx('vp-terminalLine', 'error' === line.level && 'vp-terminalLineError', 'warn' === line.level && 'vp-terminalLineWarn'),
|
|
1821
|
+
children: line.message
|
|
1822
|
+
}, line.id)) : /*#__PURE__*/ jsx("div", {
|
|
1823
|
+
className: cx('vp-terminalEmpty'),
|
|
1824
|
+
children: "No output."
|
|
1825
|
+
})
|
|
1826
|
+
})
|
|
1827
|
+
]
|
|
1828
|
+
});
|
|
1829
|
+
const fileState = {
|
|
1830
|
+
'app.tsx': {
|
|
1831
|
+
value: appCode,
|
|
1832
|
+
onChange: setAppCode
|
|
1833
|
+
},
|
|
1834
|
+
'entry.ts': {
|
|
1835
|
+
value: entryCode,
|
|
1836
|
+
onChange: setEntryCode
|
|
1837
|
+
},
|
|
1838
|
+
runtime: {
|
|
1839
|
+
value: mfCode,
|
|
1840
|
+
onChange: setMfCode
|
|
1841
|
+
},
|
|
1842
|
+
'rspack.config.mjs': {
|
|
1843
|
+
value: rspackConfigCode,
|
|
1844
|
+
onChange: setRspackConfigCode
|
|
1845
|
+
}
|
|
1846
|
+
};
|
|
1847
|
+
const activeTab = fileTabs.find((item)=>item.key === activeFile) || fileTabs[0];
|
|
1848
|
+
const activeEditor = fileState[activeTab.key];
|
|
1849
|
+
const editorPath = getEditorPath(activeTab.key, template);
|
|
1850
|
+
const editorTheme = useEditorTheme();
|
|
1851
|
+
const locale = useLocale();
|
|
1852
|
+
const isEn = 'en' === locale;
|
|
1853
|
+
const canShowCodePanel = Boolean(resolvedManifest);
|
|
1854
|
+
const displayStatus = renderError?.message || status || 'Idle';
|
|
1855
|
+
const visibleExposeOptions = expose && !exposeOptions.includes(expose) ? [
|
|
1856
|
+
expose,
|
|
1857
|
+
...exposeOptions
|
|
1858
|
+
] : exposeOptions;
|
|
1859
|
+
const moduleNameText = previewState?.kind === 'consumer' ? formatLoadedTarget(manifestName || 'remote', previewState.expose) : 'editor mode';
|
|
1860
|
+
const mainStyle = isDesktopLayout ? {
|
|
1861
|
+
gridTemplateColumns: `minmax(0, ${leftPaneWidth}fr) 10px minmax(0, ${100 - leftPaneWidth}fr)`
|
|
1862
|
+
} : void 0;
|
|
1863
|
+
return /*#__PURE__*/ jsx("div", {
|
|
1864
|
+
className: cx('vp-root'),
|
|
1865
|
+
children: /*#__PURE__*/ jsxs("main", {
|
|
1866
|
+
className: cx('vp-main'),
|
|
1867
|
+
style: mainStyle,
|
|
1868
|
+
children: [
|
|
1869
|
+
/*#__PURE__*/ jsx("section", {
|
|
1870
|
+
className: cx('vp-left'),
|
|
1871
|
+
children: /*#__PURE__*/ jsxs("div", {
|
|
1872
|
+
className: cx('vp-card'),
|
|
1873
|
+
children: [
|
|
1874
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1875
|
+
className: cx('vp-cardHeader'),
|
|
1876
|
+
children: [
|
|
1877
|
+
/*#__PURE__*/ jsx("div", {
|
|
1878
|
+
className: cx('vp-cardTitle'),
|
|
1879
|
+
children: "Workspace"
|
|
1880
|
+
}),
|
|
1881
|
+
/*#__PURE__*/ jsx("div", {
|
|
1882
|
+
className: cx('vp-paneActions'),
|
|
1883
|
+
children: /*#__PURE__*/ jsx("button", {
|
|
1884
|
+
type: "button",
|
|
1885
|
+
className: cx('vp-button', 'vp-buttonPrimary'),
|
|
1886
|
+
onClick: onRun,
|
|
1887
|
+
title: "Run Sandbox",
|
|
1888
|
+
children: /*#__PURE__*/ jsx("span", {
|
|
1889
|
+
children: "Run Sandbox"
|
|
1890
|
+
})
|
|
1891
|
+
})
|
|
1892
|
+
})
|
|
1893
|
+
]
|
|
1894
|
+
}),
|
|
1895
|
+
/*#__PURE__*/ jsx("div", {
|
|
1896
|
+
className: cx('vp-cardBody'),
|
|
1897
|
+
children: /*#__PURE__*/ jsxs("div", {
|
|
1898
|
+
className: cx('vp-collapse'),
|
|
1899
|
+
children: [
|
|
1900
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1901
|
+
className: cx('vp-collapseItem'),
|
|
1902
|
+
children: [
|
|
1903
|
+
/*#__PURE__*/ jsxs("button", {
|
|
1904
|
+
type: "button",
|
|
1905
|
+
className: cx('vp-collapseHeader', openPanels.control && 'vp-collapseHeaderActive'),
|
|
1906
|
+
onClick: ()=>setOpenPanels((current)=>({
|
|
1907
|
+
...current,
|
|
1908
|
+
control: !current.control
|
|
1909
|
+
})),
|
|
1910
|
+
"aria-expanded": openPanels.control,
|
|
1911
|
+
children: [
|
|
1912
|
+
/*#__PURE__*/ jsx("span", {
|
|
1913
|
+
className: cx('vp-collapseLabel'),
|
|
1914
|
+
children: "Control Panel"
|
|
1915
|
+
}),
|
|
1916
|
+
/*#__PURE__*/ jsx("span", {
|
|
1917
|
+
className: cx('vp-collapseArrow', openPanels.control && 'vp-collapseArrowOpen'),
|
|
1918
|
+
children: /*#__PURE__*/ jsx("svg", {
|
|
1919
|
+
viewBox: "0 0 16 16",
|
|
1920
|
+
fill: "none",
|
|
1921
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
1922
|
+
"aria-hidden": "true",
|
|
1923
|
+
children: /*#__PURE__*/ jsx("path", {
|
|
1924
|
+
d: "M4.5 6.5L8 10L11.5 6.5",
|
|
1925
|
+
stroke: "currentColor",
|
|
1926
|
+
strokeWidth: "1.6",
|
|
1927
|
+
strokeLinecap: "round",
|
|
1928
|
+
strokeLinejoin: "round"
|
|
1929
|
+
})
|
|
1930
|
+
})
|
|
1931
|
+
})
|
|
1932
|
+
]
|
|
1933
|
+
}),
|
|
1934
|
+
openPanels.control ? /*#__PURE__*/ jsx("div", {
|
|
1935
|
+
className: cx('vp-collapseBody'),
|
|
1936
|
+
children: /*#__PURE__*/ jsxs("div", {
|
|
1937
|
+
className: cx('vp-form'),
|
|
1938
|
+
children: [
|
|
1939
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1940
|
+
className: cx('vp-field'),
|
|
1941
|
+
children: [
|
|
1942
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1943
|
+
className: cx('vp-labelRow'),
|
|
1944
|
+
children: [
|
|
1945
|
+
/*#__PURE__*/ jsx("div", {
|
|
1946
|
+
className: cx('vp-label'),
|
|
1947
|
+
children: "Manifest URL"
|
|
1948
|
+
}),
|
|
1949
|
+
/*#__PURE__*/ jsx("div", {
|
|
1950
|
+
className: cx('vp-hint'),
|
|
1951
|
+
children: isEn ? 'Run Sandbox resolves this automatically' : '点击 Run Sandbox 时自动解析'
|
|
1952
|
+
})
|
|
1953
|
+
]
|
|
1954
|
+
}),
|
|
1955
|
+
/*#__PURE__*/ jsx("input", {
|
|
1956
|
+
className: cx('vp-input'),
|
|
1957
|
+
value: manifestUrl,
|
|
1958
|
+
onChange: (event)=>{
|
|
1959
|
+
setManifestUrl(event.target.value);
|
|
1960
|
+
setResolvedManifest(null);
|
|
1961
|
+
setExposeOptions([]);
|
|
1962
|
+
setExpose('');
|
|
1963
|
+
setOpenPanels((current)=>({
|
|
1964
|
+
...current,
|
|
1965
|
+
code: false
|
|
1966
|
+
}));
|
|
1967
|
+
syncGeneratedAppCode(null, '', exportName);
|
|
1968
|
+
syncGeneratedMfPlaceholder();
|
|
1969
|
+
},
|
|
1970
|
+
placeholder: "https://.../mf-manifest.json"
|
|
1971
|
+
})
|
|
1972
|
+
]
|
|
1973
|
+
}),
|
|
1974
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1975
|
+
className: cx('vp-fieldGrid'),
|
|
1976
|
+
children: [
|
|
1977
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1978
|
+
className: cx('vp-field'),
|
|
1979
|
+
children: [
|
|
1980
|
+
/*#__PURE__*/ jsxs("div", {
|
|
1981
|
+
className: cx('vp-labelRow'),
|
|
1982
|
+
children: [
|
|
1983
|
+
/*#__PURE__*/ jsx("div", {
|
|
1984
|
+
className: cx('vp-label'),
|
|
1985
|
+
children: "Expose"
|
|
1986
|
+
}),
|
|
1987
|
+
/*#__PURE__*/ jsx("div", {
|
|
1988
|
+
className: cx('vp-hint'),
|
|
1989
|
+
children: manifestName ? `Remote: ${manifestName}` : isEn ? 'Auto read from manifest' : '从 manifest 自动读取'
|
|
1990
|
+
})
|
|
1991
|
+
]
|
|
1992
|
+
}),
|
|
1993
|
+
/*#__PURE__*/ jsx("select", {
|
|
1994
|
+
className: cx('vp-select'),
|
|
1995
|
+
value: expose,
|
|
1996
|
+
onChange: (event)=>{
|
|
1997
|
+
const nextExpose = event.target.value;
|
|
1998
|
+
setExpose(nextExpose);
|
|
1999
|
+
syncGeneratedAppCode(resolvedManifest, nextExpose, exportName);
|
|
2000
|
+
syncGeneratedMfCode(manifestUrl.trim(), resolvedManifest);
|
|
2001
|
+
},
|
|
2002
|
+
disabled: isResolvingExpose,
|
|
2003
|
+
children: visibleExposeOptions.length > 0 ? visibleExposeOptions.map((item)=>/*#__PURE__*/ jsx("option", {
|
|
2004
|
+
value: item,
|
|
2005
|
+
children: item
|
|
2006
|
+
}, item)) : /*#__PURE__*/ jsx("option", {
|
|
2007
|
+
value: "",
|
|
2008
|
+
children: isEn ? 'Run Sandbox to load expose options' : '点击 Run Sandbox 后加载 expose'
|
|
2009
|
+
})
|
|
2010
|
+
})
|
|
2011
|
+
]
|
|
2012
|
+
}),
|
|
2013
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2014
|
+
className: cx('vp-field'),
|
|
2015
|
+
children: [
|
|
2016
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2017
|
+
className: cx('vp-labelRow'),
|
|
2018
|
+
children: [
|
|
2019
|
+
/*#__PURE__*/ jsx("div", {
|
|
2020
|
+
className: cx('vp-label'),
|
|
2021
|
+
children: "Export"
|
|
2022
|
+
}),
|
|
2023
|
+
/*#__PURE__*/ jsx("div", {
|
|
2024
|
+
className: cx('vp-hint'),
|
|
2025
|
+
children: isEn ? 'Default is default; you can switch to a named export' : '默认 default,可改成具名导出'
|
|
2026
|
+
})
|
|
2027
|
+
]
|
|
2028
|
+
}),
|
|
2029
|
+
/*#__PURE__*/ jsx("input", {
|
|
2030
|
+
className: cx('vp-input'),
|
|
2031
|
+
value: exportName,
|
|
2032
|
+
onChange: (event)=>{
|
|
2033
|
+
const nextExportName = event.target.value;
|
|
2034
|
+
setExportName(nextExportName);
|
|
2035
|
+
syncGeneratedAppCode(resolvedManifest, expose, nextExportName);
|
|
2036
|
+
syncGeneratedMfCode(manifestUrl.trim(), resolvedManifest);
|
|
2037
|
+
},
|
|
2038
|
+
placeholder: "default"
|
|
2039
|
+
})
|
|
2040
|
+
]
|
|
2041
|
+
})
|
|
2042
|
+
]
|
|
2043
|
+
}),
|
|
2044
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2045
|
+
className: cx('vp-field'),
|
|
2046
|
+
children: [
|
|
2047
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2048
|
+
className: cx('vp-labelRow'),
|
|
2049
|
+
children: [
|
|
2050
|
+
/*#__PURE__*/ jsx("div", {
|
|
2051
|
+
className: cx('vp-label'),
|
|
2052
|
+
children: "Preview Route"
|
|
2053
|
+
}),
|
|
2054
|
+
/*#__PURE__*/ jsx("div", {
|
|
2055
|
+
className: cx('vp-hint'),
|
|
2056
|
+
children: isEn ? 'Match the basename used by export-app' : '和 export-app 的 basename 保持一致'
|
|
2057
|
+
})
|
|
2058
|
+
]
|
|
2059
|
+
}),
|
|
2060
|
+
/*#__PURE__*/ jsx("input", {
|
|
2061
|
+
className: cx('vp-input'),
|
|
2062
|
+
value: previewRoute,
|
|
2063
|
+
onChange: (event)=>{
|
|
2064
|
+
setPreviewRoute(event.target.value);
|
|
2065
|
+
},
|
|
2066
|
+
placeholder: "/"
|
|
2067
|
+
})
|
|
2068
|
+
]
|
|
2069
|
+
})
|
|
2070
|
+
]
|
|
2071
|
+
})
|
|
2072
|
+
}) : null
|
|
2073
|
+
]
|
|
2074
|
+
}),
|
|
2075
|
+
canShowCodePanel ? /*#__PURE__*/ jsxs("div", {
|
|
2076
|
+
className: cx('vp-collapseItem'),
|
|
2077
|
+
children: [
|
|
2078
|
+
/*#__PURE__*/ jsxs("button", {
|
|
2079
|
+
type: "button",
|
|
2080
|
+
className: cx('vp-collapseHeader', openPanels.code && 'vp-collapseHeaderActive'),
|
|
2081
|
+
onClick: ()=>setOpenPanels((current)=>({
|
|
2082
|
+
...current,
|
|
2083
|
+
code: !current.code
|
|
2084
|
+
})),
|
|
2085
|
+
"aria-expanded": openPanels.code,
|
|
2086
|
+
children: [
|
|
2087
|
+
/*#__PURE__*/ jsx("span", {
|
|
2088
|
+
className: cx('vp-collapseLabel'),
|
|
2089
|
+
children: "Code"
|
|
2090
|
+
}),
|
|
2091
|
+
/*#__PURE__*/ jsx("span", {
|
|
2092
|
+
className: cx('vp-collapseArrow', openPanels.code && 'vp-collapseArrowOpen'),
|
|
2093
|
+
children: /*#__PURE__*/ jsx("svg", {
|
|
2094
|
+
viewBox: "0 0 16 16",
|
|
2095
|
+
fill: "none",
|
|
2096
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2097
|
+
"aria-hidden": "true",
|
|
2098
|
+
children: /*#__PURE__*/ jsx("path", {
|
|
2099
|
+
d: "M4.5 6.5L8 10L11.5 6.5",
|
|
2100
|
+
stroke: "currentColor",
|
|
2101
|
+
strokeWidth: "1.6",
|
|
2102
|
+
strokeLinecap: "round",
|
|
2103
|
+
strokeLinejoin: "round"
|
|
2104
|
+
})
|
|
2105
|
+
})
|
|
2106
|
+
})
|
|
2107
|
+
]
|
|
2108
|
+
}),
|
|
2109
|
+
openPanels.code ? /*#__PURE__*/ jsxs("div", {
|
|
2110
|
+
className: cx('vp-collapseBody', 'vp-collapseBodyCode'),
|
|
2111
|
+
children: [
|
|
2112
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2113
|
+
className: cx('vp-editorToolbar'),
|
|
2114
|
+
children: [
|
|
2115
|
+
/*#__PURE__*/ jsx("div", {
|
|
2116
|
+
className: cx('vp-editorTabs'),
|
|
2117
|
+
role: "tablist",
|
|
2118
|
+
"aria-label": "Files",
|
|
2119
|
+
children: fileTabs.map((item)=>/*#__PURE__*/ jsx("button", {
|
|
2120
|
+
type: "button",
|
|
2121
|
+
className: item.key === activeTab.key ? cx('vp-editorTab', 'vp-editorTabActive') : cx('vp-editorTab'),
|
|
2122
|
+
onClick: ()=>setActiveFile(item.key),
|
|
2123
|
+
children: item.label || item.key
|
|
2124
|
+
}, item.key))
|
|
2125
|
+
}),
|
|
2126
|
+
/*#__PURE__*/ jsx(CopyButton, {
|
|
2127
|
+
copyKey: activeTab.copyKey,
|
|
2128
|
+
label: "Copy",
|
|
2129
|
+
okMsg: activeTab.copyMessage,
|
|
2130
|
+
text: activeEditor.value
|
|
2131
|
+
})
|
|
2132
|
+
]
|
|
2133
|
+
}),
|
|
2134
|
+
/*#__PURE__*/ jsx("div", {
|
|
2135
|
+
className: cx('vp-codeEditor'),
|
|
2136
|
+
children: /*#__PURE__*/ jsx(react, {
|
|
2137
|
+
height: "100%",
|
|
2138
|
+
language: getEditorLanguage(activeTab.key),
|
|
2139
|
+
path: editorPath,
|
|
2140
|
+
theme: editorTheme,
|
|
2141
|
+
value: activeEditor.value,
|
|
2142
|
+
loading: /*#__PURE__*/ jsx(EditorLoadingState, {}),
|
|
2143
|
+
options: {
|
|
2144
|
+
automaticLayout: true,
|
|
2145
|
+
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
|
2146
|
+
fontSize: 13,
|
|
2147
|
+
lineHeight: 21,
|
|
2148
|
+
minimap: {
|
|
2149
|
+
enabled: false
|
|
2150
|
+
},
|
|
2151
|
+
padding: {
|
|
2152
|
+
top: 12,
|
|
2153
|
+
bottom: 12
|
|
2154
|
+
},
|
|
2155
|
+
scrollBeyondLastLine: false,
|
|
2156
|
+
tabSize: 2,
|
|
2157
|
+
wordWrap: 'on'
|
|
2158
|
+
},
|
|
2159
|
+
beforeMount: (monaco)=>configureEditor(monaco, template),
|
|
2160
|
+
onMount: (_, monaco)=>{
|
|
2161
|
+
monacoRef.current = monaco;
|
|
2162
|
+
syncEditorModels(monaco, editorFiles, template);
|
|
2163
|
+
},
|
|
2164
|
+
onChange: (value)=>activeEditor.onChange(value || '')
|
|
2165
|
+
}, editorPath)
|
|
2166
|
+
})
|
|
2167
|
+
]
|
|
2168
|
+
}) : null
|
|
2169
|
+
]
|
|
2170
|
+
}) : null
|
|
2171
|
+
]
|
|
2172
|
+
})
|
|
2173
|
+
})
|
|
2174
|
+
]
|
|
2175
|
+
})
|
|
2176
|
+
}),
|
|
2177
|
+
/*#__PURE__*/ jsx("div", {
|
|
2178
|
+
className: cx('vp-splitter'),
|
|
2179
|
+
"aria-hidden": "true",
|
|
2180
|
+
onMouseDown: isDesktopLayout ? (event)=>{
|
|
2181
|
+
resizeStateRef.current = {
|
|
2182
|
+
startWidth: leftPaneWidth,
|
|
2183
|
+
startX: event.clientX
|
|
2184
|
+
};
|
|
2185
|
+
} : void 0
|
|
2186
|
+
}),
|
|
2187
|
+
/*#__PURE__*/ jsx("section", {
|
|
2188
|
+
className: cx('vp-right'),
|
|
2189
|
+
children: /*#__PURE__*/ jsxs("div", {
|
|
2190
|
+
className: cx('vp-ide'),
|
|
2191
|
+
children: [
|
|
2192
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2193
|
+
className: cx('vp-ideTitlebar'),
|
|
2194
|
+
children: [
|
|
2195
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2196
|
+
className: cx('vp-ideDots'),
|
|
2197
|
+
children: [
|
|
2198
|
+
/*#__PURE__*/ jsx("span", {
|
|
2199
|
+
className: cx('vp-dot', 'vp-dotRed')
|
|
2200
|
+
}),
|
|
2201
|
+
/*#__PURE__*/ jsx("span", {
|
|
2202
|
+
className: cx('vp-dot', 'vp-dotYellow')
|
|
2203
|
+
}),
|
|
2204
|
+
/*#__PURE__*/ jsx("span", {
|
|
2205
|
+
className: cx('vp-dot', 'vp-dotGreen')
|
|
2206
|
+
})
|
|
2207
|
+
]
|
|
2208
|
+
}),
|
|
2209
|
+
/*#__PURE__*/ jsx("div", {
|
|
2210
|
+
className: cx('vp-ideTitle'),
|
|
2211
|
+
children: "Sandbox Preview"
|
|
2212
|
+
}),
|
|
2213
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2214
|
+
className: cx('vp-ideMeta'),
|
|
2215
|
+
children: [
|
|
2216
|
+
/*#__PURE__*/ jsx("span", {
|
|
2217
|
+
className: cx('vp-ideMetaText'),
|
|
2218
|
+
title: moduleNameText,
|
|
2219
|
+
children: moduleNameText
|
|
2220
|
+
}),
|
|
2221
|
+
/*#__PURE__*/ jsx("span", {
|
|
2222
|
+
className: cx('vp-ideStatus'),
|
|
2223
|
+
title: displayStatus,
|
|
2224
|
+
children: displayStatus
|
|
2225
|
+
})
|
|
2226
|
+
]
|
|
2227
|
+
})
|
|
2228
|
+
]
|
|
2229
|
+
}),
|
|
2230
|
+
/*#__PURE__*/ jsxs("div", {
|
|
2231
|
+
className: cx('vp-ideBody'),
|
|
2232
|
+
children: [
|
|
2233
|
+
renderPreview(),
|
|
2234
|
+
renderTerminal()
|
|
2235
|
+
]
|
|
2236
|
+
})
|
|
2237
|
+
]
|
|
2238
|
+
})
|
|
2239
|
+
})
|
|
2240
|
+
]
|
|
2241
|
+
})
|
|
2242
|
+
});
|
|
2243
|
+
}
|
|
2244
|
+
function App(props) {
|
|
2245
|
+
const defaults = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>getPlaygroundDefaults(props), [
|
|
2246
|
+
props
|
|
2247
|
+
]);
|
|
2248
|
+
return /*#__PURE__*/ jsx(RenderErrorBoundary, {
|
|
2249
|
+
children: /*#__PURE__*/ jsx(AppInner, {
|
|
2250
|
+
defaults: defaults
|
|
2251
|
+
})
|
|
2252
|
+
});
|
|
2253
|
+
}
|
|
2254
|
+
export { App as ModuleFederationPlayground, App as default };
|