@modern-js/runtime 3.10.0 → 3.10.2

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 (39) hide show
  1. package/dist/cjs/core/server/helmet.js +7 -0
  2. package/dist/cjs/core/server/stream/beforeTemplate.js +1 -2
  3. package/dist/cjs/core/server/stream/createReadableStream.js +6 -10
  4. package/dist/cjs/core/server/stream/createReadableStream.worker.js +6 -9
  5. package/dist/cjs/core/server/stream/deferredScript.js +10 -1
  6. package/dist/cjs/core/server/stream/deferredScriptOutputCoordinator.js +9 -3
  7. package/dist/cjs/core/server/stream/shared.js +22 -0
  8. package/dist/cjs/core/server/string/index.js +21 -5
  9. package/dist/cjs/core/server/string/loadable.js +1 -2
  10. package/dist/cjs/core/server/utils.js +14 -0
  11. package/dist/cjs/router/cli/code/utils.js +5 -15
  12. package/dist/esm/core/server/helmet.mjs +5 -1
  13. package/dist/esm/core/server/stream/beforeTemplate.mjs +2 -3
  14. package/dist/esm/core/server/stream/createReadableStream.mjs +8 -12
  15. package/dist/esm/core/server/stream/createReadableStream.worker.mjs +8 -11
  16. package/dist/esm/core/server/stream/deferredScript.mjs +8 -2
  17. package/dist/esm/core/server/stream/deferredScriptOutputCoordinator.mjs +9 -3
  18. package/dist/esm/core/server/stream/shared.mjs +21 -2
  19. package/dist/esm/core/server/string/index.mjs +22 -6
  20. package/dist/esm/core/server/string/loadable.mjs +2 -3
  21. package/dist/esm/core/server/utils.mjs +12 -1
  22. package/dist/esm/router/cli/code/utils.mjs +5 -15
  23. package/dist/esm-node/core/server/helmet.mjs +5 -1
  24. package/dist/esm-node/core/server/stream/beforeTemplate.mjs +2 -3
  25. package/dist/esm-node/core/server/stream/createReadableStream.mjs +8 -12
  26. package/dist/esm-node/core/server/stream/createReadableStream.worker.mjs +8 -11
  27. package/dist/esm-node/core/server/stream/deferredScript.mjs +8 -2
  28. package/dist/esm-node/core/server/stream/deferredScriptOutputCoordinator.mjs +9 -3
  29. package/dist/esm-node/core/server/stream/shared.mjs +21 -2
  30. package/dist/esm-node/core/server/string/index.mjs +22 -6
  31. package/dist/esm-node/core/server/string/loadable.mjs +2 -3
  32. package/dist/esm-node/core/server/utils.mjs +12 -1
  33. package/dist/esm-node/router/cli/code/utils.mjs +5 -15
  34. package/dist/types/core/server/helmet.d.ts +2 -0
  35. package/dist/types/core/server/stream/deferredScript.d.ts +4 -0
  36. package/dist/types/core/server/stream/deferredScriptOutputCoordinator.d.ts +7 -0
  37. package/dist/types/core/server/stream/shared.d.ts +14 -0
  38. package/dist/types/core/server/utils.d.ts +6 -0
  39. package/package.json +12 -12
@@ -56,8 +56,12 @@ class DeferredScriptOutputCoordinator {
56
56
  this.shellFinished = true;
57
57
  this.flushResolvers();
58
58
  }
