@modern-js/runtime 2.55.0 → 2.56.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 (45) hide show
  1. package/dist/cjs/cli/index.js +2 -3
  2. package/dist/cjs/cli/ssr/index.js +30 -14
  3. package/dist/cjs/core/browser/index.js +21 -1
  4. package/dist/cjs/core/plugin/index.js +2 -2
  5. package/dist/cjs/core/server/stream/createReadableStream.js +3 -3
  6. package/dist/cjs/core/server/string/index.js +2 -2
  7. package/dist/cjs/core/server/string/loadable.js +1 -1
  8. package/dist/cjs/core/server/string/prefetch.js +3 -3
  9. package/dist/cjs/core/utils/merge.js +53 -0
  10. package/dist/cjs/router/cli/code/index.js +2 -2
  11. package/dist/cjs/router/cli/entry.js +16 -15
  12. package/dist/cjs/router/runtime/PrefetchLink.js +1 -1
  13. package/dist/cjs/router/runtime/plugin.node.js +10 -17
  14. package/dist/esm/cli/index.js +1 -2
  15. package/dist/esm/cli/ssr/index.js +33 -16
  16. package/dist/esm/core/browser/index.js +19 -1
  17. package/dist/esm/core/plugin/index.js +1 -1
  18. package/dist/esm/core/server/stream/createReadableStream.js +99 -78
  19. package/dist/esm/core/server/string/index.js +3 -3
  20. package/dist/esm/core/server/string/loadable.js +1 -1
  21. package/dist/esm/core/server/string/prefetch.js +5 -5
  22. package/dist/esm/core/utils/merge.js +32 -0
  23. package/dist/esm/router/cli/code/index.js +3 -3
  24. package/dist/esm/router/cli/entry.js +19 -17
  25. package/dist/esm/router/runtime/PrefetchLink.js +1 -1
  26. package/dist/esm/router/runtime/plugin.node.js +10 -51
  27. package/dist/esm-node/cli/index.js +1 -2
  28. package/dist/esm-node/cli/ssr/index.js +30 -14
  29. package/dist/esm-node/core/browser/index.js +21 -1
  30. package/dist/esm-node/core/plugin/index.js +1 -1
  31. package/dist/esm-node/core/server/stream/createReadableStream.js +2 -2
  32. package/dist/esm-node/core/server/string/index.js +2 -2
  33. package/dist/esm-node/core/server/string/loadable.js +1 -1
  34. package/dist/esm-node/core/server/string/prefetch.js +3 -3
  35. package/dist/esm-node/core/utils/merge.js +29 -0
  36. package/dist/esm-node/router/cli/code/index.js +2 -2
  37. package/dist/esm-node/router/cli/entry.js +16 -15
  38. package/dist/esm-node/router/runtime/PrefetchLink.js +1 -1
  39. package/dist/esm-node/router/runtime/plugin.node.js +10 -16
  40. package/dist/types/core/browser/index.d.ts +1 -0
  41. package/dist/types/core/plugin/index.d.ts +1 -1
  42. package/dist/types/core/server/string/prefetch.d.ts +2 -1
  43. package/dist/types/core/utils/merge.d.ts +6 -0
  44. package/dist/types/router/runtime/plugin.node.d.ts +0 -2
  45. package/package.json +14 -15
@@ -1,7 +1,8 @@
1
+ import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
1
2
  import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
3
  import { _ as _instanceof } from "@swc/helpers/_/_instanceof";
4
+ import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
3
5
  import { Transform } from "stream";
4
- import { renderToPipeableStream } from "react-dom/server";
5
6
  import { createReadableStreamFromReadable } from "@modern-js/runtime-utils/node";
6
7
  import { ServerStyleSheet } from "styled-components";
7
8
  import checkIsBot from "isbot";
@@ -9,84 +10,104 @@ import { ESCAPED_SHELL_STREAM_END_MARK } from "../../../common";
9
10
  import { RenderLevel } from "../../constants";
10
11
  import { getTemplates } from "./template";
11
12
  import { ShellChunkStatus, getReadableStreamFromString } from "./shared";
