@ecopages/react 0.2.0-alpha.4 → 0.2.0-alpha.40
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.
- package/README.md +161 -18
- package/package.json +16 -12
- package/src/eco-embed.d.ts +11 -0
- package/src/eco-embed.js +11 -0
- package/src/react-hmr-strategy.d.ts +42 -32
- package/src/react-hmr-strategy.js +103 -124
- package/src/react-renderer.d.ts +169 -42
- package/src/react-renderer.js +484 -164
- package/src/react.constants.d.ts +1 -0
- package/src/react.constants.js +4 -0
- package/src/react.plugin.d.ts +38 -111
- package/src/react.plugin.js +132 -61
- package/src/react.types.d.ts +88 -0
- package/src/react.types.js +0 -0
- package/src/router-adapter.d.ts +7 -14
- package/src/services/react-bundle.service.d.ts +15 -26
- package/src/services/react-bundle.service.js +45 -93
- package/src/services/react-hmr-page-metadata-cache.d.ts +9 -0
- package/src/services/react-hmr-page-metadata-cache.js +18 -2
- package/src/services/react-hydration-asset.service.d.ts +26 -19
- package/src/services/react-hydration-asset.service.js +72 -66
- package/src/services/react-mdx-config-dependency.service.d.ts +36 -0
- package/src/services/react-mdx-config-dependency.service.js +122 -0
- package/src/services/react-page-module.service.d.ts +10 -2
- package/src/services/react-page-module.service.js +47 -39
- package/src/services/react-page-payload.service.d.ts +46 -0
- package/src/services/react-page-payload.service.js +67 -0
- package/src/services/react-runtime-bundle.service.d.ts +15 -13
- package/src/services/react-runtime-bundle.service.js +103 -180
- package/src/utils/client-graph-boundary-plugin.d.ts +1 -1
- package/src/utils/client-graph-boundary-plugin.js +149 -11
- package/src/utils/component-config-traversal.d.ts +36 -0
- package/src/utils/component-config-traversal.js +54 -0
- package/src/utils/declared-modules.d.ts +1 -1
- package/src/utils/declared-modules.js +7 -16
- package/src/utils/dynamic.test.browser.d.ts +1 -0
- package/src/utils/dynamic.test.browser.js +33 -0
- package/src/utils/hydration-scripts.d.ts +25 -6
- package/src/utils/hydration-scripts.js +150 -44
- package/src/utils/hydration-scripts.test.browser.d.ts +1 -0
- package/src/utils/hydration-scripts.test.browser.js +198 -0
- package/src/utils/reachability-analyzer.d.ts +12 -1
- package/src/utils/reachability-analyzer.js +101 -5
- package/src/utils/react-dom-runtime-interop-plugin.d.ts +5 -0
- package/src/utils/react-dom-runtime-interop-plugin.js +29 -0
- package/src/utils/react-mdx-loader-plugin.d.ts +1 -1
- package/src/utils/react-mdx-loader-plugin.js +13 -5
- package/src/utils/react-runtime-alias-map.d.ts +6 -0
- package/src/utils/react-runtime-alias-map.js +33 -0
- package/src/utils/use-sync-external-store-shim-plugin.d.ts +5 -0
- package/src/utils/use-sync-external-store-shim-plugin.js +41 -0
- package/CHANGELOG.md +0 -62
- package/src/react-hmr-strategy.ts +0 -444
- package/src/react-renderer.ts +0 -403
- package/src/react.plugin.ts +0 -241
- package/src/router-adapter.ts +0 -95
- package/src/services/react-bundle.service.ts +0 -212
- package/src/services/react-hmr-page-metadata-cache.ts +0 -24
- package/src/services/react-hydration-asset.service.ts +0 -260
- package/src/services/react-page-module.service.ts +0 -214
- package/src/services/react-runtime-bundle.service.ts +0 -271
- package/src/utils/client-graph-boundary-plugin.ts +0 -590
- package/src/utils/client-only.ts +0 -27
- package/src/utils/declared-modules.ts +0 -99
- package/src/utils/dynamic.ts +0 -27
- package/src/utils/hmr-scripts.ts +0 -47
- package/src/utils/html-boundary.ts +0 -66
- package/src/utils/hydration-scripts.ts +0 -338
- package/src/utils/reachability-analyzer.ts +0 -440
- package/src/utils/react-mdx-loader-plugin.ts +0 -40
|
@@ -1,96 +1,44 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
-
import { pathToFileURL } from "node:url";
|
|
3
2
|
import { HmrStrategy, HmrStrategyType } from "@ecopages/core/hmr/hmr-strategy";
|
|
4
|
-
import {
|
|
3
|
+
import { rewriteRuntimeSpecifierAliases } from "@ecopages/core/build/runtime-specifier-aliases";
|
|
4
|
+
import { createRuntimeSpecifierAliasPlugin } from "@ecopages/core/build/runtime-specifier-alias-plugin";
|
|
5
5
|
import { FileNotFoundError, fileSystem } from "@ecopages/file-system";
|
|
6
6
|
import { Logger } from "@ecopages/logger";
|
|
7
7
|
import { injectHmrHandler } from "./utils/hmr-scripts.js";
|
|
8
8
|
import { createClientGraphBoundaryPlugin } from "./utils/client-graph-boundary-plugin.js";
|
|
9
9
|
import { collectPageDeclaredModules, collectPageDeclaredModulesFromModule } from "./utils/declared-modules.js";
|
|
10
|
+
import { createReactMdxLoaderPlugin } from "./utils/react-mdx-loader-plugin.js";
|
|
11
|
+
import { getReactClientGraphAllowSpecifiers } from "./utils/react-runtime-alias-map.js";
|
|
12
|
+
import { createUseSyncExternalStoreShimPlugin } from "./utils/use-sync-external-store-shim-plugin.js";
|
|
10
13
|
const appLogger = new Logger("[ReactHmrStrategy]");
|
|
11
14
|
class ReactHmrStrategy extends HmrStrategy {
|
|
15
|
+
type = HmrStrategyType.INTEGRATION;
|
|
16
|
+
mdxCompilerOptions;
|
|
17
|
+
ownedTemplateExtensions;
|
|
18
|
+
allTemplateExtensions;
|
|
19
|
+
async importNodePageModule(entrypointPath) {
|
|
20
|
+
return await this.context.importServerModule(entrypointPath);
|
|
21
|
+
}
|
|
12
22
|
/**
|
|
13
23
|
* Creates a new React HMR strategy instance.
|
|
14
24
|
*
|
|
15
|
-
* @param
|
|
16
|
-
* and the layouts directory for detecting layout file changes that require full
|
|
17
|
-
* page reloads instead of module-level HMR updates.
|
|
18
|
-
* @param pageMetadataCache - React-only cache of declared browser modules discovered during
|
|
19
|
-
* server rendering. This avoids re-importing unchanged page modules
|
|
20
|
-
* during save-time Fast Refresh rebuilds.
|
|
21
|
-
* @param mdxCompilerOptions - Optional MDX compiler options for processing .mdx files
|
|
22
|
-
* @param explicitGraphEnabled - Enables explicit graph mode for React HMR bundling.
|
|
23
|
-
* In explicit mode, HMR builds omit AST server-only stripping plugins in React paths.
|
|
25
|
+
* @param options - React HMR runtime services and behavior flags.
|
|
24
26
|
*/
|
|
25
|
-
|
|
27
|
+
context;
|
|
28
|
+
pageMetadataCache;
|
|
29
|
+
explicitGraphEnabled;
|
|
30
|
+
runtimeAliasMap;
|
|
31
|
+
constructor(options) {
|
|
26
32
|
super();
|
|
27
|
-
this.context = context;
|
|
28
|
-
this.pageMetadataCache = pageMetadataCache;
|
|
29
|
-
this.
|
|
30
|
-
this.
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const srcDir = this.context.getSrcDir();
|
|
37
|
-
const rootDir = path.dirname(srcDir);
|
|
38
|
-
const outdir = path.join(path.resolve(this.context.getDistDir(), "..", ".."), ".server-modules");
|
|
39
|
-
const fileBaseName = path.basename(entrypointPath, path.extname(entrypointPath));
|
|
40
|
-
const fileHash = fileSystem.hash(entrypointPath);
|
|
41
|
-
const outputFileName = `${fileBaseName}-${fileHash}.js`;
|
|
42
|
-
const buildResult = await defaultBuildAdapter.build({
|
|
43
|
-
entrypoints: [entrypointPath],
|
|
44
|
-
root: rootDir,
|
|
45
|
-
outdir,
|
|
46
|
-
target: "node",
|
|
47
|
-
format: "esm",
|
|
48
|
-
sourcemap: "none",
|
|
49
|
-
splitting: false,
|
|
50
|
-
minify: false,
|
|
51
|
-
naming: outputFileName
|
|
52
|
-
});
|
|
53
|
-
if (!buildResult.success) {
|
|
54
|
-
const details = buildResult.logs.map((log) => log.message).join(" | ");
|
|
55
|
-
throw new Error(`Error transpiling React HMR page module: ${details}`);
|
|
56
|
-
}
|
|
57
|
-
const preferredOutputPath = path.join(outdir, outputFileName);
|
|
58
|
-
const compiledOutput = buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ?? buildResult.outputs.find((output) => output.path.endsWith(".js"))?.path;
|
|
59
|
-
if (!compiledOutput) {
|
|
60
|
-
throw new Error(`No transpiled output generated for React HMR page module: ${entrypointPath}`);
|
|
61
|
-
}
|
|
62
|
-
return await import(pathToFileURL(compiledOutput).href);
|
|
63
|
-
}
|
|
64
|
-
createUseSyncExternalStoreShimPlugin() {
|
|
65
|
-
return {
|
|
66
|
-
name: "react-hmr-use-sync-external-store-shim",
|
|
67
|
-
setup(build) {
|
|
68
|
-
build.onResolve({ filter: /^use-sync-external-store\/shim(?:\/index\.js)?$/ }, () => ({
|
|
69
|
-
path: "use-sync-external-store/shim",
|
|
70
|
-
namespace: "ecopages-react-hmr-shim"
|
|
71
|
-
}));
|
|
72
|
-
build.onLoad(
|
|
73
|
-
{ filter: /^use-sync-external-store\/shim$/, namespace: "ecopages-react-hmr-shim" },
|
|
74
|
-
() => ({
|
|
75
|
-
contents: "export { useSyncExternalStore } from 'react';",
|
|
76
|
-
loader: "js"
|
|
77
|
-
})
|
|
78
|
-
);
|
|
79
|
-
build.onLoad({ filter: /[\\/]use-sync-external-store[\\/]shim[\\/]index\.js$/ }, () => ({
|
|
80
|
-
contents: "export { useSyncExternalStore } from 'react';",
|
|
81
|
-
loader: "js"
|
|
82
|
-
}));
|
|
83
|
-
build.onLoad(
|
|
84
|
-
{
|
|
85
|
-
filter: /[\\/]use-sync-external-store[\\/]cjs[\\/]use-sync-external-store-shim\.development\.js$/
|
|
86
|
-
},
|
|
87
|
-
() => ({
|
|
88
|
-
contents: "export { useSyncExternalStore } from 'react';",
|
|
89
|
-
loader: "js"
|
|
90
|
-
})
|
|
91
|
-
);
|
|
92
|
-
}
|
|
93
|
-
};
|
|
33
|
+
this.context = options.context;
|
|
34
|
+
this.pageMetadataCache = options.pageMetadataCache;
|
|
35
|
+
this.runtimeAliasMap = options.runtimeAliasMap;
|
|
36
|
+
this.explicitGraphEnabled = options.explicitGraphEnabled ?? false;
|
|
37
|
+
this.mdxCompilerOptions = options.mdxCompilerOptions;
|
|
38
|
+
this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? [".tsx"]);
|
|
39
|
+
this.allTemplateExtensions = [...options.allTemplateExtensions ?? [".tsx"]].sort(
|
|
40
|
+
(a, b) => b.length - a.length
|
|
41
|
+
);
|
|
94
42
|
}
|
|
95
43
|
/**
|
|
96
44
|
* Returns build plugins for React HMR bundling.
|
|
@@ -99,30 +47,59 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
99
47
|
* (including `node:*`) from breaking the browser bundle.
|
|
100
48
|
*/
|
|
101
49
|
getBuildPlugins(declaredModules) {
|
|
102
|
-
const allowSpecifiers =
|
|
103
|
-
|
|
104
|
-
"react"
|
|
105
|
-
|
|
106
|
-
"react/jsx-runtime",
|
|
107
|
-
"react/jsx-dev-runtime",
|
|
108
|
-
"react-dom/client",
|
|
109
|
-
...Array.from(this.context.getSpecifierMap().keys())
|
|
110
|
-
];
|
|
50
|
+
const allowSpecifiers = getReactClientGraphAllowSpecifiers(this.runtimeAliasMap.keys());
|
|
51
|
+
const runtimeAliasPlugin = createRuntimeSpecifierAliasPlugin(this.runtimeAliasMap, {
|
|
52
|
+
name: "react-hmr-runtime-specifier-alias"
|
|
53
|
+
});
|
|
111
54
|
return [
|
|
112
55
|
createClientGraphBoundaryPlugin({
|
|
113
56
|
absWorkingDir: path.dirname(this.context.getSrcDir()),
|
|
114
57
|
alwaysAllowSpecifiers: allowSpecifiers,
|
|
115
58
|
declaredModules
|
|
116
59
|
}),
|
|
60
|
+
...runtimeAliasPlugin ? [runtimeAliasPlugin] : [],
|
|
117
61
|
...this.context.getPlugins(),
|
|
118
|
-
|
|
62
|
+
createUseSyncExternalStoreShimPlugin({
|
|
63
|
+
name: "react-hmr-use-sync-external-store-shim",
|
|
64
|
+
namespace: "ecopages-react-hmr-shim"
|
|
65
|
+
})
|
|
119
66
|
];
|
|
120
67
|
}
|
|
121
68
|
isReactEntrypoint(filePath) {
|
|
122
|
-
if (filePath.endsWith(".
|
|
69
|
+
if (filePath.endsWith(".mdx")) {
|
|
70
|
+
return this.mdxCompilerOptions !== void 0;
|
|
71
|
+
}
|
|
72
|
+
if (!filePath.endsWith(".tsx")) {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
const templateExtension = this.resolveTemplateExtension(filePath);
|
|
76
|
+
if (templateExtension && templateExtension !== ".tsx") {
|
|
77
|
+
return this.ownedTemplateExtensions.has(templateExtension);
|
|
78
|
+
}
|
|
79
|
+
if (!this.isRouteTemplate(filePath)) {
|
|
123
80
|
return true;
|
|
124
81
|
}
|
|
125
|
-
|
|
82
|
+
if (!templateExtension) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
return this.ownedTemplateExtensions.has(templateExtension);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Returns true when a route file uses a compound extension like `page.foo.tsx`.
|
|
89
|
+
*
|
|
90
|
+
* @remarks
|
|
91
|
+
* React integration owns plain `.tsx` route templates. Compound extensions in
|
|
92
|
+
* pages/layouts are integration-specific route templates and should not be
|
|
93
|
+
* claimed by React HMR strategy.
|
|
94
|
+
*/
|
|
95
|
+
isRouteTemplate(filePath) {
|
|
96
|
+
return filePath.startsWith(this.context.getPagesDir()) || filePath.startsWith(this.context.getLayoutsDir());
|
|
97
|
+
}
|
|
98
|
+
resolveTemplateExtension(filePath) {
|
|
99
|
+
return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
|
|
100
|
+
}
|
|
101
|
+
ownsWatchedEntrypoint(filePath) {
|
|
102
|
+
return this.pageMetadataCache.ownsEntrypoint(filePath);
|
|
126
103
|
}
|
|
127
104
|
/**
|
|
128
105
|
* Determines if the file is a React/MDX entrypoint that's registered for HMR.
|
|
@@ -136,6 +113,9 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
136
113
|
if (watchedFiles.size === 0) {
|
|
137
114
|
return false;
|
|
138
115
|
}
|
|
116
|
+
if (watchedFiles.has(filePath)) {
|
|
117
|
+
return this.ownsWatchedEntrypoint(filePath);
|
|
118
|
+
}
|
|
139
119
|
return this.isReactEntrypoint(filePath);
|
|
140
120
|
}
|
|
141
121
|
/**
|
|
@@ -174,8 +154,12 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
174
154
|
if (isLayout) {
|
|
175
155
|
appLogger.debug(`Detected layout file change: ${_filePath}`);
|
|
176
156
|
}
|
|
177
|
-
const
|
|
178
|
-
this.
|
|
157
|
+
const changedEntrypointOutput = watchedFiles.get(_filePath);
|
|
158
|
+
if (changedEntrypointOutput && !this.ownsWatchedEntrypoint(_filePath)) {
|
|
159
|
+
appLogger.debug(`Skipping non-React watched entrypoint: ${_filePath}`);
|
|
160
|
+
return { type: "none" };
|
|
161
|
+
}
|
|
162
|
+
const entrypointsToBuild = changedEntrypointOutput ? [[_filePath, changedEntrypointOutput]] : watchedFiles.entries();
|
|
179
163
|
const updates = [];
|
|
180
164
|
for (const [entrypoint, outputUrl] of entrypointsToBuild) {
|
|
181
165
|
if (!this.isReactEntrypoint(entrypoint)) {
|
|
@@ -231,20 +215,16 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
231
215
|
const declaredModules = this.pageMetadataCache.getDeclaredModules(entrypointPath) ? this.pageMetadataCache.getDeclaredModules(entrypointPath) : isMdx ? await collectPageDeclaredModules(entrypointPath) : collectPageDeclaredModulesFromModule(await this.importNodePageModule(entrypointPath));
|
|
232
216
|
const plugins = this.getBuildPlugins(declaredModules);
|
|
233
217
|
if (isMdx && this.mdxCompilerOptions) {
|
|
234
|
-
const { createReactMdxLoaderPlugin } = await import("./utils/react-mdx-loader-plugin.js");
|
|
235
218
|
const mdxPlugin = createReactMdxLoaderPlugin(this.mdxCompilerOptions);
|
|
236
219
|
plugins.unshift(mdxPlugin);
|
|
237
220
|
}
|
|
238
|
-
const result = await
|
|
221
|
+
const result = await this.context.getBrowserBundleService().bundle({
|
|
222
|
+
profile: "hmr-entrypoint",
|
|
239
223
|
entrypoints: [entrypointPath],
|
|
240
224
|
outdir: tempDir,
|
|
241
225
|
naming: `[name].[hash].tmp`,
|
|
242
|
-
target: "browser",
|
|
243
|
-
format: "esm",
|
|
244
|
-
sourcemap: "none",
|
|
245
226
|
plugins,
|
|
246
|
-
minify: false
|
|
247
|
-
external: ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime", "react-dom/client"]
|
|
227
|
+
minify: false
|
|
248
228
|
});
|
|
249
229
|
if (!result.success) {
|
|
250
230
|
appLogger.error(`Failed to build ${entrypointPath}:`, result.logs);
|
|
@@ -255,13 +235,33 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
255
235
|
appLogger.error(`No output file generated for ${entrypointPath}`);
|
|
256
236
|
return false;
|
|
257
237
|
}
|
|
258
|
-
const
|
|
238
|
+
const resolvedTempFile = await this.resolveTempOutputPath(tempFile);
|
|
239
|
+
if (!resolvedTempFile) {
|
|
240
|
+
appLogger.debug(`Skipping stale temp output for ${outputUrl}: ${tempFile}`);
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
const processed = await this.processOutput(resolvedTempFile, outputPath, outputUrl);
|
|
259
244
|
return processed;
|
|
260
245
|
} catch (error) {
|
|
261
246
|
appLogger.error(`Error bundling ${entrypointPath}:`, error);
|
|
262
247
|
return false;
|
|
263
248
|
}
|
|
264
249
|
}
|
|
250
|
+
async resolveTempOutputPath(tempPath) {
|
|
251
|
+
if (fileSystem.exists(tempPath)) {
|
|
252
|
+
return tempPath;
|
|
253
|
+
}
|
|
254
|
+
if (!tempPath.includes("[hash]")) {
|
|
255
|
+
return tempPath;
|
|
256
|
+
}
|
|
257
|
+
const directory = path.dirname(tempPath);
|
|
258
|
+
const pattern = path.basename(tempPath).replaceAll("[hash]", "*");
|
|
259
|
+
const matches = await fileSystem.glob([pattern], { cwd: directory });
|
|
260
|
+
if (matches.length === 0) {
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
return path.isAbsolute(matches[0]) ? matches[0] : path.join(directory, matches[0]);
|
|
264
|
+
}
|
|
265
265
|
/**
|
|
266
266
|
* Encodes dynamic route segments (brackets) in file paths.
|
|
267
267
|
* Converts `[slug]` to `_slug_` to avoid filesystem issues.
|
|
@@ -270,7 +270,7 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
270
270
|
return filepath.replace(/\[([^\]]+)\]/g, "_$1_");
|
|
271
271
|
}
|
|
272
272
|
/**
|
|
273
|
-
* Processes bundled output
|
|
273
|
+
* Processes bundled output and injects the React HMR handler.
|
|
274
274
|
* Writes to temp file first, then renames atomically to avoid conflicts.
|
|
275
275
|
*
|
|
276
276
|
* @param tempPath - Path to the temporary bundled file
|
|
@@ -285,7 +285,7 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
285
285
|
}
|
|
286
286
|
try {
|
|
287
287
|
let code = await fileSystem.readFile(tempPath);
|
|
288
|
-
code = this.
|
|
288
|
+
code = rewriteRuntimeSpecifierAliases(code, this.runtimeAliasMap);
|
|
289
289
|
code = injectHmrHandler(code);
|
|
290
290
|
await fileSystem.writeAsync(finalPath, code);
|
|
291
291
|
await fileSystem.removeAsync(tempPath).catch(() => {
|
|
@@ -305,27 +305,6 @@ class ReactHmrStrategy extends HmrStrategy {
|
|
|
305
305
|
return false;
|
|
306
306
|
}
|
|
307
307
|
}
|
|
308
|
-
/**
|
|
309
|
-
* Replaces bare specifiers with runtime URLs.
|
|
310
|
-
*
|
|
311
|
-
* Handles both static imports and dynamic imports.
|
|
312
|
-
*
|
|
313
|
-
* @param code - The bundled code to transform
|
|
314
|
-
* @returns The transformed code with runtime URLs
|
|
315
|
-
*/
|
|
316
|
-
replaceBareSpecifiers(code) {
|
|
317
|
-
const specifierMap = this.context.getSpecifierMap();
|
|
318
|
-
if (specifierMap.size === 0) {
|
|
319
|
-
return code;
|
|
320
|
-
}
|
|
321
|
-
let result = code;
|
|
322
|
-
for (const [bareSpec, runtimeUrl] of specifierMap.entries()) {
|
|
323
|
-
const escaped = bareSpec.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
324
|
-
result = result.replace(new RegExp(`from\\s*["']${escaped}["']`, "g"), `from "${runtimeUrl}"`);
|
|
325
|
-
result = result.replace(new RegExp(`import\\(["']${escaped}["']\\)`, "g"), `import("${runtimeUrl}")`);
|
|
326
|
-
}
|
|
327
|
-
return result;
|
|
328
|
-
}
|
|
329
308
|
}
|
|
330
309
|
export {
|
|
331
310
|
ReactHmrStrategy
|
package/src/react-renderer.d.ts
CHANGED
|
@@ -2,16 +2,24 @@
|
|
|
2
2
|
* This module contains the React renderer
|
|
3
3
|
* @module
|
|
4
4
|
*/
|
|
5
|
-
import type { ComponentRenderInput, ComponentRenderResult, EcoComponent,
|
|
6
|
-
import { IntegrationRenderer, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
|
|
7
|
-
import type { ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
|
|
8
|
-
import {
|
|
9
|
-
import type {
|
|
10
|
-
import type { ReactRouterAdapter } from './router-adapter.js';
|
|
5
|
+
import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
|
|
6
|
+
import { IntegrationRenderer, type HtmlDocumentContribution, type HtmlDocumentContributionContext, type PageBrowserGraphContributionContext, type RenderToResponseContext, type RouteModuleLoadOptions } from '@ecopages/core/route-renderer/integration-renderer';
|
|
7
|
+
import type { AssetDefinition, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
|
|
8
|
+
import type { ReactNode } from 'react';
|
|
9
|
+
import type { ReactRendererConfig } from './react.types.js';
|
|
11
10
|
import { ReactBundleService } from './services/react-bundle.service.js';
|
|
12
|
-
import {
|
|
11
|
+
import { ReactMdxConfigDependencyService } from './services/react-mdx-config-dependency.service.js';
|
|
13
12
|
import { ReactPageModuleService } from './services/react-page-module.service.js';
|
|
13
|
+
import { ReactPagePayloadService } from './services/react-page-payload.service.js';
|
|
14
14
|
import { ReactHydrationAssetService } from './services/react-hydration-asset.service.js';
|
|
15
|
+
export type { ReactRendererConfig } from './react.types.js';
|
|
16
|
+
type ReactRuntimeModules = {
|
|
17
|
+
react: Pick<typeof import('react'), 'createElement' | 'Fragment'>;
|
|
18
|
+
reactDomServer: Pick<typeof import('react-dom/server'), 'renderToReadableStream' | 'renderToString'>;
|
|
19
|
+
};
|
|
20
|
+
export type ReactRendererOptions = ConstructorParameters<typeof IntegrationRenderer>[0] & {
|
|
21
|
+
reactConfig?: ReactRendererConfig;
|
|
22
|
+
};
|
|
15
23
|
/**
|
|
16
24
|
* Error thrown when an error occurs while rendering a React component.
|
|
17
25
|
*/
|
|
@@ -32,75 +40,194 @@ export declare class BundleError extends Error {
|
|
|
32
40
|
export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
|
|
33
41
|
name: string;
|
|
34
42
|
componentDirectory: string;
|
|
35
|
-
private
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
43
|
+
private reactRuntimeModules?;
|
|
44
|
+
private readonly routerAdapter?;
|
|
45
|
+
private readonly mdxCompilerOptions?;
|
|
46
|
+
private readonly mdxExtensions;
|
|
47
|
+
private readonly hmrPageMetadataCache?;
|
|
40
48
|
/**
|
|
41
49
|
* Enables explicit graph behavior for React page-entry bundling.
|
|
42
50
|
*
|
|
43
51
|
* When true, page-entry bundles disable AST server-only stripping and rely
|
|
44
52
|
* on explicit dependency declarations for browser graph composition.
|
|
45
53
|
*/
|
|
46
|
-
|
|
54
|
+
private readonly explicitGraphEnabled;
|
|
47
55
|
/** @internal */
|
|
48
56
|
readonly bundleService: ReactBundleService;
|
|
49
57
|
/** @internal */
|
|
50
58
|
readonly pageModuleService: ReactPageModuleService;
|
|
51
59
|
/** @internal */
|
|
52
60
|
readonly hydrationAssetService: ReactHydrationAssetService;
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
});
|
|
61
|
+
/** @internal */
|
|
62
|
+
readonly pagePayloadService: ReactPagePayloadService;
|
|
63
|
+
/** @internal */
|
|
64
|
+
readonly mdxConfigDependencyService: ReactMdxConfigDependencyService;
|
|
65
|
+
constructor(options: ReactRendererOptions);
|
|
59
66
|
protected shouldRenderPageComponent(): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Reads the declared integration name for a component or layout.
|
|
69
|
+
*
|
|
70
|
+
* We honor both the explicit `config.integration` override and injected
|
|
71
|
+
* `config.__eco.integration` metadata because pages can arrive here through
|
|
72
|
+
* authored config as well as build-time component metadata.
|
|
73
|
+
*/
|
|
74
|
+
private getComponentIntegration;
|
|
75
|
+
/**
|
|
76
|
+
* Returns whether a component should stay inside the React render lane.
|
|
77
|
+
*
|
|
78
|
+
* Components without explicit integration metadata are treated as React-owned
|
|
79
|
+
* here because this renderer only receives them after the route pipeline has
|
|
80
|
+
* already selected the React integration.
|
|
81
|
+
*/
|
|
82
|
+
private isReactManagedComponent;
|
|
83
|
+
private getComponentRequires;
|
|
84
|
+
private getRouterDocumentAttributes;
|
|
85
|
+
/**
|
|
86
|
+
* Commits a framework-agnostic component to React semantics.
|
|
87
|
+
*
|
|
88
|
+
* This is one of the two real cast boundaries in this file. Core keeps
|
|
89
|
+
* `EcoComponent` broad so integrations can share the same public surface; once
|
|
90
|
+
* the React renderer is executing, `createElement()` needs a concrete React
|
|
91
|
+
* component signature.
|
|
92
|
+
*/
|
|
93
|
+
private asReactComponent;
|
|
94
|
+
/**
|
|
95
|
+
* Commits a mixed-shell component to the string-returning contract required by
|
|
96
|
+
* non-React layouts and HTML templates.
|
|
97
|
+
*
|
|
98
|
+
* This is the second real cast boundary: once we decide a shell is not managed
|
|
99
|
+
* by React, we call it directly and require serialized HTML back.
|
|
100
|
+
*/
|
|
101
|
+
private asNonReactShellComponent;
|
|
102
|
+
protected resolveReactRuntimeModules(): ReactRuntimeModules;
|
|
103
|
+
private getReactRuntimeModules;
|
|
104
|
+
/**
|
|
105
|
+
* Appends route hydration assets for a concrete page/view file to the current
|
|
106
|
+
* HTML transformer state.
|
|
107
|
+
*/
|
|
108
|
+
private appendHydrationAssetsForFile;
|
|
109
|
+
/**
|
|
110
|
+
* Renders a non-React layout or HTML template and enforces that mixed shells
|
|
111
|
+
* return serialized HTML.
|
|
112
|
+
*
|
|
113
|
+
* The React renderer can compose through another integration's shell, but only
|
|
114
|
+
* if that shell yields a string that can be inserted into the final document.
|
|
115
|
+
*/
|
|
116
|
+
private renderNonReactShellComponent;
|
|
117
|
+
/**
|
|
118
|
+
* Renders one React component while preserving already-resolved child HTML.
|
|
119
|
+
*
|
|
120
|
+
* When nested foreign-subtree resolution has already produced child HTML for this
|
|
121
|
+
* component, the child payload must remain raw SSR output rather than a React
|
|
122
|
+
* string child, otherwise React would escape it. This helper renders a unique
|
|
123
|
+
* token through React and swaps that token back to the resolved HTML
|
|
124
|
+
* afterward.
|
|
125
|
+
*
|
|
126
|
+
* @param input Component render input for the current render step.
|
|
127
|
+
* @param context React-specific render context for stable token generation.
|
|
128
|
+
* @returns Serialized component HTML with resolved child markup preserved.
|
|
129
|
+
*/
|
|
130
|
+
private renderComponentHtml;
|
|
131
|
+
/**
|
|
132
|
+
* Restores raw child HTML that was temporarily replaced by a token during React SSR.
|
|
133
|
+
*
|
|
134
|
+
* Queued foreign-subtree resolution may render children through a fragment path before all
|
|
135
|
+
* nested integration tokens are resolved. When that happens, React must never see
|
|
136
|
+
* the resolved child HTML as a normal string child or it would escape it. The
|
|
137
|
+
* runtime context stores the placeholder token and the raw child HTML so the
|
|
138
|
+
* fragment render path can reinsert it before foreign-subtree tokens are handled.
|
|
139
|
+
*/
|
|
140
|
+
private restoreRuntimeChildHtml;
|
|
141
|
+
/**
|
|
142
|
+
* Renders queued child content through React and then resolves nested foreign-subtree tokens.
|
|
143
|
+
*
|
|
144
|
+
* This path is only used for children that were deferred while React rendered the
|
|
145
|
+
* parent component. It first restores any raw child HTML placeholders owned by the
|
|
146
|
+
* current runtime context, then asks the shared queued foreign-subtree resolver to swap
|
|
147
|
+
* foreign integration tokens with their resolved HTML.
|
|
148
|
+
*/
|
|
149
|
+
private renderQueuedChildrenToHtml;
|
|
150
|
+
/**
|
|
151
|
+
* Resolves queued renderer-owned foreign-subtree tokens produced during React component rendering.
|
|
152
|
+
*
|
|
153
|
+
* React components can enqueue nested foreign subtrees while the parent HTML is being
|
|
154
|
+
* rendered. This delegates to the shared renderer-owned queue resolver but keeps
|
|
155
|
+
* the React-specific child rendering behavior local so raw child HTML and React's
|
|
156
|
+
* fragment rendering semantics stay coordinated.
|
|
157
|
+
*/
|
|
158
|
+
private resolveQueuedForeignSubtreeHtml;
|
|
159
|
+
private buildHydrationProps;
|
|
160
|
+
/**
|
|
161
|
+
* Builds shared document html contributions for router-backed React pages rendered
|
|
162
|
+
* through a non-React HTML shell.
|
|
163
|
+
*/
|
|
164
|
+
private buildNonReactDocumentContributions;
|
|
165
|
+
/**
|
|
166
|
+
* Renders a foreign integration component that participates in React composition.
|
|
167
|
+
*
|
|
168
|
+
* Non-React components must resolve to serialized HTML so React can embed them as
|
|
169
|
+
* mixed-shell children. Any component-owned dependencies still need to flow
|
|
170
|
+
* through the shared dependency resolver before queued foreign-subtree tokens are finalized.
|
|
171
|
+
*/
|
|
172
|
+
private renderForeignComponentWithSerializedHtml;
|
|
173
|
+
/**
|
|
174
|
+
* Renders a React-owned component and attaches island hydration metadata when possible.
|
|
175
|
+
*
|
|
176
|
+
* This path keeps React-owned SSR, queued foreign-subtree resolution, and optional
|
|
177
|
+
* island hydration wiring together so the public `renderComponent()` method can
|
|
178
|
+
* read as orchestration rather than implementation detail.
|
|
179
|
+
*/
|
|
180
|
+
private renderReactManagedComponent;
|
|
60
181
|
/**
|
|
61
182
|
* Renders a React component for component-level orchestration.
|
|
62
183
|
*
|
|
63
184
|
* Behavior:
|
|
64
185
|
* - SSR always returns the component's own root HTML (no synthetic wrapper).
|
|
65
|
-
* -
|
|
66
|
-
*
|
|
67
|
-
* -
|
|
186
|
+
* - When an explicit component instance id is provided, a stable
|
|
187
|
+
* `data-eco-component-id` attribute is attached so island hydration can target it.
|
|
188
|
+
* - Without an explicit instance id, component renders remain plain SSR output.
|
|
189
|
+
* - When resolved child HTML is provided, that foreign subtree is treated as a pure SSR
|
|
190
|
+
* composition step and does not emit hydration assets for the parent wrapper.
|
|
68
191
|
*
|
|
69
192
|
* This preserves DOM shape for global CSS/layout selectors while keeping a
|
|
70
193
|
* deterministic mount target per component instance.
|
|
71
194
|
*/
|
|
72
195
|
renderComponent(input: ComponentRenderInput): Promise<ComponentRenderResult>;
|
|
196
|
+
protected createForeignChildRuntime(options: {
|
|
197
|
+
renderInput: ComponentRenderInput;
|
|
198
|
+
rendererCache: Map<string, IntegrationRenderer<any>>;
|
|
199
|
+
}): import("@ecopages/core").ForeignChildRuntime;
|
|
73
200
|
/**
|
|
74
201
|
* Checks if the given file path corresponds to an MDX file based on configured extensions.
|
|
75
202
|
* @param filePath - The file path to check
|
|
76
203
|
* @returns True if the file is an MDX file
|
|
77
204
|
*/
|
|
78
205
|
isMdxFile(filePath: string): boolean;
|
|
206
|
+
protected usesIntegrationPageImporter(file: string): boolean;
|
|
207
|
+
protected importIntegrationPageFile(file: string, options?: RouteModuleLoadOptions): Promise<EcoPageFile>;
|
|
208
|
+
protected normalizeImportedPageFile<TPageModule extends EcoPageFile>(file: string, pageModule: TPageModule): TPageModule;
|
|
209
|
+
protected collectPageBrowserGraphContribution(context: PageBrowserGraphContributionContext): Promise<{
|
|
210
|
+
dependencies?: AssetDefinition[];
|
|
211
|
+
assets?: ProcessedAsset[];
|
|
212
|
+
}>;
|
|
79
213
|
/**
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
214
|
+
* Renders a full route response for the filesystem page pipeline.
|
|
215
|
+
*
|
|
216
|
+
* This path receives already-resolved route metadata, layout, locals, and HTML
|
|
217
|
+
* template instances from the shared renderer orchestration. Its main job is to
|
|
218
|
+
* serialize only the browser-safe page payload, compose the mixed React/non-
|
|
219
|
+
* React shell tree, and hand the result back as a document body.
|
|
83
220
|
*/
|
|
84
|
-
private processMdxConfigDependencies;
|
|
85
|
-
buildRouteRenderAssets(pagePath: string): Promise<ProcessedAsset[]>;
|
|
86
|
-
protected importPageFile(file: string): Promise<EcoPageFile<{
|
|
87
|
-
config?: EcoComponentConfig;
|
|
88
|
-
}>>;
|
|
89
221
|
render({ params, query, props, locals, pageLocals, metadata, Page, Layout, HtmlTemplate, pageProps, }: IntegrationRendererRenderOptions<ReactNode>): Promise<RouteRendererBody>;
|
|
222
|
+
protected getHtmlDocumentContributions(options: HtmlDocumentContributionContext<ReactNode>): HtmlDocumentContribution[] | undefined;
|
|
223
|
+
protected getDocumentAttributes(): Record<string, string> | undefined;
|
|
90
224
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
|
|
94
|
-
* request-scoped data (e.g., session). This data needs to be serialized to the
|
|
95
|
-
* client for hydration to match the server-rendered output.
|
|
96
|
-
*
|
|
97
|
-
* On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
|
|
98
|
-
* to prevent accidental use. This method safely detects that case and returns
|
|
99
|
-
* `undefined` instead of throwing.
|
|
225
|
+
* Renders an arbitrary React view through the application's HTML shell.
|
|
100
226
|
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
227
|
+
* Unlike route rendering, this path starts from a single component rather than a
|
|
228
|
+
* page module discovered by the router. It still needs to resolve metadata,
|
|
229
|
+
* layout dependencies, and hydration assets so direct `ctx.render()` calls match
|
|
230
|
+
* normal page responses.
|
|
103
231
|
*/
|
|
104
|
-
private getSerializableLocals;
|
|
105
232
|
renderToResponse<P = Record<string, unknown>>(view: EcoComponent<P>, props: P, ctx: RenderToResponseContext): Promise<Response>;
|
|
106
233
|
}
|