@bleedingdev/modern-js-runtime 3.2.0-ultramodern.8 → 3.2.0-ultramodern.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/cjs/boundary-debugger/index.js +298 -0
  2. package/dist/cjs/cli/ssr/index.js +3 -2
  3. package/dist/cjs/cli/template.server.js +1 -0
  4. package/dist/cjs/core/server/federatedCss.js +47 -0
  5. package/dist/cjs/core/server/helmet.js +2 -2
  6. package/dist/cjs/core/server/stream/afterTemplate.js +9 -6
  7. package/dist/cjs/core/server/stream/beforeTemplate.js +12 -8
  8. package/dist/cjs/core/server/stream/beforeTemplate.worker.js +109 -0
  9. package/dist/cjs/core/server/stream/createReadableStream.js +4 -2
  10. package/dist/cjs/core/server/stream/createReadableStream.worker.js +4 -2
  11. package/dist/cjs/core/server/stream/shared.js +3 -1
  12. package/dist/cjs/core/server/string/index.js +3 -1
  13. package/dist/cjs/core/server/string/loadable.js +33 -7
  14. package/dist/cjs/router/cli/code/tanstackTypes.js +116 -51
  15. package/dist/cjs/router/cli/code/templates.js +1 -8
  16. package/dist/cjs/router/runtime/tanstack/plugin.js +4 -5
  17. package/dist/cjs/router/runtime/tanstack/plugin.node.js +2 -13
  18. package/dist/cjs/router/runtime/tanstack/routeTree.js +40 -4
  19. package/dist/cjs/rsc/server.worker.js +58 -0
  20. package/dist/esm/boundary-debugger/index.mjs +262 -0
  21. package/dist/esm/cli/ssr/index.mjs +3 -2
  22. package/dist/esm/cli/template.server.mjs +1 -0
  23. package/dist/esm/core/server/federatedCss.mjs +13 -0
  24. package/dist/esm/core/server/helmet.mjs +1 -1
  25. package/dist/esm/core/server/stream/afterTemplate.mjs +10 -7
  26. package/dist/esm/core/server/stream/beforeTemplate.mjs +12 -8
  27. package/dist/esm/core/server/stream/beforeTemplate.worker.mjs +65 -0
  28. package/dist/esm/core/server/stream/createReadableStream.mjs +4 -2
  29. package/dist/esm/core/server/stream/createReadableStream.worker.mjs +4 -2
  30. package/dist/esm/core/server/stream/shared.mjs +3 -1
  31. package/dist/esm/core/server/string/index.mjs +3 -1
  32. package/dist/esm/core/server/string/loadable.mjs +33 -7
  33. package/dist/esm/router/cli/code/tanstackTypes.mjs +116 -51
  34. package/dist/esm/router/cli/code/templates.mjs +1 -8
  35. package/dist/esm/router/runtime/tanstack/plugin.mjs +8 -9
  36. package/dist/esm/router/runtime/tanstack/plugin.node.mjs +3 -14
  37. package/dist/esm/router/runtime/tanstack/routeTree.mjs +40 -4
  38. package/dist/esm/rsc/server.worker.mjs +1 -0
  39. package/dist/esm-node/boundary-debugger/index.mjs +263 -0
  40. package/dist/esm-node/cli/ssr/index.mjs +3 -2
  41. package/dist/esm-node/cli/template.server.mjs +1 -0
  42. package/dist/esm-node/core/server/federatedCss.mjs +14 -0
  43. package/dist/esm-node/core/server/helmet.mjs +1 -1
  44. package/dist/esm-node/core/server/stream/afterTemplate.mjs +10 -7
  45. package/dist/esm-node/core/server/stream/beforeTemplate.mjs +12 -8
  46. package/dist/esm-node/core/server/stream/beforeTemplate.worker.mjs +66 -0
  47. package/dist/esm-node/core/server/stream/createReadableStream.mjs +4 -2
  48. package/dist/esm-node/core/server/stream/createReadableStream.worker.mjs +4 -2
  49. package/dist/esm-node/core/server/stream/shared.mjs +3 -1
  50. package/dist/esm-node/core/server/string/index.mjs +3 -1
  51. package/dist/esm-node/core/server/string/loadable.mjs +33 -7
  52. package/dist/esm-node/router/cli/code/tanstackTypes.mjs +116 -51
  53. package/dist/esm-node/router/cli/code/templates.mjs +1 -8
  54. package/dist/esm-node/router/runtime/tanstack/plugin.mjs +8 -9
  55. package/dist/esm-node/router/runtime/tanstack/plugin.node.mjs +3 -14
  56. package/dist/esm-node/router/runtime/tanstack/routeTree.mjs +40 -4
  57. package/dist/esm-node/rsc/server.worker.mjs +2 -0
  58. package/dist/types/boundary-debugger/index.d.ts +28 -0
  59. package/dist/types/core/server/federatedCss.d.ts +5 -0
  60. package/dist/types/core/server/stream/beforeTemplate.d.ts +1 -0
  61. package/dist/types/core/server/stream/beforeTemplate.worker.d.ts +10 -0
  62. package/dist/types/core/server/stream/shared.d.ts +8 -0
  63. package/dist/types/core/server/string/loadable.d.ts +4 -0
  64. package/dist/types/rsc/server.worker.d.ts +1 -0
  65. package/package.json +22 -15
