@ecopages/react 0.2.0-beta.2 → 0.2.0-beta.21

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 (30) hide show
  1. package/README.md +12 -0
  2. package/package.json +21 -4
  3. package/src/layout-compose.d.ts +58 -0
  4. package/src/layout-compose.js +98 -0
  5. package/src/react-hmr-strategy.d.ts +16 -0
  6. package/src/react-hmr-strategy.js +142 -113
  7. package/src/react-renderer.d.ts +34 -13
  8. package/src/react-renderer.js +187 -84
  9. package/src/react.plugin.js +6 -27
  10. package/src/serialize-page-data-script.d.ts +8 -0
  11. package/src/serialize-page-data-script.js +10 -0
  12. package/src/services/react-bundle.service.d.ts +3 -2
  13. package/src/services/react-bundle.service.js +17 -8
  14. package/src/services/react-mdx-config-dependency.service.js +5 -7
  15. package/src/services/react-page-module.service.d.ts +4 -43
  16. package/src/services/react-page-module.service.js +0 -90
  17. package/src/services/react-page-payload.service.js +2 -2
  18. package/src/services/react-runtime-bundle.service.d.ts +5 -1
  19. package/src/services/react-runtime-bundle.service.js +8 -2
  20. package/src/utils/client-graph-ast-transform.d.ts +18 -0
  21. package/src/utils/client-graph-ast-transform.js +335 -0
  22. package/src/utils/client-graph-boundary-plugin.d.ts +1 -12
  23. package/src/utils/client-graph-boundary-plugin.js +8 -454
  24. package/src/utils/client-graph-reachability.d.ts +75 -0
  25. package/src/utils/client-graph-reachability.js +148 -0
  26. package/src/utils/component-config-traversal.js +4 -2
  27. package/src/utils/hydration-scripts.d.ts +2 -0
  28. package/src/utils/hydration-scripts.js +27 -14
  29. package/src/utils/react-mdx-loader-plugin.d.ts +2 -3
  30. package/src/utils/react-mdx-loader-plugin.js +5 -39
@@ -1,14 +1,13 @@
1
1
  /**
2
2
  * Page module loading and configuration resolution service for React integration.
3
3
  *
4
- * Handles MDX compilation, component config metadata resolution,
5
- * and module hydration analysis.
4
+ * Handles component config metadata resolution and module hydration analysis.
5
+ * MDX page modules load through the core {@link PageModuleImportService} path
6
+ * using the React plugin's server build contributions.
6
7
  *
7
8
  * @module
8
9
  */
9
10
  import type { EcoComponentConfig, EcoPageFile } from '@ecopages/core';
10
- import { type BuildExecutor } from '@ecopages/core/build/build-adapter';
11
- import type { CompileOptions } from '@mdx-js/mdx';
12
11
  /**
13
12
  * Configuration for the ReactPageModuleService.
14
13
  */
@@ -16,70 +15,32 @@ export interface ReactPageModuleServiceConfig {
16
15
  rootDir: string;
17
16
  distDir: string;
18
17
  workDir: string;
19
- buildExecutor: BuildExecutor;
20
18
  layoutsDir?: string;
21
19
  componentsDir?: string;
22
- mdxCompilerOptions?: CompileOptions;
23
20
  mdxExtensions: string[];
24
21
  integrationName: string;
25
22
  hasRouterAdapter: boolean;
26
23
  }
27
24
  /**
28
- * Manages page module loading (including MDX compilation), config metadata
29
- * resolution, and hydration analysis for React pages.
25
+ * Manages page module metadata resolution and hydration analysis for React pages.
30
26
  */
