@ecopages/react 0.9.0 → 0.10.1
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 +12 -22
- package/package.json +4 -4
- package/src/bundling/bundle.js +16 -9
- package/src/client-graph/ast-transform-eco-page.d.ts +14 -1
- package/src/client-graph/ast-transform-eco-page.js +60 -13
- package/src/client-graph/ast-transform-stripped-imports.js +1 -1
- package/src/client-graph/ast-transform-walk-imports.js +1 -1
- package/src/client-graph/boundary-plugin.d.ts +19 -0
- package/src/client-graph/boundary-plugin.js +51 -12
- package/src/client-graph/foreign-boundary-rewrite.d.ts +18 -3
- package/src/client-graph/foreign-boundary-rewrite.js +196 -45
- package/src/client-graph/foreign-jsx-reach.d.ts +21 -2
- package/src/client-graph/foreign-jsx-reach.js +25 -9
- package/src/client-graph/foreign-module.d.ts +45 -0
- package/src/client-graph/foreign-module.js +132 -0
- package/src/client-graph/reachability-client-roots.js +28 -0
- package/src/hmr/hmr-strategy.d.ts +3 -0
- package/src/hmr/hmr-strategy.js +7 -0
- package/src/hydration/browser/foreign-boundary.d.ts +12 -0
- package/src/hydration/browser/foreign-boundary.js +19 -0
- package/src/hydration/browser/page-hydration-hmr.d.ts +1 -0
- package/src/hydration/browser/page-hydration-hmr.js +1 -1
- package/src/hydration/browser/page-hydration.d.ts +2 -1
- package/src/hydration/browser/page-hydration.js +3 -2
- package/src/hydration/hydration-page-entry-source.js +3 -3
- package/src/hydration/page-data-manifest.d.ts +22 -1
- package/src/hydration/page-data-manifest.js +38 -3
- package/src/hydration/page-data-reader.d.ts +2 -1
- package/src/hydration/page-data-reader.js +4 -2
- package/src/hydration/page-payload.d.ts +6 -15
- package/src/hydration/page-payload.js +5 -42
- package/src/hydration/serialize-page-data-script.d.ts +4 -4
- package/src/hydration/serialize-page-data-script.js +6 -6
- package/src/plugin/react.plugin.js +2 -0
- package/src/render/component-ownership.d.ts +1 -6
- package/src/render/component-ownership.js +0 -3
- package/src/render/component-ssr.d.ts +0 -1
- package/src/render/component-ssr.js +0 -7
- package/src/render/layout-compose.d.ts +16 -8
- package/src/render/layout-compose.js +13 -36
- package/src/render/react-renderer.js +24 -37
package/README.md
CHANGED
|
@@ -120,7 +120,7 @@ The client-graph boundary analyzes project modules during each browser build and
|
|
|
120
120
|
|
|
121
121
|
`reactPlugin({ explicitGraph: true })` forces the page browser graph (hydration assets) to emit for every React page, even when the page does not declare `dependencies.modules` and no router is configured.
|
|
122
122
|
|
|
123
|
-
It does **not** disable the client-graph AST boundary. Server-only `eco.page(...)` options such as `middleware` and `
|
|
123
|
+
It does **not** disable the client-graph AST boundary. Server-only `eco.page(...)` options such as `middleware` and `props` are still stripped from browser bundles. With a router adapter, page hydration is already always on, so the option is redundant for SPA apps.
|
|
124
124
|
|
|
125
125
|
The option name is historical — it forces hydration asset emission, it does not mean “skip graph transforms.”
|
|
126
126
|
|
|
@@ -141,8 +141,7 @@ The client bundle removes or excludes:
|
|
|
141
141
|
|
|
142
142
|
Important:
|
|
143
143
|
|
|
144
|
-
- `render` must stay in the client bundle, because hydration needs it to reconstruct the page tree.
|
|
145
|
-
- `requires` does **not** stay in the browser page config. It is used on the server to decide which `locals` keys may be serialized into the hydration payload.
|
|
144
|
+
- `render` must stay in the client bundle, because hydration needs it to reconstruct the page tree. It receives no `locals`, only what `props` returned, so it needs no request code in the browser.
|
|
146
145
|
|
|
147
146
|
### AST Pipeline Order
|
|
148
147
|
|
|
@@ -177,7 +176,6 @@ const getProps = async () => ({ post: await getPost() });
|
|
|
177
176
|
export default eco.page({
|
|
178
177
|
cache: 'dynamic',
|
|
179
178
|
middleware: [authMiddleware],
|
|
180
|
-
requires: ['session'] as const,
|
|
181
179
|
props: getProps,
|
|
182
180
|
render: () => <div>Dashboard</div>,
|
|
183
181
|
});
|
|
@@ -195,26 +193,18 @@ Move that code into a server-only Page option, into a helper only those options
|
|
|
195
193
|
|
|
196
194
|
### Hydration Contract for `locals`
|
|
197
195
|
|
|
198
|
-
The browser
|
|
199
|
-
|
|
200
|
-
The React renderer in [src/render/react-renderer.ts](src/render/react-renderer.ts) serializes only the top-level `locals` keys explicitly declared by `Page.requires`. If a page does not declare `requires`, no `locals` are serialized for hydration.
|
|
201
|
-
|
|
202
|
-
Example:
|
|
196
|
+
The browser never receives request locals. `render` does not get them: a dynamic Page reads them in `props` and returns what `render` needs, and the hydration payload carries exactly that return value, with the Params, Query and each layout tier's props.
|
|
203
197
|
|
|
204
198
|
```tsx
|
|
205
199
|
export default eco.page({
|
|
206
|
-
|
|
207
|
-
|
|
200
|
+
cache: 'dynamic',
|
|
201
|
+
middleware: [authMiddleware],
|
|
202
|
+
props: ({ locals }) => ({ user: locals.session.user }),
|
|
203
|
+
render: ({ user }) => <Dashboard user={user} />,
|
|
208
204
|
});
|
|
209
205
|
```
|
|
210
206
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
Important:
|
|
214
|
-
|
|
215
|
-
- This filtering is currently top-level only.
|
|
216
|
-
- If `locals.session` itself contains sensitive nested fields, those fields will still be serialized.
|
|
217
|
-
- Middleware should therefore expose a client-safe shape for any key declared in `requires`.
|
|
207
|
+
Whatever `props` returns is serialized, nested fields included, so return a client-safe shape: the user, not the session that holds its token.
|
|
218
208
|
|
|
219
209
|
### Layout Hydration Invariant
|
|
220
210
|
|
|
@@ -225,17 +215,17 @@ That applies to both:
|
|
|
225
215
|
- page hydration lifecycle in [src/hydration/browser/page-hydration.ts](src/hydration/browser/page-hydration.ts)
|
|
226
216
|
- router-backed hydration in [../../react-router/src/router.ts](../../react-router/src/router.ts)
|
|
227
217
|
|
|
228
|
-
|
|
218
|
+
The server resolves each layout tier's props once from its entry's `props` factory and ships them as `tiers`; the browser renders each tier from those props without running a factory, so a layout cannot differ between server and browser.
|
|
229
219
|
|
|
230
220
|
### Tests That Guard This Contract
|
|
231
221
|
|
|
232
222
|
The main regression coverage lives in:
|
|
233
223
|
|
|
234
224
|
- [src/client-graph/boundary-plugin.test.ts](src/client-graph/boundary-plugin.test.ts): verifies server-only `eco.page(...)` options are stripped from browser bundles.
|
|
235
|
-
- [src/render/react-renderer.locals.test.ts](src/render/react-renderer.locals.test.ts):
|
|
225
|
+
- [src/render/react-renderer.locals.test.ts](src/render/react-renderer.locals.test.ts) and [src/test/react-renderer.test.tsx](src/test/react-renderer.test.tsx): the hydration payload holds the page props, Params, Query and tiers, never `locals`, even when middleware provided a secret.
|
|
236
226
|
- [src/hydration/hydration-entry-source.test.ts](src/hydration/hydration-entry-source.test.ts): a generated island entry registers, and a generated Page entry hydrates, through the bootstrap module it imports.
|
|
237
227
|
- [../../../e2e/fixtures/react-production-start/react-production-start.test.e2e.ts](../../../e2e/fixtures/react-production-start/react-production-start.test.e2e.ts): a built app serves a static and a dynamic Page under `ecopages start`, and their React island hydrates.
|
|
238
|
-
- [../../react-router/test/layout-persistence.test.browser.ts](../../react-router/test/layout-persistence.test.browser.ts): verifies router-backed
|
|
228
|
+
- [../../react-router/test/layout-persistence.test.browser.ts](../../react-router/test/layout-persistence.test.browser.ts): verifies router-backed layouts render from the server-resolved tier props with `persistLayouts` both enabled and disabled.
|
|
239
229
|
- [src/hydration/hydration-lifecycle.test.browser.ts](src/hydration/hydration-lifecycle.test.browser.ts): an uncaught `React.lazy` rejection during first hydration restores the server HTML, keeps body nodes added after mount, drops the page root and makes the next HMR update reload; a Page-level error boundary around the entry still shows its fallback.
|
|
240
230
|
- [../../../playground/kitchen-sink/e2e/content-lazy.test.e2e.ts](../../../playground/kitchen-sink/e2e/content-lazy.test.e2e.ts): a collection chunk that fails during first hydration restores the server HTML (including the playground shell) and is not retried. A Page-level error boundary around the entry keeps the rest of the Page and shows the boundary fallback.
|
|
241
231
|
- [../../../e2e/fixtures/react-lazy-first-load/lazy-first-load.test.e2e.ts](../../../e2e/fixtures/react-lazy-first-load/lazy-first-load.test.e2e.ts): the same first-hydration outcomes for a React Page without the router.
|
|
@@ -252,7 +242,7 @@ A server render tracks which tiers and the page it reached (`LayoutRenderTracker
|
|
|
252
242
|
|
|
253
243
|
During SSR, `ReactRenderer` passes the app-resolved React runtime into `composeLayoutPageTree` via `options.react` so layout trees are built with the same module instance the server renders them with. App code should import hooks and context from `react` normally; keep a single React version in the app dependency graph (avoid duplicate `react` copies in monorepos).
|
|
254
244
|
|
|
255
|
-
Layout prop factories receive `
|
|
245
|
+
Layout prop factories run on the server only and receive `params`, `query` and, on a dynamic Page, `locals` typed from the Page's `middleware` list. The browser renders each tier from the props the server shipped as `tiers`, and the browser build removes the factory of an entry written inline in `eco.page({ layout })`. Serialized page props never carry `locals`.
|
|
256
246
|
|
|
257
247
|
- [src/render/layout-compose.ts](src/render/layout-compose.ts): shared client/SSR tree builder.
|
|
258
248
|
- [src/test/react-ssr-hydration-parity.test.tsx](src/test/react-ssr-hydration-parity.test.tsx): nested tier order parity between SSR and `composeLayoutPageTree`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.1",
|
|
4
4
|
"description": "React integration for Ecopages",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ecopages",
|
|
@@ -123,16 +123,16 @@
|
|
|
123
123
|
"directory": "packages/integrations/react"
|
|
124
124
|
},
|
|
125
125
|
"peerDependencies": {
|
|
126
|
-
"@ecopages/core": "0.
|
|
126
|
+
"@ecopages/core": "0.10.1",
|
|
127
127
|
"@types/react": "^19",
|
|
128
128
|
"@types/react-dom": "^19",
|
|
129
129
|
"react": "^19",
|
|
130
130
|
"react-dom": "^19"
|
|
131
131
|
},
|
|
132
132
|
"dependencies": {
|
|
133
|
-
"@ecopages/file-system": "0.
|
|
133
|
+
"@ecopages/file-system": "0.10.1",
|
|
134
134
|
"@ecopages/logger": "^0.2.3",
|
|
135
|
-
"@ecopages/mdx": "0.
|
|
135
|
+
"@ecopages/mdx": "0.10.1",
|
|
136
136
|
"@mdx-js/mdx": "^3.1.1",
|
|
137
137
|
"oxc-parser": "^0.141.0"
|
|
138
138
|
}
|
package/src/bundling/bundle.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
-
import { createClientGraphBoundaryPlugin, createForeignBoundaryPlugin, createForeignJsxScope, } from '../client-graph/boundary-plugin.js';
|
|
9
|
+
import { createClientGraphBoundaryPlugin, createForeignBoundaryPlugin, createForeignJsxScope, createReactModuleSource, } from '../client-graph/boundary-plugin.js';
|
|
10
|
+
import { createForeignModuleReader } from '../client-graph/foreign-module.js';
|
|
10
11
|
import { findIntegrationForFile, findJsxExtensionOwner, getHostScopedJsxOwnershipPlugins, isProductionRuntime, } from '@ecopages/core/build';
|
|
11
12
|
import { getReactBrowserPackages } from './bootstrap-package-paths.js';
|
|
12
13
|
/**
|
|
@@ -33,24 +34,30 @@ export class BundleService {
|
|
|
33
34
|
mdxLoaderPlugin;
|
|
34
35
|
constructor(config) {
|
|
35
36
|
this.config = config;
|
|
37
|
+
const projectRoot = config.appConfig?.absolutePaths?.projectDir ?? config.rootDir;
|
|
38
|
+
const integrations = config.appConfig?.integrations ?? [];
|
|
39
|
+
const isForeignFile = (filePath) => {
|
|
40
|
+
const owner = findIntegrationForFile(integrations, filePath);
|
|
41
|
+
return owner !== undefined && owner.name !== config.hostIntegrationName;
|
|
42
|
+
};
|
|
43
|
+
const foreignModuleOf = createForeignModuleReader({
|
|
44
|
+
rootDir: config.appConfig?.rootDir ?? config.rootDir,
|
|
45
|
+
integrationOf: (filePath) => findIntegrationForFile(integrations, filePath)?.name,
|
|
46
|
+
});
|
|
47
|
+
const reactModuleSource = createReactModuleSource({ projectRoot, isForeignFile, foreignModuleOf });
|
|
36
48
|
[this.foreignJsxOverridePlugin] = getHostScopedJsxOwnershipPlugins(config.appConfig, config.hostIntegrationName, {
|
|
37
49
|
name: 'react-renderer-foreign-jsx-override',
|
|
38
50
|
scope: createForeignJsxScope({
|
|
39
|
-
projectRoot
|
|
51
|
+
projectRoot,
|
|
40
52
|
hostIntegrationName: config.hostIntegrationName,
|
|
53
|
+
reactModuleSource,
|
|
41
54
|
findForeignOwner: (filePath) => {
|
|
42
55
|
const owner = findJsxExtensionOwner(config.appConfig, filePath);
|
|
43
56
|
return owner === config.hostIntegrationName ? undefined : owner;
|
|
44
57
|
},
|
|
45
58
|
}),
|
|
46
59
|
});
|
|
47
|
-
this.foreignBoundaryPlugin = createForeignBoundaryPlugin({
|
|
48
|
-
projectRoot: config.appConfig?.absolutePaths?.projectDir ?? config.rootDir,
|
|
49
|
-
isForeignFile: (filePath) => {
|
|
50
|
-
const owner = findIntegrationForFile(config.appConfig?.integrations ?? [], filePath);
|
|
51
|
-
return owner !== undefined && owner.name !== config.hostIntegrationName;
|
|
52
|
-
},
|
|
53
|
-
});
|
|
60
|
+
this.foreignBoundaryPlugin = createForeignBoundaryPlugin({ projectRoot, isForeignFile, foreignModuleOf });
|
|
54
61
|
}
|
|
55
62
|
/**
|
|
56
63
|
* Creates bundle options for a page or component entry.
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Finds the server-only `eco.page(...)` options of browser-bound modules
|
|
2
|
+
* Finds the server-only `eco.page(...)` options of browser-bound modules, and the `props` factories of the layout
|
|
3
|
+
* entries written inline in its `layout` option.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* Nodes are typed `any`, as in `walkAstNodes`: they come from the parser as untyped ESTree objects, and each helper
|
|
7
|
+
* checks `type` before reading a field.
|
|
3
8
|
*/
|
|
4
9
|
import type { SourceEdit } from './ast-transform-import-edits.js';
|
|
5
10
|
export type ServerOnlyPageCode = {
|
|
@@ -8,6 +13,14 @@ export type ServerOnlyPageCode = {
|
|
|
8
13
|
/** Nodes whose subtrees the edits remove; references inside them do not reach the browser. */
|
|
9
14
|
strippedNodes: Set<unknown>;
|
|
10
15
|
};
|
|
16
|
+
export declare function isPropertyNamed(property: any, name: string): boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Returns the tiers of a `layout` option, each unwrapped from type-only wrappers: the value itself, or the elements
|
|
19
|
+
* of an array. A hole stays `null`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function getLayoutTiers(layout: any): any[];
|
|
22
|
+
/** Returns the layout entries written as object literals in a `layout` option. */
|
|
23
|
+
export declare function getInlineLayoutEntries(layout: any): any[];
|
|
11
24
|
/**
|
|
12
25
|
* Collects the server-only `eco.page(...)` options of a browser-bound module and the edits that remove them.
|
|
13
26
|
*/
|
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Finds the server-only `eco.page(...)` options of browser-bound modules
|
|
2
|
+
* Finds the server-only `eco.page(...)` options of browser-bound modules, and the `props` factories of the layout
|
|
3
|
+
* entries written inline in its `layout` option.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* Nodes are typed `any`, as in `walkAstNodes`: they come from the parser as untyped ESTree objects, and each helper
|
|
7
|
+
* checks `type` before reading a field.
|
|
3
8
|
*/
|
|
4
9
|
import { walkAstNodes } from './ast-walk.js';
|
|
5
|
-
const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = new Set([
|
|
6
|
-
'cache',
|
|
7
|
-
'middleware',
|
|
8
|
-
'dependencies',
|
|
9
|
-
'requires',
|
|
10
|
-
'metadata',
|
|
11
|
-
'props',
|
|
12
|
-
'paths',
|
|
13
|
-
]);
|
|
10
|
+
const SERVER_ONLY_ECO_PAGE_OPTION_KEYS = new Set(['cache', 'middleware', 'dependencies', 'metadata', 'props', 'paths']);
|
|
14
11
|
function isEcoPageOptionsCall(node) {
|
|
15
12
|
return (node.type === 'CallExpression' &&
|
|
16
13
|
node.callee?.type === 'MemberExpression' &&
|
|
@@ -36,6 +33,36 @@ function isServerOnlyOption(property) {
|
|
|
36
33
|
const keyName = getObjectPropertyKeyName(property.key);
|
|
37
34
|
return keyName !== undefined && SERVER_ONLY_ECO_PAGE_OPTION_KEYS.has(keyName);
|
|
38
35
|
}
|
|
36
|
+
export function isPropertyNamed(property, name) {
|
|
37
|
+
return property?.type === 'Property' && !property.computed && getObjectPropertyKeyName(property.key) === name;
|
|
38
|
+
}
|
|
39
|
+
const TRANSPARENT_EXPRESSION_TYPES = new Set([
|
|
40
|
+
'ParenthesizedExpression',
|
|
41
|
+
'TSAsExpression',
|
|
42
|
+
'TSSatisfiesExpression',
|
|
43
|
+
'TSNonNullExpression',
|
|
44
|
+
'TSTypeAssertion',
|
|
45
|
+
]);
|
|
46
|
+
/** Returns the expression inside parentheses and type-only wrappers such as `as const` and `satisfies`. */
|
|
47
|
+
function unwrapExpression(node) {
|
|
48
|
+
let current = node;
|
|
49
|
+
while (current && TRANSPARENT_EXPRESSION_TYPES.has(current.type))
|
|
50
|
+
current = current.expression;
|
|
51
|
+
return current;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Returns the tiers of a `layout` option, each unwrapped from type-only wrappers: the value itself, or the elements
|
|
55
|
+
* of an array. A hole stays `null`.
|
|
56
|
+
*/
|
|
57
|
+
export function getLayoutTiers(layout) {
|
|
58
|
+
const value = unwrapExpression(layout);
|
|
59
|
+
const tiers = value?.type === 'ArrayExpression' ? value.elements : [value];
|
|
60
|
+
return tiers.map(unwrapExpression);
|
|
61
|
+
}
|
|
62
|
+
/** Returns the layout entries written as object literals in a `layout` option. */
|
|
63
|
+
export function getInlineLayoutEntries(layout) {
|
|
64
|
+
return getLayoutTiers(layout).filter((tier) => tier?.type === 'ObjectExpression');
|
|
65
|
+
}
|
|
39
66
|
/**
|
|
40
67
|
* Returns the range that removes one property and its separating comma.
|
|
41
68
|
*
|
|
@@ -66,11 +93,10 @@ function mergeRanges(ranges) {
|
|
|
66
93
|
}
|
|
67
94
|
return merged;
|
|
68
95
|
}
|
|
69
|
-
function
|
|
70
|
-
const objectExpression = node.arguments[0];
|
|
96
|
+
function collectPropertyEdits(objectExpression, isStripped, code) {
|
|
71
97
|
const ranges = [];
|
|
72
98
|
objectExpression.properties.forEach((property, index) => {
|
|
73
|
-
if (!
|
|
99
|
+
if (!isStripped(property))
|
|
74
100
|
return;
|
|
75
101
|
code.strippedNodes.add(property);
|
|
76
102
|
ranges.push(getPropertyRemovalRange(objectExpression, index));
|
|
@@ -78,6 +104,27 @@ function collectPageOptionEdits(node, code) {
|
|
|
78
104
|
for (const range of mergeRanges(ranges))
|
|
79
105
|
code.edits.push({ ...range, replacement: '' });
|
|
80
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Removes the `props` factory of each layout entry written inline in the `layout` option.
|
|
109
|
+
*
|
|
110
|
+
* @remarks
|
|
111
|
+
* The factory runs only on the server: the browser renders each tier from the props the server resolved and
|
|
112
|
+
* shipped as `tiers`. An entry imported from another module cannot be edited here; its module reaches the
|
|
113
|
+
* browser whole, so a server import its factory uses fails the browser build.
|
|
114
|
+
*/
|
|
115
|
+
function collectLayoutEntryEdits(objectExpression, code) {
|
|
116
|
+
const layout = objectExpression.properties.find((property) => isPropertyNamed(property, 'layout'));
|
|
117
|
+
if (!layout)
|
|
118
|
+
return;
|
|
119
|
+
for (const entry of getInlineLayoutEntries(layout.value)) {
|
|
120
|
+
collectPropertyEdits(entry, (property) => isPropertyNamed(property, 'props'), code);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function collectPageOptionEdits(node, code) {
|
|
124
|
+
const objectExpression = node.arguments[0];
|
|
125
|
+
collectPropertyEdits(objectExpression, isServerOnlyOption, code);
|
|
126
|
+
collectLayoutEntryEdits(objectExpression, code);
|
|
127
|
+
}
|
|
81
128
|
/**
|
|
82
129
|
* Collects the server-only `eco.page(...)` options of a browser-bound module and the edits that remove them.
|
|
83
130
|
*/
|
|
@@ -140,7 +140,7 @@ function assertNoStrippedBindingReferences(browserUnits, input) {
|
|
|
140
140
|
if (!first)
|
|
141
141
|
return;
|
|
142
142
|
const specifier = input.strippedBindings.get(first.name);
|
|
143
|
-
throw new Error(`[Ecopages Client Graph] '${first.name}' (imported from '${specifier}') is used at ${input.filename}:${toLineColumn(input.source, first.node.start)}, but that import is server-only and the browser build removes it. Use it only in server-only Page options such as middleware or props, or in code the browser module does not reach. To use server code in the browser's render path, move it into a '.server' module and call it only from those options.`);
|
|
143
|
+
throw new Error(`[Ecopages Client Graph] '${first.name}' (imported from '${specifier}') is used at ${input.filename}:${toLineColumn(input.source, first.node.start)}, but that import is server-only and the browser build removes it. Use it only in server-only Page options such as middleware or props, or in code the browser module does not reach. A layout entry's props factory is server-only only when the entry is written inline in eco.page({ layout }), not when it is declared in a variable. To use server code in the browser's render path, move it into a '.server' module and call it only from those options.`);
|
|
144
144
|
}
|
|
145
145
|
/**
|
|
146
146
|
* Plans the removal of the top-level code the browser module does not need once server-only code is gone.
|
|
@@ -15,7 +15,7 @@ function pruneForbiddenSpecifier(node, ctx, specifier, message, replacement, bin
|
|
|
15
15
|
const reachableRules = ctx.reachability.reachableImports.get(specifier);
|
|
16
16
|
if (reachableRules && !ctx.reachability.isFallbackRoots) {
|
|
17
17
|
const used = bindings.length > 0 ? ` (${bindings.map((name) => `'${name}'`).join(', ')})` : '';
|
|
18
|
-
throw new Error(`[Ecopages Client Reachability] ${message} at ${ctx.filename}:${node.start}. This server-only import${used} is reachable from the React render function, which runs in the browser. Move the code that uses it into a '.server' module and call it only from server-only Page options such as props.`);
|
|
18
|
+
throw new Error(`[Ecopages Client Reachability] ${message} at ${ctx.filename}:${node.start}. This server-only import${used} is reachable from the React render function, which runs in the browser. Move the code that uses it into a '.server' module and call it only from server-only Page options such as props. A layout entry's props factory is server-only only when the entry is written inline in eco.page({ layout }), not when it is declared in a variable.`);
|
|
19
19
|
}
|
|
20
20
|
ctx.edits.push({ start: node.start, end: node.end, replacement });
|
|
21
21
|
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* Build plugin securing the Ecopages isomorphic compilation pipeline.
|
|
5
5
|
*/
|
|
6
6
|
import type { EcoBuildPlugin, EcoBuildPluginBuilder } from '@ecopages/core/integration';
|
|
7
|
+
import { type ForeignBoundaryRewriteOptions } from './foreign-boundary-rewrite.js';
|
|
7
8
|
/**
|
|
8
9
|
* Configuration options for the Client Graph Boundary build plugin.
|
|
9
10
|
*/
|
|
@@ -16,6 +17,20 @@ type ClientGraphBoundaryOptions = {
|
|
|
16
17
|
declaredModules?: readonly string[];
|
|
17
18
|
alwaysAllowSpecifiers?: string[];
|
|
18
19
|
};
|
|
20
|
+
/** The source of a module as React's graph compiles it, or `undefined` when React keeps it as it is. */
|
|
21
|
+
export type ReactModuleSource = (filePath: string, source: string) => string | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* The foreign boundary rewrite as the reach scans apply it: to React's own modules, with the identity stubs.
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* Without `foreignModuleOf` the rewrite only wraps bindings and keeps every import, so the scans read the
|
|
27
|
+
* original source.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createReactModuleSource(options: {
|
|
30
|
+
projectRoot: string;
|
|
31
|
+
isForeignFile: (filePath: string) => boolean;
|
|
32
|
+
foreignModuleOf?: ForeignBoundaryRewriteOptions['foreignModuleOf'];
|
|
33
|
+
}): ReactModuleSource | undefined;
|
|
19
34
|
/**
|
|
20
35
|
* Scope for React's foreign-JSX override: a file another JSX Integration owns gets React's JSX runtime only when
|
|
21
36
|
* a React entry file reaches it.
|
|
@@ -31,6 +46,8 @@ export declare function createForeignJsxScope(options: {
|
|
|
31
46
|
hostIntegrationName: string;
|
|
32
47
|
/** Name of the other JSX Integration that owns `filePath`; `undefined` when the file is not foreign. */
|
|
33
48
|
findForeignOwner: (filePath: string) => string | undefined;
|
|
49
|
+
/** How React's graph compiles a module, so the reach scan sees the imports React keeps. */
|
|
50
|
+
reactModuleSource?: ReactModuleSource;
|
|
34
51
|
}): (build: EcoBuildPluginBuilder) => (sourcePath: string) => boolean;
|
|
35
52
|
/**
|
|
36
53
|
* Instantiates the client graph boundary build plugin.
|
|
@@ -65,5 +82,7 @@ export declare function createForeignBoundaryPlugin(options: {
|
|
|
65
82
|
isForeignFile: (filePath: string) => boolean;
|
|
66
83
|
/** Whether another module graph uses `filePath`, in a build whose entries cannot say. */
|
|
67
84
|
isSharedFile?: (filePath: string) => boolean;
|
|
85
|
+
/** See {@link ForeignBoundaryRewriteOptions.foreignModuleOf}. */
|
|
86
|
+
foreignModuleOf?: ForeignBoundaryRewriteOptions['foreignModuleOf'];
|
|
68
87
|
}): EcoBuildPlugin;
|
|
69
88
|
export {};
|
|
@@ -5,13 +5,15 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { fileSystem } from '@ecopages/file-system';
|
|
7
7
|
import { path } from '@ecopages/file-system/path';
|
|
8
|
-
import { parseModuleSource
|
|
8
|
+
import { parseModuleSource } from '@ecopages/core/build';
|
|
9
9
|
import { parseDeclaredModules, toModuleBaseSpecifier } from './specifier-classification.js';
|
|
10
10
|
import { classifyClientGraphModule } from './module-classification.js';
|
|
11
11
|
import { transformClientGraphModule } from './boundary-plugin-transform.js';
|
|
12
12
|
import { inlineReadFileSyncCalls } from './boundary-plugin-read-file-inline.js';
|
|
13
|
-
import { scanForeignJsxReach, toRealPath } from './foreign-jsx-reach.js';
|
|
14
|
-
import { isReactBoundaryVariant, rewriteForeignImports } from './foreign-boundary-rewrite.js';
|
|
13
|
+
import { resolveLocalModulePath, scanForeignJsxReach, toRealPath } from './foreign-jsx-reach.js';
|
|
14
|
+
import { isReactBoundaryVariant, rewriteForeignImports, } from './foreign-boundary-rewrite.js';
|
|
15
|
+
import { createForeignStubSource, FOREIGN_STUB_ID_PREFIX, FOREIGN_STUB_SCHEME, fromForeignStubSpecifier, } from './foreign-module.js';
|
|
16
|
+
import { FOREIGN_BOUNDARY_PACKAGE } from '../bundling/bootstrap-package-paths.js';
|
|
15
17
|
import { createRequestedExportsPlan, } from './requested-exports-plan.js';
|
|
16
18
|
/** Source modules the boundary may transform; virtual ids and installed packages never reach it. */
|
|
17
19
|
const SOURCE_FILES = {
|
|
@@ -92,11 +94,7 @@ async function resolveScanImport(build, specifier, importer, projectRoot) {
|
|
|
92
94
|
catch {
|
|
93
95
|
return { kind: 'skip' };
|
|
94
96
|
}
|
|
95
|
-
const local =
|
|
96
|
-
? fileSystem.exists(specifier)
|
|
97
|
-
? specifier
|
|
98
|
-
: undefined
|
|
99
|
-
: resolveProjectModulePath(projectRoot, importer, specifier, { preserveBarrel: true });
|
|
97
|
+
const local = resolveLocalModulePath(projectRoot, importer, specifier);
|
|
100
98
|
const id = resolved ? (resolved.external ? undefined : resolved.id) : local;
|
|
101
99
|
if (!resolved && !local)
|
|
102
100
|
return { kind: 'unresolved' };
|
|
@@ -237,7 +235,7 @@ function isTransformedByBuild(context) {
|
|
|
237
235
|
return (filePath) => isTransformedSource(filePath, projectRoot) &&
|
|
238
236
|
(!entrypointFiles.has(filePath) || reactEntrypointFiles.has(filePath));
|
|
239
237
|
}
|
|
240
|
-
function getForeignJsxReach(context, projectRoot, isForeignFile) {
|
|
238
|
+
function getForeignJsxReach(context, projectRoot, isForeignFile, reactModuleSource) {
|
|
241
239
|
if (!context.foreignJsxReach) {
|
|
242
240
|
const reactEntryFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
|
|
243
241
|
context.foreignJsxReach = scanForeignJsxReach({
|
|
@@ -245,10 +243,33 @@ function getForeignJsxReach(context, projectRoot, isForeignFile) {
|
|
|
245
243
|
reactEntryFiles,
|
|
246
244
|
otherEntryFiles: [...context.entrypointFiles].map(toRealPath).filter((file) => !reactEntryFiles.has(file)),
|
|
247
245
|
isForeignFile,
|
|
246
|
+
reactModuleSource,
|
|
248
247
|
});
|
|
249
248
|
}
|
|
250
249
|
return context.foreignJsxReach;
|
|
251
250
|
}
|
|
251
|
+
/** The stub scheme and its `\0` prefix hold no regular expression syntax, so they match as written. */
|
|
252
|
+
const FOREIGN_STUB_SPECIFIER = new RegExp(`^${FOREIGN_STUB_SCHEME}`);
|
|
253
|
+
const FOREIGN_STUB_ID = new RegExp(`^${FOREIGN_STUB_ID_PREFIX}`);
|
|
254
|
+
/**
|
|
255
|
+
* The foreign boundary rewrite as the reach scans apply it: to React's own modules, with the identity stubs.
|
|
256
|
+
*
|
|
257
|
+
* @remarks
|
|
258
|
+
* Without `foreignModuleOf` the rewrite only wraps bindings and keeps every import, so the scans read the
|
|
259
|
+
* original source.
|
|
260
|
+
*/
|
|
261
|
+
export function createReactModuleSource(options) {
|
|
262
|
+
const { foreignModuleOf } = options;
|
|
263
|
+
if (!foreignModuleOf)
|
|
264
|
+
return undefined;
|
|
265
|
+
return (filePath, source) => options.isForeignFile(filePath)
|
|
266
|
+
? undefined
|
|
267
|
+
: rewriteForeignImports(source, filePath, {
|
|
268
|
+
projectRoot: options.projectRoot,
|
|
269
|
+
isForeignFile: options.isForeignFile,
|
|
270
|
+
foreignModuleOf,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
252
273
|
/**
|
|
253
274
|
* The file itself when it is a browser entry of the build that no React entry file claims.
|
|
254
275
|
*
|
|
@@ -279,7 +300,7 @@ export function createForeignJsxScope(options) {
|
|
|
279
300
|
const owner = options.findForeignOwner(sourcePath);
|
|
280
301
|
if (!context || context.configs.length === 0 || owner === undefined)
|
|
281
302
|
return true;
|
|
282
|
-
const reach = getForeignJsxReach(context, options.projectRoot, isForeignFile);
|
|
303
|
+
const reach = getForeignJsxReach(context, options.projectRoot, isForeignFile, options.reactModuleSource);
|
|
283
304
|
const filePath = toRealPath(sourcePath);
|
|
284
305
|
const otherEntry = reach.others.get(filePath) ?? findForeignEntry(context, filePath);
|
|
285
306
|
if (otherEntry === undefined)
|
|
@@ -333,7 +354,7 @@ export function createClientGraphBoundaryPlugin(options) {
|
|
|
333
354
|
};
|
|
334
355
|
}
|
|
335
356
|
/** The files React entries reach and the files other entries reach, by a static scan of the build's entries. */
|
|
336
|
-
function getEntryReach(context, projectRoot) {
|
|
357
|
+
function getEntryReach(context, projectRoot, reactModuleSource) {
|
|
337
358
|
if (!context.entryReach) {
|
|
338
359
|
const reactEntryFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
|
|
339
360
|
const otherEntryFiles = [...context.entrypointFiles]
|
|
@@ -344,6 +365,7 @@ function getEntryReach(context, projectRoot) {
|
|
|
344
365
|
reactEntryFiles,
|
|
345
366
|
otherEntryFiles,
|
|
346
367
|
isForeignFile: () => true,
|
|
368
|
+
reactModuleSource,
|
|
347
369
|
});
|
|
348
370
|
context.entryReach = {
|
|
349
371
|
reactEntryFiles,
|
|
@@ -368,10 +390,23 @@ function getEntryReach(context, projectRoot) {
|
|
|
368
390
|
* same rule. In a build without entries to compare, `isSharedFile` says which modules another graph uses.
|
|
369
391
|
*/
|
|
370
392
|
export function createForeignBoundaryPlugin(options) {
|
|
393
|
+
const reactModuleSource = createReactModuleSource(options);
|
|
394
|
+
const { foreignModuleOf } = options;
|
|
371
395
|
return {
|
|
372
396
|
name: 'ecopages-react-foreign-boundary',
|
|
373
397
|
environments: ['browser'],
|
|
374
398
|
setup(build) {
|
|
399
|
+
if (foreignModuleOf) {
|
|
400
|
+
build.onResolve({ filter: FOREIGN_STUB_SPECIFIER }, (args) => ({ path: `\0${args.path}` }));
|
|
401
|
+
build.onLoad({ filter: FOREIGN_STUB_ID }, (loaded) => {
|
|
402
|
+
const filePath = fromForeignStubSpecifier(options.projectRoot, loaded.path.slice(1));
|
|
403
|
+
build.addWatchFile(filePath);
|
|
404
|
+
const module = foreignModuleOf(filePath);
|
|
405
|
+
if (!module)
|
|
406
|
+
throw new Error(`[ecopages] ${filePath} is no longer a module React can name by identity.`);
|
|
407
|
+
return { contents: createForeignStubSource(module, FOREIGN_BOUNDARY_PACKAGE), loader: 'js' };
|
|
408
|
+
});
|
|
409
|
+
}
|
|
375
410
|
build.onLoad({ filter: /\?eco-variant=[\w-]+$/, exclude: /^\0|\/node_modules\// }, (loaded) => {
|
|
376
411
|
const filePath = stripVariant(loaded).path;
|
|
377
412
|
build.addWatchFile(filePath);
|
|
@@ -385,7 +420,9 @@ export function createForeignBoundaryPlugin(options) {
|
|
|
385
420
|
if (options.isForeignFile(filePath))
|
|
386
421
|
return undefined;
|
|
387
422
|
const context = build.entrypoints ? buildContexts.get(build.entrypoints) : undefined;
|
|
388
|
-
const reach = context && context.configs.length > 0
|
|
423
|
+
const reach = context && context.configs.length > 0
|
|
424
|
+
? getEntryReach(context, options.projectRoot, reactModuleSource)
|
|
425
|
+
: undefined;
|
|
389
426
|
const inReactGraph = !reach ||
|
|
390
427
|
isReactBoundaryVariant(id) ||
|
|
391
428
|
reach.reactEntryFiles.has(filePath) ||
|
|
@@ -395,6 +432,8 @@ export function createForeignBoundaryPlugin(options) {
|
|
|
395
432
|
return rewriteForeignImports(code, filePath, {
|
|
396
433
|
projectRoot: options.projectRoot,
|
|
397
434
|
isForeignFile: options.isForeignFile,
|
|
435
|
+
foreignModuleOf,
|
|
436
|
+
watchFile: (file) => build.addWatchFile(file),
|
|
398
437
|
isSharedFile: reach
|
|
399
438
|
? (file) => reach.others.has(file) && reach.react.has(file)
|
|
400
439
|
: options.isSharedFile,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Source rewrite that gives a React module the boundary of every Eco Component another Integration owns.
|
|
3
3
|
*/
|
|
4
|
+
import { type ForeignModule } from './foreign-module.js';
|
|
4
5
|
/** The module variant a React graph imports of a module that another graph also uses and that imports a foreign Component. */
|
|
5
6
|
export declare const REACT_BOUNDARY_VARIANT = "react-boundary";
|
|
6
7
|
/** Whether the module id or specifier names the React boundary variant of its module. */
|
|
@@ -17,6 +18,19 @@ export type ForeignBoundaryRewriteOptions = {
|
|
|
17
18
|
* the other graph a React boundary, so React imports it under a variant id and the other graph keeps the plain one.
|
|
18
19
|
*/
|
|
19
20
|
isSharedFile?: (filePath: string) => boolean;
|
|
21
|
+
/**
|
|
22
|
+
* The exports of the foreign file `filePath`, split into static Components and other values.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* With it, React's graph never loads a foreign file for its static Components: an import or re-export of them
|
|
26
|
+
* points at the file's stub module, which holds one boundary per Component and imports nothing of the app, so
|
|
27
|
+
* the module and everything it imports stay out of the graph whatever path reaches it. Other values still come
|
|
28
|
+
* from the module itself, behind the runtime boundary. Without it, every binding keeps its import and is
|
|
29
|
+
* wrapped at runtime.
|
|
30
|
+
*/
|
|
31
|
+
foreignModuleOf?: (filePath: string) => ForeignModule | undefined;
|
|
32
|
+
/** Receives each file whose exports a rewrite read, so a change to it transforms the importer again. */
|
|
33
|
+
watchFile?: (filePath: string) => void;
|
|
20
34
|
};
|
|
21
35
|
/**
|
|
22
36
|
* Rewrites the static imports of foreign-owned Components in `code`, barrels that re-export them included, or
|
|
@@ -24,8 +38,9 @@ export type ForeignBoundaryRewriteOptions = {
|
|
|
24
38
|
*
|
|
25
39
|
* @remarks
|
|
26
40
|
* A module without such an import is not touched: the caller gets `undefined`, so a React-only module compiles
|
|
27
|
-
* to the same output as before and ships no boundary code. A module already rewritten
|
|
28
|
-
* too, since a build can hold more than one
|
|
29
|
-
* Dynamic `import()` of a foreign module is
|
|
41
|
+
* to the same output as before and ships no boundary code. A module already rewritten, one that imports the
|
|
42
|
+
* boundary package or a stub module, is returned as `undefined` too, since a build can hold more than one
|
|
43
|
+
* instance of the plugin and a second pass would duplicate re-exports. Dynamic `import()` of a foreign module is
|
|
44
|
+
* left as it is.
|
|
30
45
|
*/
|
|
31
46
|
export declare function rewriteForeignImports(code: string, filePath: string, options: ForeignBoundaryRewriteOptions): string | undefined;
|