12
- var createReadableStreamFromElement = function(request, rootElement, options) {
13
- var runtimeContext = options.runtimeContext, htmlTemplate = options.htmlTemplate, config = options.config, ssrConfig = options.ssrConfig;
14
- var shellChunkStatus = ShellChunkStatus.START;
15
- var renderLevel = RenderLevel.SERVER_RENDER;
16
- var forceStream2String = Boolean(process.env.MODERN_JS_STREAM_TO_STRING);
17
- var isbot = checkIsBot(request.headers.get("user-agent"));
18
- var onReady = isbot || forceStream2String ? "onAllReady" : "onShellReady";
19
- var sheet = new ServerStyleSheet();
20
- var chunkVec = [];
21
- var root = forceStream2String ? sheet.collectStyles(rootElement) : rootElement;
22
- return new Promise(function(resolve) {
23
- var _obj;
24
- var pipe = renderToPipeableStream(root, (_obj = {
25
- nonce: config.nonce
26
- }, _define_property(_obj, onReady, function() {
27
- var _options_onReady;
28
- var styledComponentsStyleTags = forceStream2String ? sheet.getStyleTags() : "";
29
- (_options_onReady = options[onReady]) === null || _options_onReady === void 0 ? void 0 : _options_onReady.call(options);
30
- getTemplates(htmlTemplate, {
31
- request,
32
- ssrConfig,
33
- renderLevel,
34
- runtimeContext,
35
- config,
36
- styledComponentsStyleTags
37
- }).then(function(param) {
38
- var shellAfter = param.shellAfter, shellBefore = param.shellBefore;
39
- var body = new Transform({
40
- transform: function transform(chunk, _encoding, callback) {
41
- try {
42
- if (shellChunkStatus !== ShellChunkStatus.FINISH) {
43
- chunkVec.push(chunk.toString());
44
- var concatedChunk = chunkVec.join("");
45
- if (concatedChunk.includes(ESCAPED_SHELL_STREAM_END_MARK)) {
46
- concatedChunk = concatedChunk.replace(ESCAPED_SHELL_STREAM_END_MARK, "");
47
- shellChunkStatus = ShellChunkStatus.FINISH;
48
- this.push("".concat(shellBefore).concat(concatedChunk).concat(shellAfter));
49
- }
50
- } else {
51
- this.push(chunk);
52
- }
53
- callback();
54
- } catch (e) {
55
- if (_instanceof(e, Error)) {
56
- callback(e);
57
- } else {
58
- callback(new Error("Received unkown error when streaming"));
59
- }
60
- }
61
- }
62
- });
63
- var stream = createReadableStreamFromReadable(body);
64
- resolve(stream);
65
- pipe(body);
66
- });
67
- }), _define_property(_obj, "onShellError", function onShellError(error) {
68
- renderLevel = RenderLevel.CLIENT_RENDER;
69
- getTemplates(htmlTemplate, {
70
- request,
71
- ssrConfig,
72
- renderLevel,
73
- runtimeContext,
74
- config
75
- }).then(function(param) {
76
- var shellAfter = param.shellAfter, shellBefore = param.shellBefore;
77
- var _options_onShellError;
78
- var fallbackHtml = "".concat(shellBefore).concat(shellAfter);
79
- var readableStream = getReadableStreamFromString(fallbackHtml);
80
- resolve(readableStream);
81
- options === null || options === void 0 ? void 0 : (_options_onShellError = options.onShellError) === null || _options_onShellError === void 0 ? void 0 : _options_onShellError.call(options, error);
82
- });
83
- }), _define_property(_obj, "onError", function onError(error) {
84
- var _options_onError;
85
- renderLevel = RenderLevel.CLIENT_RENDER;
86
- options === null || options === void 0 ? void 0 : (_options_onError = options.onError) === null || _options_onError === void 0 ? void 0 : _options_onError.call(options, error);
87
- }), _obj)).pipe;
13
+ var createReadableStreamFromElement = function() {
14
+ var _ref = _async_to_generator(function(request, rootElement, options) {
15
+ var renderToPipeableStream, runtimeContext, htmlTemplate, config, ssrConfig, shellChunkStatus, renderLevel, forceStream2String, isbot, onReady, sheet, chunkVec, root;
16
+ return _ts_generator(this, function(_state) {
17
+ switch (_state.label) {
18
+ case 0:
19
+ return [
20
+ 4,
21
+ import("react-dom/server")
22
+ ];
23
+ case 1:
24
+ renderToPipeableStream = _state.sent().renderToPipeableStream;
25
+ runtimeContext = options.runtimeContext, htmlTemplate = options.htmlTemplate, config = options.config, ssrConfig = options.ssrConfig;
26
+ shellChunkStatus = ShellChunkStatus.START;
27
+ renderLevel = RenderLevel.SERVER_RENDER;
28
+ forceStream2String = Boolean(process.env.MODERN_JS_STREAM_TO_STRING);
29
+ isbot = checkIsBot(request.headers.get("user-agent"));
30
+ onReady = isbot || forceStream2String ? "onAllReady" : "onShellReady";
31
+ sheet = new ServerStyleSheet();
32
+ chunkVec = [];
33
+ root = forceStream2String ? sheet.collectStyles(rootElement) : rootElement;
34
+ return [
35
+ 2,
36
+ new Promise(function(resolve) {
37
+ var _obj;
38
+ var pipe = renderToPipeableStream(root, (_obj = {
39
+ nonce: config.nonce
40
+ }, _define_property(_obj, onReady, function() {
41
+ var _options_onReady;
42
+ var styledComponentsStyleTags = forceStream2String ? sheet.getStyleTags() : "";
43
+ (_options_onReady = options[onReady]) === null || _options_onReady === void 0 ? void 0 : _options_onReady.call(options);
44
+ getTemplates(htmlTemplate, {
45
+ request,
46
+ ssrConfig,
47
+ renderLevel,
48
+ runtimeContext,
49
+ config,
50
+ styledComponentsStyleTags
51
+ }).then(function(param) {
52
+ var shellAfter = param.shellAfter, shellBefore = param.shellBefore;
53
+ var body = new Transform({
54
+ transform: function transform(chunk, _encoding, callback) {
55
+ try {
56
+ if (shellChunkStatus !== ShellChunkStatus.FINISH) {
57
+ chunkVec.push(chunk.toString());
58
+ var concatedChunk = chunkVec.join("");
59
+ if (concatedChunk.includes(ESCAPED_SHELL_STREAM_END_MARK)) {
60
+ concatedChunk = concatedChunk.replace(ESCAPED_SHELL_STREAM_END_MARK, "");
61
+ shellChunkStatus = ShellChunkStatus.FINISH;
62
+ this.push("".concat(shellBefore).concat(concatedChunk).concat(shellAfter));
63
+ }
64
+ } else {
65
+ this.push(chunk);
66
+ }
67
+ callback();
68
+ } catch (e) {
69
+ if (_instanceof(e, Error)) {
70
+ callback(e);
71
+ } else {
72
+ callback(new Error("Received unkown error when streaming"));
73
+ }
74
+ }
75
+ }
76
+ });
77
+ var stream = createReadableStreamFromReadable(body);
78
+ resolve(stream);
79
+ pipe(body);
80
+ });
81
+ }), _define_property(_obj, "onShellError", function onShellError(error) {
82
+ renderLevel = RenderLevel.CLIENT_RENDER;
83
+ getTemplates(htmlTemplate, {
84
+ request,
85
+ ssrConfig,
86
+ renderLevel,
87
+ runtimeContext,
88
+ config
89
+ }).then(function(param) {
90
+ var shellAfter = param.shellAfter, shellBefore = param.shellBefore;
91
+ var _options_onShellError;
92
+ var fallbackHtml = "".concat(shellBefore).concat(shellAfter);
93
+ var readableStream = getReadableStreamFromString(fallbackHtml);
94
+ resolve(readableStream);
95
+ options === null || options === void 0 ? void 0 : (_options_onShellError = options.onShellError) === null || _options_onShellError === void 0 ? void 0 : _options_onShellError.call(options, error);
96
+ });
97
+ }), _define_property(_obj, "onError", function onError(error) {
98
+ var _options_onError;
99
+ renderLevel = RenderLevel.CLIENT_RENDER;
100
+ options === null || options === void 0 ? void 0 : (_options_onError = options.onError) === null || _options_onError === void 0 ? void 0 : _options_onError.call(options, error);
101
+ }), _obj)).pipe;
102
+ })
103
+ ];
104
+ }
105
+ });
88
106
  });
89
- };
107
+ return function createReadableStreamFromElement2(request, rootElement, options) {
108
+ return _ref.apply(this, arguments);
109
+ };
110
+ }();
90
111
  export {
91
112
  createReadableStreamFromElement
92
113
  };
@@ -25,7 +25,7 @@ var renderString = function() {
25
25
  return [
26
26
  2,
27
27
  run(headersData, /* @__PURE__ */ _async_to_generator(function() {
28
- var _runtimeContext_ssrContext, resource, runtimeContext, config, onError, onTiming, staticGenerate, tracer, routerContext, htmlTemplate, entryName, loadableStats, routeManifest, chunkSet, prefetchData, e, ssrConfig, collectors, rootElement, html;
28
+ var _runtimeContext_ssrContext, resource, runtimeContext, config, onError, onTiming, staticGenerate, tracer, routerContext, htmlTemplate, entryName, loadableStats, routeManifest, ssrConfig, chunkSet, prefetchData, e, collectors, rootElement, html;
29
29
  return _ts_generator(this, function(_state2) {
30
30
  switch (_state2.label) {
31
31
  case 0:
@@ -36,6 +36,7 @@ var renderString = function() {
36
36
  };
37
37
  routerContext = runtimeContext.routerContext;
38
38
  htmlTemplate = resource.htmlTemplate, entryName = resource.entryName, loadableStats = resource.loadableStats, routeManifest = resource.routeManifest;
39
+ ssrConfig = getSSRConfigByEntry(entryName, config.ssr, config.ssrByEntries, staticGenerate);
39
40
  chunkSet = {
40
41
  renderLevel: RenderLevel.CLIENT_RENDER,
41
42
  ssrScripts: "",
@@ -53,7 +54,7 @@ var renderString = function() {
53
54
  ]);
54
55
  return [
55
56
  4,
56
- prefetch(serverRoot, request, options, tracer)
57
+ prefetch(serverRoot, request, options, ssrConfig, tracer)
57
58
  ];
58
59
  case 2:
59
60
  prefetchData = _state2.sent();
@@ -70,7 +71,6 @@ var renderString = function() {
70
71
  4
71
72
  ];
72
73
  case 4:
73
- ssrConfig = getSSRConfigByEntry(entryName, config.ssr, config.ssrByEntries, staticGenerate);
74
74
  collectors = [
75
75
  new StyledCollector(chunkSet),
76
76
  new LoadableCollector({
@@ -243,7 +243,7 @@ var LoadableCollector = /* @__PURE__ */ function() {
243
243
  ];
244
244
  case 1:
245
245
  css = _state.sent();
246
- chunkSet.jsChunk += css.filter(function(css2) {
246
+ chunkSet.cssChunk += css.filter(function(css2) {
247
247
  return Boolean(css2);
248
248
  }).join("");
249
249
  return [
@@ -8,12 +8,12 @@ import { parseHeaders } from "@modern-js/runtime-utils/universal/request";
8
8
  import React from "react";
9
9
  import { SSRErrors, SSRTimings } from "../tracer";
10
10
  var prefetch = function() {
11
- var _ref = _async_to_generator(function(App, request, options, param) {
12
- var onError, onTiming, headersData, context, resource, config, entryName, loadableStats;
11
+ var _ref = _async_to_generator(function(App, request, options, ssrConfig, param) {
12
+ var onError, onTiming, headersData, context, resource, entryName, loadableStats;
13
13
  return _ts_generator(this, function(_state) {
14
14
  onError = param.onError, onTiming = param.onTiming;
15
15
  headersData = parseHeaders(request);
16
- context = options.runtimeContext, resource = options.resource, config = options.config;
16
+ context = options.runtimeContext, resource = options.resource;
17
17
  entryName = resource.entryName, loadableStats = resource.loadableStats;
18
18
  return [
19
19
  2,
@@ -22,7 +22,7 @@ var prefetch = function() {
22
22
  return _ts_generator(this, function(_state2) {
23
23
  switch (_state2.label) {
24
24
  case 0:
25
- if (!config.disablePrerender) {
25
+ if (typeof ssrConfig === "boolean" || !ssrConfig.disablePrerender) {
26
26
  try {
27
27
  end = time();
28
28
  if (loadableStats) {
@@ -111,7 +111,7 @@ var prefetch = function() {
111
111
  ];
112
112
  });
113
113
  });
114
- return function prefetch2(App, request, options, _) {
114
+ return function prefetch2(App, request, options, ssrConfig, _) {
115
115
  return _ref.apply(this, arguments);
116
116
  };
117
117
  }();
@@ -0,0 +1,32 @@
1
+ import { _ as _define_property } from "@swc/helpers/_/_define_property";
2
+ import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array";
3
+ function isObject(obj) {
4
+ return obj && typeof obj === "object" && !Array.isArray(obj);
5
+ }
6
+ function merge(target) {
7
+ for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
8
+ sources[_key - 1] = arguments[_key];
9
+ }
10
+ if (!sources.length) {
11
+ return target;
12
+ }
13
+ var source = sources.shift();
14
+ if (isObject(target) && isObject(source)) {
15
+ for (var key in source) {
16
+ if (isObject(source[key])) {
17
+ if (!target[key]) {
18
+ Object.assign(target, _define_property({}, key, {}));
19
+ }
20
+ merge(target[key], source[key]);
21
+ } else {
22
+ Object.assign(target, _define_property({}, key, source[key]));
23
+ }
24
+ }
25
+ }
26
+ return merge.apply(void 0, [
27
+ target
28
+ ].concat(_to_consumable_array(sources)));
29
+ }
30
+ export {
31
+ merge
32
+ };
@@ -16,18 +16,18 @@ var generateCode = function() {
16
16
  }
17
17
  function _generateEntryCode() {
18
18
  _generateEntryCode = _async_to_generator(function(entrypoint) {
19
- var entryName, isMainEntry, isAutoMount, fileSystemRoutes, metaName, _config_output, initialRoutes, nestedRoutes, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, route, routes, _$config, ssr, useSSG, mode, hasPageRoute, code, _, _tmp, routesServerFile, code1, serverLoaderCombined, serverLoaderFile;
19
+ var entryName, isMainEntry, isAutoMount, pageRoutesEntry, nestedRoutesEntry, metaName, _config_output, initialRoutes, nestedRoutes, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, route, routes, _$config, ssr, useSSG, mode, hasPageRoute, code, _, _tmp, routesServerFile, code1, serverLoaderCombined, serverLoaderFile;
20
20
  return _ts_generator(this, function(_state) {
21
21
  switch (_state.label) {
22
22
  case 0:
23
- entryName = entrypoint.entryName, isMainEntry = entrypoint.isMainEntry, isAutoMount = entrypoint.isAutoMount, fileSystemRoutes = entrypoint.fileSystemRoutes;
23
+ entryName = entrypoint.entryName, isMainEntry = entrypoint.isMainEntry, isAutoMount = entrypoint.isAutoMount, pageRoutesEntry = entrypoint.pageRoutesEntry, nestedRoutesEntry = entrypoint.nestedRoutesEntry;
24
24
  metaName = api.useAppContext().metaName;
25
25
  if (!isAutoMount)
26
26
  return [
27
27
  3,
28
28
  11
29
29
  ];
30
- if (!fileSystemRoutes)
30
+ if (!(pageRoutesEntry || nestedRoutesEntry))
31
31
  return [
32
32
  3,
33
33
  11
@@ -1,3 +1,5 @@
1
+ import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
2
+ import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
1
3
  import path from "path";
2
4
  import { JS_EXTENSIONS, findExists, fs, isRouterV5 } from "@modern-js/utils";
3
5
  import { hasApp } from "../../cli/entry";
@@ -23,31 +25,31 @@ var modifyEntrypoints = function(entrypoints) {
23
25
  if (!entrypoint.isAutoMount) {
24
26
  return entrypoint;
25
27
  }
28
+ if (entrypoint === null || entrypoint === void 0 ? void 0 : entrypoint.isCustomSourceEntry) {
29
+ if (entrypoint.fileSystemRoutes) {
30
+ if (isRouterV5(config)) {
31
+ throw Error("Custom entries with conventional routing not support use react router v5!");
32
+ }
33
+ entrypoint.nestedRoutesEntry = entrypoint.entry;
34
+ }
35
+ return entrypoint;
36
+ }
26
37
  var isHasApp = hasApp(entrypoint.absoluteEntryDir);
27
38
  if (isHasApp) {
28
39
  return entrypoint;
29
40
  }
30
- var isHasNestedRoutes = hasNestedRoutes(entrypoint.absoluteEntryDir);
31
41
  var isHasPages = hasPages(entrypoint.absoluteEntryDir);
32
- if (!isHasNestedRoutes && !isHasPages && !entrypoint.fileSystemRoutes) {
33
- return entrypoint;
34
- }
35
- if (entrypoint.fileSystemRoutes && !isRouterV5(config)) {
36
- entrypoint.nestedRoutesEntry = entrypoint.entry;
37
- } else if (!entrypoint.fileSystemRoutes) {
38
- entrypoint.fileSystemRoutes = {
42
+ if (isHasPages) {
43
+ entrypoint.pageRoutesEntry = path.join(entrypoint.absoluteEntryDir, PAGES_DIR_NAME);
44
+ entrypoint.fileSystemRoutes = _object_spread_props(_object_spread({}, entrypoint.fileSystemRoutes), {
39
45
  globalApp: findExists(JS_EXTENSIONS.map(function(ext) {
40
46
  return path.resolve(entrypoint.absoluteEntryDir, "./".concat(PAGES_DIR_NAME, "/").concat(FILE_SYSTEM_ROUTES_GLOBAL_LAYOUT).concat(ext));
41
47
  }))
42
- };
43
- if (isHasPages) {
44
- entrypoint.pageRoutesEntry = path.join(entrypoint.absoluteEntryDir, PAGES_DIR_NAME);
45
- }
46
- if (isHasNestedRoutes) {
47
- entrypoint.nestedRoutesEntry = path.join(entrypoint.absoluteEntryDir, NESTED_ROUTES_DIR);
48
- }
49
- } else {
50
- throw Error("Custom entries with conventional routing not support use react router v5!");
48
+ });
49
+ }
50
+ var isHasNestedRoutes = hasNestedRoutes(entrypoint.absoluteEntryDir);
51
+ if (isHasNestedRoutes) {
52
+ entrypoint.nestedRoutesEntry = path.join(entrypoint.absoluteEntryDir, NESTED_ROUTES_DIR);
51
53
  }
52
54
  return entrypoint;
53
55
  });
@@ -98,7 +98,7 @@ function _loadRouteModule() {
98
98
  return [
99
99
  4,
100
100
  Promise.all(chunkIds.map(function(chunkId) {
101
- return __webpack_chunk_load__ === null || __webpack_chunk_load__ === void 0 ? void 0 : __webpack_chunk_load__(String(chunkId));
101
+ return __webpack_chunk_load__ === null || __webpack_chunk_load__ === void 0 ? void 0 : __webpack_chunk_load__(chunkId);
102
102
  }))
103
103
  ];
104
104
  case 2:
@@ -2,7 +2,6 @@ import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
2
2
  import { _ as _instanceof } from "@swc/helpers/_/_instanceof";
3
3
  import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
4
4
  import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
5
- import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array";
6
5
  import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
7
6
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
8
7
  import { useContext } from "react";
@@ -18,54 +17,15 @@ import { getGlobalLayoutApp, getGlobalRoutes } from "../../core/context";
18
17
  import { renderRoutes, urlJoin } from "./utils";
19
18
  import { modifyRoutes as modifyRoutesHook } from "./hooks";
20
19
  import DeferredDataScripts from "./DeferredDataScripts.node";
21
- function createFetchHeaders(requestHeaders) {
22
- var headers = new Headers();
23
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0;
24
- try {
25
- for (var _iterator = Object.entries(requestHeaders || {})[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
26
- var _step_value = _sliced_to_array(_step.value, 2), key = _step_value[0], values = _step_value[1];
27
- if (values) {
28
- if (Array.isArray(values)) {
29
- var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = void 0;
30
- try {
31
- for (var _iterator1 = values[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true) {
32
- var value = _step1.value;
33
- headers.append(key, value);
34
- }
35
- } catch (err) {
36
- _didIteratorError1 = true;
37
- _iteratorError1 = err;
38
- } finally {
39
- try {
40
- if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
41
- _iterator1.return();
42
- }
43
- } finally {
44
- if (_didIteratorError1) {
45
- throw _iteratorError1;
46
- }
47
- }
48
- }
49
- } else {
50
- headers.set(key, values);
51
- }
52
- }
53
- }
54
- } catch (err) {
55
- _didIteratorError = true;
56
- _iteratorError = err;
57
- } finally {
58
- try {
59
- if (!_iteratorNormalCompletion && _iterator.return != null) {
60
- _iterator.return();
61
- }
62
- } finally {
63
- if (_didIteratorError) {
64
- throw _iteratorError;
65
- }
66
- }
67
- }
68
- return headers;
20
+ function createRemixReuqest(request) {
21
+ var method = "GET";
22
+ var headers = request.headers;
23
+ var controller = new AbortController();
24
+ return new Request(request.url, {
25
+ method,
26
+ headers,
27
+ signal: controller.signal
28
+ });
69
29
  }
70
30
  var routerPlugin = function(param) {
71
31
  var _param_basename = param.basename, basename = _param_basename === void 0 ? "" : _param_basename, routesConfig = param.routesConfig, createRoutes = param.createRoutes;
@@ -114,7 +74,7 @@ var routerPlugin = function(param) {
114
74
  query = createStaticHandler(routes, {
115
75
  basename: _basename
116
76
  }).query;
117
- remixRequest = context.ssrContext.request.raw;
77
+ remixRequest = createRemixReuqest(context.ssrContext.request.raw);
118
78
  end = time();
119
79
  return [
120
80
  4,
@@ -213,7 +173,6 @@ var routerPlugin = function(param) {
213
173
  var modifyRoutes = function() {
214
174
  };
215
175
  export {
216
- createFetchHeaders,
217
176
  modifyRoutes,
218
177
  routerPlugin
219
178
  };
@@ -1,6 +1,5 @@
1
1
  import path from "path";
2
2
  import { isReact18 as checkIsReact18, cleanRequireCache, createRuntimeExportsUtils } from "@modern-js/utils";
3
- import { rspack } from "@rsbuild/core";
4
3
  import { statePlugin } from "../state/cli";
5
4
  import { routerPlugin } from "../router/cli";
6
5
  import { documentPlugin } from "../document/cli";
@@ -112,7 +111,7 @@ const runtimePlugin = (params) => ({
112
111
  ]);
113
112
  }
114
113
  },
115
- rspack: (_config, { appendPlugins }) => {
114
+ rspack: (_config, { appendPlugins, rspack }) => {
116
115
  if (!isReact18) {
117
116
  appendPlugins([
118
117
  new rspack.IgnorePlugin({
@@ -19,6 +19,33 @@ const checkUseStringSSR = (config) => {
19
19
  const { output } = config;
20
20
  return Boolean(output === null || output === void 0 ? void 0 : output.ssg) || hasStringSSREntry(config);
21
21
  };
22
+ const ssrBuilderPlugin = (modernAPI) => ({
23
+ name: "@modern-js/builder-plugin-ssr",
24
+ setup(api) {
25
+ api.modifyEnvironmentConfig((config, { name, mergeEnvironmentConfig }) => {
26
+ const isServerEnvironment = config.output.target === "node" || name === "serviceWorker";
27
+ const userConfig = modernAPI.useResolvedConfigContext();
28
+ const useLoadablePlugin = isUseSSRBundle(userConfig) && !isServerEnvironment && checkUseStringSSR(userConfig);
29
+ return mergeEnvironmentConfig(config, {
30
+ source: {
31
+ define: {
32
+ "process.env.MODERN_TARGET": isServerEnvironment ? JSON.stringify("node") : JSON.stringify("browser")
33
+ }
34
+ },
35
+ tools: {
36
+ bundlerChain: useLoadablePlugin ? (chain) => {
37
+ const LoadableBundlerPlugin = require("./loadable-bundler-plugin.js");
38
+ chain.plugin("loadable").use(LoadableBundlerPlugin, [
39
+ {
40
+ filename: LOADABLE_STATS_FILE
41
+ }
42
+ ]);
43
+ } : void 0
44
+ }
45
+ });
46
+ });
47
+ }
48
+ });
22
49
  const ssrPlugin = () => ({
23
50
  name: "@modern-js/plugin-ssr",
24
51
  required: [
@@ -52,27 +79,16 @@ const ssrPlugin = () => ({
52
79
  }
53
80
  })();
54
81
  return {
82
+ builderPlugins: [
83
+ ssrBuilderPlugin(api)
84
+ ],
55
85
  source: {
56
86
  alias: {
57
87
  // ensure that all packages use the same storage in @modern-js/runtime-utils/node
58
88
  "@modern-js/runtime-utils/node$": require.resolve("@modern-js/runtime-utils/node")
59
- },
60
- globalVars: (values, { target }) => {
61
- values["process.env.MODERN_TARGET"] = target === "node" || target === "service-worker" ? "node" : "browser";
62
89
  }
63
90
  },
64
91
  tools: {
65
- bundlerChain(chain, { isServer, isServiceWorker }) {
66
- const userConfig = api.useResolvedConfigContext();
67
- if (isUseSSRBundle(userConfig) && !isServer && !isServiceWorker && checkUseStringSSR(userConfig)) {
68
- const LoadableBundlerPlugin = require("./loadable-bundler-plugin.js");
69
- chain.plugin("loadable").use(LoadableBundlerPlugin, [
70
- {
71
- filename: LOADABLE_STATS_FILE
72
- }
73
- ]);
74
- }
75
- },
76
92
  babel: babelHandler
77
93
  }
78
94
  };
@@ -1,10 +1,30 @@
1
1
  import React from "react";
2
+ import cookieTool from "cookie";
2
3
  import { getGlobalAppInit } from "../context";
3
4
  import { getInitialContext } from "../context/runtime";
4
5
  import { createLoaderManager } from "../loader/loaderManager";
5
6
  import { getGlobalRunner } from "../plugin/runner";
6
7
  import { hydrateRoot } from "./hydrate";
7
8
  const IS_REACT18 = process.env.IS_REACT18 === "true";
9
+ function getSSRData() {
10
+ const ssrData = window._SSR_DATA;
11
+ if (ssrData) {
12
+ const finalSSRData = {
13
+ ...ssrData,
14
+ context: {
15
+ ...ssrData.context,
16
+ request: {
17
+ ...ssrData.context.request,
18
+ cookieMap: cookieTool.parse(document.cookie || "") || {},
19
+ cookie: document.cookie || "",
20
+ userAgent: navigator.userAgent,
21
+ referer: document.referrer
22
+ }
23
+ }
24
+ };
25
+ return finalSSRData;
26
+ }
27
+ }
8
28
  function isClientArgs(id) {
9
29
  return typeof id === "undefined" || typeof id === "string" || typeof HTMLElement !== "undefined" && id instanceof HTMLElement;
10
30
  }
@@ -21,7 +41,7 @@ async function render(App, id) {
21
41
  });
22
42
  if (isClientArgs(id)) {
23
43
  var _ssrData_data, _ssrData_data1;
24
- const ssrData = window._SSR_DATA;
44
+ const ssrData = getSSRData();
25
45
  const loadersData = (ssrData === null || ssrData === void 0 ? void 0 : (_ssrData_data = ssrData.data) === null || _ssrData_data === void 0 ? void 0 : _ssrData_data.loadersData) || {};
26
46
  const initialLoadersState = Object.keys(loadersData).reduce((res, key) => {
27
47
  const loaderData = loadersData[key];
@@ -1,4 +1,4 @@
1
- import { merge } from "@modern-js/utils/lodash";
1
+ import { merge } from "../utils/merge";
2
2
  import { runtime } from "./base";
3
3
  import { setGlobalRunner } from "./runner";
4
4
  export * from "./base";
@@ -1,5 +1,4 @@
1
1
  import { Transform } from "stream";
2
- import { renderToPipeableStream } from "react-dom/server";
3
2
  import { createReadableStreamFromReadable } from "@modern-js/runtime-utils/node";
4
3
  import { ServerStyleSheet } from "styled-components";
5
4
  import checkIsBot from "isbot";
@@ -7,7 +6,8 @@ import { ESCAPED_SHELL_STREAM_END_MARK } from "../../../common";
7
6
  import { RenderLevel } from "../../constants";
8
7
  import { getTemplates } from "./template";
9
8
  import { ShellChunkStatus, getReadableStreamFromString } from "./shared";
10
- const createReadableStreamFromElement = (request, rootElement, options) => {
9
+ const createReadableStreamFromElement = async (request, rootElement, options) => {
10
+ const { renderToPipeableStream } = await import("react-dom/server");
11
11
  const { runtimeContext, htmlTemplate, config, ssrConfig } = options;
12
12
  let shellChunkStatus = ShellChunkStatus.START;
13
13
  let renderLevel = RenderLevel.SERVER_RENDER;
@@ -25,6 +25,7 @@ const renderString = async (request, serverRoot, options) => {
25
25
  };
26
26
  const routerContext = runtimeContext.routerContext;
27
27
  const { htmlTemplate, entryName, loadableStats, routeManifest } = resource;
28
+ const ssrConfig = getSSRConfigByEntry(entryName, config.ssr, config.ssrByEntries, staticGenerate);
28
29
  const chunkSet = {
29
30
  renderLevel: RenderLevel.CLIENT_RENDER,
30
31
  ssrScripts: "",
@@ -33,12 +34,11 @@ const renderString = async (request, serverRoot, options) => {
33
34
  };
34
35
  let prefetchData = {};
35
36
  try {
36
- prefetchData = await prefetch(serverRoot, request, options, tracer);
37
+ prefetchData = await prefetch(serverRoot, request, options, ssrConfig, tracer);
37
38
  chunkSet.renderLevel = RenderLevel.SERVER_PREFETCH;
38
39
  } catch (e) {
39
40
  chunkSet.renderLevel = RenderLevel.CLIENT_RENDER;
40
41
  }
41
- const ssrConfig = getSSRConfigByEntry(entryName, config.ssr, config.ssrByEntries, staticGenerate);
42
42
  const collectors = [
43
43
  new StyledCollector(chunkSet),
44
44
  new LoadableCollector({