@modern-js/runtime 2.67.11 → 2.68.1

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 (97) hide show
  1. package/dist/cjs/cli/alias.js +1 -1
  2. package/dist/cjs/cli/code.js +6 -3
  3. package/dist/cjs/cli/index.js +4 -2
  4. package/dist/cjs/cli/ssr/index.js +1 -1
  5. package/dist/cjs/cli/template.js +72 -21
  6. package/dist/cjs/cli/template.server.js +62 -13
  7. package/dist/cjs/core/context/index.js +19 -2
  8. package/dist/cjs/core/context/serverPayload.server.js +40 -0
  9. package/dist/cjs/core/server/requestHandler.js +47 -11
  10. package/dist/cjs/router/cli/code/index.js +13 -6
  11. package/dist/cjs/router/cli/code/templates.js +44 -20
  12. package/dist/cjs/router/cli/handler.js +17 -2
  13. package/dist/cjs/router/cli/index.js +6 -5
  14. package/dist/cjs/router/index.js +0 -21
  15. package/dist/cjs/router/internal.js +30 -0
  16. package/dist/cjs/router/runtime/PrefetchLink.js +3 -4
  17. package/dist/cjs/router/runtime/constants.js +2 -2
  18. package/dist/cjs/router/runtime/index.js +1 -12
  19. package/dist/cjs/router/runtime/internal.js +36 -0
  20. package/dist/cjs/router/runtime/plugin.js +135 -76
  21. package/dist/cjs/router/runtime/plugin.node.js +73 -32
  22. package/dist/cjs/router/runtime/rsc-router.js +322 -0
  23. package/dist/cjs/router/runtime/utils.js +76 -1
  24. package/dist/cjs/rsc/client.js +11 -0
  25. package/dist/cjs/rsc/server.js +40 -0
  26. package/dist/esm/cli/alias.js +1 -1
  27. package/dist/esm/cli/code.js +6 -3
  28. package/dist/esm/cli/index.js +4 -2
  29. package/dist/esm/cli/ssr/index.js +1 -1
  30. package/dist/esm/cli/template.js +25 -6
  31. package/dist/esm/cli/template.server.js +3 -3
  32. package/dist/esm/core/context/index.js +14 -1
  33. package/dist/esm/core/context/serverPayload.server.js +15 -0
  34. package/dist/esm/core/server/requestHandler.js +102 -9
  35. package/dist/esm/router/cli/code/index.js +12 -6
  36. package/dist/esm/router/cli/code/templates.js +29 -13
  37. package/dist/esm/router/cli/handler.js +33 -6
  38. package/dist/esm/router/cli/index.js +6 -5
  39. package/dist/esm/router/index.js +0 -6
  40. package/dist/esm/router/internal.js +5 -0
  41. package/dist/esm/router/runtime/PrefetchLink.js +2 -2
  42. package/dist/esm/router/runtime/constants.js +2 -2
  43. package/dist/esm/router/runtime/index.js +1 -9
  44. package/dist/esm/router/runtime/internal.js +10 -0
  45. package/dist/esm/router/runtime/plugin.js +135 -85
  46. package/dist/esm/router/runtime/plugin.node.js +110 -40
  47. package/dist/esm/router/runtime/rsc-router.js +437 -0
  48. package/dist/esm/router/runtime/utils.js +95 -1
  49. package/dist/esm/rsc/client.js +6 -0
  50. package/dist/esm/rsc/server.js +86 -0
  51. package/dist/esm-node/cli/alias.js +1 -1
  52. package/dist/esm-node/cli/code.js +6 -3
  53. package/dist/esm-node/cli/index.js +4 -2
  54. package/dist/esm-node/cli/ssr/index.js +1 -1
  55. package/dist/esm-node/cli/template.js +72 -21
  56. package/dist/esm-node/cli/template.server.js +62 -13
  57. package/dist/esm-node/core/context/index.js +14 -1
  58. package/dist/esm-node/core/context/serverPayload.server.js +15 -0
  59. package/dist/esm-node/core/server/requestHandler.js +45 -9
  60. package/dist/esm-node/router/cli/code/index.js +12 -6
  61. package/dist/esm-node/router/cli/code/templates.js +44 -20
  62. package/dist/esm-node/router/cli/handler.js +17 -2
  63. package/dist/esm-node/router/cli/index.js +6 -5
  64. package/dist/esm-node/router/index.js +0 -6
  65. package/dist/esm-node/router/internal.js +5 -0
  66. package/dist/esm-node/router/runtime/PrefetchLink.js +2 -2
  67. package/dist/esm-node/router/runtime/constants.js +2 -2
  68. package/dist/esm-node/router/runtime/index.js +1 -9
  69. package/dist/esm-node/router/runtime/internal.js +10 -0
  70. package/dist/esm-node/router/runtime/plugin.js +127 -78
  71. package/dist/esm-node/router/runtime/plugin.node.js +75 -34
  72. package/dist/esm-node/router/runtime/rsc-router.js +284 -0
  73. package/dist/esm-node/router/runtime/utils.js +74 -1
  74. package/dist/esm-node/rsc/client.js +6 -0
  75. package/dist/esm-node/rsc/server.js +35 -0
  76. package/dist/types/cli/template.d.ts +4 -2
  77. package/dist/types/cli/template.server.d.ts +2 -1
  78. package/dist/types/common.d.ts +1 -1
  79. package/dist/types/config.d.ts +1 -1
  80. package/dist/types/core/context/index.d.ts +38 -3
  81. package/dist/types/core/context/serverPayload.server.d.ts +3 -0
  82. package/dist/types/core/server/requestHandler.d.ts +1 -1
  83. package/dist/types/index.d.ts +1 -1
  84. package/dist/types/router/cli/code/index.d.ts +1 -0
  85. package/dist/types/router/cli/code/templates.d.ts +4 -2
  86. package/dist/types/router/index.d.ts +0 -2
  87. package/dist/types/router/internal.d.ts +2 -0
  88. package/dist/types/router/runtime/PrefetchLink.d.ts +0 -1
  89. package/dist/types/router/runtime/constants.d.ts +3 -3
  90. package/dist/types/router/runtime/index.d.ts +1 -9
  91. package/dist/types/router/runtime/internal.d.ts +8 -0
  92. package/dist/types/router/runtime/rsc-router.d.ts +14 -0
  93. package/dist/types/router/runtime/utils.d.ts +26 -5
  94. package/dist/types/rsc/client.d.ts +1 -0
  95. package/dist/types/rsc/server.d.ts +1 -0
  96. package/package.json +22 -13
  97. package/static/modern-inline.js +1 -1