59
+ markNoResolvers() {
60
+ this.expectsResolvers = false;
61
+ }
59
62
  writeReact(chunk) {
60
63
  if (this.closed || !chunk) return;
64
+ if (!this.expectsResolvers) return void this.emit(chunk);
61
65
  this.flushResolvers();
62
66
  let emittedUntil = 0;
63
67
  for(let index = 0; index < chunk.length; index++){
@@ -75,7 +79,7 @@ class DeferredScriptOutputCoordinator {
75
79
  if (this.closed) return;
76
80
  this.flushResolvers();
77
81
  this.closed = true;
78
- if (this.pendingResolvers.length > 0) throw new Error("Cannot emit deferred resolver scripts because the React stream ended outside a safe HTML boundary.");
82
+ if (this.pendingResolvers.length > 0) throw new Error(this.expectsResolvers ? "Cannot emit deferred resolver scripts because the React stream ended outside a safe HTML boundary." : "Cannot emit deferred resolver scripts that were queued after the stream was marked as having no resolvers.");
79
83
  }
80
84
  abort() {
81
85
  this.closed = true;
@@ -85,7 +89,7 @@ class DeferredScriptOutputCoordinator {
85
89
  return this.shellFinished && 'data' === this.state && 0 === this.openElements.length && !this.awaitingContinuationProtocol;
86
90
  }
87
91
  flushResolvers() {
88
- if (!this.isSafeBoundary() || 0 === this.pendingResolvers.length) return;
92
+ if (!this.expectsResolvers || !this.isSafeBoundary() || 0 === this.pendingResolvers.length) return;
89
93
  while(this.pendingResolvers.length > 0){
90
94
  const resolver = this.pendingResolvers.shift();
91
95
  if (resolver) this.emit(resolver);
@@ -282,11 +286,12 @@ class DeferredScriptOutputCoordinator {
282
286
  this.state = 'data';
283
287
  return;
284
288
  }
285
- const endTagPrefix = `</${rawTextElement}`;
286
289
  if (this.continuationProtocolScript) {
287
290
  this.continuationProtocolTail = `${this.continuationProtocolTail}${char}`.slice(-4);
288
291
  if (/\$(?:RC|RS|RX|RB|RR)\b/.test(this.continuationProtocolTail)) this.hasContinuationProtocolCall = true;
289
292
  }
293
+ if (!this.rawTextSearch && '<' !== char) return;
294
+ const endTagPrefix = `</${rawTextElement}`;
290
295
  this.rawTextSearch = getSuffix(`${this.rawTextSearch}${char.toLowerCase()}`, endTagPrefix);
291
296
  if (this.rawTextSearch === endTagPrefix) this.state = 'raw-end-tag';
292
297
  }
@@ -313,6 +318,7 @@ class DeferredScriptOutputCoordinator {
313
318
  this.pendingResolvers = [];
314
319
  this.openElements = [];
315
320
  this.shellFinished = false;
321
+ this.expectsResolvers = true;
316
322
  this.closed = false;
317
323
  this.state = 'data';
318
324
  this.currentTagName = '';
@@ -1,7 +1,7 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
2
  import { time } from "@modern-js/runtime-utils/time";
3
3
  import isbot from "isbot";
4
- import { JSX_SHELL_STREAM_END_MARK } from "../../../common.mjs";
4
+ import { ESCAPED_SHELL_STREAM_END_MARK, JSX_SHELL_STREAM_END_MARK } from "../../../common.mjs";
5
5
  import { wrapRuntimeContextProvider } from "../../react/wrapper.mjs";
6
6
  import { SSRErrors, SSRTimings } from "../tracer.mjs";
7
7
  import { getSSRConfigByEntry } from "../utils.mjs";
@@ -10,6 +10,25 @@ var shared_ShellChunkStatus = /*#__PURE__*/ function(ShellChunkStatus) {
10
10
  ShellChunkStatus[ShellChunkStatus["FINISH"] = 1] = "FINISH";
11
11
  return ShellChunkStatus;
12
12
  }({});
13
+ function createShellEndMarkSplitter() {
14
+ const marker = ESCAPED_SHELL_STREAM_END_MARK;
15
+ const shellChunks = [];
16
+ let tail = '';
17
+ return (text)=>{
18
+ const searchText = tail + text;
19
+ const markerIndex = searchText.indexOf(marker);
20
+ if (-1 === markerIndex) {
21
+ shellChunks.push(text);
22
+ tail = searchText.slice(-(marker.length - 1));
23
+ return;
24
+ }
25
+ const buffered = shellChunks.join('');
26
+ return {
27
+ beforeMark: buffered.slice(0, buffered.length - tail.length) + searchText.slice(0, markerIndex),
28
+ afterMark: searchText.slice(markerIndex + marker.length)
29
+ };
30
+ };
31
+ }
13
32
  const SHOULD_STREAM_ALL_HEADER = 'x-should-stream-all';
14
33
  function parseShouldStreamAllFlag(value) {
15
34
  if (!value) return;
@@ -105,4 +124,4 @@ function createRenderStreaming(createReadableStreamPromise) {
105
124
  return stream;
106
125
  };
107
126
  }
108
- export { createRenderStreaming, encodeForWebStream, getReadableStreamFromString, resolveStreamingMode, shared_ShellChunkStatus as ShellChunkStatus };
127
+ export { createRenderStreaming, createShellEndMarkSplitter, encodeForWebStream, getReadableStreamFromString, resolveStreamingMode, shared_ShellChunkStatus as ShellChunkStatus };
@@ -6,7 +6,7 @@ import { RenderLevel } from "../../constants.mjs";
6
6
  import { getGlobalInternalRuntimeContext } from "../../context/index.mjs";
7
7
  import { wrapRuntimeContextProvider } from "../../react/wrapper.mjs";
8
8
  import { CHUNK_CSS_PLACEHOLDER, CHUNK_JS_PLACEHOLDER, HTML_PLACEHOLDER, SSR_DATA_PLACEHOLDER } from "../constants.mjs";
9
- import { createReplaceHelemt } from "../helmet.mjs";
9
+ import { createReplaceHelemt, hasTitleTagBefore } from "../helmet.mjs";
10
10
  import { buildHtml } from "../shared.mjs";
11
11
  import { SSRErrors, SSRTimings } from "../tracer.mjs";
12
12
  import { getSSRConfigByEntry, safeReplace } from "../utils.mjs";
@@ -79,16 +79,32 @@ async function generateHtml(App, htmlTemplate, chunkSet, collectors, htmlModifie
79
79
  }
80
80
  await Promise.all(collectors.map((component)=>component.effect()));
81
81
  const { ssrScripts, cssChunk, jsChunk } = chunkSet;
82
- const finalHtml = await buildHtml(htmlTemplate, [
83
- createReplaceHtml(html),
82
+ const replaceChunks = [
84
83
  createReplaceChunkJs(jsChunk),
85
- createReplaceChunkCss(cssChunk),
86
- createReplaceSSRDataScript(ssrScripts),
87
- createReplaceHelemt(helmetData),
84
+ createReplaceChunkCss(cssChunk)
85
+ ];
86
+ const replaceHelmet = createReplaceHelemt(helmetData);
87
+ const appHtmlMayHaveFirstTitle = html.includes('<title') && !hasTitleTagBefore(htmlTemplate, htmlTemplate.indexOf(HTML_PLACEHOLDER));
88
+ const finalHtml = await buildHtml(htmlTemplate, [
89
+ ...appHtmlMayHaveFirstTitle ? [
90
+ createReplaceHtml(html),
91
+ ...replaceChunks,
92
+ createReplaceSSRDataScript(ssrScripts),
93
+ replaceHelmet
94
+ ] : [
95
+ (template)=>safeReplace(safeReplace(template, HTML_PLACEHOLDER, HTML_MARKER), SSR_DATA_PLACEHOLDER, SSR_DATA_MARKER),
96
+ ...replaceChunks,
97
+ replaceHelmet,
98
+ (template)=>safeReplace(template, SSR_DATA_MARKER, ssrScripts),
99
+ (template)=>safeReplace(template, HTML_MARKER, html)
100
+ ],
88
101
  ...htmlModifiers
89
102
  ]);
90
103
  return finalHtml;
91
104
  }
105
+ const markerId = Math.random().toString(36).slice(2);
106
+ const HTML_MARKER = `<!--modern-html-${markerId}-->`;
107
+ const SSR_DATA_MARKER = `<!--modern-ssr-data-${markerId}-->`;
92
108
  function createReplaceHtml(html) {
93
109
  return (template)=>safeReplace(template, HTML_PLACEHOLDER, html);
94
110
  }
@@ -1,5 +1,5 @@
1
1
  import { ChunkExtractor } from "@loadable/server";
2
- import { attributesToString, checkIsNode, hasStylesheetLink } from "../utils.mjs";
2
+ import { attributesToString, checkIsNode, hasStylesheetLink, readAssetWithCache } from "../utils.mjs";
3
3
  const extname = (uri)=>{
4
4
  if ('string' != typeof uri || !uri.includes('.')) return '';
5
5
  return `.${uri?.split('.').pop()}` || '';
@@ -11,10 +11,9 @@ const checkIsInline = (chunk, enableInline)=>{
11
11
  else return Boolean(enableInline);
12
12
  };
13
13
  const readAsset = async (chunk)=>{
14
- const fs = await import("fs/promises");
15
14
  const path = await import("path");
16
15
  const filepath = path.resolve(__dirname, chunk.filename);
17
- return fs.readFile(filepath, 'utf-8');
16
+ return readAssetWithCache(filepath);
18
17
  };
19
18
  class LoadableCollector {
20
19
  get existsAssets() {
@@ -8,6 +8,17 @@ function safeReplace(source, searchValue, replaceValue) {
8
8
  function checkIsNode() {
9
9
  return "u" > typeof process && process.release?.name === 'node';
10
10
  }
11
+ const assetCache = new Map();
12
+ function readAssetWithCache(filepath) {
13
+ const cached = assetCache.get(filepath);
14
+ if (cached) return cached;
15
+ const content = import("fs/promises").then((fs)=>fs.readFile(filepath, 'utf-8'));
16
+ assetCache.set(filepath, content);
17
+ content.catch(()=>{
18
+ if (assetCache.get(filepath) === content) assetCache.delete(filepath);
19
+ });
20
+ return content;
21
+ }
11
22
  function serializeErrors(errors) {
12
23
  if (!errors) return null;
13
24
  const entries = Object.entries(errors);
@@ -56,4 +67,4 @@ const hasStylesheetLink = (template, href)=>{
56
67
  return linkHref === href && rel?.split(/\s+/).some((relToken)=>'stylesheet' === relToken.toLowerCase());
57
68
  });
58
69
  };
59
- export { attributesToString, checkIsNode, getSSRConfigByEntry, getSSRMode, hasStylesheetLink, safeReplace, serializeErrors };
70
+ export { attributesToString, checkIsNode, getSSRConfigByEntry, getSSRMode, hasStylesheetLink, readAssetWithCache, safeReplace, serializeErrors };
@@ -62,30 +62,20 @@ const parseModule = async ({ source, filename })=>{
62
62
  }
63
63
  return parse(content);
64
64
  };
65
- const hasLoader = async (filename, source)=>{
65
+ const hasExport = async (filename, exportName, source)=>{
66
66
  let content = source;
67
67
  if (!source) content = (await utils_fs.readFile(filename, 'utf-8')).toString();
68
- if (content) {
68
+ if (content && (content.includes(exportName) || content.includes('\\'))) {
69
69
  const [, moduleExports] = await parseModule({
70
70
  source: content.toString(),
71
71
  filename
72
72
  });
73
- return moduleExports.some((e)=>e.n === LOADER_EXPORT_NAME);
74
- }
75
- return false;
76
- };
77
- const hasAction = async (filename, source)=>{
78
- let content = source;
79
- if (!source) content = (await utils_fs.readFile(filename, 'utf-8')).toString();
80
- if (content) {
81
- const [, moduleExports] = await parseModule({
82
- source: content.toString(),
83
- filename
84
- });
85
- return moduleExports.some((e)=>e.n === ACTION_EXPORT_NAME);
73
+ return moduleExports.some((e)=>e.n === exportName);
86
74
  }
87
75
  return false;
88
76
  };
77
+ const hasLoader = (filename, source)=>hasExport(filename, LOADER_EXPORT_NAME, source);
78
+ const hasAction = (filename, source)=>hasExport(filename, ACTION_EXPORT_NAME, source);
89
79
  const getServerLoadersFile = (internalDirectory, entryName)=>path.join(internalDirectory, entryName, 'route-server-loaders.js');
90
80
  const getServerCombinedModuleFile = (internalDirectory, entryName)=>path.join(internalDirectory, entryName, 'server-loader-combined.js');
91
81
  const getPathWithoutExt = (filename)=>{
@@ -6,6 +6,10 @@ const RE_BODY_ATTR = /<body[^>]*>/;
6
6
  const RE_LAST_IN_HEAD = /<\/head>/;
7
7
  const RE_TITLE = /<title[^>]*>([\s\S\n\r]*?)<\/title>/;
8
8
  const TEST_TITLE_CONTENT = /(?<=<title[^>]*>)([\s\S\n\r]*?)([.|\S])([\s\S\n\r]*?)(?=<\/title>)/;
9
+ function hasTitleTagBefore(html, index) {
10
+ const match = RE_TITLE.exec(html);
11
+ return null !== match && match.index < index;
12
+ }
9
13
  function createReplaceHelemt(helmetData) {
10
14
  return helmetData ? (template)=>helmetReplace(template, helmetData) : (tempalte)=>tempalte;
11
15
  }
@@ -36,4 +40,4 @@ function helmetReplace(content, helmetData) {
36
40
  ].reduce((pre, cur)=>pre + (cur.length > 0 ? ` ${cur}${EOL}` : ''), '');
37
41
  return safeReplace(result, RE_LAST_IN_HEAD, `${helmetStr}</head>`);
38
42
  }
39
- export { createReplaceHelemt, helmetReplace };
43
+ export { createReplaceHelemt, hasTitleTagBefore, helmetReplace };
@@ -4,15 +4,14 @@ import react_helmet from "react-helmet";
4
4
  import { CHUNK_CSS_PLACEHOLDER } from "../constants.mjs";
5
5
  import { createReplaceHelemt } from "../helmet.mjs";
6
6
  import { buildHtml } from "../shared.mjs";
7
- import { checkIsNode, hasStylesheetLink, safeReplace } from "../utils.mjs";
7
+ import { checkIsNode, hasStylesheetLink, readAssetWithCache, safeReplace } from "../utils.mjs";
8
8
  import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
9
9
  import { dirname as __rspack_dirname } from "node:path";
10
10
  var __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
11
11
  const readAsset = async (chunk)=>{
12
- const fs = await import("fs/promises");
13
12
  const path = await import("path");
14
13
  const filepath = path.join(__rspack_import_meta_dirname__, chunk);
15
- return fs.readFile(filepath, 'utf-8');
14
+ return readAssetWithCache(filepath);
16
15
  };
17
16
  const checkIsInline = (chunk, enableInline)=>{
18
17
  if ('production' !== process.env.NODE_ENV) return false;
@@ -3,13 +3,12 @@ import { PassThrough, Readable, Transform } from "stream";
3
3
  import { StringDecoder } from "string_decoder";
4
4
  import { storage } from "@modern-js/runtime-utils/node";
5
5
  import { SSR_HYDRATION_ID_PREFIX } from "@modern-js/utils/universal/constants";
6
- import { ESCAPED_SHELL_STREAM_END_MARK } from "../../../common.mjs";
7
6
  import { RenderLevel } from "../../constants.mjs";
8
7
  import { getGlobalInternalRuntimeContext } from "../../context/index.mjs";
9
8
  import { getMonitors } from "../../context/monitors/index.mjs";
10
- import { enqueueFromEntries } from "./deferredScript.mjs";
9
+ import { enqueueFromEntries, hasDeferredResolvers } from "./deferredScript.mjs";
11
10
  import { DeferredScriptOutputCoordinator } from "./deferredScriptOutputCoordinator.mjs";
12
- import { ShellChunkStatus, getReadableStreamFromString, resolveStreamingMode } from "./shared.mjs";
11
+ import { ShellChunkStatus, createShellEndMarkSplitter, getReadableStreamFromString, resolveStreamingMode } from "./shared.mjs";
13
12
  import { getTemplates } from "./template.mjs";
14
13
  const defaultExtender = {
15
14
  modifyRootElement: (rootElement)=>rootElement,
@@ -37,7 +36,7 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
37
36
  extenders.forEach((extender)=>{
38
37
  if (extender.modifyRootElement) processedRootElement = extender.modifyRootElement(processedRootElement);
39
38
  });
40
- const chunkVec = [];
39
+ const splitAtShellEndMark = createShellEndMarkSplitter();
41
40
  return new Promise((resolve)=>{
42
41
  const { pipe: reactStreamingPipe } = renderToPipeableStream(processedRootElement, {
43
42
  nonce: config.nonce,
@@ -69,12 +68,9 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
69
68
  transform (chunk, _encoding, callback) {
70
69
  try {
71
70
  if (shellChunkStatus !== ShellChunkStatus.FINISH) {
72
- chunkVec.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
73
- const concatedChunk = Buffer.concat(chunkVec).toString('utf-8');
74
- const markerIndex = concatedChunk.indexOf(ESCAPED_SHELL_STREAM_END_MARK);
75
- if (-1 !== markerIndex) {
76
- const beforeMark = concatedChunk.slice(0, markerIndex);
77
- const afterMark = concatedChunk.slice(markerIndex + ESCAPED_SHELL_STREAM_END_MARK.length);
71
+ const shell = splitAtShellEndMark(decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
72
+ if (shell) {
73
+ const { beforeMark, afterMark } = shell;
78
74
  shellChunkStatus = ShellChunkStatus.FINISH;
79
75
  writeReact(`${shellBefore}${beforeMark}${shellAfter}`);
80
76
  if (afterMark) writeReact(afterMark);
@@ -131,14 +127,14 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
131
127
  const activeDeferreds = storageContext?.activeDeferreds;
132
128
  const deferredScriptKeys = storageContext?.deferredScriptKeys;
133
129
  const entries = activeDeferreds instanceof Map ? Array.from(activeDeferreds.entries()) : [];
134
- if (entries.length > 0) {
130
+ if (hasDeferredResolvers(entries, deferredScriptKeys)) {
135
131
  const enqueueScript = (s)=>{
136
132
  if (!outputState.coordinator) throw new Error("Deferred script coordinator is not ready");
137
133
  if (shellChunkStatus === ShellChunkStatus.FINISH) outputState.coordinator.enqueueResolver(s);
138
134
  else pendingScripts.push(s);
139
135
  };
140
136
  deferredResolversComplete = enqueueFromEntries(entries, deferredScriptKeys, config.nonce, enqueueScript);
141
- }
137
+ } else coordinator.markNoResolvers();
142
138
  } catch (err) {
143
139
  const monitors = getMonitors();
144
140
  monitors.error("cannot inject router data script", err);
@@ -1,15 +1,14 @@
1
1
  import "node:module";
2
2
  import { renderSSRStream } from "@modern-js/render/ssr";
3
3
  import { storage } from "@modern-js/runtime-utils/node";
4
- import { ESCAPED_SHELL_STREAM_END_MARK } from "../../../common.mjs";
5
4
  import { RenderLevel } from "../../constants.mjs";
6
- import { enqueueFromEntries } from "./deferredScript.mjs";
5
+ import { enqueueFromEntries, hasDeferredResolvers } from "./deferredScript.mjs";
7
6
  import { DeferredScriptOutputCoordinator } from "./deferredScriptOutputCoordinator.mjs";
8
- import { ShellChunkStatus, encodeForWebStream, getReadableStreamFromString, resolveStreamingMode } from "./shared.mjs";
7
+ import { ShellChunkStatus, createShellEndMarkSplitter, encodeForWebStream, getReadableStreamFromString, resolveStreamingMode } from "./shared.mjs";
9
8
  import { getTemplates } from "./template.mjs";
10
9
  const createReadableStreamFromElement = async (request, rootElement, options)=>{
11
10
  let shellChunkStatus = ShellChunkStatus.START;
12
- const chunkVec = [];
11
+ const splitAtShellEndMark = createShellEndMarkSplitter();
13
12
  const { htmlTemplate, runtimeContext, config, ssrConfig, entryName, rscRoot } = options;
14
13
  const { shellBefore, shellAfter } = await getTemplates(htmlTemplate, {
15
14
  renderLevel: RenderLevel.SERVER_RENDER,
@@ -67,11 +66,12 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
67
66
  const activeDeferreds = storageContext?.activeDeferreds;
68
67
  const deferredScriptKeys = storageContext?.deferredScriptKeys;
69
68
  const entries = activeDeferreds instanceof Map ? Array.from(activeDeferreds.entries()) : [];
70
- if (entries.length > 0) deferredResolversComplete = enqueueFromEntries(entries, deferredScriptKeys, config.nonce, (script)=>{
69
+ if (hasDeferredResolvers(entries, deferredScriptKeys)) deferredResolversComplete = enqueueFromEntries(entries, deferredScriptKeys, config.nonce, (script)=>{
71
70
  if (!coordinator) throw new Error("Deferred script coordinator is not ready");
72
71
  if (shellChunkStatus === ShellChunkStatus.FINISH) coordinator.enqueueResolver(script);
73
72
  else pendingScripts.push(script);
74
73
  });
74
+ else coordinator.markNoResolvers();
75
75
  async function push() {
76
76
  try {
77
77
  const { done, value } = await reader.read();
@@ -85,14 +85,11 @@ const createReadableStreamFromElement = async (request, rootElement, options)=>{
85
85
  }
86
86
  if (isClosed) return;
87
87
  if (shellChunkStatus !== ShellChunkStatus.FINISH) {
88
- chunkVec.push(decoder.decode(value, {
88
+ const shell = splitAtShellEndMark(decoder.decode(value, {
89
89
  stream: true
90
90
  }));
91
- const concatedChunk = chunkVec.join('');
92
- const markerIndex = concatedChunk.indexOf(ESCAPED_SHELL_STREAM_END_MARK);
93
- if (-1 !== markerIndex) {
94
- const beforeMark = concatedChunk.slice(0, markerIndex);
95
- const afterMark = concatedChunk.slice(markerIndex + ESCAPED_SHELL_STREAM_END_MARK.length);
91
+ if (shell) {
92
+ const { beforeMark, afterMark } = shell;
96
93
  shellChunkStatus = ShellChunkStatus.FINISH;
97
94
  coordinator?.writeReact(`${shellBefore}${beforeMark}${shellAfter}`);
98
95
  if (afterMark) coordinator?.writeReact(afterMark);
@@ -41,11 +41,17 @@ function buildDeferredDataScript(nonce, args) {
41
41
  const nonceAttr = nonce ? ` nonce="${nonce}"` : '';
42
42
  return `<script async${nonceAttr} data-fn-name="r" data-script-src="modern-run-router-data-fn" data-fn-args='${escaped}' suppressHydrationWarning>${runRouterDataFnStr}</script>`;
43
43
  }
44
+ function getSerializedKeys(routeId, value, deferredScriptKeys) {
45
+ return deferredScriptKeys ? deferredScriptKeys.get(routeId) ?? [] : value.pendingKeys ?? [];
46
+ }
47
+ function hasDeferredResolvers(entries, deferredScriptKeys) {
48
+ return entries.some(([routeId, value])=>isDeferredDataLike(value) && getSerializedKeys(routeId, value, deferredScriptKeys).some((key)=>isPromiseLike(value.data?.[key])));
49
+ }
44
50
  function enqueueFromEntries(entries, deferredScriptKeys, nonce, emit) {
45
51
  const pendingResolvers = [];
46
52
  entries.forEach(([routeId, value])=>{
47
53
  if (!isDeferredDataLike(value)) return;
48
- const serializedKeys = deferredScriptKeys ? deferredScriptKeys.get(routeId) ?? [] : value.pendingKeys ?? [];
54
+ const serializedKeys = getSerializedKeys(routeId, value, deferredScriptKeys);
49
55
  serializedKeys.forEach((key)=>{
50
56
  const tracked = value.data?.[key];
51
57
  if (isPromiseLike(tracked)) pendingResolvers.push(Promise.resolve(tracked).then((val)=>{
@@ -66,4 +72,4 @@ function enqueueFromEntries(entries, deferredScriptKeys, nonce, emit) {
66
72
  });
67
73
  return Promise.all(pendingResolvers).then(()=>void 0);
68
74
  }
69
- export { buildDeferredDataScript, enqueueFromEntries, escapeAttr, isDeferredDataLike, isPromiseLike, isRecord, toErrorInfo };
75
+ export { buildDeferredDataScript, enqueueFromEntries, escapeAttr, hasDeferredResolvers, isDeferredDataLike, isPromiseLike, isRecord, toErrorInfo };
@@ -57,8 +57,12 @@ class DeferredScriptOutputCoordinator {
57
57
  this.shellFinished = true;
58
58
  this.flushResolvers();
59
59
  }
60
+ markNoResolvers() {
61
+ this.expectsResolvers = false;
62
+ }
60
63
  writeReact(chunk) {
61
64
  if (this.closed || !chunk) return;
65
+ if (!this.expectsResolvers) return void this.emit(chunk);
62
66
  this.flushResolvers();
63
67
  let emittedUntil = 0;
64
68
  for(let index = 0; index < chunk.length; index++){
@@ -76,7 +80,7 @@ class DeferredScriptOutputCoordinator {
76
80
  if (this.closed) return;
77
81
  this.flushResolvers();
78
82
  this.closed = true;
79
- if (this.pendingResolvers.length > 0) throw new Error("Cannot emit deferred resolver scripts because the React stream ended outside a safe HTML boundary.");
83
+ if (this.pendingResolvers.length > 0) throw new Error(this.expectsResolvers ? "Cannot emit deferred resolver scripts because the React stream ended outside a safe HTML boundary." : "Cannot emit deferred resolver scripts that were queued after the stream was marked as having no resolvers.");
80
84
  }
81
85
  abort() {
82
86
  this.closed = true;
@@ -86,7 +90,7 @@ class DeferredScriptOutputCoordinator {
86
90
  return this.shellFinished && 'data' === this.state && 0 === this.openElements.length && !this.awaitingContinuationProtocol;
87
91
  }
88
92
  flushResolvers() {
89
- if (!this.isSafeBoundary() || 0 === this.pendingResolvers.length) return;
93
+ if (!this.expectsResolvers || !this.isSafeBoundary() || 0 === this.pendingResolvers.length) return;
90
94
  while(this.pendingResolvers.length > 0){
91
95
  const resolver = this.pendingResolvers.shift();
92
96
  if (resolver) this.emit(resolver);
@@ -283,11 +287,12 @@ class DeferredScriptOutputCoordinator {
283
287
  this.state = 'data';
284
288
  return;
285
289
  }
286
- const endTagPrefix = `</${rawTextElement}`;
287
290
  if (this.continuationProtocolScript) {
288
291
  this.continuationProtocolTail = `${this.continuationProtocolTail}${char}`.slice(-4);
289
292
  if (/\$(?:RC|RS|RX|RB|RR)\b/.test(this.continuationProtocolTail)) this.hasContinuationProtocolCall = true;
290
293
  }
294
+ if (!this.rawTextSearch && '<' !== char) return;
295
+ const endTagPrefix = `</${rawTextElement}`;
291
296
  this.rawTextSearch = getSuffix(`${this.rawTextSearch}${char.toLowerCase()}`, endTagPrefix);
292
297
  if (this.rawTextSearch === endTagPrefix) this.state = 'raw-end-tag';
293
298
  }
@@ -314,6 +319,7 @@ class DeferredScriptOutputCoordinator {
314
319
  this.pendingResolvers = [];
315
320
  this.openElements = [];
316
321
  this.shellFinished = false;
322
+ this.expectsResolvers = true;
317
323
  this.closed = false;
318
324
  this.state = 'data';
319
325
  this.currentTagName = '';
@@ -2,7 +2,7 @@ import "node:module";
2
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
3
  import { time } from "@modern-js/runtime-utils/time";
4
4
  import isbot from "isbot";
5
- import { JSX_SHELL_STREAM_END_MARK } from "../../../common.mjs";
5
+ import { ESCAPED_SHELL_STREAM_END_MARK, JSX_SHELL_STREAM_END_MARK } from "../../../common.mjs";
6
6
  import { wrapRuntimeContextProvider } from "../../react/wrapper.mjs";
7
7
  import { SSRErrors, SSRTimings } from "../tracer.mjs";
8
8
  import { getSSRConfigByEntry } from "../utils.mjs";
@@ -11,6 +11,25 @@ var shared_ShellChunkStatus = /*#__PURE__*/ function(ShellChunkStatus) {
11
11
  ShellChunkStatus[ShellChunkStatus["FINISH"] = 1] = "FINISH";
12
12
  return ShellChunkStatus;
13
13
  }({});
14
+ function createShellEndMarkSplitter() {
15
+ const marker = ESCAPED_SHELL_STREAM_END_MARK;
16
+ const shellChunks = [];
17
+ let tail = '';
18
+ return (text)=>{
19
+ const searchText = tail + text;
20
+ const markerIndex = searchText.indexOf(marker);
21
+ if (-1 === markerIndex) {
22
+ shellChunks.push(text);
23
+ tail = searchText.slice(-(marker.length - 1));
24
+ return;
25
+ }
26
+ const buffered = shellChunks.join('');
27
+ return {
28
+ beforeMark: buffered.slice(0, buffered.length - tail.length) + searchText.slice(0, markerIndex),
29
+ afterMark: searchText.slice(markerIndex + marker.length)
30
+ };
31
+ };
32
+ }
14
33
  const SHOULD_STREAM_ALL_HEADER = 'x-should-stream-all';
15
34
  function parseShouldStreamAllFlag(value) {
16
35
  if (!value) return;
@@ -106,4 +125,4 @@ function createRenderStreaming(createReadableStreamPromise) {
106
125
  return stream;
107
126
  };
108
127
  }
109
- export { createRenderStreaming, encodeForWebStream, getReadableStreamFromString, resolveStreamingMode, shared_ShellChunkStatus as ShellChunkStatus };
128
+ export { createRenderStreaming, createShellEndMarkSplitter, encodeForWebStream, getReadableStreamFromString, resolveStreamingMode, shared_ShellChunkStatus as ShellChunkStatus };
@@ -7,7 +7,7 @@ import { RenderLevel } from "../../constants.mjs";
7
7
  import { getGlobalInternalRuntimeContext } from "../../context/index.mjs";
8
8
  import { wrapRuntimeContextProvider } from "../../react/wrapper.mjs";
9
9
  import { CHUNK_CSS_PLACEHOLDER, CHUNK_JS_PLACEHOLDER, HTML_PLACEHOLDER, SSR_DATA_PLACEHOLDER } from "../constants.mjs";
10
- import { createReplaceHelemt } from "../helmet.mjs";
10
+ import { createReplaceHelemt, hasTitleTagBefore } from "../helmet.mjs";
11
11
  import { buildHtml } from "../shared.mjs";
12
12
  import { SSRErrors, SSRTimings } from "../tracer.mjs";
13
13
  import { getSSRConfigByEntry, safeReplace } from "../utils.mjs";
@@ -80,16 +80,32 @@ async function generateHtml(App, htmlTemplate, chunkSet, collectors, htmlModifie
80
80
  }
81
81
  await Promise.all(collectors.map((component)=>component.effect()));
82
82
  const { ssrScripts, cssChunk, jsChunk } = chunkSet;
83
- const finalHtml = await buildHtml(htmlTemplate, [
84
- createReplaceHtml(html),
83
+ const replaceChunks = [
85
84
  createReplaceChunkJs(jsChunk),
86
- createReplaceChunkCss(cssChunk),
87
- createReplaceSSRDataScript(ssrScripts),
88
- createReplaceHelemt(helmetData),
85
+ createReplaceChunkCss(cssChunk)
86
+ ];
87
+ const replaceHelmet = createReplaceHelemt(helmetData);
88
+ const appHtmlMayHaveFirstTitle = html.includes('<title') && !hasTitleTagBefore(htmlTemplate, htmlTemplate.indexOf(HTML_PLACEHOLDER));
89
+ const finalHtml = await buildHtml(htmlTemplate, [
90
+ ...appHtmlMayHaveFirstTitle ? [
91
+ createReplaceHtml(html),
92
+ ...replaceChunks,
93
+ createReplaceSSRDataScript(ssrScripts),
94
+ replaceHelmet
95
+ ] : [
96
+ (template)=>safeReplace(safeReplace(template, HTML_PLACEHOLDER, HTML_MARKER), SSR_DATA_PLACEHOLDER, SSR_DATA_MARKER),
97
+ ...replaceChunks,
98
+ replaceHelmet,
99
+ (template)=>safeReplace(template, SSR_DATA_MARKER, ssrScripts),
100
+ (template)=>safeReplace(template, HTML_MARKER, html)
101
+ ],
89
102
  ...htmlModifiers
90
103
  ]);
91
104
  return finalHtml;
92
105
  }
106
+ const markerId = Math.random().toString(36).slice(2);
107
+ const HTML_MARKER = `<!--modern-html-${markerId}-->`;
108
+ const SSR_DATA_MARKER = `<!--modern-ssr-data-${markerId}-->`;
93
109
  function createReplaceHtml(html) {
94
110
  return (template)=>safeReplace(template, HTML_PLACEHOLDER, html);
95
111
  }
@@ -1,6 +1,6 @@
1
1
  import "node:module";
2
2
  import { ChunkExtractor } from "@loadable/server";
3
- import { attributesToString, checkIsNode, hasStylesheetLink } from "../utils.mjs";
3
+ import { attributesToString, checkIsNode, hasStylesheetLink, readAssetWithCache } from "../utils.mjs";
4
4
  import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
5
5
  import { dirname as __rspack_dirname } from "node:path";
6
6
  var __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
@@ -15,10 +15,9 @@ const checkIsInline = (chunk, enableInline)=>{
15
15
  else return Boolean(enableInline);
16
16
  };
17
17
  const readAsset = async (chunk)=>{
18
- const fs = await import("fs/promises");
19
18
  const path = await import("path");
20
19
  const filepath = path.resolve(__rspack_import_meta_dirname__, chunk.filename);
21
- return fs.readFile(filepath, 'utf-8');
20
+ return readAssetWithCache(filepath);
22
21
  };
23
22
  class LoadableCollector {
24
23
  get existsAssets() {
@@ -9,6 +9,17 @@ function safeReplace(source, searchValue, replaceValue) {
9
9
  function checkIsNode() {
10
10
  return "u" > typeof process && process.release?.name === 'node';
11
11
  }
12
+ const assetCache = new Map();
13
+ function readAssetWithCache(filepath) {
14
+ const cached = assetCache.get(filepath);
15
+ if (cached) return cached;
16
+ const content = import("fs/promises").then((fs)=>fs.readFile(filepath, 'utf-8'));
17
+ assetCache.set(filepath, content);
18
+ content.catch(()=>{
19
+ if (assetCache.get(filepath) === content) assetCache.delete(filepath);
20
+ });
21
+ return content;
22
+ }
12
23
  function serializeErrors(errors) {
13
24
  if (!errors) return null;
14
25
  const entries = Object.entries(errors);
@@ -57,4 +68,4 @@ const hasStylesheetLink = (template, href)=>{
57
68
  return linkHref === href && rel?.split(/\s+/).some((relToken)=>'stylesheet' === relToken.toLowerCase());
58
69
  });
59
70
  };
60
- export { attributesToString, checkIsNode, getSSRConfigByEntry, getSSRMode, hasStylesheetLink, safeReplace, serializeErrors };
71
+ export { attributesToString, checkIsNode, getSSRConfigByEntry, getSSRMode, hasStylesheetLink, readAssetWithCache, safeReplace, serializeErrors };
@@ -63,30 +63,20 @@ const parseModule = async ({ source, filename })=>{
63
63
  }
64
64
  return parse(content);
65
65
  };
66
- const hasLoader = async (filename, source)=>{
66
+ const hasExport = async (filename, exportName, source)=>{
67
67
  let content = source;
68
68
  if (!source) content = (await utils_fs.readFile(filename, 'utf-8')).toString();
69
- if (content) {
69
+ if (content && (content.includes(exportName) || content.includes('\\'))) {
70
70
  const [, moduleExports] = await parseModule({
71
71
  source: content.toString(),
72
72
  filename
73
73
  });
74
- return moduleExports.some((e)=>e.n === LOADER_EXPORT_NAME);
75
- }
76
- return false;
77
- };
78
- const hasAction = async (filename, source)=>{
79
- let content = source;
80
- if (!source) content = (await utils_fs.readFile(filename, 'utf-8')).toString();
81
- if (content) {
82
- const [, moduleExports] = await parseModule({
83
- source: content.toString(),
84
- filename
85
- });
86
- return moduleExports.some((e)=>e.n === ACTION_EXPORT_NAME);
74
+ return moduleExports.some((e)=>e.n === exportName);
87
75
  }
88
76
  return false;
89
77
  };
78
+ const hasLoader = (filename, source)=>hasExport(filename, LOADER_EXPORT_NAME, source);
79
+ const hasAction = (filename, source)=>hasExport(filename, ACTION_EXPORT_NAME, source);
90
80
  const getServerLoadersFile = (internalDirectory, entryName)=>path.join(internalDirectory, entryName, 'route-server-loaders.js');
91
81
  const getServerCombinedModuleFile = (internalDirectory, entryName)=>path.join(internalDirectory, entryName, 'server-loader-combined.js');
92
82
  const getPathWithoutExt = (filename)=>{
@@ -1,3 +1,5 @@
1
1
  import type { HelmetData } from 'react-helmet';
2
+ /** Whether the first <title> of `html` starts before `index`. */
3
+ export declare function hasTitleTagBefore(html: string, index: number): boolean;
2
4
  export declare function createReplaceHelemt(helmetData?: HelmetData): (template: string) => string;
3
5
  export declare function helmetReplace(content: string, helmetData: HelmetData): string;
@@ -12,4 +12,8 @@ export declare function toErrorInfo(error: unknown): {
12
12
  stack?: string;
13
13
  };
14
14
  export declare function buildDeferredDataScript(nonce: string | undefined, args: unknown[]): string;
15
+ /**
16
+ * Whether `enqueueFromEntries` would emit any resolver script for `entries`.
17
+ */
18
+ export declare function hasDeferredResolvers(entries: Array<[string, unknown]>, deferredScriptKeys: Map<string, string[]> | undefined): boolean;
15
19
  export declare function enqueueFromEntries(entries: Array<[string, unknown]>, deferredScriptKeys: Map<string, string[]> | undefined, nonce: string | undefined, emit: (script: string) => void): Promise<void>;