@ecopages/react 0.8.0 → 0.10.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 (56) hide show
  1. package/README.md +17 -27
  2. package/package.json +4 -4
  3. package/src/bundling/bundle.d.ts +6 -0
  4. package/src/bundling/bundle.js +23 -9
  5. package/src/client-graph/ast-transform-eco-page.d.ts +14 -1
  6. package/src/client-graph/ast-transform-eco-page.js +60 -13
  7. package/src/client-graph/ast-transform-stripped-imports.js +1 -1
  8. package/src/client-graph/ast-transform-walk-imports.d.ts +0 -1
  9. package/src/client-graph/ast-transform-walk-imports.js +5 -10
  10. package/src/client-graph/ast-transform.d.ts +1 -1
  11. package/src/client-graph/ast-transform.js +1 -2
  12. package/src/client-graph/boundary-plugin-transform.d.ts +0 -1
  13. package/src/client-graph/boundary-plugin-transform.js +1 -2
  14. package/src/client-graph/boundary-plugin.d.ts +19 -0
  15. package/src/client-graph/boundary-plugin.js +54 -16
  16. package/src/client-graph/foreign-boundary-rewrite.d.ts +18 -3
  17. package/src/client-graph/foreign-boundary-rewrite.js +199 -48
  18. package/src/client-graph/foreign-jsx-reach.d.ts +21 -2
  19. package/src/client-graph/foreign-jsx-reach.js +56 -14
  20. package/src/client-graph/foreign-module.d.ts +45 -0
  21. package/src/client-graph/foreign-module.js +132 -0
  22. package/src/client-graph/module-classification.d.ts +0 -1
  23. package/src/client-graph/module-classification.js +0 -4
  24. package/src/client-graph/reachability-analyzer.d.ts +0 -1
  25. package/src/client-graph/reachability-analyzer.js +0 -5
  26. package/src/client-graph/reachability-client-roots.js +28 -0
  27. package/src/client-graph/requested-exports-plan.d.ts +1 -1
  28. package/src/client-graph/requested-exports-plan.js +1 -1
  29. package/src/client-graph/specifier-classification.js +2 -2
  30. package/src/hmr/hmr-strategy.d.ts +5 -2
  31. package/src/hmr/hmr-strategy.js +12 -5
  32. package/src/hydration/browser/foreign-boundary.d.ts +12 -0
  33. package/src/hydration/browser/foreign-boundary.js +19 -0
  34. package/src/hydration/browser/page-hydration-hmr.d.ts +1 -0
  35. package/src/hydration/browser/page-hydration-hmr.js +2 -2
  36. package/src/hydration/browser/page-hydration.d.ts +2 -1
  37. package/src/hydration/browser/page-hydration.js +3 -2
  38. package/src/hydration/hydration-page-entry-source.js +3 -3
  39. package/src/hydration/page-data-manifest.d.ts +22 -1
  40. package/src/hydration/page-data-manifest.js +38 -3
  41. package/src/hydration/page-data-reader.d.ts +2 -1
  42. package/src/hydration/page-data-reader.js +4 -2
  43. package/src/hydration/page-payload.d.ts +6 -15
  44. package/src/hydration/page-payload.js +5 -42
  45. package/src/hydration/serialize-page-data-script.d.ts +4 -4
  46. package/src/hydration/serialize-page-data-script.js +6 -6
  47. package/src/page/page-module.d.ts +4 -2
  48. package/src/page/page-module.js +8 -23
  49. package/src/plugin/react.plugin.js +2 -0
  50. package/src/render/component-ownership.d.ts +1 -6
  51. package/src/render/component-ownership.js +0 -3
  52. package/src/render/component-ssr.d.ts +0 -1
  53. package/src/render/component-ssr.js +0 -7
  54. package/src/render/layout-compose.d.ts +16 -8
  55. package/src/render/layout-compose.js +13 -36
  56. package/src/render/react-renderer.js +37 -55
@@ -1,7 +1,9 @@
1
1
  import { path } from '@ecopages/file-system/path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
