@bleedingdev/modern-js-runtime 3.5.0-ultramodern.102 → 3.5.0-ultramodern.103

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 (72) hide show
  1. package/dist/cjs/cli/ssr/index.js +1 -0
  2. package/dist/cjs/core/browser/hydrate.js +31 -27
  3. package/dist/cjs/core/react/wrapper.js +23 -28
  4. package/dist/cjs/core/server/requestResponse.js +5 -5
  5. package/dist/cjs/core/server/scriptOrder.js +1 -1
  6. package/dist/cjs/core/server/stream/beforeTemplate.worker.js +1 -10
  7. package/dist/cjs/core/server/utils.js +3 -3
  8. package/dist/cjs/module-federation/distributed-ssr.js +13 -12
  9. package/dist/cjs/module-federation/last-known-good.js +1 -1
  10. package/dist/cjs/module-federation/manifest-recovery-runtime-plugin.js +27 -38
  11. package/dist/cjs/router/cli/code/index.js +13 -7
  12. package/dist/cjs/router/cli/code/templates.js +33 -24
  13. package/dist/cjs/router/cli/handler.js +2 -0
  14. package/dist/cjs/router/runtime/plugin.js +11 -6
  15. package/dist/cjs/router/runtime/plugin.node.js +11 -3
  16. package/dist/cjs/router/runtime/provider.js +2 -2
  17. package/dist/cjs/router/runtime/redirect.js +51 -0
  18. package/dist/cjs/router/runtime/routerHelper.js +4 -0
  19. package/dist/cjs/router/runtime/rsc-router.js +2 -13
  20. package/dist/cjs/router/runtime/utils.js +3 -2
  21. package/dist/esm/cli/ssr/index.mjs +1 -0
  22. package/dist/esm/core/browser/hydrate.mjs +30 -22
  23. package/dist/esm/core/react/wrapper.mjs +23 -28
  24. package/dist/esm/core/server/requestResponse.mjs +4 -4
  25. package/dist/esm/core/server/scriptOrder.mjs +1 -1
  26. package/dist/esm/core/server/stream/beforeTemplate.worker.mjs +1 -10
  27. package/dist/esm/core/server/utils.mjs +1 -1
  28. package/dist/esm/module-federation/distributed-ssr.mjs +13 -12
  29. package/dist/esm/module-federation/last-known-good.mjs +1 -1
  30. package/dist/esm/module-federation/manifest-recovery-runtime-plugin.mjs +22 -33
  31. package/dist/esm/router/cli/code/index.mjs +13 -7
  32. package/dist/esm/router/cli/code/templates.mjs +33 -24
  33. package/dist/esm/router/cli/handler.mjs +2 -0
  34. package/dist/esm/router/runtime/plugin.mjs +13 -8
  35. package/dist/esm/router/runtime/plugin.node.mjs +12 -4
  36. package/dist/esm/router/runtime/provider.mjs +2 -2
  37. package/dist/esm/router/runtime/redirect.mjs +13 -0
  38. package/dist/esm/router/runtime/routerHelper.mjs +2 -1
  39. package/dist/esm/router/runtime/rsc-router.mjs +2 -13
  40. package/dist/esm/router/runtime/utils.mjs +2 -1
  41. package/dist/esm-node/cli/ssr/index.mjs +1 -0
  42. package/dist/esm-node/core/browser/hydrate.mjs +30 -22
  43. package/dist/esm-node/core/react/wrapper.mjs +23 -28
  44. package/dist/esm-node/core/server/requestResponse.mjs +4 -4
  45. package/dist/esm-node/core/server/scriptOrder.mjs +1 -1
  46. package/dist/esm-node/core/server/stream/beforeTemplate.worker.mjs +1 -10
  47. package/dist/esm-node/core/server/utils.mjs +1 -1
  48. package/dist/esm-node/module-federation/distributed-ssr.mjs +13 -12
  49. package/dist/esm-node/module-federation/last-known-good.mjs +1 -1
  50. package/dist/esm-node/module-federation/manifest-recovery-runtime-plugin.mjs +22 -33
  51. package/dist/esm-node/router/cli/code/index.mjs +13 -7
  52. package/dist/esm-node/router/cli/code/templates.mjs +33 -24
  53. package/dist/esm-node/router/cli/handler.mjs +2 -0
  54. package/dist/esm-node/router/runtime/plugin.mjs +13 -8
  55. package/dist/esm-node/router/runtime/plugin.node.mjs +12 -4
  56. package/dist/esm-node/router/runtime/provider.mjs +2 -2
  57. package/dist/esm-node/router/runtime/redirect.mjs +14 -0
  58. package/dist/esm-node/router/runtime/routerHelper.mjs +2 -1
  59. package/dist/esm-node/router/runtime/rsc-router.mjs +2 -13
  60. package/dist/esm-node/router/runtime/utils.mjs +2 -1
  61. package/dist/types/core/browser/hydrate.d.ts +0 -1
  62. package/dist/types/core/server/utils.d.ts +1 -1
  63. package/dist/types/module-federation/distributed-ssr.d.ts +3 -3
  64. package/dist/types/module-federation/manifest-recovery-runtime-plugin.d.ts +1 -1
  65. package/dist/types/router/cli/code/index.d.ts +2 -0
  66. package/dist/types/router/cli/code/templates.d.ts +5 -2
  67. package/dist/types/router/cli/handler.d.ts +2 -0
  68. package/dist/types/router/runtime/redirect.d.ts +1 -0
  69. package/dist/types/router/runtime/routerHelper.d.ts +7 -0
  70. package/dist/types/router/runtime/rsc-router.d.ts +1 -2
  71. package/package.json +14 -14
  72. package/rstest.config.mts +2 -0