@@ -0,0 +1,284 @@
1
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { ElementsContext, createFromReadableStream } from "@modern-js/render/client";
3
+ import { StaticRouterProvider, createStaticRouter } from "@modern-js/runtime-utils/node/router";
4
+ import { createBrowserRouter, redirect } from "@modern-js/runtime-utils/router";
5
+ import React from "react";
6
+ const safeUse = (promise) => {
7
+ if (typeof React.use === "function") {
8
+ return React.use(promise);
9
+ }
10
+ return null;
11
+ };
12
+ const createServerPayload = (routerContext, routes) => {
13
+ return {
14
+ type: "render",
15
+ actionData: routerContext.actionData,
16
+ errors: routerContext.errors,
17
+ loaderData: routerContext.loaderData,
18
+ location: routerContext.location,
19
+ routes: routerContext.matches.map((match, index, matches) => {
20
+ const element = match.route.element;
21
+ const parentMatch = index > 0 ? matches[index - 1] : void 0;
22
+ let processedElement;
23
+ if (element) {
24
+ var _routerContext_loaderData, _routerContext_actionData;
25
+ const ElementComponent = element.type;
26
+ processedElement = /* @__PURE__ */ React.createElement(ElementComponent, {
27
+ loaderData: routerContext === null || routerContext === void 0 ? void 0 : (_routerContext_loaderData = routerContext.loaderData) === null || _routerContext_loaderData === void 0 ? void 0 : _routerContext_loaderData[match.route.id],
28
+ actionData: routerContext === null || routerContext === void 0 ? void 0 : (_routerContext_actionData = routerContext.actionData) === null || _routerContext_actionData === void 0 ? void 0 : _routerContext_actionData[match.route.id],
29
+ params: match.params,
30
+ matches: routerContext.matches.map((m) => {
31
+ var _routerContext_loaderData2;
32
+ const { route, pathname, params } = m;
33
+ return {
34
+ id: route.id,
35
+ pathname,
36
+ params,
37
+ data: routerContext === null || routerContext === void 0 ? void 0 : (_routerContext_loaderData2 = routerContext.loaderData) === null || _routerContext_loaderData2 === void 0 ? void 0 : _routerContext_loaderData2[route.id],
38
+ handle: route.handle
39
+ };
40
+ })
41
+ });
42
+ }
43
+ return {
44
+ element: processedElement,
45
+ errorElement: match.route.errorElement,
46
+ handle: match.route.handle,
47
+ hasAction: !!match.route.action,
48
+ hasErrorBoundary: !!match.route.hasErrorBoundary,
49
+ hasLoader: !!match.route.loader,
50
+ hasClientLoader: !!match.route.hasClientLoader,
51
+ id: match.route.id,
52
+ index: match.route.index,
53
+ params: match.params,
54
+ parentId: (parentMatch === null || parentMatch === void 0 ? void 0 : parentMatch.route.id) || match.route.parentId,
55
+ path: match.route.path,
56
+ pathname: match.pathname,
57
+ pathnameBase: match.pathnameBase
58
+ };
59
+ })
60
+ };
61
+ };
62
+ const handleRSCRedirect = (headers, basename, status) => {
63
+ const newHeaders = new Headers(headers);
64
+ let redirectUrl = headers.get("Location");
65
+ if (basename !== "/") {
66
+ redirectUrl = redirectUrl.replace(basename, "");
67
+ }
68
+ newHeaders.set("X-Modernjs-Redirect", redirectUrl);
69
+ newHeaders.set("X-Modernjs-BaseUrl", basename);
70
+ newHeaders.delete("Location");
71
+ return new Response(null, {
72
+ status,
73
+ headers: newHeaders
74
+ });
75
+ };
76
+ const prepareRSCRoutes = async (routes) => {
77
+ const isLazyComponent = (component) => {
78
+ return component && typeof component === "object" && component._init !== void 0 && component._payload !== void 0;
79
+ };
80
+ const processRoutes = async (routesList) => {
81
+ await Promise.all(routesList.map(async (route) => {
82
+ if ("lazyImport" in route && isLazyComponent(route.component)) {
83
+ route.component = (await route.lazyImport()).default;
84
+ }
85
+ if (route.children && Array.isArray(route.children)) {
86
+ await processRoutes(route.children);
87
+ }
88
+ }));
89
+ };
90
+ await processRoutes(routes);
91
+ };
92
+ const mergeRoutes = (routes, originalRoutes) => {
93
+ if (!originalRoutes || !Array.isArray(originalRoutes)) {
94
+ return routes;
95
+ }
96
+ const routesMap = /* @__PURE__ */ new Map();
97
+ const buildRoutesMap = (routesList) => {
98
+ routesList.forEach((route) => {
99
+ if (route.id) {
100
+ routesMap.set(route.id, route);
101
+ }
102
+ if ("children" in route && route.children && Array.isArray(route.children)) {
103
+ buildRoutesMap(route.children);
104
+ }
105
+ });
106
+ };
107
+ buildRoutesMap(routes);
108
+ const mergeRoutesRecursive = (origRoutes) => {
109
+ return origRoutes.map((origRoute) => {
110
+ if (origRoute.id && routesMap.has(origRoute.id)) {
111
+ const matchedRoute = routesMap.get(origRoute.id);
112
+ const result = {
113
+ loader: origRoute.hasClientLoader ? origRoute.loader : void 0,
114
+ ...matchedRoute
115
+ };
116
+ if (origRoute.children && Array.isArray(origRoute.children)) {
117
+ result.children = mergeRoutesRecursive(origRoute.children);
118
+ }
119
+ return result;
120
+ }
121
+ return origRoute;
122
+ });
123
+ };
124
+ return mergeRoutesRecursive(originalRoutes);
125
+ };
126
+ const findRouteInTree = (routes, routeId) => {
127
+ for (const route of routes) {
128
+ if (route.id === routeId) {
129
+ return route;
130
+ }
131
+ if (route.children && Array.isArray(route.children)) {
132
+ const found = findRouteInTree(route.children, routeId);
133
+ if (found) {
134
+ return found;
135
+ }
136
+ }
137
+ }
138
+ return null;
139
+ };
140
+ const createClientRouterFromPayload = (payload, originalRoutes, basename = "") => {
141
+ const processedRoutes = payload.routes.reduceRight((previous, route) => {
142
+ if (previous.length > 0) {
143
+ return [
144
+ {
145
+ ...route,
146
+ children: previous
147
+ }
148
+ ];
149
+ }
150
+ return [
151
+ route
152
+ ];
153
+ }, []);
154
+ const mergedRoutes = mergeRoutes(processedRoutes, originalRoutes);
155
+ const router = createBrowserRouter(mergedRoutes, {
156
+ //@ts-ignore
157
+ hydrationData: payload,
158
+ basename,
159
+ dataStrategy: async (context) => {
160
+ const { request, matches } = context;
161
+ const results = {};
162
+ const clientMatches = matches.filter((match) => match.route.hasClientLoader);
163
+ const fetchPromise = fetch(request.url, {
164
+ headers: {
165
+ "x-rsc-tree": "true"
166
+ }
167
+ });
168
+ const clientLoadersPromise = clientMatches.length > 0 ? Promise.all(clientMatches.map(async (clientMatch) => {
169
+ const foundRoute = findRouteInTree(originalRoutes, clientMatch.route.id);
170
+ clientMatch.route.loader = foundRoute === null || foundRoute === void 0 ? void 0 : foundRoute.loader;
171
+ const res2 = await clientMatch.resolve();
172
+ return {
173
+ routeId: clientMatch.route.id,
174
+ result: res2
175
+ };
176
+ })) : Promise.resolve([]);
177
+ const res = await fetchPromise;
178
+ const redirectLocation = res.headers.get("X-Modernjs-Redirect");
179
+ if (redirectLocation) {
180
+ matches.forEach((match) => {
181
+ const routeId = match.route.id;
182
+ if (routeId) {
183
+ results[routeId] = {
184
+ type: "redirect",
185
+ result: redirect(redirectLocation)
186
+ };
187
+ }
188
+ });
189
+ return results;
190
+ }
191
+ const [clientLoaderResults] = await Promise.all([
192
+ clientLoadersPromise
193
+ ]);
194
+ clientLoaderResults.forEach(({ routeId, result }) => {
195
+ results[routeId] = result;
196
+ });
197
+ const payload2 = await createFromReadableStream(res.body);
198
+ if (typeof payload2.type === "undefined" || payload2.type !== "render") {
199
+ throw new Error("Unexpected payload type");
200
+ }
201
+ matches.forEach((match) => {
202
+ var _payload_loaderData;
203
+ const routeId = match.route.id;
204
+ const matchedRoute = payload2.routes.find((route) => route.id === routeId);
205
+ if (matchedRoute) {
206
+ router.patchRoutes(matchedRoute.parentId, [
207
+ matchedRoute
208
+ ], true);
209
+ }
210
+ if ((_payload_loaderData = payload2.loaderData) === null || _payload_loaderData === void 0 ? void 0 : _payload_loaderData[routeId]) {
211
+ results[routeId] = {
212
+ type: "data",
213
+ result: payload2.loaderData[routeId]
214
+ };
215
+ }
216
+ });
217
+ return results;
218
+ }
219
+ });
220
+ return router;
221
+ };
222
+ const createRSCStaticRouterComponent = (payload, basename) => {
223
+ const routerContext = {
224
+ actionData: payload.actionData,
225
+ actionHeaders: {},
226
+ activeDeferreds: {},
227
+ basename: basename || "",
228
+ errors: payload.errors,
229
+ loaderData: payload.loaderData,
230
+ loaderHeaders: {},
231
+ location: payload.location,
232
+ statusCode: 200,
233
+ matches: payload.routes.map((match) => ({
234
+ params: match.params,
235
+ pathname: match.pathname,
236
+ pathnameBase: match.pathnameBase,
237
+ route: {
238
+ id: match.id,
239
+ action: match.hasAction || !!match.clientAction,
240
+ handle: match.handle,
241
+ hasErrorBoundary: match.hasErrorBoundary,
242
+ loader: match.hasLoader || !!match.clientLoader,
243
+ index: match.index,
244
+ path: match.path,
245
+ shouldRevalidate: match.shouldRevalidate
246
+ }
247
+ }))
248
+ };
249
+ const processedRoutes = payload.routes.reduceRight((previous, route) => {
250
+ if (previous.length > 0) {
251
+ return [
252
+ {
253
+ ...route,
254
+ children: previous
255
+ }
256
+ ];
257
+ }
258
+ return [
259
+ route
260
+ ];
261
+ }, []);
262
+ const router = createStaticRouter(processedRoutes, routerContext);
263
+ return /* @__PURE__ */ _jsx(StaticRouterProvider, {
264
+ context: routerContext,
265
+ router,
266
+ hydrate: false
267
+ });
268
+ };
269
+ const RSCStaticRouter = ({ basename }) => {
270
+ const payload = safeUse(safeUse(ElementsContext));
271
+ if (!payload || payload.type !== "render") {
272
+ return null;
273
+ }
274
+ return /* @__PURE__ */ _jsx(_Fragment, {
275
+ children: createRSCStaticRouterComponent(payload, basename)
276
+ });
277
+ };
278
+ export {
279
+ RSCStaticRouter,
280
+ createClientRouterFromPayload,
281
+ createServerPayload,
282
+ handleRSCRedirect,
283
+ prepareRSCRoutes
284
+ };
@@ -2,6 +2,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { renderNestedRoute } from "@modern-js/runtime-utils/browser";
3
3
  import { UNSAFE_ErrorResponseImpl as ErrorResponseImpl } from "@modern-js/runtime-utils/remix-router";