31
27
  export declare class ReactPageModuleService {
32
28
  private readonly config;
33
29
  constructor(config: ReactPageModuleServiceConfig);
34
30
  /**
35
31
  * Checks if the given file path corresponds to an MDX file based on configured extensions.
36
- * @param filePath - The file path to check
37
- * @returns True if the file is an MDX file
38
32
  */
39
33
  isMdxFile(filePath: string): boolean;
40
- /**
41
- * Compiles and imports an MDX file as a page module.
42
- *
43
- * @param filePath - Absolute path to the MDX file
44
- * @returns The imported module
45
- */
46
- importMdxPageFile(filePath: string, options?: {
47
- bypassCache?: boolean;
48
- cacheScope?: string;
49
- }): Promise<EcoPageFile<{
50
- config?: EcoComponentConfig;
51
- }>>;
52
34
  /**
53
35
  * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
54
- * Resolves the file path from dependency declarations when not already set.
55
- *
56
- * @param config - The component config to augment
57
- * @param pagePath - Fallback file path if dependency resolution fails
58
- * @returns Config with `__eco` metadata populated
59
36
  */
60
37
  ensureConfigFileMetadata(config: EcoComponentConfig, pagePath: string): EcoComponentConfig;
61
- /**
62
- * Recursively checks whether a component config tree declares any browser modules.
63
- * Used to determine if a page needs hydration.
64
- */
65
38
  hasModulesInConfig(config: EcoComponentConfig | undefined): boolean;
66
- /**
67
- * Determines whether a page needs client-side hydration.
68
- *
69
- * @param pageModule - The imported page module
70
- * @returns True if the page should be hydrated
71
- */
72
39
  shouldHydratePage(pageModule: EcoPageFile<{
73
40
  config?: EcoComponentConfig;
74
41
  }> & {
75
42
  config?: EcoComponentConfig;
76
43
  }): boolean;
77
- /**
78
- * Collects all explicitly declared browser module specifiers from a page module.
79
- *
80
- * @param pageModule - The imported page module
81
- * @returns Deduplicated list of declared module specifiers
82
- */
83
44
  collectPageDeclaredModules(pageModule: EcoPageFile<{
84
45
  config?: EcoComponentConfig;
85
46
  }> & {
@@ -1,12 +1,8 @@
1
1
  import path from "node:path";
2
- import { pathToFileURL } from "node:url";
3
- import { build } from "@ecopages/core/build/build-adapter";
4
- import { normalizeNodeRuntimeBuildOutputFile } from "@ecopages/core/build/runtime-build-output-normalizer";
5
2
  import { rapidhash } from "@ecopages/core/hash";
6
3
  import { fileSystem } from "@ecopages/file-system";
7
4
  import { someInConfigTree } from "../utils/component-config-traversal.js";
8
5
  import { collectDeclaredModulesInConfig } from "../utils/declared-modules.js";
9
- import { createReactMdxLoaderPlugin } from "../utils/react-mdx-loader-plugin.js";
10
6
  class ReactPageModuleService {
11
7
  config;
12
8
  constructor(config) {
@@ -14,79 +10,12 @@ class ReactPageModuleService {
14
10
  }
15
11
  /**
16
12
  * Checks if the given file path corresponds to an MDX file based on configured extensions.
17
- * @param filePath - The file path to check
18
- * @returns True if the file is an MDX file
19
13
  */
20
14
  isMdxFile(filePath) {
21
15
  return this.config.mdxExtensions.some((ext) => filePath.endsWith(ext));
22
16
  }
23
- /**
24
- * Compiles and imports an MDX file as a page module.
25
- *
26
- * @param filePath - Absolute path to the MDX file
27
- * @returns The imported module
28
- */
29
- async importMdxPageFile(filePath, options) {
30
- const mdxPlugin = createReactMdxLoaderPlugin(
31
- this.config.mdxCompilerOptions ?? {
32
- jsxImportSource: "react",
33
- jsxRuntime: "automatic",
34
- development: process?.env?.NODE_ENV === "development"
35
- }
36
- );
37
- const outdir = path.join(this.config.workDir, ".server-modules-react-mdx");
38
- const fileBaseName = path.basename(filePath, path.extname(filePath));
39
- const fileHash = fileSystem.hash(filePath);
40
- const cacheScopeSuffix = options?.cacheScope ? `-${sanitizeCacheScope(options.cacheScope)}` : "";
41
- const cacheBuster = options?.bypassCache || process?.env?.NODE_ENV === "development" ? `-${Date.now()}` : "";
42
- const outputFileName = `${fileBaseName}-${fileHash}${cacheScopeSuffix}${cacheBuster}.mjs`;
43
- const outputNamingTemplate = `${fileBaseName}-${fileHash}${cacheScopeSuffix}${cacheBuster}.[ext]`;
44
- const buildResult = await build(
45
- {
46
- entrypoints: [filePath],
47
- root: this.config.rootDir,
48
- outdir,
49
- target: "es2022",
50
- format: "esm",
51
- sourcemap: "none",
52
- splitting: false,
53
- minify: false,
54
- treeshaking: false,
55
- externalPackages: true,
56
- naming: outputNamingTemplate,
57
- plugins: [mdxPlugin]
58
- },
59
- this.config.buildExecutor
60
- );
61
- if (!buildResult.success) {
62
- const details = buildResult.logs.map((log) => log.message).join(" | ");
63
- throw new Error(`Failed to compile MDX page module: ${details}`);
64
- }
65
- const preferredOutputPath = path.join(outdir, outputFileName);
66
- const compiledOutput = buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ?? buildResult.outputs.find((output) => /\.(?:[cm]?js)$/u.test(output.path))?.path;
67
- if (!compiledOutput) {
68
- throw new Error(`No compiled MDX output generated for page: ${filePath}`);
69
- }
70
- normalizeNodeRuntimeBuildOutputFile(compiledOutput, this.config.rootDir);
71
- const compiledOutputUrl = pathToFileURL(compiledOutput);
72
- if (process?.env?.NODE_ENV === "development" || options?.cacheScope) {
73
- compiledOutputUrl.searchParams.set(
74
- "update",
75
- [fileHash, options?.cacheScope ? sanitizeCacheScope(options.cacheScope) : void 0].filter((value) => value !== void 0).join("-")
76
- );
77
- }
78
- return await import(
79
- /* @vite-ignore */
80
- compiledOutputUrl.href
81
- );
82
- }
83
17
  /**
84
18
  * Ensures that an EcoComponentConfig has proper `__eco` metadata attached.
85
- * Resolves the file path from dependency declarations when not already set.
86
- *
87
- * @param config - The component config to augment
88
- * @param pagePath - Fallback file path if dependency resolution fails
89
- * @returns Config with `__eco` metadata populated
90
19
  */
91
20
  ensureConfigFileMetadata(config, pagePath) {
92
21
  if (config.__eco?.file) {
@@ -121,22 +50,12 @@ class ReactPageModuleService {
121
50
  __eco: buildEcoMeta(pagePath)
122
51
  };
123
52
  }
124
- /**
125
- * Recursively checks whether a component config tree declares any browser modules.
126
- * Used to determine if a page needs hydration.
127
- */
128
53
  hasModulesInConfig(config) {
129
54
  return someInConfigTree(
130
55
  config,
131
56
  (node) => node.dependencies?.modules?.some((entry) => entry.trim().length > 0) ?? false
132
57
  );
133
58
  }
134
- /**
135
- * Determines whether a page needs client-side hydration.
136
- *
137
- * @param pageModule - The imported page module
138
- * @returns True if the page should be hydrated
139
- */
140
59
  shouldHydratePage(pageModule) {
141
60
  if (this.config.hasRouterAdapter) {
142
61
  return true;
@@ -144,12 +63,6 @@ class ReactPageModuleService {
144
63
  const pageConfig = pageModule.default?.config;
145
64
  return this.hasModulesInConfig(pageConfig) || this.hasModulesInConfig(pageModule.config);
146
65
  }
147
- /**
148
- * Collects all explicitly declared browser module specifiers from a page module.
149
- *
150
- * @param pageModule - The imported page module
151
- * @returns Deduplicated list of declared module specifiers
152
- */
153
66
  collectPageDeclaredModules(pageModule) {
154
67
  const declarations = [
155
68
  ...collectDeclaredModulesInConfig(pageModule.default?.config),
@@ -158,9 +71,6 @@ class ReactPageModuleService {
158
71
  return Array.from(new Set(declarations));
159
72
  }
160
73
  }
161
- function sanitizeCacheScope(cacheScope) {
162
- return cacheScope.replace(/[^a-zA-Z0-9_-]+/g, "-");
163
- }
164
74
  export {
165
75
  ReactPageModuleService
166
76
  };
@@ -1,4 +1,5 @@
1
1
  import { LocalsAccessError } from "@ecopages/core/errors";
2
+ import { serializePageDataScript } from "../serialize-page-data-script.js";
2
3
  class ReactPagePayloadService {
3
4
  /**
4
5
  * Creates the canonical page-props payload used by router hydration.
@@ -8,8 +9,7 @@ class ReactPagePayloadService {
8
9
  * can read one shared document payload consistently.
9
10
  */
10
11
  buildRouterPageDataScript(pageProps) {
11
- const safeJson = JSON.stringify(pageProps || {}).replace(/</g, "\\u003c");
12
- return `<script id="__ECO_PAGE_DATA__" type="application/json">${safeJson}<\/script>`;
12
+ return serializePageDataScript(pageProps);
13
13
  }
14
14
  /**
15
15
  * Builds the serialized page-props payload embedded into the final HTML.
@@ -22,12 +22,14 @@ export type ReactRuntimeImports = {
22
22
  export interface ReactRuntimeBundleServiceConfig {
23
23
  routerAdapter?: ReactRouterAdapter;
24
24
  rootDir?: string;
25
+ workDir?: string;
25
26
  }
26
27
  type RuntimeMode = 'development' | 'production';
27
28
  export declare class ReactRuntimeBundleService {
28
29
  private readonly config;
29
30
  constructor(config: ReactRuntimeBundleServiceConfig);
30
31
  setRootDir(rootDir: string | undefined): void;
32
+ setWorkDir(workDir: string | undefined): void;
31
33
  private get isDevelopment();
32
34
  private getCurrentRuntimeMode;
33
35
  private createRuntimeDefines;
@@ -39,7 +41,9 @@ export declare class ReactRuntimeBundleService {
39
41
  getRuntimeImports(mode?: RuntimeMode): ReactRuntimeImports;
40
42
  getRuntimeAliasMap(mode?: RuntimeMode): Record<string, string>;
41
43
  getRuntimeManifest(mode?: RuntimeMode): BrowserRuntimeManifest;
42
- getDependencies(): AssetDefinition[];
44
+ getDependencies(options?: {
45
+ modes?: RuntimeMode[];
46
+ }): AssetDefinition[];
43
47
  createRuntimeAliasPlugin(mode?: RuntimeMode): EcoBuildPlugin;
44
48
  }
45
49
  export {};
@@ -18,6 +18,9 @@ class ReactRuntimeBundleService {
18
18
  setRootDir(rootDir) {
19
19
  this.config.rootDir = rootDir;
20
20
  }
21
+ setWorkDir(workDir) {
22
+ this.config.workDir = workDir;
23
+ }
21
24
  get isDevelopment() {
22
25
  return process.env.NODE_ENV === "development";
23
26
  }
@@ -83,9 +86,10 @@ class ReactRuntimeBundleService {
83
86
  getRuntimeManifest(mode = this.getCurrentRuntimeMode()) {
84
87
  return buildReactRuntimeManifest(this.getRuntimeImports(mode));
85
88
  }
86
- getDependencies() {
89
+ getDependencies(options) {
87
90
  const dependencies = [];
88
- for (const mode of ["production", "development"]) {
91
+ const modes = options?.modes ?? [this.getCurrentRuntimeMode()];
92
+ for (const mode of modes) {
89
93
  const reactVendorImportRewritePlugin = this.createReactVendorImportRewritePlugin(mode);
90
94
  const reactDomRuntimeInteropPlugin = createReactDomRuntimeInteropPlugin({
91
95
  reactSpecifier: buildBrowserRuntimeAssetUrl(this.getReactVendorFileName(mode))
@@ -117,6 +121,7 @@ class ReactRuntimeBundleService {
117
121
  fileName: this.getReactVendorFileName(mode),
118
122
  cacheDirName: `ecopages-react-runtime-${mode}`,
119
123
  rootDir: this.config.rootDir,
124
+ workDir: this.config.workDir,
120
125
  bundleOptions: {
121
126
  define: this.createRuntimeDefines(mode),
122
127
  excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME]
@@ -128,6 +133,7 @@ class ReactRuntimeBundleService {
128
133
  fileName: this.getReactDomVendorFileName(mode),
129
134
  cacheDirName: `ecopages-react-runtime-${mode}`,
130
135
  rootDir: this.config.rootDir,
136
+ workDir: this.config.workDir,
131
137
  bundleOptions: {
132
138
  define: this.createRuntimeDefines(mode),
133
139
  excludeAppBuildPlugins: [DEFAULT_BROWSER_RUNTIME_PLUGIN_NAME],
@@ -0,0 +1,18 @@
1
+ /**
2
+ * AST transforms for the client graph boundary plugin.
3
+ */
4
+ import type { RequestedExportRules } from './client-graph-boundary-cache.js';
5
+ /**
6
+ * Parses a module using Oxc AST and surgically removes forbidden imports.
7
+ * Filters down to the exact specifiers requested via `{namedImport}` syntax.
8
+ *
9
+ * @param source - The raw string source content of the module.
10
+ * @param filename - The absolute path of the module.
11
+ * @param globallyAllowed - A map of modules declared globally allowable by the build configuration.
12
+ * @param requestedExports - Local requested-export registry used to propagate named reachability across files.
13
+ * @returns An object containing the transformed string and a boolean indicating if changes occurred.
14
+ */
15
+ export declare function transformModuleImports(source: string, filename: string, globallyAllowed: Map<string, Set<string> | '*'>, requestedExports: Map<string, RequestedExportRules>): {
16
+ transformed: string;
17
+ modified: boolean;
18
+ };
@@ -0,0 +1,335 @@
1
+ import { extname } from "node:path";
2
+ import { cachedParseSync } from "@ecopages/core/cache";
3
+ import { analyzeReachability } from "./reachability-analyzer.js";
4
+ import {
5
+ isBareSpecifier,
6
+ isProjectAliasSpecifier,
7
+ isServerOnlySpecifier,
8
+ toModuleBaseSpecifier,
9
+ parseDeclaredModules,
10
+ mergeDeclaredModulesMap,
11
+ normalizeRequestedExportsKey,
12
+ resolveRequestedExportsKey,
13
+ mergeRequestedExportRules
14
+ } from "./client-graph-reachability.js";
15
+ const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = /* @__PURE__ */ new Set([
16
+ "cache",
17
+ "middleware",
18
+ "requires",
19
+ "metadata",
20
+ "staticProps",
21
+ "staticPaths"
22
+ ]);
23
+ function parserLanguageForFile(filename) {
24
+ const extension = extname(filename).toLowerCase();
25
+ if (extension === ".tsx") return "tsx";
26
+ if (extension === ".ts") return "ts";
27
+ if (extension === ".jsx") return "jsx";
28
+ return "js";
29
+ }
30
+ function getObjectPropertyKeyName(node) {
31
+ if (!node) return void 0;
32
+ if (node.type === "Identifier") return node.name;
33
+ if (node.type === "StringLiteral" || node.type === "Literal") {
34
+ return typeof node.value === "string" ? node.value : void 0;
35
+ }
36
+ return void 0;
37
+ }
38
+ function stripServerOnlyEcoPageOptions(source, program) {
39
+ const edits = [];
40
+ function walk(node) {
41
+ if (!node || typeof node !== "object") return;
42
+ if (Array.isArray(node)) {
43
+ for (const child of node) walk(child);
44
+ return;
45
+ }
46
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && node.callee.object?.type === "Identifier" && node.callee.object.name === "eco" && node.callee.property?.type === "Identifier" && node.callee.property.name === "page" && node.arguments?.[0]?.type === "ObjectExpression") {
47
+ const objectExpression = node.arguments[0];
48
+ const keptProperties = [];
49
+ let removedProperty = false;
50
+ for (const property of objectExpression.properties ?? []) {
51
+ if (property?.type === "Property") {
52
+ const keyName = getObjectPropertyKeyName(property.key);
53
+ if (keyName && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName)) {
54
+ removedProperty = true;
55
+ continue;
56
+ }
57
+ }
58
+ keptProperties.push(source.slice(property.start, property.end));
59
+ }
60
+ if (removedProperty) {
61
+ const replacement = keptProperties.length > 0 ? `{ ${keptProperties.join(", ")} }` : "{}";
62
+ edits.push({
63
+ start: objectExpression.start,
64
+ end: objectExpression.end,
65
+ replacement
66
+ });
67
+ }
68
+ }
69
+ for (const key in node) {
70
+ if (key !== "type" && key !== "start" && key !== "end") {
71
+ walk(node[key]);
72
+ }
73
+ }
74
+ }
75
+ walk(program);
76
+ if (edits.length === 0) {
77
+ return { transformed: source, modified: false };
78
+ }
79
+ edits.sort((a, b) => b.start - a.start);
80
+ let transformed = source;
81
+ for (const edit of edits) {
82
+ transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
83
+ }
84
+ return { transformed, modified: true };
85
+ }
86
+ function transformModuleImports(source, filename, globallyAllowed, requestedExports) {
87
+ let result;
88
+ try {
89
+ result = cachedParseSync(filename, source, {
90
+ sourceType: "module",
91
+ lang: parserLanguageForFile(filename)
92
+ });
93
+ } catch {
94
+ return { transformed: source, modified: false };
95
+ }
96
+ const { program } = result;
97
+ const localDeclared = [];
98
+ function walk(node) {
99
+ if (!node || typeof node !== "object") return;
100
+ if (Array.isArray(node)) {
101
+ for (const child of node) walk(child);
102
+ return;
103
+ }
104
+ if (node.type === "Property" && node.key?.name === "modules" && node.value?.type === "ArrayExpression") {
105
+ for (const el of node.value.elements) {
106
+ if ((el.type === "StringLiteral" || el.type === "Literal") && typeof el.value === "string") {
107
+ localDeclared.push(el.value);
108
+ }
109
+ }
110
+ }
111
+ for (const key in node) {
112
+ if (key !== "type" && key !== "start" && key !== "end") {
113
+ walk(node[key]);
114
+ }
115
+ }
116
+ }
117
+ walk(program);
118
+ const locallyAllowed = parseDeclaredModules(localDeclared);
119
+ const allowedMap = mergeDeclaredModulesMap(globallyAllowed, locallyAllowed);
120
+ const explicitRequestedExports = requestedExports.get(normalizeRequestedExportsKey(filename));
121
+ const reachability = analyzeReachability(source, filename, program, explicitRequestedExports);
122
+ for (const statement of program.body) {
123
+ if (statement.type === "ImportDeclaration") {
124
+ const reachableRules = reachability.reachableImports.get(statement.source.value);
125
+ const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
126
+ if (!requestedModuleKey || !reachableRules) continue;
127
+ mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
128
+ continue;
129
+ }
130
+ if (statement.type === "ExportNamedDeclaration" && statement.source) {
131
+ const reachableRules = reachability.reachableImports.get(statement.source.value);
132
+ const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
133
+ if (!requestedModuleKey || !reachableRules) continue;
134
+ mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
135
+ continue;
136
+ }
137
+ if (statement.type === "ExportAllDeclaration" && statement.source) {
138
+ const reachableRules = reachability.reachableImports.get(statement.source.value);
139
+ const requestedModuleKey = resolveRequestedExportsKey(filename, statement.source.value);
140
+ if (!requestedModuleKey || !reachableRules) continue;
141
+ mergeRequestedExportRules(requestedExports, requestedModuleKey, reachableRules);
142
+ }
143
+ }
144
+ const edits = [];
145
+ function processSpecifier(specifier) {
146
+ const moduleBase = toModuleBaseSpecifier(specifier);
147
+ const explicitRules = allowedMap.get(moduleBase);
148
+ if (isServerOnlySpecifier(specifier)) {
149
+ if (explicitRules) {
150
+ return { allowed: true, rules: explicitRules };
151
+ }
152
+ return { allowed: false };
153
+ }
154
+ if (isProjectAliasSpecifier(specifier)) return { allowed: true, rules: explicitRules ?? "*" };
155
+ if (!isBareSpecifier(specifier)) return { allowed: true, rules: explicitRules ?? "*" };
156
+ return { allowed: true, rules: explicitRules ?? "*" };
157
+ }
158
+ function walkImports(node) {
159
+ if (!node || typeof node !== "object") return;
160
+ if (Array.isArray(node)) {
161
+ for (const child of node) walkImports(child);
162
+ return;
163
+ }
164
+ if (node.type === "ImportDeclaration") {
165
+ const specifier = node.source.value;
166
+ const reachableRules = reachability.reachableImports.get(specifier);
167
+ const { allowed, rules } = processSpecifier(specifier);
168
+ if (!allowed) {
169
+ if (reachableRules && !reachability.isFallbackRoots) {
170
+ throw new Error(
171
+ `[Ecopages Client Reachability] Forbidden client import '${specifier}' at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`
172
+ );
173
+ } else {
174
+ edits.push({ start: node.start, end: node.end, replacement: "" });
175
+ }
176
+ return;
177
+ }
178
+ if (rules instanceof Set && node.specifiers && node.specifiers.length > 0) {
179
+ let keptSpecifierCount = 0;
180
+ let defaultImportLocal;
181
+ let namespaceImportLocal;
182
+ const namedImportNodes = [];
183
+ for (const spec of node.specifiers) {
184
+ if (spec.type === "ImportSpecifier") {
185
+ const importedName = spec.imported.type === "Identifier" ? spec.imported.name : spec.imported.value;
186
+ if (rules.has(importedName)) {
187
+ keptSpecifierCount += 1;
188
+ const localName = spec.local?.name;
189
+ if (localName && localName !== importedName) {
190
+ namedImportNodes.push(`${importedName} as ${localName}`);
191
+ } else {
192
+ namedImportNodes.push(importedName);
193
+ }
194
+ }
195
+ } else if (spec.type === "ImportDefaultSpecifier") {
196
+ if (rules.has("default")) {
197
+ keptSpecifierCount += 1;
198
+ defaultImportLocal = spec.local.name;
199
+ }
200
+ } else if (spec.type === "ImportNamespaceSpecifier") {
201
+ if (rules.has("*")) {
202
+ keptSpecifierCount += 1;
203
+ namespaceImportLocal = spec.local.name;
204
+ }
205
+ }
206
+ }
207
+ if (keptSpecifierCount === 0) {
208
+ edits.push({ start: node.start, end: node.end, replacement: "" });
209
+ } else if (keptSpecifierCount < node.specifiers.length) {
210
+ let newDeclaration = "";
211
+ if (defaultImportLocal && namespaceImportLocal) {
212
+ newDeclaration = `import ${defaultImportLocal}, * as ${namespaceImportLocal} from '${specifier}';`;
213
+ } else if (namespaceImportLocal) {
214
+ newDeclaration = `import * as ${namespaceImportLocal} from '${specifier}';`;
215
+ } else if (defaultImportLocal && namedImportNodes.length > 0) {
216
+ newDeclaration = `import ${defaultImportLocal}, { ${namedImportNodes.join(", ")} } from '${specifier}';`;
217
+ } else if (defaultImportLocal) {
218
+ newDeclaration = `import ${defaultImportLocal} from '${specifier}';`;
219
+ } else {
220
+ newDeclaration = `import { ${namedImportNodes.join(", ")} } from '${specifier}';`;
221
+ }
222
+ edits.push({ start: node.start, end: node.end, replacement: newDeclaration });
223
+ }
224
+ return;
225
+ }
226
+ if (!reachableRules && (!node.specifiers || node.specifiers.length === 0)) {
227
+ edits.push({ start: node.start, end: node.end, replacement: "" });
228
+ }
229
+ return;
230
+ }
231
+ if (node.type === "ExportNamedDeclaration" && node.source) {
232
+ const specifier = node.source.value;
233
+ const { allowed } = processSpecifier(specifier);
234
+ if (!allowed) {
235
+ const reachableRules = reachability.reachableImports.get(specifier);
236
+ if (reachableRules && !reachability.isFallbackRoots) {
237
+ throw new Error(
238
+ `[Ecopages Client Reachability] Forbidden client export from '${specifier}' at ${filename}:${node.start}. This export is explicitly reachable from the React render function.`
239
+ );
240
+ } else {
241
+ edits.push({ start: node.start, end: node.end, replacement: "" });
242
+ }
243
+ }
244
+ return;
245
+ }
246
+ if (node.type === "ExportAllDeclaration" && node.source) {
247
+ const specifier = node.source.value;
248
+ const { allowed } = processSpecifier(specifier);
249
+ if (!allowed) {
250
+ const reachableRules = reachability.reachableImports.get(specifier);
251
+ if (reachableRules && !reachability.isFallbackRoots) {
252
+ throw new Error(
253
+ `[Ecopages Client Reachability] Forbidden client export * from '${specifier}' at ${filename}:${node.start}. This export is explicitly reachable from the React render function.`
254
+ );
255
+ } else {
256
+ edits.push({ start: node.start, end: node.end, replacement: "" });
257
+ }
258
+ }
259
+ return;
260
+ }
261
+ if (node.type === "ImportExpression" && node.source?.value) {
262
+ const specifier = node.source.value;
263
+ const { allowed } = processSpecifier(specifier);
264
+ const reachableRules = reachability.reachableImports.get(specifier);
265
+ if (!reachableRules) {
266
+ if (!allowed) {
267
+ edits.push({ start: node.start, end: node.end, replacement: "Promise.resolve({})" });
268
+ }
269
+ return;
270
+ }
271
+ if (!allowed) {
272
+ if (!reachability.isFallbackRoots) {
273
+ throw new Error(
274
+ `[Ecopages Client Reachability] Forbidden dynamic import('${specifier}') at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`
275
+ );
276
+ } else {
277
+ edits.push({ start: node.start, end: node.end, replacement: "Promise.resolve({})" });
278
+ }
279
+ }
280
+ return;
281
+ }
282
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require") {
283
+ const arg = node.arguments?.[0];
284
+ if (arg && (arg.type === "StringLiteral" || arg.type === "Literal") && typeof arg.value === "string") {
285
+ const specifier = arg.value;
286
+ const { allowed } = processSpecifier(specifier);
287
+ const reachableRules = reachability.reachableImports.get(specifier);
288
+ if (!reachableRules) {
289
+ if (!allowed) {
290
+ edits.push({ start: node.start, end: node.end, replacement: "({})" });
291
+ }
292
+ } else if (!allowed) {
293
+ if (!reachability.isFallbackRoots) {
294
+ throw new Error(
295
+ `[Ecopages Client Reachability] Forbidden require('${specifier}') at ${filename}:${node.start}. This import is explicitly reachable from the React render function.`
296
+ );
297
+ } else {
298
+ edits.push({ start: node.start, end: node.end, replacement: "({})" });
299
+ }
300
+ }
301
+ }
302
+ }
303
+ for (const key in node) {
304
+ if (key !== "type" && key !== "start" && key !== "end") {
305
+ walkImports(node[key]);
306
+ }
307
+ }
308
+ }
309
+ walkImports(program);
310
+ if (edits.length === 0) {
311
+ return stripServerOnlyEcoPageOptions(source, program);
312
+ }
313
+ edits.sort((a, b) => b.start - a.start);
314
+ let transformed = source;
315
+ for (const edit of edits) {
316
+ transformed = transformed.slice(0, edit.start) + edit.replacement + transformed.slice(edit.end);
317
+ }
318
+ let reparsedResult;
319
+ try {
320
+ reparsedResult = cachedParseSync(filename, transformed, {
321
+ sourceType: "module",
322
+ lang: parserLanguageForFile(filename)
323
+ });
324
+ } catch {
325
+ return { transformed, modified: true };
326
+ }
327
+ const strippedPageOptions = stripServerOnlyEcoPageOptions(transformed, reparsedResult.program);
328
+ if (strippedPageOptions.modified) {
329
+ return strippedPageOptions;
330
+ }
331
+ return { transformed, modified: true };
332
+ }
333
+ export {
334
+ transformModuleImports
335
+ };
@@ -1,18 +1,7 @@
1
1
  /**
2
2
  * @module ClientGraphBoundaryPlugin
3
3
  *
4
- * This module defines the primary build plugin responsible for securing the Ecopages
5
- * isomorphic compilation pipeline. It ensures that backend-only code, sensitive Node.js APIs,
6
- * and massive server utilities do not accidentally leak into the browser bundle.
7
- *
8
- * It achieves this by intercepting all client module compilation passes and applying the
9
- * `analyzeReachability` AST pass. If a forbidden import (e.g. `node:fs` or `*.server.ts`)
10
- * is completely unreachable from the client component's `render` function, it is surgically
11
- * pruned. If a forbidden import IS reachable, the build is intentionally failed to prevent
12
- * runtime hydration crashes.
13
- *
14
- * Additionally, this plugin provides a build-time transform that statically resolves and
15
- * inlines `fs.readFileSync(path.resolve(...))` calls to prevent server/client data mismatches.
4
+ * Build plugin securing the Ecopages isomorphic compilation pipeline.
16
5
  */
17
6
  import type { EcoBuildPlugin } from '@ecopages/core/plugins/integration-plugin';
18
7
  import { ClientGraphBoundaryCache } from './client-graph-boundary-cache.js';