@@ -151,6 +151,7 @@ const ssrBuilderPlugin = (modernAPI, outputModule, exportLoadablePath)=>({
151
151
  'process.env.MODERN_SSR_ENV': JSON.stringify(ssrEnv),
152
152
  'process.env.MODERN_ENABLE_HYDRATION': JSON.stringify((0, utils_namespaceObject.isUseSSRBundle)(userConfig)),
153
153
  'process.env.MODERN_ENABLE_RSC': JSON.stringify(Boolean(userConfig.server?.rsc)),
154
+ __MODERN_ENABLE_RSC__: JSON.stringify(Boolean(userConfig.server?.rsc)),
154
155
  'process.env.MODERN_MF_APP_SSR': JSON.stringify(isModuleFederationAppSSR)
155
156
  }
156
157
  },
@@ -29,8 +29,7 @@ var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  __webpack_require__.d(__webpack_exports__, {
31
31
  hydrateRoot: ()=>hydrateRoot,
32
- hydrateWithReact: ()=>hydrateWithReact,
33
- isReact18: ()=>isReact18
32
+ hydrateWithReact: ()=>hydrateWithReact
34
33
  });
35
34
  const jsx_runtime_namespaceObject = require("react/jsx-runtime");
36
35
  const component_namespaceObject = require("@loadable/component");
@@ -39,15 +38,23 @@ const client_namespaceObject = require("react-dom/client");
39
38
  const external_constants_js_namespaceObject = require("../constants.js");
40
39
  const wrapper_js_namespaceObject = require("../react/wrapper.js");
41
40
  const external_withCallback_js_namespaceObject = require("./withCallback.js");
42
- const isReact18 = ()=>'true' === process.env.IS_REACT18;
43
41
  const runtimeProcess = Reflect.get(globalThis, 'process');
42
+ const runtimeEnvironment = null !== runtimeProcess && 'object' == typeof runtimeProcess ? Reflect.get(runtimeProcess, 'env') : void 0;
43
+ const readRuntimeEnvironment = (name)=>{
44
+ if (null === runtimeEnvironment || 'object' != typeof runtimeEnvironment) return;
45
+ const value = Reflect.get(runtimeEnvironment, name);
46
+ return 'string' == typeof value ? value : void 0;
47
+ };
44
48
  const loadableReadyOptions = {
45
- chunkLoadingGlobal: runtimeProcess?.env?.MODERN_CHUNK_LOADING_GLOBAL || '__LOADABLE_LOADED_CHUNKS__'
49
+ chunkLoadingGlobal: (()=>{
50
+ const configured = readRuntimeEnvironment('MODERN_CHUNK_LOADING_GLOBAL');
51
+ return void 0 === configured || '' === configured ? '__LOADABLE_LOADED_CHUNKS__' : configured;
52
+ })()
46
53
  };
