@ecopages/react 0.2.0-alpha.3 → 0.2.0-alpha.31

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 (68) hide show
  1. package/CHANGELOG.md +27 -39
  2. package/README.md +161 -18
  3. package/package.json +6 -6
  4. package/src/react-hmr-strategy.d.ts +42 -32
  5. package/src/react-hmr-strategy.js +99 -123
  6. package/src/react-renderer.d.ts +168 -41
  7. package/src/react-renderer.js +466 -163
  8. package/src/react.constants.d.ts +1 -0
  9. package/src/react.constants.js +4 -0
  10. package/src/react.plugin.d.ts +38 -111
  11. package/src/react.plugin.js +132 -61
  12. package/src/react.types.d.ts +88 -0
  13. package/src/react.types.js +0 -0
  14. package/src/router-adapter.d.ts +7 -14
  15. package/src/services/react-bundle.service.d.ts +15 -26
  16. package/src/services/react-bundle.service.js +44 -92
  17. package/src/services/react-hmr-page-metadata-cache.d.ts +9 -0
  18. package/src/services/react-hmr-page-metadata-cache.js +18 -2
  19. package/src/services/react-hydration-asset.service.d.ts +17 -18
  20. package/src/services/react-hydration-asset.service.js +59 -65
  21. package/src/services/react-mdx-config-dependency.service.d.ts +36 -0
  22. package/src/services/react-mdx-config-dependency.service.js +122 -0
  23. package/src/services/react-page-module.service.d.ts +10 -2
  24. package/src/services/react-page-module.service.js +44 -37
  25. package/src/services/react-page-payload.service.d.ts +46 -0
  26. package/src/services/react-page-payload.service.js +67 -0
  27. package/src/services/react-runtime-bundle.service.d.ts +15 -13
  28. package/src/services/react-runtime-bundle.service.js +103 -180
  29. package/src/utils/client-graph-boundary-plugin.d.ts +1 -1
  30. package/src/utils/client-graph-boundary-plugin.js +149 -11
  31. package/src/utils/component-config-traversal.d.ts +36 -0
  32. package/src/utils/component-config-traversal.js +54 -0
  33. package/src/utils/declared-modules.d.ts +1 -1
  34. package/src/utils/declared-modules.js +7 -16
  35. package/src/utils/dynamic.test.browser.d.ts +1 -0
  36. package/src/utils/dynamic.test.browser.js +33 -0
  37. package/src/utils/hydration-scripts.d.ts +25 -6
  38. package/src/utils/hydration-scripts.js +150 -44
  39. package/src/utils/hydration-scripts.test.browser.d.ts +1 -0
  40. package/src/utils/hydration-scripts.test.browser.js +198 -0
  41. package/src/utils/reachability-analyzer.d.ts +12 -1
  42. package/src/utils/reachability-analyzer.js +101 -5
  43. package/src/utils/react-dom-runtime-interop-plugin.d.ts +5 -0
  44. package/src/utils/react-dom-runtime-interop-plugin.js +29 -0
  45. package/src/utils/react-mdx-loader-plugin.d.ts +1 -1
  46. package/src/utils/react-mdx-loader-plugin.js +13 -5
  47. package/src/utils/react-runtime-alias-map.d.ts +6 -0
  48. package/src/utils/react-runtime-alias-map.js +33 -0
  49. package/src/utils/use-sync-external-store-shim-plugin.d.ts +5 -0
  50. package/src/utils/use-sync-external-store-shim-plugin.js +41 -0
  51. package/src/react-hmr-strategy.ts +0 -444
  52. package/src/react-renderer.ts +0 -403
  53. package/src/react.plugin.ts +0 -241
  54. package/src/router-adapter.ts +0 -95
  55. package/src/services/react-bundle.service.ts +0 -212
  56. package/src/services/react-hmr-page-metadata-cache.ts +0 -24
  57. package/src/services/react-hydration-asset.service.ts +0 -260
  58. package/src/services/react-page-module.service.ts +0 -214
  59. package/src/services/react-runtime-bundle.service.ts +0 -271
  60. package/src/utils/client-graph-boundary-plugin.ts +0 -590
  61. package/src/utils/client-only.ts +0 -27
  62. package/src/utils/declared-modules.ts +0 -99
  63. package/src/utils/dynamic.ts +0 -27
  64. package/src/utils/hmr-scripts.ts +0 -47
  65. package/src/utils/html-boundary.ts +0 -66
  66. package/src/utils/hydration-scripts.ts +0 -338
  67. package/src/utils/reachability-analyzer.ts +0 -440
  68. package/src/utils/react-mdx-loader-plugin.ts +0 -40
