@ecopages/react 0.2.1-beta.0 → 0.3.0

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 (181) hide show
  1. package/README.md +164 -28
  2. package/package.json +67 -30
  3. package/src/app/client-only.js +10 -0
  4. package/src/app/dynamic.js +9 -0
  5. package/src/app/dynamic.test.browser.js +38 -0
  6. package/src/bundling/bootstrap-package-paths.d.ts +5 -0
  7. package/src/bundling/bootstrap-package-paths.js +5 -0
  8. package/src/{services/react-bundle.service.d.ts → bundling/bundle.d.ts} +29 -11
  9. package/src/bundling/bundle.js +130 -0
  10. package/src/bundling/runtime-alias-map.d.ts +12 -0
  11. package/src/bundling/runtime-alias-map.js +110 -0
  12. package/src/bundling/runtime-bundle.d.ts +70 -0
  13. package/src/bundling/runtime-bundle.js +233 -0
  14. package/src/{utils/react-dom-runtime-interop-plugin.d.ts → bundling/runtime-interop-plugin.d.ts} +1 -1
  15. package/src/bundling/runtime-interop-plugin.js +32 -0
  16. package/src/bundling/runtime-mode.d.ts +1 -0
  17. package/src/bundling/runtime-mode.js +10 -0
  18. package/src/bundling/runtime-modules.d.ts +21 -0
  19. package/src/bundling/runtime-modules.js +28 -0
  20. package/src/client-graph/ast-transform-eco-page.d.ts +10 -0
  21. package/src/client-graph/ast-transform-eco-page.js +71 -0
  22. package/src/client-graph/ast-transform-import-edits.d.ts +13 -0
  23. package/src/client-graph/ast-transform-import-edits.js +75 -0
  24. package/src/client-graph/ast-transform-walk-imports.d.ts +20 -0
  25. package/src/client-graph/ast-transform-walk-imports.js +105 -0
  26. package/src/client-graph/ast-transform.d.ts +12 -0
  27. package/src/client-graph/ast-transform.js +91 -0
  28. package/src/client-graph/ast-walk.d.ts +10 -0
  29. package/src/client-graph/ast-walk.js +26 -0
  30. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +7 -0
  31. package/src/client-graph/boundary-plugin-read-file-inline.js +43 -0
  32. package/src/client-graph/boundary-plugin-transform.d.ts +16 -0
  33. package/src/client-graph/boundary-plugin-transform.js +31 -0
  34. package/src/client-graph/boundary-plugin.d.ts +23 -0
  35. package/src/client-graph/boundary-plugin.js +177 -0
  36. package/src/client-graph/component-config-traversal.js +77 -0
  37. package/src/client-graph/declared-modules.js +69 -0
  38. package/src/client-graph/module-classification.d.ts +3 -0
  39. package/src/client-graph/module-classification.js +43 -0
  40. package/src/client-graph/reachability-analyzer.d.ts +26 -0
  41. package/src/client-graph/reachability-analyzer.js +55 -0
  42. package/src/client-graph/reachability-client-roots.d.ts +8 -0
  43. package/src/client-graph/reachability-client-roots.js +59 -0
  44. package/src/client-graph/reachability-export-names.d.ts +5 -0
  45. package/src/client-graph/reachability-export-names.js +34 -0
  46. package/src/client-graph/reachability-fallback-roots.d.ts +3 -0
  47. package/src/client-graph/reachability-fallback-roots.js +71 -0
  48. package/src/client-graph/reachability-preload.d.ts +10 -0
  49. package/src/client-graph/reachability-preload.js +30 -0
  50. package/src/client-graph/reachability-top-level-index.d.ts +14 -0
  51. package/src/client-graph/reachability-top-level-index.js +93 -0
  52. package/src/client-graph/reachability-traverse.d.ts +7 -0
  53. package/src/client-graph/reachability-traverse.js +201 -0
  54. package/src/client-graph/specifier-classification.d.ts +74 -0
  55. package/src/client-graph/specifier-classification.js +191 -0
  56. package/src/content/collection-component-cache.d.ts +25 -0
  57. package/src/content/collection-component-cache.js +62 -0
  58. package/src/contracts/router-adapter.js +6 -0
  59. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  60. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  61. package/src/hmr/hmr-strategy-process.d.ts +34 -0
  62. package/src/hmr/hmr-strategy-process.js +83 -0
  63. package/src/hmr/hmr-strategy.d.ts +67 -0
  64. package/src/hmr/hmr-strategy.js +306 -0
  65. package/src/{services/react-hmr-page-metadata-cache.d.ts → hmr/page-metadata-cache.d.ts} +5 -1
  66. package/src/hmr/page-metadata-cache.js +44 -0
  67. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +22 -0
  68. package/src/hmr/react-hmr-dev-transform-plugins.js +19 -0
  69. package/src/hydration/assert-no-bare-ecopages-imports.d.ts +4 -0
  70. package/src/hydration/assert-no-bare-ecopages-imports.js +7 -0
  71. package/src/hydration/bootstrap-imports.d.ts +25 -0
  72. package/src/hydration/bootstrap-imports.js +33 -0
  73. package/src/hydration/browser/island-hydration.d.ts +82 -0
  74. package/src/hydration/browser/island-hydration.js +251 -0
  75. package/src/hydration/browser/page-hydration-hmr.d.ts +11 -0
  76. package/src/hydration/browser/page-hydration-hmr.js +56 -0
  77. package/src/hydration/browser/page-hydration-module.d.ts +8 -0
  78. package/src/hydration/browser/page-hydration-module.js +17 -0
  79. package/src/hydration/browser/page-hydration.d.ts +54 -0
  80. package/src/hydration/browser/page-hydration.js +177 -0
  81. package/src/hydration/compiled-page-hydration-options.d.ts +20 -0
  82. package/src/hydration/hydration-asset.d.ts +127 -0
  83. package/src/hydration/hydration-asset.js +379 -0
  84. package/src/hydration/hydration-lifecycle.test.browser.d.ts +1 -0
  85. package/src/hydration/hydration-lifecycle.test.browser.js +461 -0
  86. package/src/hydration/hydration-page-entry-source.d.ts +5 -0
  87. package/src/hydration/hydration-page-entry-source.js +87 -0
  88. package/src/hydration/hydration-script-compiler.d.ts +48 -0
  89. package/src/hydration/hydration-script-compiler.js +213 -0
  90. package/src/hydration/page-data-manifest.d.ts +58 -0
  91. package/src/hydration/page-data-manifest.js +97 -0
  92. package/src/hydration/page-data-reader.d.ts +17 -0
  93. package/src/hydration/page-data-reader.js +31 -0
  94. package/src/hydration/page-payload.d.ts +68 -0
  95. package/src/hydration/page-payload.js +106 -0
  96. package/src/hydration/serialize-page-data-script.d.ts +27 -0
  97. package/src/hydration/serialize-page-data-script.js +30 -0
  98. package/src/{services/react-mdx-config-dependency.service.d.ts → mdx/mdx-config-dependency.d.ts} +9 -8
  99. package/src/mdx/mdx-config-dependency.js +107 -0
  100. package/src/mdx/mdx-loader-plugin.d.ts +8 -0
  101. package/src/mdx/mdx-loader-plugin.js +11 -0
  102. package/src/page/page-module.d.ts +46 -0
  103. package/src/page/page-module.js +74 -0
  104. package/src/plugin/react.constants.js +1 -0
  105. package/src/{react.plugin.d.ts → plugin/react.plugin.d.ts} +21 -27
  106. package/src/plugin/react.plugin.js +210 -0
  107. package/src/plugin/react.types.d.ts +106 -0
  108. package/src/plugin/react.types.js +1 -0
  109. package/src/render/component-ownership.d.ts +49 -0
  110. package/src/render/component-ownership.js +47 -0
  111. package/src/render/component-ssr.d.ts +59 -0
  112. package/src/render/component-ssr.js +76 -0
  113. package/src/render/eco-embed.js +9 -0
  114. package/src/render/errors.d.ts +16 -0
  115. package/src/render/errors.js +23 -0
  116. package/src/render/html-boundary.js +59 -0
  117. package/src/render/layout-compose.d.ts +66 -0
  118. package/src/render/layout-compose.js +134 -0
  119. package/src/render/react-renderer.d.ts +114 -0
  120. package/src/render/react-renderer.js +490 -0
  121. package/src/render/react-runtime.d.ts +13 -0
  122. package/src/render/react-runtime.js +26 -0
  123. package/src/render/unified-layout-composition.d.ts +22 -0
  124. package/src/render/unified-layout-composition.js +31 -0
  125. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
  126. package/src/eco-embed.js +0 -11
  127. package/src/react-hmr-strategy.d.ts +0 -230
  128. package/src/react-hmr-strategy.js +0 -657
  129. package/src/react-renderer.d.ts +0 -233
  130. package/src/react-renderer.js +0 -622
  131. package/src/react.constants.js +0 -4
  132. package/src/react.plugin.js +0 -205
  133. package/src/react.types.d.ts +0 -88
  134. package/src/react.types.js +0 -0
  135. package/src/router-adapter.js +0 -0
  136. package/src/services/pages-index.d.ts +0 -64
  137. package/src/services/pages-index.js +0 -73
  138. package/src/services/react-bundle.service.js +0 -86
  139. package/src/services/react-hmr-page-metadata-cache.js +0 -35
  140. package/src/services/react-hydration-asset.service.d.ts +0 -84
  141. package/src/services/react-hydration-asset.service.js +0 -217
  142. package/src/services/react-mdx-config-dependency.service.js +0 -122
  143. package/src/services/react-page-module.service.d.ts +0 -88
  144. package/src/services/react-page-module.service.js +0 -166
  145. package/src/services/react-page-payload.service.d.ts +0 -46
  146. package/src/services/react-page-payload.service.js +0 -67
  147. package/src/services/react-runtime-bundle.service.d.ts +0 -45
  148. package/src/services/react-runtime-bundle.service.js +0 -186
  149. package/src/utils/client-graph-boundary-cache.d.ts +0 -108
  150. package/src/utils/client-graph-boundary-cache.js +0 -116
  151. package/src/utils/client-graph-boundary-plugin.d.ts +0 -51
  152. package/src/utils/client-graph-boundary-plugin.js +0 -552
  153. package/src/utils/client-only.js +0 -19
  154. package/src/utils/component-config-traversal.js +0 -54
  155. package/src/utils/declared-modules.js +0 -47
  156. package/src/utils/dynamic.js +0 -12
  157. package/src/utils/dynamic.test.browser.js +0 -33
  158. package/src/utils/hmr-scripts.d.ts +0 -18
  159. package/src/utils/hmr-scripts.js +0 -31
  160. package/src/utils/html-boundary.js +0 -55
  161. package/src/utils/hydration-scripts.d.ts +0 -92
  162. package/src/utils/hydration-scripts.js +0 -358
  163. package/src/utils/hydration-scripts.test.browser.js +0 -198
  164. package/src/utils/reachability-analyzer.d.ts +0 -66
  165. package/src/utils/reachability-analyzer.js +0 -339
  166. package/src/utils/react-dom-runtime-interop-plugin.js +0 -38
  167. package/src/utils/react-mdx-loader-plugin.d.ts +0 -3
  168. package/src/utils/react-mdx-loader-plugin.js +0 -45
  169. package/src/utils/react-runtime-alias-map.d.ts +0 -8
  170. package/src/utils/react-runtime-alias-map.js +0 -90
  171. /package/src/{utils → app}/client-only.d.ts +0 -0
  172. /package/src/{utils → app}/dynamic.d.ts +0 -0
  173. /package/src/{utils → app}/dynamic.test.browser.d.ts +0 -0
  174. /package/src/{utils → client-graph}/component-config-traversal.d.ts +0 -0
  175. /package/src/{utils → client-graph}/declared-modules.d.ts +0 -0
  176. /package/src/{declarations.d.ts → contracts/declarations.d.ts} +0 -0
  177. /package/src/{router-adapter.d.ts → contracts/router-adapter.d.ts} +0 -0
  178. /package/src/{utils/hydration-scripts.test.browser.d.ts → hydration/compiled-page-hydration-options.js} +0 -0
  179. /package/src/{react.constants.d.ts → plugin/react.constants.d.ts} +0 -0
  180. /package/src/{eco-embed.d.ts → render/eco-embed.d.ts} +0 -0
  181. /package/src/{utils → render}/html-boundary.d.ts +0 -0