- import { resolveProjectModulePath } from '@ecopages/core/build';
4
- const IMPORT_SPECIFIER = /(?:\bfrom\s*|\bimport\s*\(?\s*)(['"])([^'"\n]+)\1/g;
3
+ import { parseModuleSource, resolveProjectModulePath } from '@ecopages/core/build';
4
+ import { compileSync } from '@mdx-js/mdx';
5
+ import { FOREIGN_STUB_SCHEME } from './foreign-module.js';
6
+ const MDX_SOURCE = /\.mdx?$/;
5
7
  const SCANNED_SOURCE = /\.(?:[cm]?[jt]sx?|mdx?)$/;
6
8
  /** `filePath` with symbolic links resolved, so paths from the build and from the scan compare equal. */
7
9
  export function toRealPath(filePath) {
@@ -12,21 +14,61 @@ export function toRealPath(filePath) {
12
14
  return path.resolve(filePath);
13
15
  }
14
16
  }
15
- function readImportSpecifiers(filePath) {
16
- let source;
17
+ /**
18
+ * Reads the module specifiers of a file from its parsed module: static imports, `export ... from` and dynamic
19
+ * `import()` with a literal specifier.
20
+ *
21
+ * @remarks
22
+ * The parser does not read MDX, so an MDX file is compiled first and its output parsed. A file that does not read,
23
+ * compile or parse has no specifiers.
24
+ */
25
+ function readImportSpecifiers(filePath, moduleSource) {
17
26
  try {
18
- source = fileSystem.readFileSync(filePath);
27
+ let source = fileSystem.readFileSync(filePath);
28
+ let parsePath = filePath;
29
+ if (MDX_SOURCE.test(filePath)) {
30
+ source = String(compileSync(source, { format: filePath.endsWith('.md') ? 'md' : 'mdx' }));
31
+ parsePath = `${filePath}.jsx`;
32
+ }
33
+ source = moduleSource?.(filePath, source) ?? source;
34
+ const { module } = parseModuleSource(parsePath, source);
35
+ return [
36
+ ...module.staticImports.map((entry) => entry.moduleRequest.value),
37
+ ...module.staticExports.flatMap((entry) => entry.entries.map((exported) => exported.moduleRequest?.value)),
38
+ ...module.dynamicImports.map((entry) => literalSpecifier(source, entry.moduleRequest)),
39
+ ].filter((specifier) => typeof specifier === 'string');
19
40
  }
20
41
  catch {
21
42
  return [];
22
43
  }
23
- return [...source.matchAll(IMPORT_SPECIFIER)].map((match) => match[2]);
44
+ }
45
+ /** The specifier of a dynamic `import()` when its argument is a plain string literal, otherwise `undefined`. */
46
+ function literalSpecifier(source, span) {
47
+ const text = source.slice(span.start, span.end);
48
+ const quote = text[0];
49
+ if ((quote !== "'" && quote !== '"') || text.at(-1) !== quote)
50
+ return undefined;
51
+ return text.slice(1, -1);
52
+ }
53
+ /**
54
+ * Resolves a specifier to a local file: a relative or tsconfig path import of the app's own files, or an absolute
55
+ * file path that exists.
56
+ *
57
+ * @remarks
58
+ * Core's grouped content-script entries import each script by its absolute path, so without the absolute case a
59
+ * script reached only through such an entry would be absent from the scan.
60
+ */
61
+ export function resolveLocalModulePath(projectRoot, fromFile, specifier) {
62
+ const filePath = specifier.replace(/[?#].*$/, '');
63
+ if (path.isAbsolute(filePath))
64
+ return fileSystem.exists(filePath) ? filePath : undefined;
65
+ return resolveProjectModulePath(projectRoot, fromFile, specifier, { preserveBarrel: true });
24
66
  }
25
67
  /**
26
68
  * Walks the static imports of the app's own source files from `roots`, never into a file in `stopAt`, and
27
69
  * returns each foreign file it reaches with the root that reached it first.
28
70
  */
29
- function collectForeignFiles(roots, stopAt, options) {
71
+ function collectForeignFiles(roots, stopAt, options, moduleSource) {
30
72
  const foreign = new Map();
31
73
  const visited = new Set();
32
74
  const pending = [...roots].map((root) => [root, root]);
@@ -35,10 +77,10 @@ function collectForeignFiles(roots, stopAt, options) {
35
77
  if (visited.has(filePath))
36
78
  continue;
37
79
  visited.add(filePath);
38
- for (const specifier of readImportSpecifiers(filePath)) {
39
- const resolved = resolveProjectModulePath(options.projectRoot, filePath, specifier, {
40
- preserveBarrel: true,
41
- });
80
+ for (const specifier of readImportSpecifiers(filePath, moduleSource)) {
81
+ if (specifier.startsWith(FOREIGN_STUB_SCHEME))
82
+ continue;
83
+ const resolved = resolveLocalModulePath(options.projectRoot, filePath, specifier);
42
84
  if (!resolved || resolved.split('/').includes('node_modules'))
43
85
  continue;
44
86
  const target = toRealPath(resolved);
@@ -56,13 +98,13 @@ function collectForeignFiles(roots, stopAt, options) {
56
98
  * Finds which foreign JSX files React entry files reach and which other entries reach, from static imports.
57
99
  *
58
100
  * @remarks
59
- * It runs before any module loads, so the answer does not depend on load order. Only relative and tsconfig path
60
- * imports of the app's own files are followed; packages are never scanned. A walk from another entry stops at a
101
+ * It runs before any module loads, so the answer does not depend on load order. Only relative, tsconfig path
102
+ * and absolute path imports of the app's own files are followed; packages are never scanned. A walk from another entry stops at a
61
103
  * React entry file, since React's bootstrap entries import their Page or island module.
62
104
  */
63
105
  export function scanForeignJsxReach(options) {
64
106
  return {
65
- react: new Set(collectForeignFiles(options.reactEntryFiles, new Set(), options).keys()),
107
+ react: new Set(collectForeignFiles(options.reactEntryFiles, new Set(), options, options.reactModuleSource).keys()),
66
108
  others: collectForeignFiles(options.otherEntryFiles, options.reactEntryFiles, options),
67
109
  };
68
110
  }
@@ -0,0 +1,45 @@
1
+ import type { ComponentIdentity } from '@ecopages/core';
2
+ /** What React's browser graph needs to know about the exports of a module another Integration owns. */
3
+ export type ForeignModule = {
4
+ /** Exports that are statically an `eco.*()` call, by name: React gets each from the stub module. */
5
+ identities: ReadonlyMap<string, ComponentIdentity>;
6
+ /** Every other value export: React gets it from the module itself, behind the runtime boundary. */
7
+ values: ReadonlySet<string>;
8
+ /** Whether the module also has an `export * from`, whose names are not known without following it. */
9
+ star: boolean;
10
+ };
11
+ /** The specifier scheme of a stub module; the rest of the specifier is the foreign file, relative to the app root. */
12
+ export declare const FOREIGN_STUB_SCHEME = "ecopages-react-foreign-stub:";
13
+ /**
14
+ * The module id a stub specifier resolves to: the specifier behind `\0`, a virtual id no other plugin loads or
15
+ * transforms, and that names no path of the machine that built it.
16
+ */
17
+ export declare const FOREIGN_STUB_ID_PREFIX = "\0ecopages-react-foreign-stub:";
18
+ /** A name as an export or import specifier writes it: bare when it is an identifier, quoted otherwise. */
19
+ export declare function exportSpecifierName(name: string): string;
20
+ /** The specifier React's graph imports the stub module of the foreign file `filePath` with. */
21
+ export declare function toForeignStubSpecifier(projectRoot: string, filePath: string): string;
22
+ /** The foreign file a stub specifier names. */
23
+ export declare function fromForeignStubSpecifier(projectRoot: string, specifier: string): string;
24
+ /**
25
+ * Returns the source of the stub module of a foreign file: one boundary per static Component export, built from
26
+ * its identity, and no import of the file or of anything it imports.
27
+ *
28
+ * @remarks
29
+ * Each boundary comes from `foreignBoundaryReference`, which keeps one boundary type per identity, so a stub that a
30
+ * development transform inlines into several modules still gives React one Component type.
31
+ */
32
+ export declare function createForeignStubSource(module: ForeignModule, boundaryPackage: string): string;
33
+ /**
34
+ * Returns the lookup of a foreign file's exports for React's browser graph.
35
+ *
36
+ * @remarks
37
+ * `rootDir` must be the app root core attributes identities against, so the ids match the ones the server
38
+ * renders. A file is read on each lookup and parsed again only when its source changed, so a development edit is
39
+ * seen without a separate invalidation. A file no Integration owns, or that does not read or parse, has no entry.
40
+ * A destructured export makes the module count as having unknown names, like `export *`.
41
+ */
42
+ export declare function createForeignModuleReader(options: {
43
+ rootDir: string;
44
+ integrationOf: (filePath: string) => string | undefined;
45
+ }): (filePath: string) => ForeignModule | undefined;
@@ -0,0 +1,132 @@
1
+ import { parseModuleSource, readExportedComponentIdentities, toRootRelativePath } from '@ecopages/core/build';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { path } from '@ecopages/file-system/path';
4
+ /** The specifier scheme of a stub module; the rest of the specifier is the foreign file, relative to the app root. */
5
+ export const FOREIGN_STUB_SCHEME = 'ecopages-react-foreign-stub:';
6
+ /**
7
+ * The module id a stub specifier resolves to: the specifier behind `\0`, a virtual id no other plugin loads or
8
+ * transforms, and that names no path of the machine that built it.
9
+ */
10
+ export const FOREIGN_STUB_ID_PREFIX = `\0${FOREIGN_STUB_SCHEME}`;
11
+ /** A name as an export or import specifier writes it: bare when it is an identifier, quoted otherwise. */
12
+ export function exportSpecifierName(name) {
13
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
14
+ }
15
+ /** The specifier React's graph imports the stub module of the foreign file `filePath` with. */
16
+ export function toForeignStubSpecifier(projectRoot, filePath) {
17
+ return `${FOREIGN_STUB_SCHEME}${toRootRelativePath(projectRoot, filePath)}`;
18
+ }
19
+ /** The foreign file a stub specifier names. */
20
+ export function fromForeignStubSpecifier(projectRoot, specifier) {
21
+ return path.resolve(projectRoot, specifier.slice(FOREIGN_STUB_SCHEME.length));
22
+ }
23
+ /**
24
+ * Returns the source of the stub module of a foreign file: one boundary per static Component export, built from
25
+ * its identity, and no import of the file or of anything it imports.
26
+ *
27
+ * @remarks
28
+ * Each boundary comes from `foreignBoundaryReference`, which keeps one boundary type per identity, so a stub that a
29
+ * development transform inlines into several modules still gives React one Component type.
30
+ */
31
+ export function createForeignStubSource(module, boundaryPackage) {
32
+ const lines = [`import { foreignBoundaryReference } from ${JSON.stringify(boundaryPackage)};`];
33
+ const exported = [];
34
+ let index = 0;
35
+ for (const [name, identity] of module.identities) {
36
+ const local = `__eco_stub_${index++}`;
37
+ lines.push(`const ${local} = /* @__PURE__ */ foreignBoundaryReference(${JSON.stringify(identity)});`);
38
+ exported.push(`${local} as ${exportSpecifierName(name)}`);
39
+ }
40
+ lines.push(`export { ${exported.join(', ')} };`);
41
+ return `${lines.join('\n')}\n`;
42
+ }
43
+ /** Declarations the build erases, so they are no value export; an `enum` stays a value. */
44
+ const TYPE_DECLARATIONS = new Set(['TSInterfaceDeclaration', 'TSTypeAliasDeclaration', 'TSModuleDeclaration']);
45
+ function exportName(node) {
46
+ return node.type === 'Identifier' ? node.name : String(node.value);
47
+ }
48
+ /** Adds the names one `export` declaration or specifier list declares; `true` when a name cannot be read. */
49
+ function addNamedExports(node, names) {
50
+ let unknown = false;
51
+ const declaration = node.declaration;
52
+ if (declaration?.type === 'VariableDeclaration') {
53
+ for (const declarator of declaration.declarations) {
54
+ if (declarator.id.type === 'Identifier')
55
+ names.add(declarator.id.name);
56
+ else
57
+ unknown = true;
58
+ }
59
+ }
60
+ else if (declaration?.id?.type === 'Identifier' &&
61
+ !declaration.declare &&
62
+ !TYPE_DECLARATIONS.has(declaration.type)) {
63
+ names.add(declaration.id.name);
64
+ }
65
+ for (const specifier of node.specifiers ?? []) {
66
+ if (specifier.exportKind !== 'type')
67
+ names.add(exportName(specifier.exported));
68
+ }
69
+ return unknown;
70
+ }
71
+ /** The value export names a module declares itself or through `export ... from`, and whether it has an `export *`. */
72
+ function readValueExports(filePath, source) {
73
+ const names = new Set();
74
+ let star = false;
75
+ const { program } = parseModuleSource(filePath, source);
76
+ for (const node of program.body) {
77
+ if (node.type === 'ExportDefaultDeclaration') {
78
+ names.add('default');
79
+ }
80
+ else if (node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') {
81
+ star = addNamedExports(node, names) || star;
82
+ }
83
+ else if (node.type === 'ExportAllDeclaration' && node.exportKind !== 'type') {
84
+ if (node.exported)
85
+ names.add(exportName(node.exported));
86
+ else
87
+ star = true;
88
+ }
89
+ }
90
+ return { names, star };
91
+ }
92
+ /**
93
+ * Returns the lookup of a foreign file's exports for React's browser graph.
94
+ *
95
+ * @remarks
96
+ * `rootDir` must be the app root core attributes identities against, so the ids match the ones the server
97
+ * renders. A file is read on each lookup and parsed again only when its source changed, so a development edit is
98
+ * seen without a separate invalidation. A file no Integration owns, or that does not read or parse, has no entry.
99
+ * A destructured export makes the module count as having unknown names, like `export *`.
100
+ */
101
+ export function createForeignModuleReader(options) {
102
+ const cache = new Map();
103
+ return (filePath) => {
104
+ const integration = options.integrationOf(filePath);
105
+ if (!integration)
106
+ return undefined;
107
+ let source;
108
+ try {
109
+ source = fileSystem.readFileSync(filePath);
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ const cached = cache.get(filePath);
115
+ if (cached?.source === source)
116
+ return cached.module;
117
+ let module;
118
+ try {
119
+ const identities = readExportedComponentIdentities(source, filePath, {
120
+ integration,
121
+ projectRoot: options.rootDir,
122
+ });
123
+ const { names, star } = readValueExports(filePath, source);
124
+ module = { identities, values: new Set([...names].filter((name) => !identities.has(name))), star };
125
+ }
126
+ catch {
127
+ module = undefined;
128
+ }
129
+ cache.set(filePath, { source, module });
130
+ return module;
131
+ };
132
+ }
@@ -1,3 +1,2 @@
1
1
  export type ClientGraphModuleKind = 'app' | 'workspace' | 'package' | 'vendored' | 'virtual';
2
2
  export declare function classifyClientGraphModule(filePath: string, projectRoot?: string): ClientGraphModuleKind;
3
- export declare function isPageOrLayoutEntry(filePath: string): boolean;
@@ -30,7 +30,3 @@ export function classifyClientGraphModule(filePath, projectRoot) {
30
30
  }
31
31
  return 'workspace';
32
32
  }
33
- export function isPageOrLayoutEntry(filePath) {
34
- const segments = pathSegments(filePath);
35
- return segments.includes('pages') || segments.includes('layouts');
36
- }
@@ -13,7 +13,6 @@ import type { ExplicitlyRequestedExports } from './reachability-export-names.js'
13
13
  export type ReachabilityResult = {
14
14
  reachableImports: Map<string, Set<string> | '*'>;
15
15
  reachableDeclarations: Set<unknown>;
16
- unreachableSideEffectImports: unknown[];
17
16
  isFallbackRoots: boolean;
18
17
  analyzed: boolean;
19
18
  };
@@ -13,7 +13,6 @@ function emptyReachabilityResult(isFallbackRoots) {
13
13
  return {
14
14
  reachableImports: new Map(),
15
15
  reachableDeclarations: new Set(),
16
- unreachableSideEffectImports: [],
17
16
  isFallbackRoots,
18
17
  analyzed: false,
19
18
  };
@@ -40,13 +39,9 @@ export function analyzeReachability(source, filename, program, explicitlyRequest
40
39
  const potentialClientRoots = index.clientRoots;
41
40
  const isFallbackRoots = resolveFallbackClientRoots(resolvedProgram, potentialClientRoots, explicitlyRequestedExports);
42
41
  const { reachableImports, reachableDeclarations } = runReachabilityTraversal(potentialClientRoots, index.topLevelImports, index.topLevelDeclarations, explicitlyRequestedExports);
43
- const unreachableSideEffectImports = index.topLevelImports
44
- .filter((imp) => imp.isSideEffect && !reachableImports.has(imp.specifier))
45
- .map((imp) => imp.node);
46
42
  return {
47
43
  reachableImports,
48
44
  reachableDeclarations,
49
- unreachableSideEffectImports,
50
45
  isFallbackRoots,
51
46
  analyzed: true,
52
47
  };
@@ -1,3 +1,28 @@
1
+ import { getInlineLayoutEntries, getLayoutTiers, isPropertyNamed } from './ast-transform-eco-page.js';
2
+ /**
3
+ * Adds the layout tiers of a `layout` option as roots: every tier except the `props` factory of an inline entry.
4
+ *
5
+ * @remarks
6
+ * The browser renders the layout components, so what they reference is browser code. An inline entry's factory
7
+ * runs only on the server and the page transform removes it. A tier that is not an object literal, such as an
8
+ * entry imported from another module, is a root whole, so its module's export is requested and its server
9
+ * imports fail the browser build instead of turning the tier into `undefined`.
10
+ */
11
+ function collectLayoutRoots(layout, roots) {
12
+ const inlineEntries = new Set(getInlineLayoutEntries(layout));
13
+ for (const tier of getLayoutTiers(layout)) {
14
+ if (!tier)
15
+ continue;
16
+ if (!inlineEntries.has(tier)) {
17
+ roots.push(tier);
18
+ continue;
19
+ }
20
+ for (const property of tier.properties) {
21
+ if (!isPropertyNamed(property, 'props'))
22
+ roots.push(property.type === 'Property' ? property.value : property);
23
+ }
24
+ }
25
+ }
1
26
  function collectEcoPageClientProperties(arg, roots) {
2
27
  if (!arg || arg.type !== 'ObjectExpression')
3
28
  return;
@@ -6,6 +31,9 @@ function collectEcoPageClientProperties(arg, roots) {
6
31
  if (['render', 'errorBoundary', 'loadingFallback', 'clientScripts'].includes(prop.key.name)) {
7
32
  roots.push(prop.value);
8
33
  }
34
+ else if (isPropertyNamed(prop, 'layout')) {
35
+ collectLayoutRoots(prop.value, roots);
36
+ }
9
37
  }
10
38
  }
11
39
  }
@@ -44,7 +44,7 @@ export type RequestedExportsPlan = {
44
44
  * A module's pruning depends on the exports its importers request, so computing them while modules load
45
45
  * made the result depend on which importer Rolldown loaded first. The plan starts from the build's entries
46
46
  * and follows only the imports a module's browser code reaches, after server-only Page options are set
47
- * aside, as the boundary's own analysis finds them: a module reached only through a stripped `staticProps`
47
+ * aside, as the boundary's own analysis finds them: a module reached only through a stripped `props`
48
48
  * is never loaded, so it requests nothing. A module the boundary does not transform, such as a
49
49
  * bootstrap entry, passes every import on and requests nothing. Requested exports flow from importers to
50
50
  * imports through a worklist that analyses a module again whenever its requests grow, so a cycle settles on
@@ -37,7 +37,7 @@ function statementSpecifiers(program) {
37
37
  * A module's pruning depends on the exports its importers request, so computing them while modules load
38
38
  * made the result depend on which importer Rolldown loaded first. The plan starts from the build's entries
39
39
  * and follows only the imports a module's browser code reaches, after server-only Page options are set
40
- * aside, as the boundary's own analysis finds them: a module reached only through a stripped `staticProps`
40
+ * aside, as the boundary's own analysis finds them: a module reached only through a stripped `props`
41
41
  * is never loaded, so it requests nothing. A module the boundary does not transform, such as a
42
42
  * bootstrap entry, passes every import on and requests nothing. Requested exports flow from importers to
43
43
  * imports through a worklist that analyses a module again whenever its requests grow, so a cycle settles on
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { loadTsconfigPathPrefixes, matchesTsconfigPathPrefix } from '@ecopages/core/build';
5
5
  import { toPackageRootSpecifier } from '@ecopages/core/build';
6
- import { isContentServerVirtualModule } from '@ecopages/core/build';
6
+ import { isContentServerVirtualModule, isNodeBuiltinSpecifier } from '@ecopages/core/build';
7
7
  import { isServerOnlyModuleSpecifier } from '@ecopages/core/build/contracts';
8
8
  import { path } from '@ecopages/file-system/path';
9
9
  export function isBareSpecifier(specifier) {
@@ -35,7 +35,7 @@ export function isProjectAliasSpecifier(specifier, projectRoot) {
35
35
  * @returns True when the import must never become client-reachable.
36
36
  */
37
37
  export function isServerOnlySpecifier(specifier) {
38
- if (specifier.startsWith('node:'))
38
+ if (isNodeBuiltinSpecifier(specifier))
39
39
  return true;
40
40
  if (isContentServerVirtualModule(specifier))
41
41
  return true;
@@ -19,6 +19,8 @@ export interface ReactHmrStrategyOptions {
19
19
  getMdxLoaderPlugin?: () => EcoBuildPlugin;
20
20
  ownedTemplateExtensions?: string[];
21
21
  allTemplateExtensions?: string[];
22
+ /** The Integration that owns a file, so React names a foreign Eco Component by its identity. */
23
+ integrationOf: (filePath: string) => string | undefined;
22
24
  }
23
25
  /**
24
26
  * Strategy for handling React component HMR updates.
@@ -32,6 +34,7 @@ export declare class ReactHmrStrategy extends HmrStrategy {
32
34
  private readonly context;
33
35
  private readonly pageMetadataCache;
34
36
  private readonly routerAdapter?;
37
+ private readonly foreignModuleOf;
35
38
  private importNodePageModule;
36
39
  private getDevTransformPluginOptions;
37
40
  constructor(options: ReactHmrStrategyOptions);
@@ -39,8 +42,8 @@ export declare class ReactHmrStrategy extends HmrStrategy {
39
42
  private isReactEntrypoint;
40
43
  /**
41
44
  * @remarks
42
- * React integration owns plain `.tsx` route templates. Compound extensions in
43
- * pages/layouts are integration-specific route templates and should not be
45
+ * React integration owns plain `.tsx` route templates: the Route Registry's Pages and the modules Pages
46
+ * reference as Layouts. Compound extensions in them are integration-specific route templates and should not be
44
47
  * claimed by React HMR strategy.
45
48
  */
46
49
  private isRouteTemplate;
@@ -14,6 +14,7 @@ import { isPathInside } from '@ecopages/core/build';
14
14
  import { Logger } from '@ecopages/logger';
15
15
  import { createClientGraphBoundaryPlugin, createForeignBoundaryPlugin } from '../client-graph/boundary-plugin.js';
16
16
  import { REACT_BOUNDARY_VARIANT } from '../client-graph/foreign-boundary-rewrite.js';
17
+ import { createForeignModuleReader } from '../client-graph/foreign-module.js';
17
18
  import { getReactClientGraphAllowSpecifiers } from '../bundling/bundle.js';
18
19
  import { getReactBrowserPackages } from '../bundling/bootstrap-package-paths.js';
19
20
  import { buildReactDevTransformPlugins, resolveReactDeclaredModulesForEntrypoint, } from './react-hmr-dev-transform-plugins.js';
@@ -31,6 +32,7 @@ export class ReactHmrStrategy extends HmrStrategy {
31
32
  context;
32
33
  pageMetadataCache;
33
34
  routerAdapter;
35
+ foreignModuleOf;
34
36
  async importNodePageModule(entrypointPath) {
35
37
  return await this.context.importServerModule(entrypointPath);
36
38
  }
@@ -51,6 +53,10 @@ export class ReactHmrStrategy extends HmrStrategy {
51
53
  this.getMdxLoaderPlugin = options.getMdxLoaderPlugin;
52
54
  this.ownedTemplateExtensions = new Set(options.ownedTemplateExtensions ?? ['.tsx']);
53
55
  this.allTemplateExtensions = [...(options.allTemplateExtensions ?? ['.tsx'])].sort((a, b) => b.length - a.length);
56
+ this.foreignModuleOf = createForeignModuleReader({
57
+ rootDir: this.projectRoot,
58
+ integrationOf: options.integrationOf,
59
+ });
54
60
  }
55
61
  getBuildPlugins(declaredModules) {
56
62
  return [
@@ -67,6 +73,7 @@ export class ReactHmrStrategy extends HmrStrategy {
67
73
  return templateExtension !== undefined && !this.ownedTemplateExtensions.has(templateExtension);
68
74
  },
69
75
  isSharedFile: (filePath) => !this.isReactEntrypoint(filePath),
76
+ foreignModuleOf: this.foreignModuleOf,
70
77
  }),
71
78
  ];
72
79
  }
@@ -91,12 +98,12 @@ export class ReactHmrStrategy extends HmrStrategy {
91
98
  }
92
99
  /**
93
100
  * @remarks
94
- * React integration owns plain `.tsx` route templates. Compound extensions in
95
- * pages/layouts are integration-specific route templates and should not be
101
+ * React integration owns plain `.tsx` route templates: the Route Registry's Pages and the modules Pages
102
+ * reference as Layouts. Compound extensions in them are integration-specific route templates and should not be
96
103
  * claimed by React HMR strategy.
97
104
  */
98
105
  isRouteTemplate(filePath) {
99
- return (isPathInside(filePath, this.context.getPagesDir()) || isPathInside(filePath, this.context.getLayoutsDir()));
106
+ return this.context.isPageFile(filePath) || this.context.isLayoutFile(filePath);
100
107
  }
101
108
  resolveTemplateExtension(filePath) {
102
109
  return this.allTemplateExtensions.find((extension) => filePath.endsWith(extension));
@@ -172,10 +179,10 @@ export class ReactHmrStrategy extends HmrStrategy {
172
179
  return buildReactDevTransformPlugins(this.getDevTransformPluginOptions(), declaredModules, sourcePath.endsWith('.mdx'));
173
180
  }
174
181
  isLayoutFile(filePath) {
175
- return isPathInside(filePath, this.context.getLayoutsDir());
182
+ return this.context.isLayoutFile(filePath);
176
183
  }
177
184
  isPageEntrypoint(filePath) {
178
- return isPathInside(filePath, this.context.getPagesDir()) && this.isReactEntrypoint(filePath);
185
+ return this.context.isPageFile(filePath) && this.isReactEntrypoint(filePath);
179
186
  }
180
187
  resolveEntrypointOutputUrl(entrypointPath) {
181
188
  return this.context.getWatchedFiles().get(path.resolve(entrypointPath));
@@ -9,6 +9,8 @@
9
9
  *
10
10
  * @module
11
11
  */
12
+ import { type ComponentType } from 'react';
13
+ import { type ComponentIdentity } from '@ecopages/core';
12
14
  /**
13
15
  * Returns the component type React renders for `value`: a boundary when it is an Eco Component another
14
16
  * Integration owns, `value` itself otherwise.
@@ -23,6 +25,16 @@
23
25
  * One boundary type per Component keeps React from re-mounting it on a parent render.
24
26
  */
25
27
  export declare function foreignBoundary<T>(value: T): T;
28
+ /**
29
+ * Returns the boundary of the Eco Component another Integration owns that `identity` names, without its module.
30
+ *
31
+ * @remarks
32
+ * The stub module React's client graph loads for a foreign file exports one of these per static Component, so the
33
+ * Component's module and its imports stay out of React's bundle; the boundary only needs the identity to find the
34
+ * server HTML. One boundary type per identity keeps React from re-mounting it on a parent render, even when a
35
+ * development transform inlines the same stub into several modules.
36
+ */
37
+ export declare function foreignBoundaryReference(identity: ComponentIdentity): ComponentType<Record<string, unknown>>;
26
38
  /**
27
39
  * Wraps a namespace import of a module another Integration owns, so `ns.Component` is its boundary.
28
40
  */
@@ -118,6 +118,25 @@ export function foreignBoundary(value) {
118
118
  }
119
119
  return boundary;
120
120
  }
121
+ const references = new Map();
122
+ /**
123
+ * Returns the boundary of the Eco Component another Integration owns that `identity` names, without its module.
124
+ *
125
+ * @remarks
126
+ * The stub module React's client graph loads for a foreign file exports one of these per static Component, so the
127
+ * Component's module and its imports stay out of React's bundle; the boundary only needs the identity to find the
128
+ * server HTML. One boundary type per identity keeps React from re-mounting it on a parent render, even when a
129
+ * development transform inlines the same stub into several modules.
130
+ */
131
+ export function foreignBoundaryReference(identity) {
132
+ let boundary = references.get(identity.id);
133
+ if (!boundary) {
134
+ const component = Object.assign(() => null, { config: { identity } });
135
+ boundary = foreignBoundary(component);
136
+ references.set(identity.id, boundary);
137
+ }
138
+ return boundary;
139
+ }
121
140
  /**
122
141
  * Wraps a namespace import of a module another Integration owns, so `ns.Component` is its boundary.
123
142
  */
@@ -2,6 +2,7 @@ import type { PageHydrationOptions } from './page-hydration.js';
2
2
  type PageData = {
3
3
  moduleUrl?: string;
4
4
  props: Record<string, unknown>;
5
+ tiers?: readonly Record<string, unknown>[];
5
6
  };
6
7
  type PageDataReader = (options: PageHydrationOptions, source?: Pick<Document, 'getElementById'>) => PageData;
7
8
  type PageStateSetter = (options: PageHydrationOptions, pageData: PageData) => void;
@@ -43,7 +43,7 @@ async function applyRouterHmrUpdate(options, newUrl, currentPage, nextPage) {
43
43
  * document, and the live boundary of a hydrated custom element no longer holds its declarative shadow root. The
44
44
  * parsed document keeps the `<template shadowrootmode>` of each, as a client navigation's does. A response that is
45
45
  * not a page, such as a server render error, throws, so the update is not applied and the next edit retries it.
46
- * The same document is the source of the Page's props, and of its module URL when the page data carries one, since an edit can change what `staticProps`
46
+ * The same document is the source of the Page's props, and of its module URL when the page data carries one, since an edit can change what `props`
47
47
  * returns and the live `__ECO_PAGE_DATA__` still holds the old values.
48
48
  */
49
49
  async function fetchCurrentDocument() {
@@ -65,7 +65,7 @@ async function applyDirectHmrRender(options, nextPage, readPageData, setPageStat
65
65
  const runtime = getRuntime();
66
66
  if (runtime.page)
67
67
  runtime.page.document = fetchedDocument;
68
- activeRoot.render(options.createTree(nextPage, pageData.props));
68
+ activeRoot.render(options.createTree(nextPage, pageData.props, pageData.tiers));
69
69
  console.log(`[ecopages] ${options.isMdx ? 'MDX' : 'React'} component updated`);
70
70
  }
71
71
  /**
@@ -24,6 +24,7 @@ export type PageReactRuntime = {
24
24
  export type PageData = {
25
25
  moduleUrl?: string;
26
26
  props: Record<string, unknown>;
27
+ tiers?: readonly Record<string, unknown>[];
27
28
  };
28
29
  export { resolvePageComponent } from './page-hydration-module.js';
29
30
  export { readPageDataDocument } from '../page-data-reader.js';
@@ -36,7 +37,7 @@ export type PageHydrationOptions = {
36
37
  readPageDataDocument: (source?: Pick<Document, 'getElementById'>) => PageData;
37
38
  };
38
39
  runtime: PageReactRuntime;
39
- createTree: (Page: unknown, props: Record<string, unknown>) => unknown;
40
+ createTree: (Page: unknown, props: Record<string, unknown>, tiers?: readonly Record<string, unknown>[]) => unknown;
40
41
  hasRouter: boolean;
41
42
  isMdx: boolean;
42
43
  normalizePageConfig?: (config: unknown) => void;
@@ -34,6 +34,7 @@ function setPageState(options, pageData) {
34
34
  runtime.page = {
35
35
  module: pageData.moduleUrl || options.pageModuleUrl,
36
36
  props: pageData.props,
37
+ ...(pageData.tiers && { tiers: pageData.tiers }),
37
38
  };
38
39
  }
39
40
  /**
@@ -176,7 +177,7 @@ function mount(options) {
176
177
  setPageState(options, pageData);
177
178
  if (runtime.react?.pageRoot) {
178
179
  if (!options.hasRouter) {
179
- runtime.react.pageRoot.render(options.createTree(options.Page, pageData.props));
180
+ runtime.react.pageRoot.render(options.createTree(options.Page, pageData.props, pageData.tiers));
180
181
  }
181
182
  return;
182
183
  }
@@ -196,7 +197,7 @@ function mount(options) {
196
197
  requireReloadForHmr(options);
197
198
  restoreChildNodes(target, serverNodes, serverClones, addedNodes);
198
199
  };
199
- root = options.runtime.hydrateRoot(target, options.createTree(options.Page, pageData.props), {
200
+ root = options.runtime.hydrateRoot(target, options.createTree(options.Page, pageData.props, pageData.tiers), {
200
201
  onRecoverableError: (error) => console.warn('[ecopages] Hydration error:', error),
201
202
  onUncaughtError: (error, errorInfo) => {
202
203
  reportError(error);
@@ -26,11 +26,11 @@ function buildRouterImports(options) {
26
26
  }
27
27
  function buildRouterTree(options) {
28
28
  if (!options.routerComponents) {
29
- return 'const createTree = (Page, props) => composeLayoutPageTree(Page, props);';
29
+ return 'const createTree = (Page, props, tiers) => composeLayoutPageTree(Page, props, tiers ? { tierProps: tiers } : undefined);';
30
30
  }
31
- return `const createTree = (Page, props) => {
31
+ return `const createTree = (Page, props, tiers) => {
32
32
  const pageContent = createElement(${options.routerComponents.pageContent});
33
- return createElement(${options.routerComponents.router}, ${options.routerPropsExpression}, pageContent);
33
+ return createElement(${options.routerComponents.router}, { ...(${options.routerPropsExpression}), tierProps: tiers }, pageContent);
34
34
  };`;
35
35
  }
36
36
  function buildNormalizationImport(options) {