@@ -0,0 +1,122 @@
1
+ import path from "node:path";
2
+ import { rapidhash } from "@ecopages/core/hash";
3
+ import {
4
+ AssetFactory
5
+ } from "@ecopages/core/services/asset-processing-service";
6
+ import { collectFromConfigForest, getComponentConfigs } from "../utils/component-config-traversal.js";
7
+ class ReactMdxConfigDependencyService {
8
+ config;
9
+ constructor(config) {
10
+ this.config = config;
11
+ }
12
+ /**
13
+ * Processes MDX-owned config dependencies and eagerly emits any SSR-marked lazy scripts.
14
+ */
15
+ async processMdxConfigDependencies(options) {
16
+ const components = this.createOwnedConfigComponents(options.pagePath, options.config);
17
+ if (components.length === 0) {
18
+ return [];
19
+ }
20
+ const processedDependencies = await options.processComponentDependencies(components);
21
+ const eagerSsrLazyDependencies = await this.processDeclaredSsrLazyDependencies(components, options.pagePath);
22
+ return [...processedDependencies, ...eagerSsrLazyDependencies];
23
+ }
24
+ createOwnedConfigComponents(pagePath, config) {
25
+ const components = [];
26
+ const resolvedLayout = config?.layout;
27
+ if (resolvedLayout?.config?.dependencies) {
28
+ const layoutConfig = this.config.pageModuleService.ensureConfigFileMetadata(
29
+ resolvedLayout.config,
30
+ pagePath
31
+ );
32
+ components.push({ config: layoutConfig });
33
+ }
34
+ if (config?.dependencies) {
35
+ components.push({
36
+ config: {
37
+ ...config,
38
+ __eco: {
39
+ id: rapidhash(pagePath).toString(36),
40
+ file: pagePath,
41
+ integration: this.config.integrationName
42
+ }
43
+ }
44
+ });
45
+ }
46
+ return components;
47
+ }
48
+ async processDeclaredSsrLazyDependencies(components, pagePath) {
49
+ if (!this.config.assetProcessingService?.processDependencies) {
50
+ return [];
51
+ }
52
+ const dependencies = this.collectDeclaredSsrLazyDependencies(components);
53
+ if (dependencies.length === 0) {
54
+ return [];
55
+ }
56
+ return this.config.assetProcessingService.processDependencies(
57
+ dependencies,
58
+ `${this.config.integrationName}-mdx-ssr-lazy:${pagePath}`
59
+ );
60
+ }
61
+ /**
62
+ * Collects `lazy` script dependencies that also opt into SSR from an MDX config graph.
63
+ */
64
+ collectDeclaredSsrLazyDependencies(components) {
65
+ const dependencies = [];
66
+ const seenKeys = /* @__PURE__ */ new Set();
67
+ const normalizeAttributes = (attributes) => ({
68
+ type: "module",
69
+ defer: "",
70
+ ...attributes ?? {}
71
+ });
72
+ collectFromConfigForest(getComponentConfigs(components), (config) => {
73
+ const componentFile = config.__eco?.file;
74
+ if (!componentFile) {
75
+ return [];
76
+ }
77
+ const componentDir = path.dirname(componentFile);
78
+ for (const script of config.dependencies?.scripts ?? []) {
79
+ if (typeof script === "string" || !script.lazy || script.ssr !== true) {
80
+ continue;
81
+ }
82
+ const attributes = normalizeAttributes(script.attributes);
83
+ if (script.content) {
84
+ const key2 = `content:${script.content}:${JSON.stringify(attributes)}`;
85
+ if (seenKeys.has(key2)) {
86
+ continue;
87
+ }
88
+ seenKeys.add(key2);
89
+ dependencies.push(
90
+ AssetFactory.createContentScript({
91
+ position: "head",
92
+ content: script.content,
93
+ attributes
94
+ })
95
+ );
96
+ continue;
97
+ }
98
+ if (!script.src) {
99
+ continue;
100
+ }
101
+ const resolvedPath = path.resolve(componentDir, script.src);
102
+ const key = `file:${resolvedPath}:${JSON.stringify(attributes)}`;
103
+ if (seenKeys.has(key)) {
104
+ continue;
105
+ }
106
+ seenKeys.add(key);
107
+ dependencies.push(
108
+ AssetFactory.createFileScript({
109
+ filepath: resolvedPath,
110
+ position: "head",
111
+ attributes
112
+ })
113
+ );
114
+ }
115
+ return [];
116
+ });
117
+ return dependencies;
118
+ }
119
+ }
120
+ export {
121
+ ReactMdxConfigDependencyService
122
+ };
@@ -7,6 +7,7 @@
7
7
  * @module