@@ -1,198 +0,0 @@
1
- import { afterEach, describe, expect, it } from "vitest";
2
- import { createHydrationScript } from "./hydration-scripts.js";
3
- const routerAdapter = {
4
- name: "eco-router",
5
- bundle: {
6
- importPath: "/assets/router.js",
7
- outputName: "router",
8
- externals: []
9
- },
10
- components: {
11
- router: "EcoRouter",
12
- pageContent: "PageContent"
13
- },
14
- getRouterProps: (page, props) => `{ page: ${page}, pageProps: ${props} }`
15
- };
16
- function createModuleUrl(source) {
17
- return `data:text/javascript;base64,${btoa(source)}`;
18
- }
19
- async function importModule(moduleUrl, scriptId) {
20
- let marker;
21
- if (scriptId) {
22
- marker = document.createElement("script");
23
- marker.setAttribute("data-eco-script-id", scriptId);
24
- document.head.appendChild(marker);
25
- }
26
- await import(
27
- /* @vite-ignore */
28
- moduleUrl
29
- );
30
- marker?.remove();
31
- }
32
- function createRuntimeModules() {
33
- const reactImportPath = createModuleUrl("export const createElement = (...args) => ({ args });");
34
- const reactDomClientImportPath = createModuleUrl(`
35
- export const hydrateRoot = (container, tree, options) => {
36
- const runtime = window.__ECO_REACT_HYDRATION_TEST__;
37
- runtime.hydrateCalls.push({
38
- containerTag: container.tagName,
39
- hasRecoverableErrorHandler: typeof options?.onRecoverableError === "function",
40
- tree,
41
- });
42
-
43
- return {
44
- render() {},
45
- unmount() {
46
- runtime.unmountCount += 1;
47
- },
48
- };
49
- };
50
- `);
51
- const importPath = createModuleUrl("export default function Page() { return null; }");
52
- const routerImportPath = createModuleUrl(`
53
- export function EcoRouter(props) {
54
- return props;
55
- }
56
-
57
- export function PageContent() {
58
- return null;
59
- }
60
- `);
61
- return {
62
- importPath,
63
- reactImportPath,
64
- reactDomClientImportPath,
65
- routerImportPath
66
- };
67
- }
68
- describe("createHydrationScript browser execution", () => {
69
- afterEach(() => {
70
- document.body.innerHTML = "";
71
- const testWindow = window;
72
- delete testWindow.__ECO_PAGES__;
73
- delete testWindow.__ECO_REACT_HYDRATION_TEST__;
74
- });
75
- it("registers router ownership and cleanup when the browser hydration bootstrap runs", async () => {
76
- const runtimeModules = createRuntimeModules();
77
- const testWindow = window;
78
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
79
- hydrateCalls: [],
80
- renderCalls: [],
81
- claimedOwners: [],
82
- releasedOwners: [],
83
- registrations: [],
84
- unmountCount: 0
85
- };
86
- testWindow.__ECO_PAGES__ = {
87
- navigation: {
88
- getOwnerState: () => ({
89
- owner: "html",
90
- canHandleSpaNavigation: false
91
- }),
92
- register: (registration) => {
93
- testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
94
- },
95
- claimOwnership: (owner) => {
96
- testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
97
- },
98
- releaseOwnership: (owner) => {
99
- testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
100
- }
101
- }
102
- };
103
- document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
104
- title: "Hello React",
105
- locals: { theme: "dark" }
106
- })}<\/script>`;
107
- const script = createHydrationScript({
108
- ...runtimeModules,
109
- scriptId: "ecopages-react-page",
110
- isDevelopment: true,
111
- isMdx: false,
112
- router: routerAdapter
113
- });
114
- const moduleUrl = createModuleUrl(script);
115
- await importModule(moduleUrl, "ecopages-react-page");
116
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1);
117
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.containerTag).toBe("BODY");
118
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.hasRecoverableErrorHandler).toBe(true);
119
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toEqual(["react-router"]);
120
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(1);
121
- expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe("function");
122
- expect(testWindow.__ECO_PAGES__?.page).toEqual({
123
- module: moduleUrl,
124
- props: {
125
- title: "Hello React",
126
- locals: { theme: "dark" }
127
- }
128
- });
129
- await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
130
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
131
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners).toEqual(["react-router"]);
132
- expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
133
- expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
134
- });
135
- it("reuses an existing router-owned page root during rerun bootstrap execution", async () => {
136
- const runtimeModules = createRuntimeModules();
137
- const testWindow = window;
138
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
139
- hydrateCalls: [],
140
- renderCalls: [],
141
- claimedOwners: [],
142
- releasedOwners: [],
143
- registrations: [],
144
- unmountCount: 0
145
- };
146
- const existingRoot = {
147
- render: (tree) => {
148
- testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree);
149
- },
150
- unmount: () => {
151
- testWindow.__ECO_REACT_HYDRATION_TEST__.unmountCount += 1;
152
- }
153
- };
154
- testWindow.__ECO_PAGES__ = {
155
- navigation: {
156
- getOwnerState: () => ({
157
- owner: "react-router",
158
- canHandleSpaNavigation: true
159
- }),
160
- register: (registration) => {
161
- testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
162
- },
163
- claimOwnership: (owner) => {
164
- testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
165
- },
166
- releaseOwnership: (owner) => {
167
- testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
168
- }
169
- },
170
- react: {
171
- pageRoot: existingRoot
172
- }
173
- };
174
- document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
175
- title: "Rerun"
176
- })}<\/script>`;
177
- const script = createHydrationScript({
178
- ...runtimeModules,
179
- scriptId: "ecopages-react-page-rerun",
180
- isDevelopment: true,
181
- isMdx: false,
182
- router: routerAdapter
183
- });
184
- const moduleUrl = createModuleUrl(script);
185
- await importModule(moduleUrl, "ecopages-react-page-rerun");
186
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
187
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
188
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toHaveLength(0);
189
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(0);
190
- expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBe(existingRoot);
191
- expect(testWindow.__ECO_PAGES__?.page).toEqual({
192
- module: moduleUrl,
193
- props: {
194
- title: "Rerun"
195
- }
196
- });
197
- });
198
- });
@@ -1,66 +0,0 @@
1
- /**
2
- * @module ReachabilityAnalyzer
3
- *
4
- * This module is responsible for performing static analysis on Ecopages client components
5
- * using the Oxc AST parser. It computes a strict "reachability graph" of all JavaScript/TypeScript
6
- * dependencies (imports, variables, functions, and classes) that begin from explicit client roots.
7
- *
8
- * In Ecopages, "client roots" are defined as the `render`, `errorBoundary`, or `loadingFallback`
9
- * properties passed into `eco.page()` or `eco.component()`. By tracing the execution path from
10
- * these roots, the analyzer determines exactly which modules and bindings are actually needed
11
- * by the browser to hydrate the page, and which imports are unused on the client (and thus can be pruned).
12
- */
13
- import { parseSync } from 'oxc-parser';
14
- type ParserLanguage = 'js' | 'jsx' | 'ts' | 'tsx';
15
- /**
16
- * Determines the appropriate parser language configuration for a given file name.
17
- *
18
- * @param filename - The absolute or relative path to the file.
19
- * @returns The Oxc parser language dialect to use ('js', 'jsx', 'ts', or 'tsx').
20
- */
21
- export declare function parserLanguageForFile(filename: string): ParserLanguage;
22
- /**
23
- * Represents the computed results of a reachability analysis pass.
24
- */
25
- export type ReachabilityResult = {
26
- /**
27
- * Map from import specifier (e.g. 'node:fs', '@/components/Button')
28
- * to a Set of imported bindings, or '*' for namespace imports.
29
- */
30
- reachableImports: Map<string, Set<string> | '*'>;
31
- /**
32
- * AST nodes of top-level declarations that are reachable.
33
- */
34
- reachableDeclarations: Set<unknown>;
35
- unreachableSideEffectImports: unknown[];
36
- /**
37
- * Indicates whether the file had explicit eco client roots, or fell back to treating all exports as roots.
38
- */
39
- isFallbackRoots: boolean;
40
- /**
41
- * Whether the file was successfully parsed and analyzed.
42
- */
43
- analyzed: boolean;
44
- };
45
- /**
46
- * Optional export filter supplied by the client graph boundary when a local
47
- * module is imported through a narrower named-export surface.
48
- *
49
- * `'*'` means the whole module namespace is considered reachable, while a
50
- * `Set` restricts analysis to the named exports that are actually requested by
51
- * downstream client-reachable modules.
52
- */
53
- type ExplicitlyRequestedExports = Set<string> | '*';
54
- /**
55
- * Analyzes a module using Oxc AST and extracts a strict reachability graph
56
- * starting from client roots (`render`, `errorBoundary`, `loadingFallback` of `eco.page` or `eco.component`).
57
- *
58
- * @param source - Raw source string of the module.
59
- * @param filename - Absolute or relative path to the module file.
60
- * @param program - Optional pre-parsed Oxc program AST. When supplied, the
61
- * internal `parseSync` call is skipped entirely (avoids double-parsing).
62
- * @param explicitlyRequestedExports - Optional named export filter propagated
63
- * from a downstream importer when this module is only partially reachable.
64
- */
65
- export declare function analyzeReachability(source: string, filename: string, program?: ReturnType<typeof parseSync>['program'], explicitlyRequestedExports?: ExplicitlyRequestedExports): ReachabilityResult;
66
- export {};
@@ -1,339 +0,0 @@
1
- import { parseSync } from "oxc-parser";
2
- import { extname } from "node:path";
3
- function parserLanguageForFile(filename) {
4
- const extension = extname(filename).toLowerCase();
5
- if (extension === ".tsx") return "tsx";
6
- if (extension === ".ts") return "ts";
7
- if (extension === ".jsx") return "jsx";
8
- return "js";
9
- }
10
- function analyzeReachability(source, filename, program, explicitlyRequestedExports) {
11
- let resolvedProgram;
12
- if (program) {
13
- resolvedProgram = program;
14
- } else {
15
- let result;
16
- try {
17
- result = parseSync(filename, source, {
18
- sourceType: "module",
19
- lang: parserLanguageForFile(filename)
20
- });
21
- } catch {
22
- return {
23
- reachableImports: /* @__PURE__ */ new Map(),
24
- reachableDeclarations: /* @__PURE__ */ new Set(),
25
- unreachableSideEffectImports: [],
26
- isFallbackRoots: true,
27
- analyzed: false
28
- };
29
- }
30
- resolvedProgram = result.program;
31
- }
32
- const topLevelImports = [];
33
- const topLevelDeclarations = /* @__PURE__ */ new Map();
34
- const potentialClientRoots = [];
35
- for (const statement of resolvedProgram.body) {
36
- if (statement.type === "ImportDeclaration") {
37
- const specifier = statement.source.value;
38
- const bindings = /* @__PURE__ */ new Map();
39
- if (!statement.specifiers || statement.specifiers.length === 0) {
40
- topLevelImports.push({ node: statement, specifier, bindings, isSideEffect: true });
41
- } else {
42
- for (const spec of statement.specifiers) {
43
- if (spec.type === "ImportDefaultSpecifier") {
44
- bindings.set(spec.local.name, "default");
45
- } else if (spec.type === "ImportNamespaceSpecifier") {
46
- bindings.set(spec.local.name, "*");
47
- } else if (spec.type === "ImportSpecifier") {
48
- const importedName = spec.imported.type === "Identifier" ? spec.imported.name : spec.imported.value;
49
- bindings.set(spec.local.name, importedName);
50
- }
51
- }
52
- topLevelImports.push({ node: statement, specifier, bindings, isSideEffect: false });
53
- }
54
- } else if (statement.type === "VariableDeclaration") {
55
- for (const decl of statement.declarations) {
56
- if (decl.id.type === "Identifier") {
57
- topLevelDeclarations.set(decl.id.name, statement);
58
- checkPotentialClientRoot(decl.init);
59
- }
60
- }
61
- } else if (statement.type === "FunctionDeclaration" || statement.type === "ClassDeclaration") {
62
- if (statement.id && statement.id.type === "Identifier") {
63
- topLevelDeclarations.set(statement.id.name, statement);
64
- }
65
- } else if (statement.type === "ExportNamedDeclaration") {
66
- if (statement.declaration) {
67
- const decl = statement.declaration;
68
- if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
69
- if (decl.id && decl.id.type === "Identifier") {
70
- topLevelDeclarations.set(decl.id.name, statement);
71
- }
72
- } else if (decl.type === "VariableDeclaration") {
73
- for (const v of decl.declarations) {
74
- if (v.id.type === "Identifier") {
75
- topLevelDeclarations.set(v.id.name, statement);
76
- checkPotentialClientRoot(v.init);
77
- }
78
- }
79
- }
80
- }
81
- } else if (statement.type === "ExportDefaultDeclaration") {
82
- checkPotentialClientRoot(statement.declaration);
83
- } else if (statement.type === "ExpressionStatement") {
84
- checkPotentialClientRoot(statement.expression);
85
- } else if (statement.type === "ExportAllDeclaration" && statement.source) {
86
- potentialClientRoots.push(statement);
87
- }
88
- }
89
- function checkPotentialClientRoot(node) {
90
- if (!node || typeof node !== "object") return;
91
- if (node.type === "CallExpression" && node.callee.type === "MemberExpression") {
92
- const obj = node.callee.object;
93
- const prop = node.callee.property;
94
- if (obj.type === "Identifier" && obj.name === "eco" && prop.type === "Identifier" && (prop.name === "page" || prop.name === "component")) {
95
- potentialClientRoots.push(node.callee);
96
- const arg = node.arguments[0];
97
- if (arg && arg.type === "ObjectExpression") {
98
- for (const prop2 of arg.properties) {
99
- if (prop2.type === "Property" && prop2.key.type === "Identifier") {
100
- if ([
101
- "render",
102
- "errorBoundary",
103
- "loadingFallback",
104
- "clientScripts",
105
- "dependencies"
106
- ].includes(prop2.key.name)) {
107
- potentialClientRoots.push(prop2.value);
108
- }
109
- }
110
- }
111
- }
112
- }
113
- } else if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "dynamic") {
114
- potentialClientRoots.push(node);
115
- }
116
- }
117
- function getExportedName(specifier) {
118
- if (specifier?.exported?.type === "Identifier") return specifier.exported.name;
119
- if (typeof specifier?.exported?.value === "string") return specifier.exported.value;
120
- if (specifier?.local?.type === "Identifier") return specifier.local.name;
121
- if (typeof specifier?.local?.value === "string") return specifier.local.value;
122
- return void 0;
123
- }
124
- function getReexportedImportName(specifier) {
125
- if (specifier?.local?.type === "Identifier") return specifier.local.name;
126
- if (typeof specifier?.local?.value === "string") return specifier.local.value;
127
- if (specifier?.imported?.type === "Identifier") return specifier.imported.name;
128
- if (typeof specifier?.imported?.value === "string") return specifier.imported.value;
129
- return getExportedName(specifier);
130
- }
131
- function getLocalExportName(specifier) {
132
- if (specifier?.local?.type === "Identifier") return specifier.local.name;
133
- if (typeof specifier?.local?.value === "string") return specifier.local.value;
134
- return void 0;
135
- }
136
- function isExplicitlyRequestedExport(name) {
137
- if (explicitlyRequestedExports === "*") return true;
138
- return explicitlyRequestedExports?.has(name) ?? false;
139
- }
140
- let isFallbackRoots = false;
141
- if (potentialClientRoots.length === 0) {
142
- if (explicitlyRequestedExports) {
143
- for (const node of resolvedProgram.body) {
144
- if (node.type === "ExportNamedDeclaration") {
145
- const exportNode = node;
146
- if (exportNode.source && exportNode.specifiers?.length) {
147
- const hasRequestedReexport = exportNode.specifiers.some((specifier) => {
148
- const exportedName = getExportedName(specifier);
149
- return exportedName ? isExplicitlyRequestedExport(exportedName) : false;
150
- });
151
- if (hasRequestedReexport) {
152
- potentialClientRoots.push(node);
153
- }
154
- continue;
155
- }
156
- if (exportNode.declaration?.type === "FunctionDeclaration" || exportNode.declaration?.type === "ClassDeclaration") {
157
- const declarationName = exportNode.declaration.id?.name;
158
- if (declarationName && isExplicitlyRequestedExport(declarationName)) {
159
- potentialClientRoots.push(node);
160
- }
161
- continue;
162
- }
163
- if (exportNode.declaration?.type === "VariableDeclaration") {
164
- const hasRequestedDeclaration = exportNode.declaration.declarations.some(
165
- (declaration) => declaration.id?.type === "Identifier" && isExplicitlyRequestedExport(declaration.id.name)
166
- );
167
- if (hasRequestedDeclaration) {
168
- potentialClientRoots.push(node);
169
- }
170
- continue;
171
- }
172
- if (exportNode.specifiers?.length) {
173
- const hasRequestedSpecifier = exportNode.specifiers.some((specifier) => {
174
- const exportedName = getExportedName(specifier);
175
- return exportedName ? isExplicitlyRequestedExport(exportedName) : false;
176
- });
177
- if (hasRequestedSpecifier) {
178
- potentialClientRoots.push(node);
179
- }
180
- }
181
- } else if (node.type === "ExportDefaultDeclaration") {
182
- if (isExplicitlyRequestedExport("default")) {
183
- potentialClientRoots.push(node);
184
- }
185
- } else if (node.type === "ExportAllDeclaration") {
186
- if (explicitlyRequestedExports === "*") {
187
- potentialClientRoots.push(node);
188
- }
189
- }
190
- }
191
- } else {
192
- isFallbackRoots = true;
193
- for (const node of resolvedProgram.body) {
194
- if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportAllDeclaration") {
195
- potentialClientRoots.push(node);
196
- }
197
- }
198
- }
199
- }
200
- const reachableImports = /* @__PURE__ */ new Map();
201
- const reachableDeclarations = /* @__PURE__ */ new Set();
202
- const queue = [...potentialClientRoots];
203
- const visitedNodes = /* @__PURE__ */ new Set();
204
- function markImportReachable(specifier, importedName) {
205
- let current = reachableImports.get(specifier);
206
- if (current === "*") return;
207
- if (importedName === "*") {
208
- reachableImports.set(specifier, "*");
209
- } else {
210
- if (!current) {
211
- current = /* @__PURE__ */ new Set();
212
- reachableImports.set(specifier, current);
213
- }
214
- current.add(importedName);
215
- }
216
- }
217
- function checkIdentifier(name) {
218
- if (topLevelDeclarations.has(name)) {
219
- const declNode = topLevelDeclarations.get(name);
220
- if (!reachableDeclarations.has(declNode)) {
221
- reachableDeclarations.add(declNode);
222
- queue.push(declNode);
223
- }
224
- }
225
- for (const imp of topLevelImports) {
226
- if (imp.bindings.has(name)) {
227
- markImportReachable(imp.specifier, imp.bindings.get(name));
228
- }
229
- }
230
- }
231
- function traverse(node, localScope) {
232
- if (!node || typeof node !== "object") return;
233
- if (visitedNodes.has(node)) return;
234
- visitedNodes.add(node);
235
- if (Array.isArray(node)) {
236
- for (const child of node) traverse(child, localScope);
237
- return;
238
- }
239
- const currentScope = localScope;
240
- if (node.type === "ExportAllDeclaration" && typeof node.source?.value === "string") {
241
- markImportReachable(node.source.value, "*");
242
- return;
243
- }
244
- if (node.type === "ExportNamedDeclaration" && typeof node.source?.value === "string") {
245
- for (const specifier of node.specifiers ?? []) {
246
- const importedName = getReexportedImportName(specifier);
247
- if (importedName) {
248
- markImportReachable(node.source.value, importedName);
249
- }
250
- }
251
- return;
252
- }
253
- if (node.type === "ExportNamedDeclaration" && !node.source && explicitlyRequestedExports && node.specifiers?.length) {
254
- for (const specifier of node.specifiers) {
255
- const exportedName = getExportedName(specifier);
256
- if (!exportedName || !isExplicitlyRequestedExport(exportedName)) {
257
- continue;
258
- }
259
- const localName = getLocalExportName(specifier);
260
- if (localName && !currentScope.has(localName)) {
261
- checkIdentifier(localName);
262
- }
263
- }
264
- return;
265
- }
266
- if (node.type === "Identifier" || node.type === "JSXIdentifier" && /^[A-Z]/.test(node.name)) {
267
- if (!currentScope.has(node.name)) {
268
- checkIdentifier(node.name);
269
- }
270
- } else if (node.type === "MemberExpression") {
271
- traverse(node.object, currentScope);
272
- if (node.computed) {
273
- traverse(node.property, currentScope);
274
- }
275
- return;
276
- } else if (node.type === "Property") {
277
- if (node.computed) traverse(node.key, currentScope);
278
- traverse(node.value, currentScope);
279
- return;
280
- } else if (node.type === "JSXOpeningElement" || node.type === "JSXClosingElement") {
281
- traverse(node.name, currentScope);
282
- if (node.attributes) {
283
- for (const attr of node.attributes) traverse(attr, currentScope);
284
- }
285
- return;
286
- } else if (node.type === "JSXIdentifier") {
287
- if (/^[A-Z]/.test(node.name) && !currentScope.has(node.name)) {
288
- checkIdentifier(node.name);
289
- }
290
- } else if (node.type === "JSXMemberExpression") {
291
- traverse(node.object, currentScope);
292
- return;
293
- } else if (node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "dynamic") {
294
- const arg = node.arguments[0];
295
- if (arg && (arg.type === "ArrowFunctionExpression" || arg.type === "FunctionExpression")) {
296
- const body = arg.body;
297
- if (body.type === "ImportExpression" && body.source.type === "Literal") {
298
- markImportReachable(body.source.value, "*");
299
- }
300
- }
301
- } else if (node.type === "ImportExpression" && node.source.type === "Literal") {
302
- markImportReachable(node.source.value, "*");
303
- }
304
- if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration") {
305
- const newScope = new Set(currentScope);
306
- if (node.id && node.id.type === "Identifier") newScope.add(node.id.name);
307
- if (node.params && node.params.items) {
308
- for (const p of node.params.items) {
309
- if (p.pattern && p.pattern.type === "Identifier") {
310
- newScope.add(p.pattern.name);
311
- }
312
- }
313
- }
314
- traverse(node.body, newScope);
315
- return;
316
- }
317
- for (const key in node) {
318
- if (key !== "type" && key !== "start" && key !== "end") {
319
- traverse(node[key], currentScope);
320
- }
321
- }
322
- }
323
- while (queue.length > 0) {
324
- const root = queue.shift();
325
- traverse(root, /* @__PURE__ */ new Set());
326
- }
327
- const unreachableSideEffectImports = topLevelImports.filter((imp) => imp.isSideEffect && !reachableImports.has(imp.specifier)).map((imp) => imp.node);
328
- return {
329
- reachableImports,
330
- reachableDeclarations,
331
- unreachableSideEffectImports,
332
- isFallbackRoots,
333
- analyzed: true
334
- };
335
- }
336
- export {
337
- analyzeReachability,
338
- parserLanguageForFile
339
- };
@@ -1,38 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- function escapeRegExp(value) {
4
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
- }
6
- function createReactDomRuntimeInteropPlugin(options) {
7
- const reactDomFileFilter = /[\\/]react-dom[\\/].*\.js$/;
8
- const reactRequirePattern = /\brequire\((['"])react\1\)/g;
9
- const reactSpecifier = options?.reactSpecifier ?? "react";
10
- return {
11
- name: options?.name ?? "react-dom-runtime-interop",
12
- setup(build) {
13
- if (reactSpecifier.startsWith("/")) {
14
- build.onResolve({ filter: new RegExp(`^${escapeRegExp(reactSpecifier)}$`) }, (args) => ({
15
- path: args.path,
16
- external: true
17
- }));
18
- }
19
- build.onLoad({ filter: reactDomFileFilter }, (args) => {
20
- const content = fs.readFileSync(args.path, "utf-8");
21
- if (!reactRequirePattern.test(content)) {
22
- return void 0;
23
- }
24
- reactRequirePattern.lastIndex = 0;
25
- const rewritten = content.replace(reactRequirePattern, "__ecopages_react_runtime");
26
- return {
27
- contents: `import * as __ecopages_react_runtime from '${reactSpecifier}';
28
- ${rewritten}`,
29
- loader: "js",
30
- resolveDir: path.dirname(args.path)
31
- };
32
- });
33
- }
34
- };
35
- }
36
- export {
37
- createReactDomRuntimeInteropPlugin
38
- };
@@ -1,3 +0,0 @@
1
- import type { EcoBuildPlugin } from '@ecopages/core/plugins/integration-plugin';
2
- import { type CompileOptions } from '@mdx-js/mdx';
3
- export declare function createReactMdxLoaderPlugin(compilerOptions?: CompileOptions): EcoBuildPlugin;
@@ -1,45 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { compile } from "@mdx-js/mdx";
4
- import sourceMap from "source-map";
5
- import { VFile } from "vfile";
6
- function resolveCompileFormat(filePath, compilerOptions) {
7
- const configuredFormat = compilerOptions?.format;
8
- if (configuredFormat && configuredFormat !== "detect") {
9
- return configuredFormat;
10
- }
11
- return path.extname(filePath).toLowerCase() === ".md" ? "mdx" : configuredFormat;
12
- }
13
- function createReactMdxLoaderPlugin(compilerOptions) {
14
- const mdxExtensions = compilerOptions?.mdxExtensions ?? [".mdx"];
15
- const mdExtensions = compilerOptions?.mdExtensions ?? [];
16
- const allExtensions = [...mdxExtensions, ...mdExtensions];
17
- const escapedExts = allExtensions.map((ext) => ext.replace(".", "\\."));
18
- const filter = new RegExp(`(${escapedExts.join("|")})(\\?.*)?$`);
19
- return {
20
- name: "react-mdx-loader",
21
- setup(build) {
22
- build.onLoad({ filter }, async (args) => {
23
- const filePath = args.path.includes("?") ? args.path.split("?")[0] : args.path;
24
- const source = readFileSync(filePath, "utf-8");
25
- const file = new VFile({ path: filePath, value: source });
26
- const compiled = await compile(file, {
27
- ...compilerOptions,
28
- format: resolveCompileFormat(filePath, compilerOptions),
29
- SourceMapGenerator: sourceMap.SourceMapGenerator
30
- });
31
- const inlineSourceMap = compiled.map ? `
32
- //# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(compiled.map)).toString("base64")}
33
- ` : "";
34
- return {
35
- contents: `${String(compiled.value)}${inlineSourceMap}`,
36
- loader: compilerOptions?.jsx ? "jsx" : "js",
37
- resolveDir: path.dirname(args.path)
38
- };
39
- });
40
- }
41
- };
42
- }
43
- export {
44
- createReactMdxLoaderPlugin
45
- };