47
- async function hydrateWithReact(App, rootElement) {
48
- return (0, client_namespaceObject.hydrateRoot)(rootElement, App, {
54
+ function hydrateWithReact(App, rootElement) {
55
+ return Promise.resolve((0, client_namespaceObject.hydrateRoot)(rootElement, App, {
49
56
  identifierPrefix: constants_namespaceObject.SSR_HYDRATION_ID_PREFIX
50
- });
57
+ }));
51
58
  }
52
59
  function hydrateRoot(App, context, ModernRender, ModernHydrate) {
53
60
  const hydrateContext = {
@@ -60,9 +67,9 @@ function hydrateRoot(App, context, ModernRender, ModernHydrate) {
60
67
  const callback = ()=>{
61
68
  delete hydrateContext._hydration;
62
69
  };
63
- const renderLevel = window?._SSR_DATA?.renderLevel || external_constants_js_namespaceObject.RenderLevel.CLIENT_RENDER;
64
- const renderMode = window?._SSR_DATA?.mode || 'string';
65
- if (isReact18() && 'stream' === renderMode) return streamSSRHydrate();
70
+ const renderLevel = window?._SSR_DATA?.renderLevel ?? external_constants_js_namespaceObject.RenderLevel.CLIENT_RENDER;
71
+ const renderMode = window?._SSR_DATA?.mode ?? 'string';
72
+ if ('stream' === renderMode) return streamSSRHydrate();
66
73
  function streamSSRHydrate() {
67
74
  if (renderLevel !== external_constants_js_namespaceObject.RenderLevel.SERVER_RENDER) return ModernRender((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(App, context));
68
75
  {
@@ -76,33 +83,30 @@ function hydrateRoot(App, context, ModernRender, ModernHydrate) {
76
83
  return stringSSRHydrate();
77
84
  function stringSSRHydrate() {
78
85
  if (renderLevel === external_constants_js_namespaceObject.RenderLevel.CLIENT_RENDER) return ModernRender((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(App, context));
79
- if (renderLevel === external_constants_js_namespaceObject.RenderLevel.SERVER_RENDER) return new Promise((resolve)=>{
80
- if (isReact18()) (0, component_namespaceObject.loadableReady)(()=>{
86
+ {
87
+ if (renderLevel === external_constants_js_namespaceObject.RenderLevel.SERVER_RENDER) return (0, component_namespaceObject.loadableReady)(()=>void 0, loadableReadyOptions).then(()=>{
81
88
  const SSRApp = ()=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_withCallback_js_namespaceObject.WithCallback, {
82
89
  callback: callback,
83
90
  children: App
84
91
  });
85
- ModernHydrate((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SSRApp, {}), hydrateContext)).then((root)=>{
86
- resolve(root);
87
- });
88
- }, loadableReadyOptions);
89
- else (0, component_namespaceObject.loadableReady)(()=>{
90
- ModernHydrate((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(App, hydrateContext), callback).then((root)=>{
91
- resolve(root);
92
- });
93
- }, loadableReadyOptions);
94
- });
95
- console.warn(`unknow render level: ${renderLevel}, execute render()`);
96
- return ModernRender((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(App, context));
92
+ return ModernHydrate((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SSRApp, {}), hydrateContext));
93
+ });
94
+ const runtimeConsole = Reflect.get(globalThis, 'console');
95
+ if (null !== runtimeConsole && 'object' == typeof runtimeConsole) {
96
+ const warn = Reflect.get(runtimeConsole, 'warn');
97
+ if ('function' == typeof warn) Reflect.apply(warn, runtimeConsole, [
98
+ `unknow render level: ${renderLevel}, execute render()`
99
+ ]);
100
+ }
101
+ return ModernRender((0, wrapper_js_namespaceObject.wrapRuntimeContextProvider)(App, context));
102
+ }
97
103
  }
98
104
  }
99
105
  exports.hydrateRoot = __webpack_exports__.hydrateRoot;
100
106
  exports.hydrateWithReact = __webpack_exports__.hydrateWithReact;
101
- exports.isReact18 = __webpack_exports__.isReact18;
102
107
  for(var __rspack_i in __webpack_exports__)if (-1 === [
103
108
  "hydrateRoot",
104
- "hydrateWithReact",
105
- "isReact18"
109
+ "hydrateWithReact"
106
110
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
107
111
  Object.defineProperty(exports, '__esModule', {
108
112
  value: true
@@ -35,39 +35,34 @@ const external_react_helmet_async_namespaceObject = require("react-helmet-async"
35
35
  const index_js_namespaceObject = require("../context/index.js");
36
36
  const extensions_js_namespaceObject = require("../context/extensions.js");
37
37
  const helmetContext_js_namespaceObject = require("../context/helmetContext.js");
38
- function toRscSafeRecord(value) {
39
- if (!value || 'object' != typeof value) return value;
40
- return Object.fromEntries(Object.entries(value));
41
- }
42
- function createRscSafeSsrContext(ssrContext) {
43
- if (!ssrContext) return ssrContext;
44
- const { request } = ssrContext;
38
+ function createRscSafeRequestContext(ssrContext) {
39
+ if (void 0 === ssrContext) return {
40
+ request: {},
41
+ response: {
42
+ locals: {}
43
+ }
44
+ };
45
+ const { request, response } = ssrContext;
45
46
  return {
46
- nonce: ssrContext.nonce,
47
- useJsonScript: ssrContext.useJsonScript,
48
- htmlModifiers: [],
49
- baseUrl: ssrContext.baseUrl,
50
- request: request ? {
47
+ request: {
51
48
  url: request.url,
52
49
  userAgent: request.userAgent,
53
50
  cookie: request.cookie,
54
51
  pathname: request.pathname,
55
- query: toRscSafeRecord(request.query),
56
- params: toRscSafeRecord(request.params),
57
- headers: toRscSafeRecord(request.headers),
52
+ query: {
53
+ ...request.query
54
+ },
55
+ params: {
56
+ ...request.params
57
+ },
58
+ headers: {
59
+ ...request.headers
60
+ },
58
61
  host: request.host,
59
62
  referer: request.referer
60
- } : request,
61
- mode: ssrContext.mode,
62
- loaderFailureMode: ssrContext.loaderFailureMode
63
- };
64
- }
65
- function createRscSafeRequestContext(ssrContext) {
66
- const safeSsrContext = createRscSafeSsrContext(ssrContext);
67
- return {
68
- request: safeSsrContext?.request || {},
63
+ },
69
64
  response: {
70
- locals: ssrContext?.response?.locals || {}
65
+ locals: response.locals ?? {}
71
66
  }
72
67
  };
73
68
  }
@@ -83,14 +78,14 @@ function wrapRuntimeContextProvider(App, contextValue) {
83
78
  ...rest
84
79
  };
85
80
  (0, extensions_js_namespaceObject.stripRuntimeContextExtensions)(runtimeContextValue);
86
- if ((0, index_js_namespaceObject.getGlobalEnableRsc)() && !isBrowser) {
81
+ if (true === (0, index_js_namespaceObject.getGlobalEnableRsc)() && false === isBrowser) {
87
82
  const rscSafeRequestContext = createRscSafeRequestContext(ssrContext);
88
83
  const rscInternalContextValue = {
89
84
  ...internalContextValue,
90
85
  context: rscSafeRequestContext,
91
- requestContext: rscSafeRequestContext,
92
- ssrContext: createRscSafeSsrContext(ssrContext)
86
+ requestContext: rscSafeRequestContext
93
87
  };
88
+ delete rscInternalContextValue.ssrContext;
94
89
  const rscRuntimeContextValue = {
95
90
  ...runtimeContextValue,
96
91
  context: rscSafeRequestContext,
@@ -33,12 +33,12 @@ __webpack_require__.d(__webpack_exports__, {
33
33
  finalizeRenderResponse: ()=>finalizeRenderResponse
34
34
  });
35
35
  const lifecycle_js_namespaceObject = require("../../router/runtime/lifecycle.js");
36
- const rsc_router_js_namespaceObject = require("../../router/runtime/rsc-router.js");
36
+ const redirect_js_namespaceObject = require("../../router/runtime/redirect.js");
37
37
  const external_tracer_js_namespaceObject = require("./tracer.js");
38
38
  const isRedirectStatus = (status)=>status >= 300 && status <= 399;
39
39
  const isNullBodyStatus = (status)=>204 === status || 205 === status || 304 === status;
40
40
  const processRedirect = (headers, status, ctx)=>{
41
- if (ctx.enableRsc && ctx.isRSCNavigation) return (0, rsc_router_js_namespaceObject.handleRSCRedirect)(headers, ctx.basename, status);
41
+ if (ctx.enableRsc && ctx.isRSCNavigation) return (0, redirect_js_namespaceObject.handleRSCRedirect)(headers, ctx.basename, status);
42
42
  return new Response(null, {
43
43
  status,
44
44
  headers
@@ -47,12 +47,12 @@ const processRedirect = (headers, status, ctx)=>{
47
47
  const applyRouterSnapshotResult = (context, onError)=>{
48
48
  const routerServerSnapshot = (0, lifecycle_js_namespaceObject.getRouterServerSnapshot)(context);
49
49
  const routerStatusCode = routerServerSnapshot?.statusCode ?? context.routerContext?.statusCode;
50
- if (routerStatusCode && 200 !== routerStatusCode) context.ssrContext?.response.status(routerStatusCode);
50
+ if (void 0 !== routerStatusCode && 0 !== routerStatusCode && !Number.isNaN(routerStatusCode) && 200 !== routerStatusCode) context.ssrContext?.response.status(routerStatusCode);
51
51
  const errors = Object.values(routerServerSnapshot?.errors || context.routerContext?.errors || {});
52
52
  if (errors.length > 0) onError(errors[0], external_tracer_js_namespaceObject.SSRErrors.LOADER_ERROR);
53
53
  };
54
54
  const createLoaderRedirectResponse = (beforeRenderResult, redirectCtx)=>{
55
- if (!beforeRenderResult || !isRedirectStatus(beforeRenderResult.status)) return;
55
+ if (void 0 === beforeRenderResult || !isRedirectStatus(beforeRenderResult.status)) return;
56
56
  if (beforeRenderResult.headers.has('X-Modernjs-Redirect')) return beforeRenderResult;
57
57
  const redirectUrl = beforeRenderResult.headers.get('Location') || '/';
58
58
  return processRedirect(new Headers({
@@ -60,7 +60,7 @@ const createLoaderRedirectResponse = (beforeRenderResult, redirectCtx)=>{
60
60
  }), beforeRenderResult.status, redirectCtx);
61
61
  };
62
62
  const finalizeRenderResponse = (response, responseProxy, redirectCtx, routerCleanup)=>{
63
- if (-1 !== responseProxy.status && isRedirectStatus(responseProxy.status) && responseProxy.headers.Location) return processRedirect(new Headers(responseProxy.headers), responseProxy.status, redirectCtx);
63
+ if (-1 !== responseProxy.status && isRedirectStatus(responseProxy.status) && void 0 !== responseProxy.headers.Location && '' !== responseProxy.headers.Location) return processRedirect(new Headers(responseProxy.headers), responseProxy.status, redirectCtx);
64
64
  Object.entries(responseProxy.headers).forEach(([key, value])=>{
65
65
  response.headers.set(key, value);
66
66
  });
@@ -79,7 +79,7 @@ function getMatchedRouteAssets(runtimeContext, routeManifest) {
79
79
  return matchedRouteIds.flatMap((routeId)=>routeAssets[routeId]?.assets ?? []);
80
80
  }
81
81
  function getMatchedRouteChunks(runtimeContext, routeManifest, routeAssetToChunk) {
82
- if (!routeManifest) return [];
82
+ if (void 0 === routeManifest) return [];
83
83
  return getMatchedRouteAssets(runtimeContext, routeManifest).map(routeAssetToChunk);
84
84
  }
85
85
  const orderHydrationScriptChunks = ({ asyncEntryChunks, collectedChunks, matchedRouteChunks, entryName })=>{
@@ -30,7 +30,6 @@ __webpack_require__.r(__webpack_exports__);
30
30
  __webpack_require__.d(__webpack_exports__, {
31
31
  buildShellBeforeTemplate: ()=>buildShellBeforeTemplate
32
32
  });
33
- const router_namespaceObject = require("@modern-js/runtime-utils/router");
34
33
  const lifecycle_js_namespaceObject = require("../../../router/runtime/lifecycle.js");
35
34
  const external_constants_js_namespaceObject = require("../constants.js");
36
35
  const external_federatedCss_js_namespaceObject = require("../federatedCss.js");
@@ -59,20 +58,12 @@ async function buildShellBeforeTemplate(beforeAppTemplate, options) {
59
58
  });
60
59
  return (0, external_utils_js_namespaceObject.safeReplace)(template, external_constants_js_namespaceObject.CHUNK_CSS_PLACEHOLDER, css);
61
60
  async function getCssChunks() {
62
- const { routeManifest, routerContext, routes } = runtimeContext;
61
+ const { routeManifest } = runtimeContext;
63
62
  const routeAssets = routeManifest?.routeAssets;
64
63
  if (!routeAssets) return '';
65
64
  let matchedRouteManifests = [];
66
65
  const matchedRouteIds = (0, lifecycle_js_namespaceObject.getRouterMatchedRouteIds)(runtimeContext);
67
66
  if (matchedRouteIds?.length) matchedRouteManifests = matchedRouteIds.map((routeId)=>routeAssets[routeId]).filter(Boolean);
68
- else if (routerContext && routes) {
69
- const matches = (0, router_namespaceObject.matchRoutes)(routes, routerContext.location, routerContext.basename);
70
- matchedRouteManifests = matches?.map((match, index)=>{
71
- if (!index) return;
72
- const routeId = match.route.id;
73
- if (routeId) return routeAssets[routeId];
74
- }).filter((routeManifest)=>void 0 !== routeManifest) ?? [];
75
- }
76
67
  const asyncEntry = routeAssets[`async-${entryName}`];
77
68
  if (asyncEntry) matchedRouteManifests.push(asyncEntry);
78
69
  const cssChunks = matchedRouteManifests.reduce((chunks, routeManifest)=>{
@@ -36,7 +36,7 @@ __webpack_require__.d(__webpack_exports__, {
36
36
  safeReplace: ()=>safeReplace,
37
37
  serializeErrors: ()=>serializeErrors
38
38
  });
39
- const router_namespaceObject = require("@modern-js/runtime-utils/router");
39
+ const routerHelper_js_namespaceObject = require("../../router/runtime/routerHelper.js");
40
40
  function attributesToString(attributes) {
41
41
  return Object.entries(attributes).reduce((str, [key, value])=>void 0 === value ? str : `${str} ${key}="${value}"`, '');
42
42
  }
@@ -50,7 +50,7 @@ function serializeErrors(errors) {
50
50
  if (!errors) return null;
51
51
  const entries = Object.entries(errors);
52
52
  const serialized = {};
53
- for (const [key, val] of entries)if ((0, router_namespaceObject.isRouteErrorResponse)(val)) serialized[key] = serializeRouteErrorResponse(val);
53
+ for (const [key, val] of entries)if ((0, routerHelper_js_namespaceObject.isRouteErrorResponse)(val)) serialized[key] = serializeRouteErrorResponse(val);
54
54
  else if (val instanceof Error) serialized[key] = serializeError(val);
55
55
  else serialized[key] = val;
56
56
  return serialized;
@@ -71,7 +71,7 @@ function serializeError(error) {
71
71
  };
72
72
  }
73
73
  function serializeRouteErrorResponse(error) {
74
- if (!(0, router_namespaceObject.isRouteErrorResponse)(error)) return error;
74
+ if (!(0, routerHelper_js_namespaceObject.isRouteErrorResponse)(error)) return error;
75
75
  if (error.status >= 500 && shouldRedactServerError()) return {
76
76
  status: error.status,
77
77
  statusText: 'Internal Server Error',
@@ -44,24 +44,24 @@ function distributedSsrFragmentKey(remote, expose) {
44
44
  }
45
45
  function getDistributedSsrFragmentContext(response) {
46
46
  const locals = response?.locals;
47
- if (!locals || 'object' != typeof locals) return;
48
- const context = locals[DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY];
49
- if (!context || 'object' != typeof context) return;
47
+ if ('object' != typeof locals || null === locals) return;
48
+ const context = DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY in locals ? locals[DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY] : void 0;
49
+ if ('object' != typeof context || null === context) return;
50
50
  return context;
51
51
  }
52
52
  function useDistributedSsrFragmentProps({ boundaryId, expose }) {
53
53
  const runtimeContext = (0, runtime_js_namespaceObject.useRuntimeContext)();
54
54
  const locals = runtimeContext.requestContext?.response?.locals;
55
- const request = locals && 'object' == typeof locals ? locals[DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY] : void 0;
56
- if (!request || 'object' != typeof request || request.boundaryId !== boundaryId || request.expose !== expose) throw new Error(`Distributed SSR fragment request contract mismatch for ${boundaryId} ${expose}.`);
57
- const props = request.props;
58
- if (!props || 'object' != typeof props || Array.isArray(props)) throw new Error(`Distributed SSR fragment request props must be an object for ${boundaryId} ${expose}.`);
55
+ const request = 'object' == typeof locals && null !== locals && DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY in locals ? locals[DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY] : void 0;
56
+ if ('object' != typeof request || null === request || !('boundaryId' in request) || request.boundaryId !== boundaryId || !('expose' in request) || request.expose !== expose) throw new Error(`Distributed SSR fragment request contract mismatch for ${boundaryId} ${expose}.`);
57
+ const props = 'props' in request ? request.props : void 0;
58
+ if ('object' != typeof props || null === props || Array.isArray(props)) throw new Error(`Distributed SSR fragment request props must be an object for ${boundaryId} ${expose}.`);
59
59
  return props;
60
60
  }
61
61
  function isThenable(value) {
62
- return 'function' == typeof value.then;
62
+ return void 0 !== value && 'then' in value && 'function' == typeof value.then;
63
63
  }
64
- function DistributedSsrBoundary({ children, expose, fallback, fragmentProps = {}, remote }) {
64
+ function DistributedSsrBoundary({ children, expose, fallback, fragmentProps, remote }) {
65
65
  const runtimeContext = (0, runtime_js_namespaceObject.useRuntimeContext)();
66
66
  const key = distributedSsrFragmentKey(remote, expose);
67
67
  const attributes = {
@@ -72,12 +72,13 @@ function DistributedSsrBoundary({ children, expose, fallback, fragmentProps = {}
72
72
  children: children
73
73
  });
74
74
  const fragmentContext = getDistributedSsrFragmentContext(runtimeContext.requestContext?.response);
75
- if (!fragmentContext) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
75
+ if (void 0 === fragmentContext) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
76
76
  ...attributes,
77
77
  children: children
78
78
  });
79
- const fragmentOrPromise = fragmentContext.resolve?.(remote, expose, fragmentProps) ?? fragmentContext.fragments?.[key];
80
- if (fragmentOrPromise && isThenable(fragmentOrPromise)) throw fragmentOrPromise;
79
+ const resolverFragmentProps = void 0 === fragmentProps ? {} : Object.fromEntries(Object.entries(fragmentProps));
80
+ const fragmentOrPromise = fragmentContext.resolve?.(remote, expose, resolverFragmentProps) ?? fragmentContext.fragments?.[key];
81
+ if (isThenable(fragmentOrPromise)) throw fragmentOrPromise;
81
82
  const fragment = fragmentOrPromise;
82
83
  if (fragment?.status === 'ready') return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
83
84
  ...attributes,
@@ -67,7 +67,7 @@ function staleRecordResult(ref, env, ageMs, maxStaleMs) {
67
67
  }
68
68
  function createLastKnownGoodProvider(options) {
69
69
  const storage = options.storage ?? createInMemoryLkgStorage();
70
- const now = options.now ?? (()=>Date.now());
70
+ const now = options.now ?? (()=>Math.floor(performance.timeOrigin + performance.now()));
71
71
  const maxStaleMs = options.freshness?.maxStaleMs;
72
72
  async function serveFromCache(ref, env, fallback) {
73
73
  const key = (0, external_surface_resolution_types_js_namespaceObject.deliveryUnitResolutionKey)(ref.unitId, env);
@@ -27,6 +27,11 @@ var __webpack_require__ = {};
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ createModuleFederationManifestRecoveryPlugin: ()=>createModuleFederationManifestRecoveryPlugin,
32
+ default: ()=>manifest_recovery_runtime_plugin
33
+ });
34
+ const universal_namespaceObject = require("@modern-js/utils/universal");
30
35
  const DEFAULT_ATTEMPTS = 3;
31
36
  const DEFAULT_RETRY_DELAY_MS = 100;
32
37
  const DEFAULT_TIMEOUT_MS = 1000;
@@ -72,7 +77,7 @@ const isRetryableError = (error)=>{
72
77
  return error instanceof TypeError || /(?:fetch failed|network|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN)/i.test(message);
73
78
  };
74
79
  const isHttpManifestUrl = (id)=>{
75
- if (!id) return false;
80
+ if (void 0 === id || 0 === id.length) return false;
76
81
  try {
77
82
  const url = new URL(id);
78
83
  return ('http:' === url.protocol || 'https:' === url.protocol) && url.pathname.endsWith('.json');
@@ -80,55 +85,39 @@ const isHttpManifestUrl = (id)=>{
80
85
  return false;
81
86
  }
82
87
  };
83
- const defaultWait = (milliseconds)=>new Promise((resolve)=>{
84
- setTimeout(resolve, milliseconds);
88
+ const defaultWait = (milliseconds)=>(0, universal_namespaceObject.wait)(milliseconds).then(()=>void 0);
89
+ const fetchWithTimeout = (fetchImpl, url, timeoutMs)=>fetchImpl(url, {
90
+ signal: AbortSignal.timeout(timeoutMs)
85
91
  });
86
- const fetchWithTimeout = async (fetchImpl, url, timeoutMs)=>{
87
- const controller = new AbortController();
88
- const timeout = setTimeout(()=>controller.abort(), timeoutMs);
89
- try {
90
- return await fetchImpl(url, {
91
- signal: controller.signal
92
- });
93
- } finally{
94
- clearTimeout(timeout);
95
- }
96
- };
97
92
  const createModuleFederationManifestRecoveryPlugin = (options = {})=>{
98
93
  const attempts = clampInteger(options.attempts, DEFAULT_ATTEMPTS, 1, MAX_ATTEMPTS);
99
94
  const retryDelayMs = clampInteger(options.retryDelayMs, DEFAULT_RETRY_DELAY_MS, 0, MAX_RETRY_DELAY_MS);
100
95
  const timeoutMs = clampInteger(options.timeoutMs, DEFAULT_TIMEOUT_MS, 1, MAX_TIMEOUT_MS);
101
96
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
102
97
  const waitImpl = options.waitImpl ?? defaultWait;
98
+ const recoverManifest = (url, attempt)=>{
99
+ const fetchManifest = ()=>Promise.resolve().then(()=>fetchWithTimeout(fetchImpl, url, timeoutMs)).then((response)=>{
100
+ if (!response.ok) {
101
+ if (!RETRYABLE_HTTP_STATUSES.has(response.status) || attempt === attempts - 1) return;
102
+ return recoverManifest(url, attempt + 1);
103
+ }
104
+ return Promise.resolve().then(()=>response.json()).then((manifest)=>manifest, ()=>void 0);
105
+ }, (error)=>{
106
+ if (!isRetryableError(error) || attempt === attempts - 1) return;
107
+ return recoverManifest(url, attempt + 1);
108
+ });
109
+ if (attempt > 0 && retryDelayMs > 0) return waitImpl(retryDelayMs).then(fetchManifest);
110
+ return fetchManifest();
111
+ };
103
112
  return {
104
113
  name: 'modern-js-manifest-recovery-plugin',
105
- async errorLoadRemote (args) {
106
- if ('afterResolve' !== args.lifecycle || !isHttpManifestUrl(args.id) || !isRetryableError(args.error) || 'function' != typeof fetchImpl) return;
107
- for(let attempt = 0; attempt < attempts; attempt++){
108
- if (attempt > 0 && retryDelayMs > 0) await waitImpl(retryDelayMs);
109
- try {
110
- const response = await fetchWithTimeout(fetchImpl, args.id, timeoutMs);
111
- if (!response.ok) {
112
- if (!RETRYABLE_HTTP_STATUSES.has(response.status) || attempt === attempts - 1) return;
113
- continue;
114
- }
115
- try {
116
- return await response.json();
117
- } catch {
118
- break;
119
- }
120
- } catch (error) {
121
- if (!isRetryableError(error) || attempt === attempts - 1) break;
122
- }
123
- }
114
+ errorLoadRemote (args) {
115
+ if ('afterResolve' !== args.lifecycle || !isHttpManifestUrl(args.id) || !isRetryableError(args.error) || 'function' != typeof fetchImpl) return Promise.resolve(void 0);
116
+ return recoverManifest(args.id, 0);
124
117
  }
125
118
  };
126
119
  };
127
- const __rspack_default_export = createModuleFederationManifestRecoveryPlugin;
128
- __webpack_require__.d(__webpack_exports__, {}, {
129
- createModuleFederationManifestRecoveryPlugin: createModuleFederationManifestRecoveryPlugin,
130
- default: __rspack_default_export
131
- });
120
+ const manifest_recovery_runtime_plugin = createModuleFederationManifestRecoveryPlugin;
132
121
  exports.createModuleFederationManifestRecoveryPlugin = __webpack_exports__.createModuleFederationManifestRecoveryPlugin;
133
122
  exports["default"] = __webpack_exports__["default"];
134
123
  for(var __rspack_i in __webpack_exports__)if (-1 === [
@@ -86,6 +86,7 @@ async function generateRoutesForEntry(entrypoint, appContext) {
86
86
  }
87
87
  const generateCode = async (appContext, config, entrypoints, api, options = {})=>{
88
88
  const { internalDirectory, srcDirectory, internalSrcAlias, packageName } = appContext;
89
+ const includeRouteServerLoadersInSsrEntry = false !== options.includeRouteServerLoadersInSsrEntry || !(0, utils_namespaceObject.isUseRsc)(config);
89
90
  const hooks = api.getHooks();
90
91
  const generatedRoutesByEntry = {};
91
92
  const eagerRouteComponentFilesByEntry = new Map();
@@ -151,12 +152,14 @@ const generateCode = async (appContext, config, entrypoints, api, options = {})=
151
152
  if (entrypoint.nestedRoutesEntry && ((0, utils_namespaceObject.isUseSSRBundle)(config) || (0, utils_namespaceObject.isUseRsc)(config))) {
152
153
  const routesServerFile = (0, external_utils_js_namespaceObject.getServerLoadersFile)(internalDirectory, entryName);
153
154
  const filtedRoutesForServer = (0, utils_namespaceObject.filterRoutesForServer)(routes);
154
- const routesForServerLoaderMatches = (0, utils_namespaceObject.filterRoutesLoader)(routes);
155
- const code = external_templates_js_namespaceObject.routesForServer({
156
- routesForServerLoaderMatches
157
- });
158
- await utils_namespaceObject.fs.ensureFile(routesServerFile);
159
- await utils_namespaceObject.fs.writeFile(routesServerFile, code);
155
+ if (includeRouteServerLoadersInSsrEntry) {
156
+ const routesForServerLoaderMatches = (0, utils_namespaceObject.filterRoutesLoader)(routes);
157
+ const code = external_templates_js_namespaceObject.routesForServer({
158
+ routesForServerLoaderMatches
159
+ });
160
+ await utils_namespaceObject.fs.ensureFile(routesServerFile);
161
+ await utils_namespaceObject.fs.writeFile(routesServerFile, code);
162
+ } else await utils_namespaceObject.fs.remove(routesServerFile);
160
163
  const serverRoutesCode = await external_templates_js_namespaceObject.fileSystemRoutes({
161
164
  metaName,
162
165
  routes: filtedRoutesForServer,
@@ -166,12 +169,15 @@ const generateCode = async (appContext, config, entrypoints, api, options = {})=
166
169
  internalDirectory,
167
170
  splitRouteChunks: config?.output?.splitRouteChunks,
168
171
  isRscClientBundle: false,
172
+ isolateRouteDataInRscLayer: (0, utils_namespaceObject.isUseRsc)(config) && options.isolateRouteDataInRscLayer,
169
173
  srcDirectory,
170
174
  internalSrcAlias: appContext.internalSrcAlias
171
175
  });
172
176
  await utils_namespaceObject.fs.outputFile(external_path_default().resolve(internalDirectory, `./${entryName}/${options.serverRoutesFileName || 'routes.server.js'}`), serverRoutesCode, 'utf8');
173
177
  }
174
- const serverLoaderCombined = external_templates_js_namespaceObject.ssrLoaderCombinedModule(entrypoints, entrypoint, config, appContext);
178
+ const serverLoaderCombined = external_templates_js_namespaceObject.ssrLoaderCombinedModule(entrypoints, entrypoint, config, appContext, {
179
+ includeRouteServerLoaders: includeRouteServerLoadersInSsrEntry
180
+ });
175
181
  if (serverLoaderCombined) {
176
182
  const serverLoaderFile = (0, external_utils_js_namespaceObject.getServerCombinedModuleFile)(internalDirectory, entryName);
177
183
  await utils_namespaceObject.fs.outputFile(serverLoaderFile, serverLoaderCombined);
@@ -134,7 +134,7 @@ async function hasUseClientDirective(componentPath, srcDirectory, internalSrcAli
134
134
  await fh?.close();
135
135
  }
136
136
  }
137
- const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry, entryName, internalDirectory, splitRouteChunks = true, isRscClientBundle = false, hydrateRscClientRoutes = false, srcDirectory, internalSrcAlias })=>{
137
+ const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry, entryName, internalDirectory, splitRouteChunks = true, isRscClientBundle = false, hydrateRscClientRoutes = false, isolateRouteDataInRscLayer = false, srcDirectory, internalSrcAlias })=>{
138
138
  const components = [];
139
139
  const loadings = [];
140
140
  const errors = [];
@@ -226,9 +226,9 @@ const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry,
226
226
  component = `component_${components.length - 1}`;
227
227
  }
228
228
  const isClientComponent = 'nested' === route.type && Boolean(route._component) && Boolean(srcDirectory) && Boolean(internalSrcAlias) && await hasUseClientDirective(route._component, srcDirectory, internalSrcAlias);
229
- const shouldHydrateRscRoute = hydrateRscClientRoutes && isRscClientBundle && !isClientComponent && !route.loader && !route.data;
229
+ const shouldHydrateRscRoute = hydrateRscClientRoutes && isRscClientBundle && !isClientComponent && ('nested' !== route.type || !route.loader && !route.data);
230
230
  const shouldIncludeClientBundle = !isRscClientBundle || isClientComponent || shouldHydrateRscRoute;
231
- if (route.isRoot && route._component && shouldIncludeClientBundle) rootLayoutCode = `import RootLayout from '${route._component}'`;
231
+ if ('nested' === route.type && route.isRoot && route._component && shouldIncludeClientBundle) rootLayoutCode = `import RootLayout from '${route._component}'`;
232
232
  const finalRoute = {
233
233
  ...route,
234
234
  loading,
@@ -289,32 +289,30 @@ const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry,
289
289
  const importComponentsCode = components.map((component, index)=>`import component_${index} from '${component}';\n`).join('');
290
290
  const importErrorComponentsCode = errors.map((error, index)=>`import error_${index} from '${error}';\n`).join('');
291
291
  let importLoadersCode = '';
292
- for (const [key, loaderInfo] of Object.entries(loadersMap))if (loaderInfo.inline) {
292
+ const isolatedRouteDataDirectory = external_path_default().join(internalDirectory, entryName, '__rsc_route_data__');
293
+ await utils_namespaceObject.fs.remove(isolatedRouteDataDirectory);
294
+ if (isolateRouteDataInRscLayer) await utils_namespaceObject.fs.ensureDir(isolatedRouteDataDirectory);
295
+ for (const [key, loaderInfo] of Object.entries(loadersMap)){
293
296
  const { route } = loaderInfo;
294
- if (route.action) importLoadersCode += `import { loader as ${key}, action as action_${loaderInfo.loaderId} } from "${(0, utils_namespaceObject.slash)(loaderInfo.filePath)}${getDataLoaderPath({
297
+ const loaderRequest = `${(0, utils_namespaceObject.slash)(loaderInfo.filePath)}${getDataLoaderPath({
295
298
  loaderId: key,
296
299
  clientData: loaderInfo.clientData,
297
- action: route.action,
300
+ action: route.action || false,
298
301
  inline: loaderInfo.inline,
299
302
  routeId: loaderInfo.routeId,
300
303
  inValidSSRRoute: loaderInfo.inValidSSRRoute
301
- })}";\n`;
302
- else importLoadersCode += `import { loader as ${key} } from "${(0, utils_namespaceObject.slash)(loaderInfo.filePath)}${getDataLoaderPath({
303
- loaderId: key,
304
- clientData: loaderInfo.clientData,
305
- action: false,
306
- inline: loaderInfo.inline,
307
- routeId: route.id,
308
- inValidSSRRoute: loaderInfo.inValidSSRRoute
309
- })}";\n`;
310
- } else importLoadersCode += `import ${key} from "${(0, utils_namespaceObject.slash)(loaderInfo.filePath)}${getDataLoaderPath({
311
- loaderId: key,
312
- clientData: loaderInfo.clientData,
313
- action: false,
314
- inline: loaderInfo.inline,
315
- routeId: loaderInfo.routeId,
316
- inValidSSRRoute: loaderInfo.inValidSSRRoute
317
- })}";\n`;
304
+ })}`;
305
+ let loaderImport = loaderRequest;
306
+ if (isolateRouteDataInRscLayer) {
307
+ const isolatedLoaderFile = external_path_default().join(isolatedRouteDataDirectory, `${key}.js`);
308
+ const isolatedLoaderCode = loaderInfo.inline ? route.action ? `export { loader, action } from ${JSON.stringify(loaderRequest)};` : `export { loader } from ${JSON.stringify(loaderRequest)};` : `export { default } from ${JSON.stringify(loaderRequest)};`;
309
+ await utils_namespaceObject.fs.outputFile(isolatedLoaderFile, isolatedLoaderCode, 'utf8');
310
+ loaderImport = `./__rsc_route_data__/${key}.js`;
311
+ }
312
+ if (loaderInfo.inline) if (route.action) importLoadersCode += `import { loader as ${key}, action as action_${loaderInfo.loaderId} } from "${loaderImport}";\n`;
313
+ else importLoadersCode += `import { loader as ${key} } from "${loaderImport}";\n`;
314
+ else importLoadersCode += `import ${key} from "${loaderImport}";\n`;
315
+ }
318
316
  let importConfigsCode = '';
319
317
  for (const [key, configPath] of Object.entries(configsMap))importConfigsCode += `import * as ${key} from "${(0, utils_namespaceObject.slash)(configPath)}";\n`;
320
318
  await utils_namespaceObject.fs.ensureFile(loadersMapFile);
@@ -340,7 +338,7 @@ const fileSystemRoutes = async ({ metaName, routes, ssrMode, nestedRoutesEntry,
340
338
  ${routeComponentsCode}
341
339
  `;
342
340
  };
343
- function ssrLoaderCombinedModule(entrypoints, entrypoint, config, appContext) {
341
+ function ssrLoaderCombinedModule(entrypoints, entrypoint, config, appContext, options = {}) {
344
342
  const { entryName, isMainEntry } = entrypoint;
345
343
  const { packageName } = appContext;
346
344
  const ssr = (0, utils_namespaceObject.getEntryOptions)(entryName, isMainEntry, config.server.ssr, config.server.ssrByEntries, packageName);
@@ -348,6 +346,17 @@ function ssrLoaderCombinedModule(entrypoints, entrypoint, config, appContext) {
348
346
  if (entrypoint.nestedRoutesEntry && (ssr || ssg)) {
349
347
  const serverLoaderRuntime = require.resolve('@modern-js/plugin-data-loader/runtime');
350
348
  const serverLoadersFile = './route-server-loaders.js';
349
+ const includeRouteServerLoaders = false !== options.includeRouteServerLoaders;
350
+ if (!includeRouteServerLoaders) {
351
+ if (!config.source.enableAsyncEntry) return `export * from "${(0, utils_namespaceObject.slash)(serverLoaderRuntime)}"`;
352
+ return `
353
+ async function loadModules() {
354
+ return import("${(0, utils_namespaceObject.slash)(serverLoaderRuntime)}");
355
+ }
356
+
357
+ export { loadModules };
358
+ `;
359
+ }
351
360
  const combinedModule = `export * from "${(0, utils_namespaceObject.slash)(serverLoaderRuntime)}"; export * from "${serverLoadersFile}"`;
352
361
  if (!config.source.enableAsyncEntry) return combinedModule;
353
362
  return `
@@ -66,6 +66,8 @@ async function handleGeneratorEntryCode(api, entrypoints, options = {}) {
66
66
  const enableRsc = resolvedConfig?.server?.rsc;
67
67
  const routesByEntry = await generateCode(appContext, resolvedConfig, entrypoints, api, {
68
68
  hydrateRscClientRoutes: normalizedOptions.hydrateRscClientRoutes,
69
+ includeRouteServerLoadersInSsrEntry: normalizedOptions.includeRouteServerLoadersInSsrEntry,
70
+ isolateRouteDataInRscLayer: normalizedOptions.isolateRouteDataInRscLayer,
69
71
  serverRoutesFileName: normalizedOptions.serverRoutesFileName
70
72
  });
71
73
  await Promise.all(entrypoints.map(async (entrypoint)=>{