8
8
  */
9
9
  import type { EcoComponentConfig, EcoPageFile } from '@ecopages/core';
10
+ import type { BuildExecutor } from '@ecopages/core/build/build-adapter';
10
11
  import type { CompileOptions } from '@mdx-js/mdx';
11
12
  /**
12
13
  * Configuration for the ReactPageModuleService.
@@ -14,6 +15,8 @@ import type { CompileOptions } from '@mdx-js/mdx';
14
15
  export interface ReactPageModuleServiceConfig {
15
16
  rootDir: string;
16
17
  distDir: string;
18
+ workDir: string;
19
+ buildExecutor: BuildExecutor;
17
20
  layoutsDir?: string;
18
21
  componentsDir?: string;
19
22
  mdxCompilerOptions?: CompileOptions;
@@ -40,7 +43,12 @@ export declare class ReactPageModuleService {
40
43
  * @param filePath - Absolute path to the MDX file
41
44
  * @returns The imported module
42
45
  */
43
- importMdxPageFile(filePath: string): Promise<unknown>;
46
+ importMdxPageFile(filePath: string, options?: {
47
+ bypassCache?: boolean;
48
+ cacheScope?: string;
49
+ }): Promise<EcoPageFile<{
50
+ config?: EcoComponentConfig;
51
+ }>>;
44
52
  /**
45
53
  * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
46
54
  * Resolves the file path from dependency declarations when not already set.
@@ -54,7 +62,7 @@ export declare class ReactPageModuleService {
54
62
  * Recursively checks whether a component config tree declares any browser modules.
55
63
  * Used to determine if a page needs hydration.
56
64
  */
57
- hasModulesInConfig(config: EcoComponentConfig | undefined, visited?: Set<EcoComponentConfig>): boolean;
65
+ hasModulesInConfig(config: EcoComponentConfig | undefined): boolean;
58
66
  /**
59
67
  * Determines whether a page needs client-side hydration.
60
68
  *
@@ -1,10 +1,12 @@
1
1
  import path from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import { rapidhash } from "@ecopages/core/hash";
4
- import { defaultBuildAdapter } from "@ecopages/core/build/build-adapter";
4
+ import { build } from "@ecopages/core/build/build-adapter";
5
5
  import { fileSystem } from "@ecopages/file-system";
6
+ import { someInConfigTree } from "../utils/component-config-traversal.js";
6
7
  import { collectDeclaredModulesInConfig } from "../utils/declared-modules.js";
7
8
  class ReactPageModuleService {
9
+ config;
8
10
  constructor(config) {
9
11
  this.config = config;
10
12
  }
@@ -22,7 +24,7 @@ class ReactPageModuleService {
22
24
  * @param filePath - Absolute path to the MDX file
23
25
  * @returns The imported module
24
26
  */
