@ecopages/react 0.6.0 → 0.7.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 (95) hide show
  1. package/README.md +50 -87
  2. package/package.json +32 -14
  3. package/src/bundling/bootstrap-package-paths.d.ts +13 -1
  4. package/src/bundling/bootstrap-package-paths.js +25 -3
  5. package/src/bundling/bundle.d.ts +8 -36
  6. package/src/bundling/bundle.js +42 -73
  7. package/src/client-graph/ast-transform-eco-page.d.ts +10 -6
  8. package/src/client-graph/ast-transform-eco-page.js +56 -35
  9. package/src/client-graph/ast-transform-import-edits.d.ts +10 -2
  10. package/src/client-graph/ast-transform-import-edits.js +36 -6
  11. package/src/client-graph/ast-transform-stripped-imports.d.ts +37 -0
  12. package/src/client-graph/ast-transform-stripped-imports.js +191 -0
  13. package/src/client-graph/ast-transform-walk-imports.d.ts +4 -0
  14. package/src/client-graph/ast-transform-walk-imports.js +15 -1
  15. package/src/client-graph/ast-transform.d.ts +12 -3
  16. package/src/client-graph/ast-transform.js +41 -56
  17. package/src/client-graph/boundary-plugin-read-file-inline.d.ts +3 -0
  18. package/src/client-graph/boundary-plugin-read-file-inline.js +14 -10
  19. package/src/client-graph/boundary-plugin-transform.d.ts +5 -4
  20. package/src/client-graph/boundary-plugin-transform.js +6 -13
  21. package/src/client-graph/boundary-plugin.d.ts +47 -1
  22. package/src/client-graph/boundary-plugin.js +267 -53
  23. package/src/client-graph/foreign-boundary-rewrite.d.ts +31 -0
  24. package/src/client-graph/foreign-boundary-rewrite.js +360 -0
  25. package/src/client-graph/foreign-jsx-reach.d.ts +25 -0
  26. package/src/client-graph/foreign-jsx-reach.js +68 -0
  27. package/src/client-graph/module-classification.js +3 -10
  28. package/src/client-graph/reachability-traverse.js +35 -105
  29. package/src/client-graph/requested-exports-plan.d.ts +62 -0
  30. package/src/client-graph/requested-exports-plan.js +125 -0
  31. package/src/client-graph/scope-walk.d.ts +37 -0
  32. package/src/client-graph/scope-walk.js +407 -0
  33. package/src/client-graph/specifier-classification.d.ts +2 -1
  34. package/src/client-graph/specifier-classification.js +9 -7
  35. package/src/contracts/router-adapter.d.ts +9 -24
  36. package/src/dev-transform/react-dev-transform-contributor.d.ts +4 -4
  37. package/src/dev-transform/react-dev-transform-contributor.js +6 -7
  38. package/src/hmr/hmr-strategy-process.d.ts +7 -5
  39. package/src/hmr/hmr-strategy-process.js +21 -16
  40. package/src/hmr/hmr-strategy.d.ts +11 -10
  41. package/src/hmr/hmr-strategy.js +32 -53
  42. package/src/hmr/page-metadata-cache.js +1 -1
  43. package/src/hydration/browser/foreign-boundary.d.ts +29 -0
  44. package/src/hydration/browser/foreign-boundary.js +128 -0
  45. package/src/hydration/browser/island-hydration.d.ts +3 -4
  46. package/src/hydration/browser/island-hydration.js +3 -4
  47. package/src/hydration/browser/page-hydration-hmr.d.ts +8 -7
  48. package/src/hydration/browser/page-hydration-hmr.js +53 -10
  49. package/src/hydration/browser/page-hydration.d.ts +6 -5
  50. package/src/hydration/browser/page-hydration.js +8 -6
  51. package/src/hydration/foreign-subtree.d.ts +27 -0
  52. package/src/hydration/foreign-subtree.js +69 -0
  53. package/src/hydration/hydration-asset.d.ts +37 -29
  54. package/src/hydration/hydration-asset.js +74 -138
  55. package/src/hydration/hydration-island-entry-source.d.ts +17 -0
  56. package/src/hydration/hydration-island-entry-source.js +32 -0
  57. package/src/hydration/hydration-page-entry-source.d.ts +20 -2
  58. package/src/hydration/hydration-page-entry-source.js +17 -12
  59. package/src/hydration/page-data-reader.d.ts +4 -7
  60. package/src/hydration/page-data-reader.js +5 -10
  61. package/src/mdx/mdx-config-dependency.d.ts +10 -15
  62. package/src/mdx/mdx-config-dependency.js +9 -22
  63. package/src/mdx/mdx-loader-plugin.d.ts +2 -0
  64. package/src/mdx/mdx-loader-plugin.js +1 -0
  65. package/src/page/page-module.js +1 -1
  66. package/src/plugin/react.plugin.d.ts +0 -7
  67. package/src/plugin/react.plugin.js +4 -33
  68. package/src/plugin/react.types.d.ts +0 -29
  69. package/src/render/component-ssr.d.ts +18 -0
  70. package/src/render/component-ssr.js +37 -0
  71. package/src/render/layout-compose.d.ts +4 -2
  72. package/src/render/layout-compose.js +13 -6
  73. package/src/render/layout-render-tracker.d.ts +20 -0
  74. package/src/render/layout-render-tracker.js +33 -0
  75. package/src/render/react-renderer.d.ts +28 -10
  76. package/src/render/react-renderer.js +103 -38
  77. package/src/render/react-runtime.js +2 -2
  78. package/src/bundling/runtime-alias-map.d.ts +0 -12
  79. package/src/bundling/runtime-alias-map.js +0 -110
  80. package/src/bundling/runtime-bundle.d.ts +0 -70
  81. package/src/bundling/runtime-bundle.js +0 -233
  82. package/src/bundling/runtime-interop-plugin.d.ts +0 -5
  83. package/src/bundling/runtime-interop-plugin.js +0 -32
  84. package/src/bundling/runtime-mode.d.ts +0 -1
  85. package/src/bundling/runtime-mode.js +0 -10
  86. package/src/bundling/runtime-modules.d.ts +0 -21
  87. package/src/bundling/runtime-modules.js +0 -28
  88. package/src/hydration/bootstrap-imports.d.ts +0 -25
  89. package/src/hydration/bootstrap-imports.js +0 -33
  90. package/src/hydration/compiled-page-hydration-options.d.ts +0 -19
  91. package/src/hydration/compiled-page-hydration-options.js +0 -1
  92. package/src/hydration/hydration-script-compiler.d.ts +0 -47
  93. package/src/hydration/hydration-script-compiler.js +0 -213
  94. package/src/runtime/use-sync-external-store-with-selector.d.ts +0 -3
  95. package/src/runtime/use-sync-external-store-with-selector.js +0 -54
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Source rewrite that gives a React module the boundary of every Eco Component another Integration owns.
3
+ */
4
+ import { fileSystem } from '@ecopages/file-system';
5
+ import { parseModuleSource, resolveProjectModulePath } from '@ecopages/core/build';
6
+ import { FOREIGN_BOUNDARY_PACKAGE } from '../bundling/bootstrap-package-paths.js';
7
+ import { toRealPath } from './foreign-jsx-reach.js';
8
+ import { collectLexicalDeclarations, walkScopedReferences } from './scope-walk.js';
9
+ const HELPER_BINDING = '__ecoForeignBoundary';
10
+ const NAMESPACE_HELPER_BINDING = '__ecoForeignBoundaryNamespace';
11
+ /** The module variant a React graph imports of a module that another graph also uses and that imports a foreign Component. */
12
+ export const REACT_BOUNDARY_VARIANT = 'react-boundary';
13
+ const VARIANT_QUERY = `eco-variant=${REACT_BOUNDARY_VARIANT}`;
14
+ /** Whether the module id or specifier names the React boundary variant of its module. */
15
+ export function isReactBoundaryVariant(idOrSpecifier) {
16
+ return idOrSpecifier.includes(VARIANT_QUERY);
17
+ }
18
+ function moduleName(node) {
19
+ return node.type === 'Identifier' ? node.name : String(node.value);
20
+ }
21
+ const RE_EXPORT = /\bexport\s*(?:\*|\{[^}]*\})\s*(?:as\s+\w+\s*)?from\b/;
22
+ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/;
23
+ /**
24
+ * Follows the `export { a as b } from` and `export * from` chains of project modules to the file that declares
25
+ * an export, so a barrel that re-exports a foreign Component counts as foreign for that name.
26
+ *
27
+ * @remarks
28
+ * The barrel itself is never rewritten: it may be shared with an entry that needs the Component, and each React
29
+ * import site decides for its own bindings. A file without a re-export is not parsed.
30
+ */
31
+ class ForeignExports {
32
+ options;
33
+ reexports = new Map();
34
+ constructor(options) {
35
+ this.options = options;
36
+ }
37
+ resolve(importer, specifier) {
38
+ const resolved = resolveProjectModulePath(this.options.projectRoot, importer, specifier, {
39
+ preserveBarrel: true,
40
+ });
41
+ return resolved ? toRealPath(resolved) : undefined;
42
+ }
43
+ getReexports(filePath) {
44
+ let nodes = this.reexports.get(filePath);
45
+ if (!nodes) {
46
+ nodes = [];
47
+ this.reexports.set(filePath, nodes);
48
+ if (SOURCE_FILE.test(filePath) && fileSystem.exists(filePath)) {
49
+ const source = fileSystem.readFileSync(filePath);
50
+ if (RE_EXPORT.test(source)) {
51
+ const { program } = parseModuleSource(filePath, source);
52
+ nodes.push(...program.body.filter((node) => (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') &&
53
+ node.source &&
54
+ node.exportKind !== 'type'));
55
+ }
56
+ }
57
+ }
58
+ return nodes;
59
+ }
60
+ importing = new Map();
61
+ imports = new Map();
62
+ getImports(filePath) {
63
+ let nodes = this.imports.get(filePath);
64
+ if (!nodes) {
65
+ nodes = [];
66
+ this.imports.set(filePath, nodes);
67
+ if (SOURCE_FILE.test(filePath) && fileSystem.exists(filePath)) {
68
+ const source = fileSystem.readFileSync(filePath);
69
+ if (/\b(?:import|export)\b/.test(source)) {
70
+ const { program } = parseModuleSource(filePath, source);
71
+ nodes.push(...program.body.filter((node) => (node.type === 'ImportDeclaration' ||
72
+ node.type === 'ExportNamedDeclaration' ||
73
+ node.type === 'ExportAllDeclaration') &&
74
+ node.source &&
75
+ (node.importKind ?? node.exportKind) !== 'type'));
76
+ }
77
+ }
78
+ }
79
+ return nodes;
80
+ }
81
+ /** Whether `filePath` imports a foreign Component, directly or through a module that does. */
82
+ importsForeign(filePath, seen = new Set()) {
83
+ const known = this.importing.get(filePath);
84
+ if (known !== undefined)
85
+ return known;
86
+ if (seen.has(filePath))
87
+ return false;
88
+ seen.add(filePath);
89
+ let result = false;
90
+ for (const node of this.getImports(filePath)) {
91
+ const target = this.resolve(filePath, node.source.value);
92
+ if (!target)
93
+ continue;
94
+ if (node.type === 'ImportDeclaration' && this.valueImportOf(node, target)) {
95
+ result = true;
96
+ break;
97
+ }
98
+ if (!this.options.isForeignFile(target) && this.importsForeign(target, seen)) {
99
+ result = true;
100
+ break;
101
+ }
102
+ }
103
+ this.importing.set(filePath, result);
104
+ return result;
105
+ }
106
+ /** Whether an import declaration binds at least one value that `target` declares as foreign. */
107
+ valueImportOf(node, target) {
108
+ return (node.specifiers ?? []).some((specifier) => {
109
+ if (specifier.importKind === 'type')
110
+ return false;
111
+ if (specifier.type === 'ImportNamespaceSpecifier')
112
+ return this.isForeign(target, undefined);
113
+ const imported = specifier.type === 'ImportDefaultSpecifier' ? 'default' : moduleName(specifier.imported);
114
+ return this.isForeign(target, imported) || this.isForeignNamespace(target, imported);
115
+ });
116
+ }
117
+ /** Whether React imports `target` under the variant id: another graph shares it and it imports a foreign Component. */
118
+ needsVariant(target) {
119
+ return (!this.options.isForeignFile(target) &&
120
+ this.options.isSharedFile?.(target) === true &&
121
+ this.importsForeign(target));
122
+ }
123
+ declared = new Map();
124
+ getDeclaredExports(filePath) {
125
+ if (this.declared.has(filePath))
126
+ return this.declared.get(filePath);
127
+ this.declared.set(filePath, undefined);
128
+ if (!SOURCE_FILE.test(filePath) || !fileSystem.exists(filePath))
129
+ return undefined;
130
+ const { program } = parseModuleSource(filePath, fileSystem.readFileSync(filePath));
131
+ const names = new Set();
132
+ const stars = [];
133
+ for (const node of program.body) {
134
+ if (node.type === 'ExportDefaultDeclaration') {
135
+ names.add('default');
136
+ }
137
+ else if (node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') {
138
+ collectLexicalDeclarations(node, names);
139
+ for (const specifier of node.specifiers ?? [])
140
+ names.add(moduleName(specifier.exported));
141
+ }
142
+ else if (node.type === 'ExportAllDeclaration' && node.exportKind !== 'type') {
143
+ if (node.exported)
144
+ names.add(moduleName(node.exported));
145
+ else
146
+ stars.push(node.source.value);
147
+ }
148
+ }
149
+ const result = { names, stars };
150
+ this.declared.set(filePath, result);
151
+ return result;
152
+ }
153
+ /**
154
+ * Whether the module `filePath` exports `name` itself or through an `export *`.
155
+ *
156
+ * @remarks
157
+ * A file that cannot be read as source answers `true`, so an unknown export keeps counting as foreign.
158
+ */
159
+ declaresExport(filePath, name, seen = new Set()) {
160
+ if (seen.has(filePath))
161
+ return false;
162
+ seen.add(filePath);
163
+ const declared = this.getDeclaredExports(filePath);
164
+ if (!declared)
165
+ return true;
166
+ if (declared.names.has(name))
167
+ return true;
168
+ if (name === 'default')
169
+ return false;
170
+ return declared.stars.some((star) => {
171
+ const target = this.resolve(filePath, star);
172
+ return target === undefined || this.declaresExport(target, name, seen);
173
+ });
174
+ }
175
+ /** Whether `export * from target` brings in the foreign export `name`: a foreign target must declare it, and `export *` never carries `default`. */
176
+ starExportIsForeign(target, name, seen) {
177
+ if (name === 'default')
178
+ return false;
179
+ if (name !== undefined && this.options.isForeignFile(target))
180
+ return this.declaresExport(target, name);
181
+ return this.isForeign(target, name, seen);
182
+ }
183
+ reexportIsForeignNamespace(node, target, name, explicit, seen) {
184
+ if (node.type === 'ExportAllDeclaration') {
185
+ if (node.exported)
186
+ return moduleName(node.exported) === name && this.isForeign(target, undefined);
187
+ return !explicit && name !== 'default' && this.isForeignNamespace(target, name, seen);
188
+ }
189
+ return node.specifiers.some((specifier) => specifier.exportKind !== 'type' &&
190
+ moduleName(specifier.exported) === name &&
191
+ this.isForeignNamespace(target, moduleName(specifier.local), seen));
192
+ }
193
+ /**
194
+ * Whether the export `name` of `filePath` is a namespace of a foreign file, through `export * as name from`.
195
+ *
196
+ * @remarks
197
+ * The binding is a module namespace object, so React wraps it in the namespace proxy: a member that is a foreign
198
+ * Eco Component gets its boundary, and any other member comes back unchanged.
199
+ */
200
+ isForeignNamespace(filePath, name, seen = new Set()) {
201
+ if (this.options.isForeignFile(filePath) || seen.has(filePath))
202
+ return false;
203
+ seen.add(filePath);
204
+ const explicit = this.getDeclaredExports(filePath)?.names.has(name) === true;
205
+ for (const node of this.getReexports(filePath)) {
206
+ const target = this.resolve(filePath, node.source.value);
207
+ if (target && this.reexportIsForeignNamespace(node, target, name, explicit, seen))
208
+ return true;
209
+ }
210
+ return false;
211
+ }
212
+ reexportIsForeign(node, target, name, explicit, seen) {
213
+ if (node.type === 'ExportAllDeclaration') {
214
+ const isStar = node.exported === null || node.exported === undefined;
215
+ return isStar && !explicit && this.starExportIsForeign(target, name, seen);
216
+ }
217
+ return node.specifiers.some((specifier) => specifier.exportKind !== 'type' &&
218
+ (name === undefined || moduleName(specifier.exported) === name) &&
219
+ this.isForeign(target, moduleName(specifier.local), seen));
220
+ }
221
+ /** Whether the export `name` of `filePath` is declared by a foreign file; `undefined` asks about any export. */
222
+ isForeign(filePath, name, seen = new Set()) {
223
+ if (this.options.isForeignFile(filePath))
224
+ return true;
225
+ if (seen.has(filePath))
226
+ return false;
227
+ seen.add(filePath);
228
+ const explicit = name !== undefined && this.getDeclaredExports(filePath)?.names.has(name) === true;
229
+ for (const node of this.getReexports(filePath)) {
230
+ const target = this.resolve(filePath, node.source.value);
231
+ if (target && this.reexportIsForeign(node, target, name, explicit, seen))
232
+ return true;
233
+ }
234
+ return false;
235
+ }
236
+ }
237
+ /** The specifier an import is written with: the variant id when `target` needs one. */
238
+ function importSourceOf(node, target, foreignExports) {
239
+ const specifier = node.source.value;
240
+ return foreignExports.needsVariant(target) && !specifier.includes('?')
241
+ ? `${specifier}?${VARIANT_QUERY}`
242
+ : specifier;
243
+ }
244
+ /** The helper that wraps the export `imported` of `target`, or `undefined` when it is not foreign. */
245
+ function boundaryHelperOf(foreignExports, target, imported) {
246
+ if (foreignExports.isForeign(target, imported))
247
+ return HELPER_BINDING;
248
+ return foreignExports.isForeignNamespace(target, imported) ? NAMESPACE_HELPER_BINDING : undefined;
249
+ }
250
+ /**
251
+ * Rewrites an import declaration so each binding that resolves to a foreign Component goes through the boundary.
252
+ *
253
+ * @remarks
254
+ * The declaration keeps its line: the replacement holds no newline, so positions after it stay valid. Only a
255
+ * binding the module reads as a value is wrapped; a type or an unused binding keeps its plain import, so the
256
+ * bundler drops it as it would without the rewrite.
257
+ */
258
+ function rewriteImport(node, source, filePath, foreignExports, uid, valueReads) {
259
+ if (node.importKind === 'type' || !node.specifiers?.length)
260
+ return undefined;
261
+ const target = foreignExports.resolve(filePath, node.source.value);
262
+ if (!target)
263
+ return undefined;
264
+ const from = JSON.stringify(importSourceOf(node, target, foreignExports));
265
+ const imports = [];
266
+ const extra = [];
267
+ const bindings = [];
268
+ let foreign = false;
269
+ for (const specifier of node.specifiers) {
270
+ if (specifier.importKind === 'type') {
271
+ imports.push(source.slice(specifier.start, specifier.end));
272
+ continue;
273
+ }
274
+ const local = specifier.local.name;
275
+ if (specifier.type === 'ImportNamespaceSpecifier') {
276
+ if (!valueReads.has(local) || !foreignExports.isForeign(target, undefined)) {
277
+ extra.push(`import * as ${local} from ${from};`);
278
+ continue;
279
+ }
280
+ foreign = true;
281
+ const temporary = `__eco_foreign_${uid()}`;
282
+ extra.push(`import * as ${temporary} from ${from};`);
283
+ bindings.push(`const ${local} = ${NAMESPACE_HELPER_BINDING}(${temporary});`);
284
+ continue;
285
+ }
286
+ const imported = specifier.type === 'ImportDefaultSpecifier' ? 'default' : moduleName(specifier.imported);
287
+ const wrapper = valueReads.has(local) ? boundaryHelperOf(foreignExports, target, imported) : undefined;
288
+ if (!wrapper) {
289
+ imports.push(`${JSON.stringify(imported)} as ${local}`);
290
+ continue;
291
+ }
292
+ foreign = true;
293
+ const temporary = `__eco_foreign_${uid()}`;
294
+ imports.push(`${JSON.stringify(imported)} as ${temporary}`);
295
+ bindings.push(`const ${local} = ${wrapper}(${temporary});`);
296
+ }
297
+ if (!foreign)
298
+ return undefined;
299
+ const named = imports.length > 0 ? `import { ${imports.join(', ')} } from ${from};` : '';
300
+ return [named, ...extra, ...bindings].filter(Boolean).join(' ');
301
+ }
302
+ /** The edit one top-level node needs: wrapped bindings, or the variant id for a shared module that reaches a foreign Component. */
303
+ function planEdit(node, code, filePath, foreignExports, uid, valueReads) {
304
+ if (!node.source || (node.importKind ?? node.exportKind) === 'type')
305
+ return undefined;
306
+ const replacement = node.type === 'ImportDeclaration'
307
+ ? rewriteImport(node, code, filePath, foreignExports, uid, valueReads)
308
+ : undefined;
309
+ if (replacement !== undefined)
310
+ return { start: node.start, end: node.end, replacement };
311
+ const specifier = node.source.value;
312
+ if (specifier.includes('?'))
313
+ return undefined;
314
+ const target = foreignExports.resolve(filePath, specifier);
315
+ if (!target || !foreignExports.needsVariant(target))
316
+ return undefined;
317
+ return {
318
+ start: node.source.start,
319
+ end: node.source.end,
320
+ replacement: JSON.stringify(`${specifier}?${VARIANT_QUERY}`),
321
+ };
322
+ }
323
+ /**
324
+ * Rewrites the static imports of foreign-owned Components in `code`, barrels that re-export them included, or
325
+ * returns `undefined`.
326
+ *
327
+ * @remarks
328
+ * A module without such an import is not touched: the caller gets `undefined`, so a React-only module compiles
329
+ * to the same output as before and ships no boundary code. A module already rewritten is returned as `undefined`
330
+ * too, since a build can hold more than one instance of the plugin. A namespace import is wrapped in a proxy.
331
+ * Dynamic `import()` of a foreign module is left as it is.
332
+ */
333
+ export function rewriteForeignImports(code, filePath, options) {
334
+ if (!/\bimport\b|\bexport\b/.test(code) || code.includes(FOREIGN_BOUNDARY_PACKAGE))
335
+ return undefined;
336
+ const lang = /\.(?:mdx?)$/.test(filePath) ? 'jsx' : undefined;
337
+ const { program } = parseModuleSource(filePath, code, lang ? { lang } : {});
338
+ let counter = 0;
339
+ const uid = () => String(counter++);
340
+ const foreignExports = new ForeignExports(options);
341
+ const valueReads = new Set();
342
+ walkScopedReferences(program.body, { onReference: (name) => valueReads.add(name) });
343
+ const edits = [];
344
+ for (const node of program.body) {
345
+ const edit = planEdit(node, code, filePath, foreignExports, uid, valueReads);
346
+ if (edit)
347
+ edits.push(edit);
348
+ }
349
+ if (edits.length === 0)
350
+ return undefined;
351
+ let rewritten = code;
352
+ for (const edit of edits.reverse()) {
353
+ rewritten = `${rewritten.slice(0, edit.start)}${edit.replacement}${rewritten.slice(edit.end)}`;
354
+ }
355
+ if (!rewritten.includes(HELPER_BINDING))
356
+ return rewritten;
357
+ const helpers = `import { foreignBoundary as ${HELPER_BINDING}, foreignBoundaryNamespace as ${NAMESPACE_HELPER_BINDING} } ` +
358
+ `from ${JSON.stringify(FOREIGN_BOUNDARY_PACKAGE)};`;
359
+ return `${helpers}${rewritten}`;
360
+ }
@@ -0,0 +1,25 @@
1
+ export type ForeignJsxReachOptions = {
2
+ projectRoot: string;
3
+ /** React entry files: island and Page modules. */
4
+ reactEntryFiles: ReadonlySet<string>;
5
+ /** Every other entry file of the build. */
6
+ otherEntryFiles: Iterable<string>;
7
+ isForeignFile: (filePath: string) => boolean;
8
+ };
9
+ export type ForeignJsxReach = {
10
+ /** Foreign files a React entry file reaches. */
11
+ react: ReadonlySet<string>;
12
+ /** Foreign files another entry reaches without passing a React entry file, each with that entry. */
13
+ others: ReadonlyMap<string, string>;
14
+ };
15
+ /** `filePath` with symbolic links resolved, so paths from the build and from the scan compare equal. */
16
+ export declare function toRealPath(filePath: string): string;
17
+ /**
18
+ * Finds which foreign JSX files React entry files reach and which other entries reach, from static imports.
19
+ *
20
+ * @remarks
21
+ * It runs before any module loads, so the answer does not depend on load order. Only relative and tsconfig path
22
+ * imports of the app's own files are followed; packages are never scanned. A walk from another entry stops at a
23
+ * React entry file, since React's bootstrap entries import their Page or island module.
24
+ */
25
+ export declare function scanForeignJsxReach(options: ForeignJsxReachOptions): ForeignJsxReach;
@@ -0,0 +1,68 @@
1
+ import { path } from '@ecopages/file-system/path';
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;
5
+ const SCANNED_SOURCE = /\.(?:[cm]?[jt]sx?|mdx?)$/;
6
+ /** `filePath` with symbolic links resolved, so paths from the build and from the scan compare equal. */
7
+ export function toRealPath(filePath) {
8
+ try {
9
+ return fileSystem.realpath(filePath);
10
+ }
11
+ catch {
12
+ return path.resolve(filePath);
13
+ }
14
+ }
15
+ function readImportSpecifiers(filePath) {
16
+ let source;
17
+ try {
18
+ source = fileSystem.readFileSync(filePath);
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ return [...source.matchAll(IMPORT_SPECIFIER)].map((match) => match[2]);
24
+ }
25
+ /**
26
+ * Walks the static imports of the app's own source files from `roots`, never into a file in `stopAt`, and
27
+ * returns each foreign file it reaches with the root that reached it first.
28
+ */
29
+ function collectForeignFiles(roots, stopAt, options) {
30
+ const foreign = new Map();
31
+ const visited = new Set();
32
+ const pending = [...roots].map((root) => [root, root]);
33
+ while (pending.length > 0) {
34
+ const [filePath, root] = pending.pop();
35
+ if (visited.has(filePath))
36
+ continue;
37
+ visited.add(filePath);
38
+ for (const specifier of readImportSpecifiers(filePath)) {
39
+ const resolved = resolveProjectModulePath(options.projectRoot, filePath, specifier, {
40
+ preserveBarrel: true,
41
+ });
42
+ if (!resolved || resolved.split('/').includes('node_modules'))
43
+ continue;
44
+ const target = toRealPath(resolved);
45
+ if (stopAt.has(target))
46
+ continue;
47
+ if (options.isForeignFile(target) && !foreign.has(target))
48
+ foreign.set(target, root);
49
+ if (SCANNED_SOURCE.test(target))
50
+ pending.push([target, root]);
51
+ }
52
+ }
53
+ return foreign;
54
+ }
55
+ /**
56
+ * Finds which foreign JSX files React entry files reach and which other entries reach, from static imports.
57
+ *
58
+ * @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
61
+ * React entry file, since React's bootstrap entries import their Page or island module.
62
+ */
63
+ export function scanForeignJsxReach(options) {
64
+ return {
65
+ react: new Set(collectForeignFiles(options.reactEntryFiles, new Set(), options).keys()),
66
+ others: collectForeignFiles(options.otherEntryFiles, options.reactEntryFiles, options),
67
+ };
68
+ }
@@ -1,13 +1,6 @@
1
- import path from 'node:path';
2
- /**
3
- * Splits a file path into OS-agnostic segments.
4
- *
5
- * @remarks
6
- * Bundlers may pass POSIX or Windows separators; classification must not depend
7
- * on the host's `path.sep` alone.
8
- */
1
+ import { path } from '@ecopages/file-system/path';
9
2
  function pathSegments(filePath) {
10
- return filePath.split(/[\\/]+/).filter(Boolean);
3
+ return filePath.split('/').filter(Boolean);
11
4
  }
12
5
  function hasPathSegment(filePath, segment) {
13
6
  return pathSegments(filePath).includes(segment);
@@ -31,7 +24,7 @@ export function classifyClientGraphModule(filePath, projectRoot) {
31
24
  if (projectRoot) {
32
25
  const resolvedRoot = path.resolve(projectRoot);
33
26
  const resolvedFile = path.resolve(filePath);
34
- if (resolvedFile === resolvedRoot || resolvedFile.startsWith(`${resolvedRoot}${path.sep}`)) {
27
+ if (resolvedFile === resolvedRoot || resolvedFile.startsWith(`${resolvedRoot}/`)) {
35
28
  return 'app';
36
29
  }
37
30
  }
@@ -1,4 +1,5 @@
1
1
  import { getExportedName, getLocalExportName, getReexportedImportName, isExplicitlyRequestedExport, } from './reachability-export-names.js';
2
+ import { walkScopedReferences } from './scope-walk.js';
2
3
  function markImportReachable(reachableImports, specifier, importedName) {
3
4
  let current = reachableImports.get(specifier);
4
5
  if (current === '*')
@@ -41,13 +42,7 @@ function createTraversalContext(topLevelImports, topLevelDeclarations, explicitl
41
42
  explicitlyRequestedExports,
42
43
  };
43
44
  }
44
- function visitExportAll(node, ctx) {
45
- if (typeof node.source?.value !== 'string')
46
- return false;
47
- markImportReachable(ctx.reachableImports, node.source.value, '*');
48
- return true;
49
- }
50
- function visitExportNamed(node, ctx, localScope) {
45
+ function visitExportNamed(node, ctx) {
51
46
  if (typeof node.source?.value === 'string') {
52
47
  for (const specifier of node.specifiers ?? []) {
53
48
  const importedName = getReexportedImportName(specifier);
@@ -66,53 +61,14 @@ function visitExportNamed(node, ctx, localScope) {
66
61
  continue;
67
62
  }
68
63
  const localName = getLocalExportName(specifier);
69
- if (localName && !localScope.has(localName)) {
64
+ if (localName)
70
65
  ctx.checkIdentifier(localName);
71
- }
72
- }
73
- return true;
74
- }
75
- function visitIdentifier(node, ctx, localScope) {
76
- if (!localScope.has(node.name)) {
77
- ctx.checkIdentifier(node.name);
78
- }
79
- return false;
80
- }
81
- function visitJsxIdentifier(node, ctx, localScope) {
82
- if (/^[A-Z]/.test(node.name) && !localScope.has(node.name)) {
83
- ctx.checkIdentifier(node.name);
84
- }
85
- return false;
86
- }
87
- function visitMemberExpression(node, ctx, localScope) {
88
- traverseNode(node.object, ctx, localScope);
89
- if (node.computed) {
90
- traverseNode(node.property, ctx, localScope);
91
66
  }
92
67
  return true;
93
68
  }
94
- function visitProperty(node, ctx, localScope) {
95
- if (node.computed)
96
- traverseNode(node.key, ctx, localScope);
97
- traverseNode(node.value, ctx, localScope);
98
- return true;
99
- }
100
- function visitJsxElement(node, ctx, localScope) {
101
- traverseNode(node.name, ctx, localScope);
102
- if (node.attributes) {
103
- for (const attr of node.attributes)
104
- traverseNode(attr, ctx, localScope);
105
- }
106
- return true;
107
- }
108
- function visitJsxMemberExpression(node, ctx, localScope) {
109
- traverseNode(node.object, ctx, localScope);
110
- return true;
111
- }
112
69
  function visitCallExpression(node, ctx) {
113
- if (node.callee?.type !== 'Identifier') {
114
- return false;
115
- }
70
+ if (node.callee?.type !== 'Identifier')
71
+ return;
116
72
  if (node.callee.name === 'dynamic') {
117
73
  const arg = node.arguments[0];
118
74
  if (arg && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
@@ -121,7 +77,7 @@ function visitCallExpression(node, ctx) {
121
77
  markImportReachable(ctx.reachableImports, body.source.value, '*');
122
78
  }
123
79
  }
124
- return false;
80
+ return;
125
81
  }
126
82
  if (node.callee.name === 'require') {
127
83
  const arg = node.arguments?.[0];
@@ -129,70 +85,44 @@ function visitCallExpression(node, ctx) {
129
85
  markImportReachable(ctx.reachableImports, arg.value, '*');
130
86
  }
131
87
  }
132
- return false;
133
- }
134
- function visitImportExpression(node, ctx) {
135
- if (node.source.type === 'Literal') {
136
- markImportReachable(ctx.reachableImports, node.source.value, '*');
137
- }
138
- return false;
139
- }
140
- function visitFunctionNode(node, ctx, localScope) {
141
- const newScope = new Set(localScope);
142
- if (node.id?.type === 'Identifier')
143
- newScope.add(node.id.name);
144
- if (node.params?.items) {
145
- for (const p of node.params.items) {
146
- if (p.pattern?.type === 'Identifier') {
147
- newScope.add(p.pattern.name);
148
- }
149
- }
150
- }
151
- traverseNode(node.body, ctx, newScope);
152
- return true;
153
88
  }
154
- const NODE_VISITORS = new Map([
155
- ['ExportAllDeclaration', visitExportAll],
156
- ['ExportNamedDeclaration', visitExportNamed],
157
- ['Identifier', visitIdentifier],
158
- ['JSXIdentifier', visitJsxIdentifier],
159
- ['MemberExpression', visitMemberExpression],
160
- ['Property', visitProperty],
161
- ['JSXOpeningElement', visitJsxElement],
162
- ['JSXClosingElement', visitJsxElement],
163
- ['JSXMemberExpression', visitJsxMemberExpression],
164
- ['CallExpression', visitCallExpression],
165
- ['ImportExpression', visitImportExpression],
166
- ['ArrowFunctionExpression', visitFunctionNode],
167
- ['FunctionExpression', visitFunctionNode],
168
- ['FunctionDeclaration', visitFunctionNode],
169
- ]);
170
- function traverseNode(node, ctx, localScope) {
171
- if (!node || typeof node !== 'object')
172
- return;
89
+ /**
90
+ * Records the import edges a node creates without naming a binding.
91
+ *
92
+ * @returns `true` when the node needs no further walk.
93
+ */
94
+ function visitImportEdges(node, ctx) {
173
95
  if (ctx.visitedNodes.has(node))
174
- return;
96
+ return true;
175
97
  ctx.visitedNodes.add(node);
176
- if (Array.isArray(node)) {
177
- for (const child of node)
178
- traverseNode(child, ctx, localScope);
179
- return;
180
- }
181
- const visitor = NODE_VISITORS.get(node.type);
182
- if (visitor?.(node, ctx, localScope))
183
- return;
184
- for (const key in node) {
185
- if (key !== 'type' && key !== 'start' && key !== 'end') {
186
- traverseNode(node[key], ctx, localScope);
187
- }
98
+ switch (node.type) {
99
+ case 'ExportAllDeclaration':
100
+ if (typeof node.source?.value !== 'string')
101
+ return false;
102
+ markImportReachable(ctx.reachableImports, node.source.value, '*');
103
+ return true;
104
+ case 'ExportNamedDeclaration':
105
+ return visitExportNamed(node, ctx);
106
+ case 'CallExpression':
107
+ visitCallExpression(node, ctx);
108
+ return false;
109
+ case 'ImportExpression':
110
+ if (node.source.type === 'Literal') {
111
+ markImportReachable(ctx.reachableImports, node.source.value, '*');
112
+ }
113
+ return false;
188
114
  }
115
+ return false;
189
116
  }
190
117
  export function runReachabilityTraversal(roots, topLevelImports, topLevelDeclarations, explicitlyRequestedExports) {
191
118
  const ctx = createTraversalContext(topLevelImports, topLevelDeclarations, explicitlyRequestedExports);
192
119
  ctx.queue.push(...roots);
120
+ const visitor = {
121
+ onReference: (name) => ctx.checkIdentifier(name),
122
+ onNode: (node) => visitImportEdges(node, ctx),
123
+ };
193
124
  while (ctx.queue.length > 0) {
194
- const root = ctx.queue.shift();
195
- traverseNode(root, ctx, new Set());
125
+ walkScopedReferences(ctx.queue.shift(), visitor);
196
126
  }
197
127
  return {
198
128
  reachableImports: ctx.reachableImports,