@@ -0,0 +1,263 @@
1
+ import "node:module";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useMemo, useState } from "react";
4
+ const defaultStorageKey = 'modernjs:boundary-debugger:enabled';
5
+ const queryParamName = 'modern-boundaries';
6
+ const boundarySelector = '[data-modern-boundary-id]';
7
+ const defaultLabels = {
8
+ cs: {
9
+ toggle: 'zobrazit hranice týmů'
10
+ },
11
+ en: {
12
+ toggle: 'show team boundaries'
13
+ }
14
+ };
15
+ const palette = [
16
+ '#ff5a5f',
17
+ '#30e27a',
18
+ '#f6cf45',
19
+ '#7c8cff',
20
+ '#29b6f6'
21
+ ];
22
+ const readStoredEnabled = (storageKey, fallback)=>{
23
+ if ("u" < typeof window) return fallback;
24
+ try {
25
+ const stored = window.localStorage.getItem(storageKey);
26
+ return null === stored ? fallback : 'true' === stored;
27
+ } catch {
28
+ return fallback;
29
+ }
30
+ };
31
+ const writeStoredEnabled = (storageKey, enabled)=>{
32
+ if ("u" < typeof window) return;
33
+ try {
34
+ window.localStorage.setItem(storageKey, String(enabled));
35
+ } catch {}
36
+ };
37
+ const parseEnabledOverride = (value)=>{
38
+ if (null === value) return;
39
+ const normalized = value.toLowerCase();
40
+ if ('1' === normalized || 'true' === normalized) return true;
41
+ if ('0' === normalized || 'false' === normalized) return false;
42
+ };
43
+ const readQueryEnabledOverride = ()=>{
44
+ if ("u" < typeof window) return;
45
+ try {
46
+ return parseEnabledOverride(new URLSearchParams(window.location.search).get(queryParamName));
47
+ } catch {
48
+ return;
49
+ }
50
+ };
51
+ const detectLanguage = ()=>{
52
+ if ("u" < typeof document) return 'en';
53
+ const htmlLanguage = document.documentElement.lang;
54
+ if (htmlLanguage) return htmlLanguage.split('-')[0] || 'en';
55
+ if ("u" < typeof window) return 'en';
56
+ return window.location.pathname.split('/').filter(Boolean)[0] || 'en';
57
+ };
58
+ const hashBoundaryId = (id)=>{
59
+ let hash = 0;
60
+ for(let index = 0; index < id.length; index++)hash = 31 * hash + id.charCodeAt(index) >>> 0;
61
+ return hash;
62
+ };
63
+ const formatRectKey = (rect)=>[
64
+ Math.round(100 * rect.left) / 100,
65
+ Math.round(100 * rect.top) / 100,
66
+ Math.round(100 * rect.width) / 100,
67
+ Math.round(100 * rect.height) / 100
68
+ ].join(':');
69
+ const getBoundaryId = (element)=>element.dataset.modernBoundaryId ?? element.dataset.mfRemote ?? element.getAttribute('data-mf-remote') ?? void 0;
70
+ const collectBoundaryElements = (legacySelector)=>{
71
+ const elements = new Set();
72
+ for (const element of document.querySelectorAll(boundarySelector))elements.add(element);
73
+ if (!legacySelector) return Array.from(elements);
74
+ try {
75
+ for (const element of document.querySelectorAll(legacySelector))elements.add(element);
76
+ } catch {}
77
+ return Array.from(elements);
78
+ };
79
+ function BoundaryDebugger({ controlMode = 'visible', enabledByDefault = false, labels = defaultLabels, legacySelector, metadata, storageKey = defaultStorageKey }) {
80
+ const [mounted, setMounted] = useState(false);
81
+ const [enabled, setEnabled] = useState(false);
82
+ const [boxes, setBoxes] = useState([]);
83
+ const boundaries = useMemo(()=>new Map(metadata.boundaries.map((entry, index)=>[
84
+ entry.mfName,
85
+ {
86
+ ...entry,
87
+ color: entry.color ?? palette[index % palette.length],
88
+ label: entry.label ?? entry.appId
89
+ }
90
+ ])), [
91
+ metadata
92
+ ]);
93
+ const language = mounted ? detectLanguage() : 'en';
94
+ const toggleLabel = labels[language]?.toggle ?? labels.en?.toggle ?? defaultLabels.en?.toggle ?? 'show team boundaries';
95
+ useEffect(()=>{
96
+ setMounted(true);
97
+ const queryOverride = readQueryEnabledOverride();
98
+ setEnabled(queryOverride ?? readStoredEnabled(storageKey, enabledByDefault));
99
+ }, [
100
+ enabledByDefault,
101
+ storageKey
102
+ ]);
103
+ useEffect(()=>{
104
+ if (!mounted) return;
105
+ writeStoredEnabled(storageKey, enabled);
106
+ }, [
107
+ enabled,
108
+ mounted,
109
+ storageKey
110
+ ]);
111
+ useEffect(()=>{
112
+ if (!enabled) return void setBoxes([]);
113
+ const readBoxes = ()=>{
114
+ const seenBoxes = new Set();
115
+ const nextBoxes = collectBoundaryElements(legacySelector).map((element)=>{
116
+ const boundaryId = getBoundaryId(element);
117
+ if (!boundaryId) return;
118
+ const rect = element.getBoundingClientRect();
119
+ if (rect.width <= 0 || rect.height <= 0) return;
120
+ const rectKey = formatRectKey(rect);
121
+ const boxKey = `${boundaryId}:${rectKey}`;
122
+ if (seenBoxes.has(boxKey)) return;
123
+ seenBoxes.add(boxKey);
124
+ const boundary = boundaries.get(boundaryId);
125
+ const color = boundary?.color ?? palette[hashBoundaryId(boundaryId) % palette.length];
126
+ const label = boundary?.label ?? boundary?.appId ?? boundaryId;
127
+ const expose = element.dataset.modernMfExpose;
128
+ const detail = expose && expose !== label && expose !== boundaryId ? expose : void 0;
129
+ const box = {
130
+ color,
131
+ height: rect.height,
132
+ id: boxKey,
133
+ label,
134
+ left: rect.left,
135
+ top: rect.top,
136
+ width: rect.width
137
+ };
138
+ if (detail) box.detail = detail;
139
+ return box;
140
+ }).filter((box)=>void 0 !== box);
141
+ setBoxes(nextBoxes);
142
+ };
143
+ readBoxes();
144
+ const resizeObserver = "u" < typeof ResizeObserver ? void 0 : new ResizeObserver(readBoxes);
145
+ for (const element of collectBoundaryElements(legacySelector))resizeObserver?.observe(element);
146
+ const mutationObserver = new MutationObserver(readBoxes);
147
+ mutationObserver.observe(document.body, {
148
+ childList: true,
149
+ subtree: true
150
+ });
151
+ window.addEventListener('resize', readBoxes);
152
+ window.addEventListener('scroll', readBoxes, true);
153
+ return ()=>{
154
+ mutationObserver.disconnect();
155
+ resizeObserver?.disconnect();
156
+ window.removeEventListener('resize', readBoxes);
157
+ window.removeEventListener('scroll', readBoxes, true);
158
+ };
159
+ }, [
160
+ boundaries,
161
+ enabled,
162
+ legacySelector
163
+ ]);
164
+ if (!mounted) return null;
165
+ const shouldRenderToggle = 'visible' === controlMode || 'hidden-when-off' === controlMode && enabled;
166
+ return /*#__PURE__*/ jsxs(Fragment, {
167
+ children: [
168
+ shouldRenderToggle ? /*#__PURE__*/ jsxs("label", {
169
+ style: {
170
+ alignItems: 'center',
171
+ background: 'rgba(255, 255, 255, 0.96)',
172
+ border: '1px solid rgba(0, 0, 0, 0.1)',
173
+ borderRadius: 12,
174
+ bottom: 20,
175
+ boxShadow: '0 16px 40px rgba(0, 0, 0, 0.16)',
176
+ color: '#111827',
177
+ display: 'flex',
178
+ font: '600 14px/1.2 system-ui, sans-serif',
179
+ gap: 8,
180
+ left: 20,
181
+ padding: '12px 14px',
182
+ position: 'fixed',
183
+ zIndex: 2147483000
184
+ },
185
+ children: [
186
+ /*#__PURE__*/ jsx("input", {
187
+ checked: enabled,
188
+ onChange: (event)=>setEnabled(event.currentTarget.checked),
189
+ type: "checkbox"
190
+ }),
191
+ /*#__PURE__*/ jsx("span", {
192
+ children: toggleLabel
193
+ })
194
+ ]
195
+ }) : null,
196
+ enabled ? /*#__PURE__*/ jsx("div", {
197
+ "aria-hidden": "true",
198
+ children: boxes.map((box)=>/*#__PURE__*/ jsx("div", {
199
+ style: {
200
+ border: `2px solid ${box.color}`,
201
+ borderRadius: 8,
202
+ boxShadow: `0 0 0 1px rgba(255,255,255,.72), 0 6px 20px color-mix(in srgb, ${box.color} 20%, transparent)`,
203
+ height: box.height,
204
+ left: box.left,
205
+ pointerEvents: 'none',
206
+ position: 'fixed',
207
+ top: box.top,
208
+ width: box.width,
209
+ zIndex: 2147482999
210
+ },
211
+ children: /*#__PURE__*/ jsxs("span", {
212
+ style: {
213
+ background: box.color,
214
+ borderRadius: 999,
215
+ color: '#111827',
216
+ display: 'grid',
217
+ font: '800 11px/1.1 system-ui, sans-serif',
218
+ gap: 3,
219
+ maxWidth: 'min(280px, calc(100vw - 24px))',
220
+ padding: '5px 8px',
221
+ position: 'absolute',
222
+ right: 4,
223
+ top: 4,
224
+ whiteSpace: 'nowrap'
225
+ },
226
+ children: [
227
+ /*#__PURE__*/ jsx("span", {
228
+ children: box.label
229
+ }),
230
+ box.detail ? /*#__PURE__*/ jsx("span", {
231
+ style: {
232
+ font: '700 10px/1.1 system-ui, sans-serif',
233
+ opacity: 0.82,
234
+ overflow: 'hidden',
235
+ textOverflow: 'ellipsis'
236
+ },
237
+ children: box.detail
238
+ }) : null
239
+ ]
240
+ })
241
+ }, box.id))
242
+ }) : null
243
+ ]
244
+ });
245
+ }
246
+ const ultramodernBoundaryDebuggerPlugin = (options)=>({
247
+ name: '@modern-js/runtime/boundary-debugger',
248
+ setup: (api)=>{
249
+ api.wrapRoot((App)=>(props)=>/*#__PURE__*/ jsxs(Fragment, {
250
+ children: [
251
+ /*#__PURE__*/ jsx(App, {
252
+ ...props
253
+ }),
254
+ /*#__PURE__*/ jsx(BoundaryDebugger, {
255
+ ...options
256
+ })
257
+ ]
258
+ }));
259
+ }
260
+ });
261
+ const boundary_debugger = ultramodernBoundaryDebuggerPlugin;
262
+ export default boundary_debugger;
263
+ export { ultramodernBoundaryDebuggerPlugin };
@@ -86,13 +86,14 @@ const ssrBuilderPlugin = (modernAPI, outputModule, exportLoadablePath)=>({
86
86
  const hasServerRendering = hasServerRenderingConfig(userConfig);
87
87
  const hasModuleFederationRuntimeMarker = hasServerRendering && shouldUseModuleFederationNodeOutput(config);
88
88
  const hasExplicitMfSsrFlag = isModuleFederationAppSSREnabled(userConfig);
89
+ const isCloudflareWorkerSSR = 'workerSSR' === name && userConfig.deploy?.target === 'cloudflare';
89
90
  const requireExplicitMfSsrFlag = 'true' === process.env.MODERN_MF_APP_SSR_REQUIRE_EXPLICIT;
90
91
  if (hasServerRendering && hasModuleFederationRuntimeMarker && !hasExplicitMfSsrFlag) {
91
92
  const warningMessage = '[modernjs][mf-ssr] Module Federation SSR was auto-detected from runtime markers. Set server.ssr.moduleFederationAppSSR=true explicitly in host and remotes to avoid heuristic drift.';
92
93
  if (requireExplicitMfSsrFlag) throw new Error(`${warningMessage} (enforced by MODERN_MF_APP_SSR_REQUIRE_EXPLICIT=true)`);
93
94
  console.warn(warningMessage);
94
95
  }
95
- const isModuleFederationAppSSR = hasServerRendering && hasExplicitMfSsrFlag;
96
+ const isModuleFederationAppSSR = hasServerRendering && hasExplicitMfSsrFlag && !isCloudflareWorkerSSR;
96
97
  const useModuleFederationNodeOutput = hasServerRendering && isModuleFederationAppSSR && isNodeEnvironmentTarget(config.output.target);
97
98
  const ssrEnv = userConfig.deploy?.worker?.ssr || userConfig.server?.rsc ? 'edge' : 'node';
98
99
  const appContext = modernAPI.getAppContext();
@@ -109,7 +110,7 @@ const ssrBuilderPlugin = (modernAPI, outputModule, exportLoadablePath)=>({
109
110
  } : void 0;
110
111
  const useLoadablePlugin = isUseSSRBundle(userConfig) && !isServerEnvironment && checkUseStringSSR(userConfig, appDirectory, entrypoints);
111
112
  const outputConfig = {
112
- module: isServerEnvironment && !useModuleFederationNodeOutput && outputModule
113
+ module: isServerEnvironment && !useModuleFederationNodeOutput && (outputModule || 'workerSSR' === name && userConfig.deploy?.target === 'cloudflare')
113
114
  };
114
115
  const useLoadableComponents = isUseSSRBundle(userConfig) && checkUseStringSSR(userConfig, appDirectory, entrypoints);
115
116
  return mergeEnvironmentConfig(config, {
@@ -36,6 +36,7 @@ const handleRequest = async (request, ServerRoot, options) => {
36
36
  </ServerRoot>,
37
37
  {
38
38
  ...options,
39
+ rscManifest: __rspack_rsc_manifest__,
39
40
  rscRoot: options.rscRoot,
40
41
  },
41
42
  );
@@ -0,0 +1,14 @@
1
+ import "node:module";
2
+ import { attributesToString } from "./utils.mjs";
3
+ const createFederatedCssLinks = (assets, options)=>{
4
+ if (!assets?.length) return '';
5
+ const seen = new Set(options.existingAssets || []);
6
+ const attributes = attributesToString(options.attributes || {});
7
+ const links = [];
8
+ for (const asset of assets)if (!(!asset || seen.has(asset) || options.template.includes(asset))) {
9
+ seen.add(asset);
10
+ links.push(`<link${attributes} href="${asset}" rel="stylesheet" />`);
11
+ }
12
+ return links.join('');
13
+ };
14
+ export { createFederatedCssLinks };
@@ -1,6 +1,6 @@
1
1
  import "node:module";
2
- import { EOL } from "os";
3
2
  import { safeReplace } from "./utils.mjs";
3
+ const EOL = '\n';
4
4
  const RE_HTML_ATTR = /<html[^>]*>/;
5
5
  const RE_BODY_ATTR = /<body[^>]*>/;
6
6
  const RE_LAST_IN_HEAD = /<\/head>/;
@@ -1,6 +1,6 @@
1
1
  import "node:module";
2
2
  import { serializeJson } from "@modern-js/runtime-utils/node";
3
- import { getRouterHydrationScripts } from "../../../router/runtime/lifecycle.mjs";
3
+ import { getRouterHydrationScripts, getRouterMatchedRouteIds } from "../../../router/runtime/lifecycle.mjs";
4
4
  import { SSR_DATA_JSON_ID } from "../../constants.mjs";
5
5
  import { SSR_DATA_PLACEHOLDER } from "../constants.mjs";
6
6
  import { buildHtml } from "../shared.mjs";
@@ -23,12 +23,15 @@ function buildShellAfterTemplate(afterAppTemplate, options) {
23
23
  if (!routeManifest) return template;
24
24
  const { routeAssets } = routeManifest;
25
25
  if (!routeAssets) return template;
26
- const asyncEntry = routeAssets[`async-${entryName}`];
27
- if (asyncEntry) {
28
- const { assets } = asyncEntry;
29
- const jsChunkStr = assets?.filter((asset)=>asset.endsWith('.js'))?.map((asset)=>`<script src=${asset} nonce="${nonce}"></script>`).join(' ');
30
- if (jsChunkStr) return safeReplace(template, '<!--<?- chunksMap.js ?>-->', jsChunkStr);
31
- }
26
+ const matchedRouteIds = getRouterMatchedRouteIds(runtimeContext) ?? [];
27
+ const assetEntries = [
28
+ ...matchedRouteIds.map((routeId)=>routeAssets[routeId]),
29
+ routeAssets[`async-${entryName}`]
30
+ ].filter(Boolean);
31
+ const jsAssets = Array.from(new Set(assetEntries.flatMap((entry)=>(entry.assets ?? []).filter((asset)=>asset.endsWith('.js')))));
32
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : '';
33
+ const jsChunkStr = jsAssets.filter((asset)=>!template.includes(asset)).map((asset)=>`<script src=${asset}${nonceAttr}></script>`).join(' ');
34
+ if (jsChunkStr) return safeReplace(template, '<!--<?- chunksMap.js ?>-->', jsChunkStr);
32
35
  return template;
33
36
  }
34
37
  return buildHtml(afterAppTemplate, callbacks);
@@ -3,6 +3,7 @@ import { matchRoutes } from "@modern-js/runtime-utils/router";
3
3
  import react_helmet from "react-helmet";
4
4
  import { getRouterMatchedRouteIds } from "../../../router/runtime/lifecycle.mjs";
5
5
  import { CHUNK_CSS_PLACEHOLDER } from "../constants.mjs";
6
+ import { createFederatedCssLinks } from "../federatedCss.mjs";
6
7
  import { createReplaceHelemt } from "../helmet.mjs";
7
8
  import { buildHtml } from "../shared.mjs";
8
9
  import { checkIsNode, safeReplace } from "../utils.mjs";
@@ -21,7 +22,7 @@ const checkIsInline = (chunk, enableInline)=>{
21
22
  return Boolean(enableInline);
22
23
  };
23
24
  async function buildShellBeforeTemplate(beforeAppTemplate, options) {
24
- const { config, runtimeContext, styledComponentsStyleTags, entryName } = options;
25
+ const { config, runtimeContext, styledComponentsStyleTags, entryName, moduleFederationCssAssets } = options;
25
26
  const helmetData = react_helmet.renderStatic();
26
27
  const callbacks = [
27
28
  createReplaceHelemt(helmetData),
@@ -31,33 +32,36 @@ async function buildShellBeforeTemplate(beforeAppTemplate, options) {
31
32
  async function injectCss(template, entryName, styledComponentsStyleTags) {
32
33
  let css = await getCssChunks();
33
34
  if (styledComponentsStyleTags) css += styledComponentsStyleTags;
35
+ css += createFederatedCssLinks(moduleFederationCssAssets, {
36
+ template,
37
+ existingAssets: css.match(/href="([^"]+)"/g)?.map((item)=>item.replace(/^href="/, '').replace(/"$/, ''))
38
+ });
34
39
  return safeReplace(template, CHUNK_CSS_PLACEHOLDER, css);
35
40
  async function getCssChunks() {
36
41
  const { routeManifest, routerContext, routes } = runtimeContext;
37
42
  if (!routeManifest) return '';
38
43
  const { routeAssets } = routeManifest;
39
- let matchedRouteManifests;
44
+ let matchedRouteManifests = [];
40
45
  const matchedRouteIds = getRouterMatchedRouteIds(runtimeContext);
41
46
  if (matchedRouteIds?.length) matchedRouteManifests = matchedRouteIds.map((routeId)=>routeAssets[routeId]).filter(Boolean);
42
- else {
43
- if (!routerContext || !routes) return '';
47
+ else if (routerContext && routes) {
44
48
  const matches = matchRoutes(routes, routerContext.location, routerContext.basename);
45
49
  matchedRouteManifests = matches?.map((match, index)=>{
46
50
  if (!index) return;
47
51
  const routeId = match.route.id;
48
52
  if (routeId) return routeAssets[routeId];
49
- }).filter(Boolean);
53
+ }).filter(Boolean) ?? [];
50
54
  }
51
55
  const asyncEntry = routeAssets[`async-${entryName}`];
52
- if (asyncEntry) matchedRouteManifests?.push(asyncEntry);
53
- const cssChunks = matchedRouteManifests ? matchedRouteManifests.reduce((chunks, routeManifest)=>{
56
+ if (asyncEntry) matchedRouteManifests.push(asyncEntry);
57
+ const cssChunks = matchedRouteManifests.reduce((chunks, routeManifest)=>{
54
58
  const { referenceCssAssets = [] } = routeManifest;
55
59
  const _cssChunks = referenceCssAssets.filter((asset)=>asset?.endsWith('.css') && !template.includes(asset));
56
60
  return [
57
61
  ...chunks,
58
62
  ..._cssChunks
59
63
  ];
60
- }, []) : [];
64
+ }, []);
61
65
  const { inlineStyles } = config;
62
66
  const styles = await Promise.all(cssChunks.map(async (chunk)=>{
63
67
  const link = `<link href="${chunk}" rel="stylesheet" />`;
@@ -0,0 +1,66 @@
1
+ import "node:module";
2
+ import { matchRoutes } from "@modern-js/runtime-utils/router";
3
+ import react_helmet from "react-helmet";
4
+ import { getRouterMatchedRouteIds } from "../../../router/runtime/lifecycle.mjs";
5
+ import { CHUNK_CSS_PLACEHOLDER } from "../constants.mjs";
6
+ import { createFederatedCssLinks } from "../federatedCss.mjs";
7
+ import { createReplaceHelemt } from "../helmet.mjs";
8
+ import { buildHtml } from "../shared.mjs";
9
+ import { safeReplace } from "../utils.mjs";
10
+ const checkIsInline = (chunk, enableInline)=>{
11
+ if ('production' !== process.env.NODE_ENV) return false;
12
+ if (enableInline instanceof RegExp) return enableInline.test(chunk);
13
+ return Boolean(enableInline);
14
+ };
15
+ async function buildShellBeforeTemplate(beforeAppTemplate, options) {
16
+ const { config, runtimeContext, styledComponentsStyleTags, entryName, moduleFederationCssAssets } = options;
17
+ const helmetData = react_helmet.renderStatic();
18
+ const callbacks = [
19
+ createReplaceHelemt(helmetData),
20
+ (template)=>injectCss(template, entryName, styledComponentsStyleTags)
21
+ ];
22
+ return buildHtml(beforeAppTemplate, callbacks);
23
+ async function injectCss(template, entryName, styledComponentsStyleTags) {
24
+ let css = await getCssChunks();
25
+ if (styledComponentsStyleTags) css += styledComponentsStyleTags;
26
+ css += createFederatedCssLinks(moduleFederationCssAssets, {
27
+ template,
28
+ existingAssets: css.match(/href="([^"]+)"/g)?.map((item)=>item.replace(/^href="/, '').replace(/"$/, ''))
29
+ });
30
+ return safeReplace(template, CHUNK_CSS_PLACEHOLDER, css);
31
+ async function getCssChunks() {
32
+ const { routeManifest, routerContext, routes } = runtimeContext;
33
+ if (!routeManifest) return '';
34
+ const { routeAssets } = routeManifest;
35
+ let matchedRouteManifests = [];
36
+ const matchedRouteIds = getRouterMatchedRouteIds(runtimeContext);
37
+ if (matchedRouteIds?.length) matchedRouteManifests = matchedRouteIds.map((routeId)=>routeAssets[routeId]).filter(Boolean);
38
+ else if (routerContext && routes) {
39
+ const matches = matchRoutes(routes, routerContext.location, routerContext.basename);
40
+ matchedRouteManifests = matches?.map((match, index)=>{
41
+ if (!index) return;
42
+ const routeId = match.route.id;
43
+ if (routeId) return routeAssets[routeId];
44
+ }).filter(Boolean) ?? [];
45
+ }
46
+ const asyncEntry = routeAssets[`async-${entryName}`];
47
+ if (asyncEntry) matchedRouteManifests.push(asyncEntry);
48
+ const cssChunks = matchedRouteManifests.reduce((chunks, routeManifest)=>{
49
+ const { referenceCssAssets = [] } = routeManifest;
50
+ const _cssChunks = referenceCssAssets.filter((asset)=>asset?.endsWith('.css') && !template.includes(asset));
51
+ return [
52
+ ...chunks,
53
+ ..._cssChunks
54
+ ];
55
+ }, []);
56
+ const { inlineStyles } = config;
57
+ const styles = cssChunks.map((chunk)=>{
58
+ const link = `<link href="${chunk}" rel="stylesheet" />`;
59
+ checkIsInline(chunk, inlineStyles);
60
+ return link;
61
+ });
62
+ return `${styles.join('')}`;
63
+ }
64
+ }
65
+ }
66
+ export { buildShellBeforeTemplate };
@@ -16,7 +16,7 @@ const defaultExtender = {
16
16
  };
17
17
  const createReadableStreamFromElement = async (request, rootElement, options)=>{
18
18
  const { renderToPipeableStream } = await import("react-dom/server");
19
- const { runtimeContext, htmlTemplate, config, ssrConfig, entryName } = options;
19
+ const { runtimeContext, htmlTemplate, config, ssrConfig, entryName, moduleFederationCssAssets } = options;
20
20
  let shellChunkStatus = ShellChunkStatus.START;
21
21
  let renderLevel = RenderLevel.SERVER_RENDER;
22
22
  const forceStream2String = Boolean(process.env.MODERN_JS_STREAM_TO_STRING);
@@ -53,6 +53,7 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
53
53
  runtimeContext,
54
54
  config,
55
55
  entryName,
56
+ moduleFederationCssAssets,
56
57
  styledComponentsStyleTags
57
58
  }).then(({ shellAfter, shellBefore })=>{
58
59
  const pendingScripts = [];
@@ -110,7 +111,8 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
110
111
  renderLevel,
111
112
  runtimeContext,
112
113
  entryName,
113
- config
114
+ config,
115
+ moduleFederationCssAssets
114
116
  }).then(({ shellAfter, shellBefore })=>{
115
117
  const fallbackHtml = `${shellBefore}${shellAfter}`;
116
118
  const readableStream = getReadableStreamFromString(fallbackHtml);
@@ -9,19 +9,21 @@ import { getTemplates } from "./template.mjs";
9
9
  const createReadableStreamFromElement = async (request, rootElement, options)=>{
10
10
  let shellChunkStatus = ShellChunkStatus.START;
11
11
  const chunkVec = [];
12
- const { htmlTemplate, runtimeContext, config, ssrConfig, entryName, rscRoot } = options;
12
+ const { htmlTemplate, runtimeContext, config, ssrConfig, entryName, moduleFederationCssAssets, rscManifest, rscRoot } = options;
13
13
  const { shellBefore, shellAfter } = await getTemplates(htmlTemplate, {
14
14
  renderLevel: RenderLevel.SERVER_RENDER,
15
15
  runtimeContext,
16
16
  ssrConfig,
17
17
  request,
18
18
  config,
19
- entryName
19
+ entryName,
20
+ moduleFederationCssAssets
20
21
  });
21
22
  try {
22
23
  const readableOriginal = await renderSSRStream(rootElement, {
23
24
  request,
24
25
  nonce: config.nonce,
26
+ rscManifest,
25
27
  rscRoot: rscRoot,
26
28
  routes: runtimeContext.routes,
27
29
  onError (error) {
@@ -64,7 +64,7 @@ function createRenderStreaming(createReadableStreamPromise) {
64
64
  const end = time();
65
65
  const { runtimeContext, config, resource } = options;
66
66
  const { onError, onTiming } = options;
67
- const { htmlTemplate, entryName } = resource;
67
+ const { htmlTemplate, entryName, moduleFederationCssAssets } = resource;
68
68
  const ssrConfig = getSSRConfigByEntry(entryName, config.ssr, config.ssrByEntries);
69
69
  const StreamServerRootWrapper = ({ children })=>/*#__PURE__*/ jsxs(Fragment, {
70
70
  children: [
@@ -84,9 +84,11 @@ function createRenderStreaming(createReadableStreamPromise) {
84
84
  runtimeContext,
85
85
  ssrConfig,
86
86
  entryName,
87
+ moduleFederationCssAssets,
87
88
  rscClientManifest: options.rscClientManifest,
88
89
  rscSSRManifest: options.rscSSRManifest,
89
90
  rscServerManifest: options.rscServerManifest,
91
+ rscManifest: options.rscManifest,
90
92
  rscRoot: options.rscRoot,
91
93
  onShellReady () {
92
94
  const cost = end();
@@ -20,7 +20,7 @@ const renderString = async (request, serverRoot, options)=>{
20
20
  onTiming
21
21
  };
22
22
  const routerContext = runtimeContext.routerContext;
23
- const { htmlTemplate, entryName, loadableStats, routeManifest } = resource;
23
+ const { htmlTemplate, entryName, loadableStats, routeManifest, moduleFederationCssAssets } = resource;
24
24
  const ssrConfig = getSSRConfigByEntry(entryName, config.ssr, config.ssrByEntries);
25
25
  const chunkSet = {
26
26
  renderLevel: RenderLevel.CLIENT_RENDER,
@@ -33,8 +33,10 @@ const renderString = async (request, serverRoot, options)=>{
33
33
  stats: loadableStats,
34
34
  nonce: config.nonce,
35
35
  routeManifest,
36
+ runtimeContext,
36
37
  template: htmlTemplate,
37
38
  entryName,
39
+ moduleFederationCssAssets,
38
40
  chunkSet,
39
41
  config
40
42
  }),
@@ -1,5 +1,7 @@
1
1
  import "node:module";
2
2
  import { ChunkExtractor } from "@loadable/server";
3
+ import { getRouterMatchedRouteIds } from "../../../router/runtime/lifecycle.mjs";
4
+ import { createFederatedCssLinks } from "../federatedCss.mjs";
3
5
  import { attributesToString, checkIsNode } from "../utils.mjs";
4
6
  import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
5
7
  import { dirname as __rspack_dirname } from "node:path";
@@ -25,6 +27,20 @@ class LoadableCollector {
25
27
  const { routeManifest, entryName } = this.options;
26
28
  return routeManifest?.routeAssets?.[entryName]?.assets;
27
29
  }
30
+ getMatchedRouteChunks() {
31
+ const { routeManifest, runtimeContext } = this.options;
32
+ const routeAssets = routeManifest?.routeAssets;
33
+ if (!routeAssets) return [];
34
+ const matchedRouteIds = getRouterMatchedRouteIds(runtimeContext) ?? [];
35
+ return matchedRouteIds.flatMap((routeId)=>{
36
+ const routeAsset = routeAssets[routeId];
37
+ return (routeAsset?.assets ?? []).map((asset)=>({
38
+ filename: asset.replace(/^\//, ''),
39
+ path: asset,
40
+ url: asset
41
+ }));
42
+ });
43
+ }
28
44
  collect(comopnent) {
29
45
  const { stats, entryName } = this.options;
30
46
  if (!stats) return comopnent;
@@ -37,20 +53,21 @@ class LoadableCollector {
37
53
  return this.extractor.collectChunks(comopnent);
38
54
  }
39
55
  async effect() {
40
- if (!this.extractor) return;
41
56
  const { extractor, options } = this;
42
57
  const { entryName, config } = options;
43
58
  const asyncChunks = [];
44
- if (config.enableAsyncEntry) try {
59
+ if (extractor && config.enableAsyncEntry) try {
45
60
  asyncChunks.push(...extractor.getChunkAssets([
46
61
  `async-${entryName}`
47
62
  ]));
48
63
  } catch (e) {}
49
- const chunks = [].concat(asyncChunks).concat(extractor.getChunkAssets(extractor.chunks));
64
+ const chunks = [].concat(asyncChunks).concat(extractor ? extractor.getChunkAssets(extractor.chunks) : []).concat(this.getMatchedRouteChunks());
50
65
  const scriptChunks = generateChunks(chunks, 'js');
51
66
  const styleChunks = generateChunks(chunks, 'css');
52
- this.emitLoadableScripts(extractor);
53
- await this.emitScriptAssets(scriptChunks);
67
+ if (extractor) {
68
+ this.emitLoadableScripts(extractor);
69
+ await this.emitScriptAssets(scriptChunks);
70
+ }
54
71
  await this.emitStyleAssets(styleChunks);
55
72
  }
56
73
  emitLoadableScripts(extractor) {
@@ -85,19 +102,28 @@ class LoadableCollector {
85
102
  chunkSet.jsChunk += scripts.filter((script)=>Boolean(script)).join('');
86
103
  }
87
104
  async emitStyleAssets(chunks) {
88
- const { template, chunkSet, config, entryName } = this.options;
105
+ const { template, chunkSet, config, moduleFederationCssAssets } = this.options;
89
106
  const { inlineStyles } = config;
90
107
  const atrributes = attributesToString(this.generateAttributes());
91
108
  const linkRegExp = /<link .*?href="([^"]+)".*?>/g;
92
109
  const matchs = template.matchAll(linkRegExp);
93
110
  const existedLinks = [];
94
111
  for (const match of matchs)existedLinks.push(match[1]);
95
- const css = await Promise.all(chunks.filter((chunk)=>!existedLinks.includes(chunk.url) && !this.existsAssets?.includes(chunk.path)).map(async (chunk)=>{
112
+ const emittedChunks = chunks.filter((chunk)=>!existedLinks.includes(chunk.url) && !this.existsAssets?.includes(chunk.path));
113
+ const css = await Promise.all(emittedChunks.map(async (chunk)=>{
96
114
  const link = `<link${atrributes} href="${chunk.url}" rel="stylesheet" />`;
97
115
  if (checkIsNode() && checkIsInline(chunk, inlineStyles)) return readAsset(chunk).then((content)=>`<style>${content}</style>`).catch((_)=>link);
98
116
  return link;
99
117
  }));
100
118
  chunkSet.cssChunk += css.filter((css)=>Boolean(css)).join('');
119
+ chunkSet.cssChunk += createFederatedCssLinks(moduleFederationCssAssets, {
120
+ template,
121
+ attributes: this.generateAttributes(),
122
+ existingAssets: [
123
+ ...existedLinks,
124
+ ...emittedChunks.map((chunk)=>chunk.url)
125
+ ]
126
+ });
101
127
  }
102
128
  generateAttributes(extraAtr = {}) {
103
129
  const { config } = this.options;