25
- async importMdxPageFile(filePath) {
27
+ async importMdxPageFile(filePath, options) {
26
28
  const { createReactMdxLoaderPlugin } = await import("../utils/react-mdx-loader-plugin.js");
27
29
  const mdxPlugin = createReactMdxLoaderPlugin(
28
30
  this.config.mdxCompilerOptions ?? {
@@ -31,24 +33,28 @@ class ReactPageModuleService {
31
33
  development: process?.env?.NODE_ENV === "development"
32
34
  }
33
35
  );
34
- const outdir = path.join(this.config.distDir, ".server-modules-react-mdx");
36
+ const outdir = path.join(this.config.workDir, ".server-modules-react-mdx");
35
37
  const fileBaseName = path.basename(filePath, path.extname(filePath));
36
38
  const fileHash = fileSystem.hash(filePath);
37
- const cacheBuster = process?.env?.NODE_ENV === "development" ? `-${Date.now()}` : "";
38
- const outputFileName = `${fileBaseName}-${fileHash}${cacheBuster}.js`;
39
- const buildResult = await defaultBuildAdapter.build({
40
- entrypoints: [filePath],
41
- root: this.config.rootDir,
42
- outdir,
43
- target: "node",
44
- format: "esm",
45
- sourcemap: "none",
46
- splitting: false,
47
- minify: false,
48
- treeshaking: false,
49
- naming: outputFileName,
50
- plugins: [mdxPlugin]
51
- });
39
+ const cacheScopeSuffix = options?.cacheScope ? `-${sanitizeCacheScope(options.cacheScope)}` : "";
40
+ const cacheBuster = options?.bypassCache || process?.env?.NODE_ENV === "development" ? `-${Date.now()}` : "";
41
+ const outputFileName = `${fileBaseName}-${fileHash}${cacheScopeSuffix}${cacheBuster}.js`;
42
+ const buildResult = await build(
43
+ {
44
+ entrypoints: [filePath],
45
+ root: this.config.rootDir,
46
+ outdir,
47
+ target: "es2022",
48
+ format: "esm",
49
+ sourcemap: "none",
50
+ splitting: false,
51
+ minify: false,
52
+ treeshaking: false,
53
+ naming: outputFileName,
54
+ plugins: [mdxPlugin]
55
+ },
56
+ this.config.buildExecutor
57
+ );
52
58
  if (!buildResult.success) {
53
59
  const details = buildResult.logs.map((log) => log.message).join(" | ");
54
60
  throw new Error(`Failed to compile MDX page module: ${details}`);
@@ -58,7 +64,17 @@ class ReactPageModuleService {
58
64
  if (!compiledOutput) {
59
65
  throw new Error(`No compiled MDX output generated for page: ${filePath}`);
60
66
  }
61
- return await import(pathToFileURL(compiledOutput).href);
67
+ const compiledOutputUrl = pathToFileURL(compiledOutput);
68
+ if (process?.env?.NODE_ENV === "development" || options?.cacheScope) {
69
+ compiledOutputUrl.searchParams.set(
70
+ "update",
71
+ [fileHash, options?.cacheScope ? sanitizeCacheScope(options.cacheScope) : void 0].filter((value) => value !== void 0).join("-")
72
+ );
73
+ }
74
+ return await import(
75
+ /* @vite-ignore */
76
+ compiledOutputUrl.href
77
+ );
62
78
  }
63
79
  /**
64
80
  * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
@@ -91,7 +107,7 @@ class ReactPageModuleService {
91
107
  if (fileSystem.exists(resolvedDependency)) {
92
108
  return {
93
109
  ...config,
94
- __eco: buildEcoMeta(resolvedDependency)
110
+ __eco: buildEcoMeta(path.join(candidateDir, path.basename(pagePath)))
95
111
  };
96
112
  }
97
113
  }
@@ -105,23 +121,11 @@ class ReactPageModuleService {
105
121
  * Recursively checks whether a component config tree declares any browser modules.
106
122
  * Used to determine if a page needs hydration.
107
123
  */
108
- hasModulesInConfig(config, visited = /* @__PURE__ */ new Set()) {
109
- if (!config || visited.has(config)) {
110
- return false;
111
- }
112
- visited.add(config);
113
- if (config.dependencies?.modules?.some((entry) => entry.trim().length > 0)) {
114
- return true;
115
- }
116
- if (config.layout?.config && this.hasModulesInConfig(config.layout.config, visited)) {
117
- return true;
118
- }
119
- for (const component of config.dependencies?.components ?? []) {
120
- if (this.hasModulesInConfig(component.config, visited)) {
121
- return true;
122
- }
123
- }
124
- return false;
124
+ hasModulesInConfig(config) {
125
+ return someInConfigTree(
126
+ config,
127
+ (node) => node.dependencies?.modules?.some((entry) => entry.trim().length > 0) ?? false
128
+ );
125
129
  }
126
130
  /**
127
131
  * Determines whether a page needs client-side hydration.
@@ -150,6 +154,9 @@ class ReactPageModuleService {
150
154
  return Array.from(new Set(declarations));
151
155
  }
152
156
  }
157
+ function sanitizeCacheScope(cacheScope) {
158
+ return cacheScope.replace(/[^a-zA-Z0-9_-]+/g, "-");
159
+ }
153
160
  export {
154
161
  ReactPageModuleService
155
162
  };
@@ -0,0 +1,46 @@
1
+ import type { HtmlTemplateProps, IntegrationRendererRenderOptions, RequestLocals } from '@ecopages/core';
2
+ import type { ReactNode } from 'react';
3
+ type PagePayloadOptions = {
4
+ pageProps?: HtmlTemplateProps['pageProps'];
5
+ params: IntegrationRendererRenderOptions<ReactNode>['params'];
6
+ query: IntegrationRendererRenderOptions<ReactNode>['query'];
7
+ safeLocals?: RequestLocals;
8
+ };
9
+ /**
10
+ * Builds the serialized page payload React exposes to document shells and the browser.
11
+ *
12
+ * This keeps hydration payload shaping away from the renderer so the renderer can
13
+ * stay focused on component orchestration instead of data serialization rules.
14
+ */
15
+ export declare class ReactPagePayloadService {
16
+ /**
17
+ * Creates the canonical page-props payload used by router hydration.
18
+ *
19
+ * React pages embedded in a non-React HTML shell still need to expose the same
20
+ * page-data contract as fully React-owned documents so navigation and hydration
21
+ * can read one shared document payload consistently.
22
+ */
23
+ buildRouterPageDataScript(pageProps: HtmlTemplateProps['pageProps'] | undefined): string;
24
+ /**
25
+ * Builds the serialized page-props payload embedded into the final HTML.
26
+ *
27
+ * The document payload is intentionally narrower than the full server render
28
+ * input: only routing data, public page props, and explicitly allowed locals are
29
+ * exposed to the browser.
30
+ */
31
+ buildSerializedPageProps(options: PagePayloadOptions): HtmlTemplateProps['pageProps'];
32
+ /**
33
+ * Safely extracts the declared subset of locals for client-side hydration.
34
+ *
35
+ * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
36
+ * request-scoped data (e.g., session). Only keys explicitly declared via
37
+ * `Page.requires` are serialized to the client so sensitive request-only data
38
+ * is not leaked into hydration payloads by default.
39
+ *
40
+ * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
41
+ * to prevent accidental use. This method safely detects that case and returns
42
+ * `undefined` instead of throwing.
43
+ */
44
+ getSerializableLocals(locals: RequestLocals | undefined, requiredLocals?: string | readonly string[]): RequestLocals | undefined;
45
+ }
46
+ export {};
@@ -0,0 +1,67 @@
1
+ import { LocalsAccessError } from "@ecopages/core/errors";
2
+ class ReactPagePayloadService {
3
+ /**
4
+ * Creates the canonical page-props payload used by router hydration.
5
+ *
6
+ * React pages embedded in a non-React HTML shell still need to expose the same
7
+ * page-data contract as fully React-owned documents so navigation and hydration
8
+ * can read one shared document payload consistently.
9
+ */
10
+ buildRouterPageDataScript(pageProps) {
11
+ const safeJson = JSON.stringify(pageProps || {}).replace(/</g, "\\u003c");
12
+ return `<script id="__ECO_PAGE_DATA__" type="application/json">${safeJson}<\/script>`;
13
+ }
14
+ /**
15
+ * Builds the serialized page-props payload embedded into the final HTML.
16
+ *
17
+ * The document payload is intentionally narrower than the full server render
18
+ * input: only routing data, public page props, and explicitly allowed locals are
19
+ * exposed to the browser.
20
+ */
21
+ buildSerializedPageProps(options) {
22
+ return {
23
+ ...options.pageProps,
24
+ params: options.params,
25
+ query: options.query,
26
+ ...options.safeLocals && { locals: options.safeLocals }
27
+ };
28
+ }
29
+ /**
30
+ * Safely extracts the declared subset of locals for client-side hydration.
31
+ *
32
+ * On dynamic pages with `cache: 'dynamic'`, middleware populates `locals` with
33
+ * request-scoped data (e.g., session). Only keys explicitly declared via
34
+ * `Page.requires` are serialized to the client so sensitive request-only data
35
+ * is not leaked into hydration payloads by default.
36
+ *
37
+ * On static pages, `locals` is a Proxy that throws `LocalsAccessError` on access
38
+ * to prevent accidental use. This method safely detects that case and returns
39
+ * `undefined` instead of throwing.
40
+ */
41
+ getSerializableLocals(locals, requiredLocals) {
42
+ try {
43
+ if (!locals) {
44
+ return void 0;
45
+ }
46
+ const requiredKeys = requiredLocals ? Array.isArray(requiredLocals) ? requiredLocals : [requiredLocals] : [];
47
+ if (requiredKeys.length === 0) {
48
+ return void 0;
49
+ }
50
+ const serializedLocals = Object.fromEntries(
51
+ requiredKeys.filter((key) => Object.prototype.hasOwnProperty.call(locals, key)).map((key) => [key, locals[key]])
52
+ );
53
+ if (Object.keys(serializedLocals).length > 0) {
54
+ return serializedLocals;
55
+ }
56
+ return void 0;
57
+ } catch (error) {
58
+ if (error instanceof LocalsAccessError) {
59
+ return void 0;
60
+ }
61
+ throw error;
62
+ }
63
+ }
64
+ }
65
+ export {
66
+ ReactPagePayloadService
67
+ };
@@ -2,12 +2,11 @@
2
2
  * Runtime bundle service for React integration.
3
3
  *
4
4
  * Owns creation of the browser runtime assets for React and React DOM,
5
- * including temporary entry generation, specifier mapping, and React DOM
6
- * interop rewriting.
5
+ * including shared runtime entry generation and specifier mapping.
7
6
  *
8
7
  * @module
9
8
  */
10
- import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
9
+ import type { EcoBuildPlugin } from '@ecopages/core/plugins/integration-plugin';
11
10
  import { type AssetDefinition } from '@ecopages/core/services/asset-processing-service';
12
11
  import type { ReactRouterAdapter } from '../router-adapter.js';
13
12
  export type ReactRuntimeImports = {
@@ -20,19 +19,22 @@ export type ReactRuntimeImports = {
20
19
  };
21
20
  export interface ReactRuntimeBundleServiceConfig {
22
21
  routerAdapter?: ReactRouterAdapter;
22
+ rootDir?: string;
23
23
  }
24
+ type RuntimeMode = 'development' | 'production';
24
25
  export declare class ReactRuntimeBundleService {
25
26
  private readonly config;
26
27
  constructor(config: ReactRuntimeBundleServiceConfig);
27
- getRuntimeImports(): ReactRuntimeImports;
28
- getSpecifierMap(): Record<string, string>;
28
+ setRootDir(rootDir: string | undefined): void;
29
+ private get isDevelopment();
30
+ private getCurrentRuntimeMode;
31
+ private createRuntimeDefines;
32
+ private getReactVendorFileName;
33
+ private getReactDomVendorFileName;
34
+ private getRouterVendorFileName;
35
+ getRuntimeImports(mode?: RuntimeMode): ReactRuntimeImports;
36
+ getRuntimeAliasMap(mode?: RuntimeMode): Record<string, string>;
29
37
  getDependencies(): AssetDefinition[];
30
- createRuntimeAliasPlugin(): EcoBuildPlugin;
31
- private buildImportMapSourceUrl;
32
- private createRuntimeSpecifierAliasPlugin;
33
- private createReactDomRuntimeInteropPlugin;
34
- private getRuntimeArtifactsDir;
35
- private createRuntimeEntry;
36
- private getModuleExportNames;
37
- private isValidExportName;
38
+ createRuntimeAliasPlugin(mode?: RuntimeMode): EcoBuildPlugin;
38
39
  }
40
+ export {};