4
4
  import { Route, isRouteErrorResponse } from "@modern-js/runtime-utils/router";
5
+ import React from "react";
5
6
  import { DefaultNotFound } from "./DefaultNotFound";
6
7
  import DeferredDataScripts from "./DeferredDataScripts";
7
8
  function getRouteComponents(routes, { globalApp, ssrMode, props }) {
@@ -41,6 +42,76 @@ function getRouteComponents(routes, { globalApp, ssrMode, props }) {
41
42
  }, "*"));
42
43
  return routeElements;
43
44
  }
45
+ function getRouteObjects(routes, { globalApp, ssrMode, props }) {
46
+ const createLayoutElement = (Component) => {
47
+ const GlobalLayout = globalApp;
48
+ if (!GlobalLayout) {
49
+ return Component;
50
+ }
51
+ const LayoutWrapper = (props2) => {
52
+ const LayoutComponent = GlobalLayout;
53
+ return /* @__PURE__ */ _jsx(LayoutComponent, {
54
+ Component,
55
+ ...props2
56
+ });
57
+ };
58
+ return LayoutWrapper;
59
+ };
60
+ const routeObjects = [];
61
+ for (const route of routes) {
62
+ if (route.type === "nested") {
63
+ const nestedRouteObject = {
64
+ path: route.path,
65
+ id: route.id,
66
+ loader: route.loader,
67
+ action: route.action,
68
+ hasErrorBoundary: route.hasErrorBoundary,
69
+ shouldRevalidate: route.shouldRevalidate,
70
+ handle: route.handle,
71
+ index: route.index,
72
+ hasClientLoader: !!route.clientData,
73
+ Component: route.component ? route.component : void 0,
74
+ errorElement: route.error ? /* @__PURE__ */ _jsx(route.error, {}) : void 0,
75
+ children: route.children ? route.children.map((child) => getRouteObjects([
76
+ child
77
+ ], {
78
+ globalApp,
79
+ ssrMode,
80
+ props
81
+ })[0]) : void 0
82
+ };
83
+ routeObjects.push(nestedRouteObject);
84
+ } else {
85
+ if (typeof route.component === "function" || typeof route.component === "object") {
86
+ const LayoutComponent = createLayoutElement(route.component);
87
+ const routeObject = {
88
+ path: route.path,
89
+ element: /* @__PURE__ */ React.createElement(LayoutComponent)
90
+ };
91
+ routeObjects.push(routeObject);
92
+ }
93
+ }
94
+ }
95
+ routeObjects.push({
96
+ path: "*",
97
+ element: /* @__PURE__ */ _jsx(DefaultNotFound, {})
98
+ });
99
+ return routeObjects;
100
+ }
101
+ function createRouteObjectsFromConfig({ routesConfig, props, ssrMode }) {
102
+ if (!routesConfig) {
103
+ return null;
104
+ }
105
+ const { routes, globalApp } = routesConfig;
106
+ if (!routes) {
107
+ return null;
108
+ }
109
+ return getRouteObjects(routes, {
110
+ globalApp,
111
+ ssrMode,
112
+ props
113
+ });
114
+ }
44
115
  function renderRoutes({ routesConfig, props, ssrMode }) {
45
116
  if (!routesConfig) {
46
117
  return null;
@@ -58,7 +129,7 @@ function renderRoutes({ routesConfig, props, ssrMode }) {
58
129
  }
59
130
  function getLocation(serverContext) {
60
131
  var _url_replace;
61
- const { pathname, url } = (serverContext === null || serverContext === void 0 ? void 0 : serverContext.request) || {};
132
+ const { pathname = "", url = "" } = (serverContext === null || serverContext === void 0 ? void 0 : serverContext.request) || {};
62
133
  const cleanUrl = url === null || url === void 0 ? void 0 : (_url_replace = url.replace("http://", "")) === null || _url_replace === void 0 ? void 0 : _url_replace.replace("https://", "");
63
134
  const index = (cleanUrl || "").indexOf(pathname);
64
135
  if (index === -1) {
@@ -131,9 +202,11 @@ function deserializeErrors(errors) {
131
202
  return serialized;
132
203
  }
133
204
  export {
205
+ createRouteObjectsFromConfig,
134
206
  deserializeErrors,
135
207
  getLocation,
136
208
  getRouteComponents,
209
+ getRouteObjects,
137
210
  renderRoutes,
138
211
  serializeErrors,
139
212
  standardSlash,
@@ -1 +1,7 @@
1
1
  export * from "@modern-js/render/client";
2
+ const isRedirectResponse = (res) => {
3
+ return res.headers.get("X-Modernjs-Redirect") != null;
4
+ };
5
+ export {
6
+ isRedirectResponse
7
+ };
@@ -1 +1,36 @@
1
1
  export * from "@modern-js/render/rsc";
2
+ async function processRSCStream(rscStream, controller, encoder) {
3
+ try {
4
+ const reader = rscStream.getReader();
5
+ const decoder = new TextDecoder("utf-8", {
6
+ fatal: true
7
+ });
8
+ while (true) {
9
+ const { done, value } = await reader.read();
10
+ if (done)
11
+ break;
12
+ try {
13
+ const chunk = JSON.stringify(decoder.decode(value, {
14
+ stream: true
15
+ }));
16
+ const scriptTag = `<script>(self.__FLIGHT_DATA||=[]).push(${chunk})</script>`;
17
+ controller.enqueue(encoder.encode(scriptTag));
18
+ } catch (err) {
19
+ const base64 = JSON.stringify(btoa(String.fromCodePoint(...value)));
20
+ const scriptTag = `<script>(self.__FLIGHT_DATA||=[]).push(Uint8Array.from(atob(${base64}), m => m.codePointAt(0)))</script>`;
21
+ controller.enqueue(encoder.encode(scriptTag));
22
+ }
23
+ }
24
+ const remaining = decoder.decode();
25
+ if (remaining.length) {
26
+ const scriptTag = `<script>(self.__FLIGHT_DATA||=[]).push(${JSON.stringify(remaining)})</script>`;
27
+ controller.enqueue(encoder.encode(scriptTag));
28
+ }
29
+ controller.close();
30
+ } catch (error) {
31
+ controller.error(error);
32
+ }
33
+ }
34
+ export {
35
+ processRSCStream
36
+ };
@@ -1,11 +1,12 @@
1
1
  import type { RuntimePluginConfig } from '@modern-js/app-tools';
2
- export declare const entryForCSRWithRSC: ({ metaName, entryName, urlPath, mountId, }: {
2
+ export declare const entryForCSRWithRSC: ({ metaName, entryName, urlPath, mountId, isNestedRouter, }: {
3
3
  metaName: string;
4
4
  entryName: string;
5
5
  urlPath?: string;
6
6
  mountId?: string;
7
+ isNestedRouter?: string;
7
8
  }) => string;
8
- export declare const index: ({ srcDirectory, internalSrcAlias, metaName, entry, entryName, customEntry, customBootstrap, mountId, enableRsc, }: {
9
+ export declare const index: ({ srcDirectory, internalSrcAlias, metaName, entry, entryName, customEntry, customBootstrap, mountId, enableRsc, isNestedRouter, }: {
9
10
  srcDirectory: string;
10
11
  internalSrcAlias: string;
11
12
  metaName: string;
@@ -15,6 +16,7 @@ export declare const index: ({ srcDirectory, internalSrcAlias, metaName, entry,
15
16
  customBootstrap?: string | false;
16
17
  mountId?: string;
17
18
  enableRsc?: boolean;
19
+ isNestedRouter?: boolean;
18
20
  }) => string;
19
21
  export declare const register: () => string;
20
22
  export declare const runtimeRegister: ({ entryName, srcDirectory, internalSrcAlias, metaName, runtimeConfigFile, runtimePlugins, }: {
@@ -2,8 +2,9 @@ type ServerIndexOptinos = GenHandlerCodeOptions & {
2
2
  entryName: string;
3
3
  };
4
4
  export declare const serverIndex: (options: ServerIndexOptinos) => string;
5
- export declare const entryForCSRWithRSC: ({ metaName, }: {
5
+ export declare const entryForCSRWithRSC: ({ metaName, entryName, }: {
6
6
  metaName: string;
7
+ entryName: string;
7
8
  }) => string;
8
9
  type GenHandlerCodeOptions = {
9
10
  customServerEntry?: string | false;
@@ -1,5 +1,5 @@
1
1
  import type { Plugin, RuntimePluginFuture } from './core/plugin';
2
- import type { RouterConfig } from './router';
2
+ import type { RouterConfig } from './router/internal';
3
3
  export declare const isBrowser: () => boolean;
4
4
  export interface AppConfig {
5
5
  router?: Pick<RouterConfig, 'future' | 'basename'>;
@@ -1,4 +1,4 @@
1
- import type { RouterConfig } from './router';
1
+ import type { RouterConfig } from './router/internal';
2
2
  export interface RuntimeUserConfig {
3
3
  runtime?: {
4
4
  router?: boolean | RouterConfig;
@@ -1,8 +1,37 @@
1
1
  import type { InternalRuntimeContext } from '@modern-js/plugin-v2';
2
+ import type { RouterState } from '@modern-js/runtime-utils/remix-router';
2
3
  import type { NestedRoute, PageRoute } from '@modern-js/types';
4
+ import type React from 'react';
3
5
  import type { AppConfig } from '../../common';
4
6
  import type { RuntimeExtends } from '../plugin/types';
5
7
  export { type RuntimeContext, RuntimeReactContext, getInitialContext, } from './runtime';
8
+ export type PayloadRoute = {
9
+ clientAction?: any;
10
+ clientLoader?: any;
11
+ element?: React.ReactNode;
12
+ errorElement?: React.ReactNode;
13
+ handle?: any;
14
+ hasAction: boolean;
15
+ hasErrorBoundary: boolean;
16
+ hasLoader: boolean;
17
+ id: string;
18
+ index?: boolean;
19
+ params: Record<string, string>;
20
+ parentId?: string;
21
+ path?: string;
22
+ pathname: string;
23
+ pathnameBase: string;
24
+ shouldRevalidate?: any;
25
+ };
26
+ export type ServerPayload = {
27
+ type: 'render';
28
+ actionData: RouterState['actionData'];
29
+ errors: RouterState['errors'];
30
+ loaderData: RouterState['loaderData'];
31
+ location: RouterState['location'];
32
+ routes: PayloadRoute[];
33
+ originalRoutes?: PayloadRoute[];
34
+ };
6
35
  interface GlobalContext {
7
36
  entryName?: string;
8
37
  /**
@@ -30,16 +59,22 @@ interface GlobalContext {
30
59
  * RSCRoot
31
60
  */
32
61
  RSCRoot?: React.ComponentType;
62
+ isRscClient?: boolean;
63
+ serverPayload?: ServerPayload;
64
+ enableRsc?: boolean;
33
65
  }
66
+ export { getServerPayload, setServerPayload } from './serverPayload.server';
67
+ export declare function getGlobalIsRscClient(): boolean | undefined;
68
+ export declare function getGlobalEnableRsc(): boolean | undefined;
34
69
  export declare function setGlobalContext(context: Omit<GlobalContext, 'appConfig' | 'internalRuntimeContext'> & {
35
70
  appConfig?: () => AppConfig;
36
71
  }): void;
37
72
  export declare function getCurrentEntryName(): string | undefined;
38
- export declare function getGlobalRSCRoot(): import("react").ComponentType<{}> | undefined;
73
+ export declare function getGlobalRSCRoot(): React.ComponentType<{}> | undefined;
39
74
  export declare function setGlobalInternalRuntimeContext(context: InternalRuntimeContext<RuntimeExtends>): void;
40
75
  export declare function getGlobalInternalRuntimeContext(): InternalRuntimeContext<Required<import("@modern-js/plugin-v2").RuntimePluginExtends<import("../plugin/types").RuntimeConfig, import("./runtime").RuntimeContext, {}, {}>>>;
41
- export declare function getGlobalApp(): import("react").ComponentType<{}> | undefined;
76
+ export declare function getGlobalApp(): React.ComponentType<{}> | undefined;
42
77
  export declare function getGlobalRoutes(): undefined | (NestedRoute | PageRoute)[];
43
78
  export declare function getGlobalAppInit(): any;
44
79
  export declare function getGlobalAppConfig(): any;
45
- export declare function getGlobalLayoutApp(): import("react").ComponentType<{}> | undefined;
80
+ export declare function getGlobalLayoutApp(): React.ComponentType<{}> | undefined;
@@ -0,0 +1,3 @@
1
+ import type { ServerPayload } from './index';
2
+ export declare const getServerPayload: () => ServerPayload | undefined;
3
+ export declare const setServerPayload: (payload: ServerPayload) => void;
@@ -8,6 +8,6 @@ export type HandleRequestOptions = Exclude<RequestHandlerOptions, 'staticGenerat
8
8
  export type HandleRequest = (request: Request, ServerRoot: React.ComponentType, // App, routes,
9
9
  options: HandleRequestOptions) => Promise<Response>;
10
10
  export type CreateRequestHandler = (handleRequest: HandleRequest, options?: {
11
- enableRsc: boolean;
11
+ enableRsc?: boolean;
12
12
  }) => Promise<RequestHandler>;
13
13
  export declare const createRequestHandler: CreateRequestHandler;
@@ -1,4 +1,4 @@
1
- import type { RouterConfig } from './router';
1
+ import type { RouterConfig } from './router/internal';
2
2
  export type { Plugin, RuntimePluginFuture } from './core';
3
3
  export type { AppConfig, RuntimeConfig } from './common';
4
4
  export { isBrowser } from './common';
@@ -3,3 +3,4 @@ import type { CLIPluginAPI } from '@modern-js/plugin-v2';
3
3
  import type { Entrypoint } from '@modern-js/types';
4
4
  export declare const generateCode: (appContext: AppToolsContext<"shared">, config: AppNormalizedConfig<"shared">, entrypoints: Entrypoint[], api: CLIPluginAPI<AppTools<"shared">>, isRouterV5: boolean) => Promise<void>;
5
5
  export declare function generatorRegisterCode(internalDirectory: string, entryName: string, code: string): void;
6
+ export declare function generatorServerRegisterCode(internalDirectory: string, entryName: string, code: string): void;
@@ -3,7 +3,7 @@ import type { Entrypoint, NestedRouteForCli, PageRoute, RouteLegacy, SSRMode } f
3
3
  export declare const routesForServer: ({ routesForServerLoaderMatches, }: {
4
4
  routesForServerLoaderMatches: (NestedRouteForCli | PageRoute)[];
5
5
  }) => string;
6
- export declare const fileSystemRoutes: ({ metaName, routes, ssrMode, nestedRoutesEntry, entryName, internalDirectory, splitRouteChunks, }: {
6
+ export declare const fileSystemRoutes: ({ metaName, routes, ssrMode, nestedRoutesEntry, entryName, internalDirectory, splitRouteChunks, isRscClient, }: {
7
7
  metaName: string;
8
8
  routes: RouteLegacy[] | (NestedRouteForCli | PageRoute)[];
9
9
  ssrMode?: SSRMode;
@@ -11,13 +11,15 @@ export declare const fileSystemRoutes: ({ metaName, routes, ssrMode, nestedRoute
11
11
  entryName: string;
12
12
  internalDirectory: string;
13
13
  splitRouteChunks?: boolean;
14
+ isRscClient?: boolean;
14
15
  }) => Promise<string>;
15
16
  export declare function ssrLoaderCombinedModule(entrypoints: Entrypoint[], entrypoint: Entrypoint, config: AppNormalizedConfig<'shared'>, appContext: AppToolsContext<'shared'>): string | null;
16
- export declare const runtimeGlobalContext: ({ entryName, metaName, srcDirectory, nestedRoutesEntry, internalSrcAlias, globalApp, }: {
17
+ export declare const runtimeGlobalContext: ({ entryName, metaName, srcDirectory, nestedRoutesEntry, internalSrcAlias, globalApp, rscType, }: {
17
18
  entryName: string;
18
19
  metaName: string;
19
20
  srcDirectory: string;
20
21
  nestedRoutesEntry?: string;
21
22
  internalSrcAlias: string;
22
23
  globalApp?: string | false;
24
+ rscType?: "server" | "client" | false;
23
25
  }) => Promise<string>;
@@ -1,3 +1 @@
1
- export { default as router } from './runtime';
2
- export { default } from './runtime';
3
1
  export * from './runtime';
@@ -0,0 +1,2 @@
1
+ export * from './runtime/internal';
2
+ export { routerPlugin as default } from './runtime/internal';
@@ -1,6 +1,5 @@
1
1
  import { type LinkProps as RouterLinkProps, type NavLinkProps as RouterNavLinkProps } from '@modern-js/runtime-utils/router';
2
2
  import React from 'react';
3
- export declare function composeEventHandlers<EventType extends React.SyntheticEvent | Event>(theirHandler: ((event: EventType) => any) | undefined, ourHandler: (event: EventType) => any): (event: EventType) => any;
4
3
  /**
5
4
  * Modified from https://github.com/remix-run/remix/blob/9a0601bd704d2f3ee622e0ddacab9b611eb0c5bc/packages/remix-react/components.tsx#L218
6
5
  *
@@ -109,7 +109,7 @@ export declare const preResolvedFnStr = "function p(e,r){return void 0!==r?Promi
109
109
  Object.assign(_ROUTER_DATA.loaderData[routeIdJsonStr], source);
110
110
  };
111
111
  */
112
- export declare const mergeLoaderDataStr = "function mergeLoaderData(e,n){const r=n.reduce((function(e,{key:n,routerDataFnName:r,routerDataFnArgs:a}){const t=a.map((e=>{if(\"undefined\"!==e&&null!==e)return JSON.parse(e)}));return console.info(\"args\",t),{...e,[n]:_ROUTER_DATA[r](...t)}}),{});Object.assign(_ROUTER_DATA.loaderData[e],r)}";
112
+ export declare const mergeLoaderDataStr = "function mergeLoaderData(e,n){var r=n.reduce((function(e,{key:n,routerDataFnName:r,routerDataFnArgs:a}){var t=a.map((e=>{if(\"undefined\"!==e&&null!==e)return JSON.parse(e)}));return console.info(\"args\",t),{...e,[n]:_ROUTER_DATA[r](...t)}}),{});Object.assign(_ROUTER_DATA.loaderData[e],r)}";
113
113
  /**
114
114
  * This original string is: ${setupFnStr};${resolveFnStr};${preResolvedFnStr};
115
115
  * function mergeData (routeIdJsonStr, deferredKeyPromiseManifests) {
@@ -119,7 +119,7 @@ export declare const mergeLoaderDataStr = "function mergeLoaderData(e,n){const r
119
119
  Object.assign(_ROUTER_DATA.loaderData[routeIdJsonStr], source);
120
120
  };
121
121
  */
122
- export declare const initRouterDataAttrs = "_ROUTER_DATA.s = function s(r,e){_ROUTER_DATA.r=_ROUTER_DATA.r||{},_ROUTER_DATA.r[r]=_ROUTER_DATA.r[r]||{};return new Promise((function(A,R){_ROUTER_DATA.r[r][e]={resolve:A,reject:R}}))};_ROUTER_DATA.r = function r(e,r,o,A){A?_ROUTER_DATA.r[e][r].reject(A):_ROUTER_DATA.r[e][r].resolve(o)};_ROUTER_DATA.p = function p(e,r){return void 0!==r?Promise.reject(new Error(r.message)):Promise.resolve(e)};function mergeLoaderData(e,n){const r=n.reduce((function(e,{key:n,routerDataFnName:r,routerDataFnArgs:a}){const t=a.map((e=>{if(\"undefined\"!==e&&null!==e)return JSON.parse(e)}));return console.info(\"args\",t),{...e,[n]:_ROUTER_DATA[r](...t)}}),{});Object.assign(_ROUTER_DATA.loaderData[e],r)}";
122
+ export declare const initRouterDataAttrs = "_ROUTER_DATA.s = function s(r,e){_ROUTER_DATA.r=_ROUTER_DATA.r||{},_ROUTER_DATA.r[r]=_ROUTER_DATA.r[r]||{};return new Promise((function(A,R){_ROUTER_DATA.r[r][e]={resolve:A,reject:R}}))};_ROUTER_DATA.r = function r(e,r,o,A){A?_ROUTER_DATA.r[e][r].reject(A):_ROUTER_DATA.r[e][r].resolve(o)};_ROUTER_DATA.p = function p(e,r){return void 0!==r?Promise.reject(new Error(r.message)):Promise.resolve(e)};function mergeLoaderData(e,n){var r=n.reduce((function(e,{key:n,routerDataFnName:r,routerDataFnArgs:a}){var t=a.map((e=>{if(\"undefined\"!==e&&null!==e)return JSON.parse(e)}));return console.info(\"args\",t),{...e,[n]:_ROUTER_DATA[r](...t)}}),{});Object.assign(_ROUTER_DATA.loaderData[e],r)}";
123
123
  /**
124
124
  function runWindowFn() {
125
125
  window[document.currentScript.getAttribute('data-fn-name')](...JSON.parse(document.currentScript.getAttribute('data-fn-args')))
@@ -141,6 +141,6 @@ export declare const initRouterDataAttrs = "_ROUTER_DATA.s = function s(r,e){_RO
141
141
  initRouterData();
142
142
  ${initRouterDataAttrs}
143
143
  */
144
- export declare const modernInline = "function runWindowFn(){window[document.currentScript.getAttribute(\"data-fn-name\")](...JSON.parse(document.currentScript.getAttribute(\"data-fn-args\")))}function runRouterDataFn(){_ROUTER_DATA[document.currentScript.getAttribute(\"data-fn-name\")](...JSON.parse(document.currentScript.getAttribute(\"data-fn-args\")))}function initRouterData(e){var r=document.getElementById(e);if(r)try{_ROUTER_DATA=JSON.parse(r.textContent)}catch(r){console.error(\"parse \".concat(e,\" error\"),t),_ROUTER_DATA={}}};initRouterData('__MODERN_ROUTER_DATA__');_ROUTER_DATA.s = function s(r,e){_ROUTER_DATA.r=_ROUTER_DATA.r||{},_ROUTER_DATA.r[r]=_ROUTER_DATA.r[r]||{};return new Promise((function(A,R){_ROUTER_DATA.r[r][e]={resolve:A,reject:R}}))};_ROUTER_DATA.r = function r(e,r,o,A){A?_ROUTER_DATA.r[e][r].reject(A):_ROUTER_DATA.r[e][r].resolve(o)};_ROUTER_DATA.p = function p(e,r){return void 0!==r?Promise.reject(new Error(r.message)):Promise.resolve(e)};function mergeLoaderData(e,n){const r=n.reduce((function(e,{key:n,routerDataFnName:r,routerDataFnArgs:a}){const t=a.map((e=>{if(\"undefined\"!==e&&null!==e)return JSON.parse(e)}));return console.info(\"args\",t),{...e,[n]:_ROUTER_DATA[r](...t)}}),{});Object.assign(_ROUTER_DATA.loaderData[e],r)}";
144
+ export declare const modernInline = "function runWindowFn(){window[document.currentScript.getAttribute(\"data-fn-name\")].apply(window,JSON.parse(document.currentScript.getAttribute(\"data-fn-args\")))}function runRouterDataFn(){_ROUTER_DATA[document.currentScript.getAttribute(\"data-fn-name\")].apply(_ROUTER_DATA,JSON.parse(document.currentScript.getAttribute(\"data-fn-args\")))}function initRouterData(e){var r=document.getElementById(e);if(r)try{_ROUTER_DATA=JSON.parse(r.textContent)}catch(r){console.error(\"parse \".concat(e,\" error\"),t),_ROUTER_DATA={}}};initRouterData('__MODERN_ROUTER_DATA__');_ROUTER_DATA.s = function s(r,e){_ROUTER_DATA.r=_ROUTER_DATA.r||{},_ROUTER_DATA.r[r]=_ROUTER_DATA.r[r]||{};return new Promise((function(A,R){_ROUTER_DATA.r[r][e]={resolve:A,reject:R}}))};_ROUTER_DATA.r = function r(e,r,o,A){A?_ROUTER_DATA.r[e][r].reject(A):_ROUTER_DATA.r[e][r].resolve(o)};_ROUTER_DATA.p = function p(e,r){return void 0!==r?Promise.reject(new Error(r.message)):Promise.resolve(e)};function mergeLoaderData(e,n){var r=n.reduce((function(e,{key:n,routerDataFnName:r,routerDataFnArgs:a}){var t=a.map((e=>{if(\"undefined\"!==e&&null!==e)return JSON.parse(e)}));return console.info(\"args\",t),{...e,[n]:_ROUTER_DATA[r](...t)}}),{});Object.assign(_ROUTER_DATA.loaderData[e],r)}";
145
145
  export declare const runRouterDataFnStr = "runRouterDataFn();";
146
146
  export declare const runWindowFnStr = "runWindowFn();";