@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
@@ -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, resolveProjectModulePath } from '@ecopages/core/build';
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 = path.isAbsolute(specifier)
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' };
@@ -139,7 +137,7 @@ async function takeModule(build, state, sourcePath, options, transforms) {
139
137
  state.loadedEntries.set(realPath, module);
140
138
  return { module, plan };
141
139
  }
142
- async function loadClientGraphBoundaryModule(build, args, options, state, transforms, isEntrypoint = options.entrypointFile === path.resolve(options.absWorkingDir, args.path)) {
140
+ async function loadClientGraphBoundaryModule(build, args, options, state, transforms) {
143
141
  const sourcePath = path.resolve(options.absWorkingDir, args.path);
144
142
  if (options.entrypointFile &&
145
143
  options.groupedEntrypointFiles.has(sourcePath) &&
@@ -168,7 +166,6 @@ async function loadClientGraphBoundaryModule(build, args, options, state, transf
168
166
  category,
169
167
  globallyDeclaredSources,
170
168
  requestedExports: plan?.requestedExports(sourcePath),
171
- preserveUnreachableSideEffectImports: !isEntrypoint,
172
169
  });
173
170
  }
174
171
  function resolveEntryImports(entrypointFiles, entrypoint) {
@@ -238,7 +235,7 @@ function isTransformedByBuild(context) {
238
235
  return (filePath) => isTransformedSource(filePath, projectRoot) &&
239
236
  (!entrypointFiles.has(filePath) || reactEntrypointFiles.has(filePath));
240
237
  }
241
- function getForeignJsxReach(context, projectRoot, isForeignFile) {
238
+ function getForeignJsxReach(context, projectRoot, isForeignFile, reactModuleSource) {
242
239
  if (!context.foreignJsxReach) {
243
240
  const reactEntryFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
244
241
  context.foreignJsxReach = scanForeignJsxReach({
@@ -246,10 +243,33 @@ function getForeignJsxReach(context, projectRoot, isForeignFile) {
246
243
  reactEntryFiles,
247
244
  otherEntryFiles: [...context.entrypointFiles].map(toRealPath).filter((file) => !reactEntryFiles.has(file)),
248
245
  isForeignFile,
246
+ reactModuleSource,
249
247
  });
250
248
  }
251
249
  return context.foreignJsxReach;
252
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
+ }
253
273
  /**
254
274
  * The file itself when it is a browser entry of the build that no React entry file claims.
255
275
  *
@@ -280,7 +300,7 @@ export function createForeignJsxScope(options) {
280
300
  const owner = options.findForeignOwner(sourcePath);
281
301
  if (!context || context.configs.length === 0 || owner === undefined)
282
302
  return true;
283
- const reach = getForeignJsxReach(context, options.projectRoot, isForeignFile);
303
+ const reach = getForeignJsxReach(context, options.projectRoot, isForeignFile, options.reactModuleSource);
284
304
  const filePath = toRealPath(sourcePath);
285
305
  const otherEntry = reach.others.get(filePath) ?? findForeignEntry(context, filePath);
286
306
  if (otherEntry === undefined)
@@ -322,7 +342,7 @@ export function createClientGraphBoundaryPlugin(options) {
322
342
  loadedEntries: new Map(),
323
343
  };
324
344
  const transforms = () => (filePath) => isTransformedSource(filePath, normalizedOptions.projectRoot);
325
- build.onLoad(SOURCE_FILES, (loaded) => loadClientGraphBoundaryModule(build, stripVariant(loaded), normalizedOptions, state, transforms, entrypointFiles.has(path.resolve(normalizedOptions.absWorkingDir, stripVariant(loaded).path))));
345
+ build.onLoad(SOURCE_FILES, (loaded) => loadClientGraphBoundaryModule(build, stripVariant(loaded), normalizedOptions, state, transforms));
326
346
  return;
327
347
  }
328
348
  const context = getBuildContext(build.entrypoints, normalizedOptions);
@@ -334,7 +354,7 @@ export function createClientGraphBoundaryPlugin(options) {
334
354
  };
335
355
  }
336
356
  /** The files React entries reach and the files other entries reach, by a static scan of the build's entries. */
337
- function getEntryReach(context, projectRoot) {
357
+ function getEntryReach(context, projectRoot, reactModuleSource) {
338
358
  if (!context.entryReach) {
339
359
  const reactEntryFiles = new Set([...getReactEntrypointFiles(context)].map(toRealPath));
340
360
  const otherEntryFiles = [...context.entrypointFiles]
@@ -345,6 +365,7 @@ function getEntryReach(context, projectRoot) {
345
365
  reactEntryFiles,
346
366
  otherEntryFiles,
347
367
  isForeignFile: () => true,
368
+ reactModuleSource,
348
369
  });
349
370
  context.entryReach = {
350
371
  reactEntryFiles,
@@ -369,10 +390,23 @@ function getEntryReach(context, projectRoot) {
369
390
  * same rule. In a build without entries to compare, `isSharedFile` says which modules another graph uses.
370
391
  */
371
392
  export function createForeignBoundaryPlugin(options) {
393
+ const reactModuleSource = createReactModuleSource(options);
394
+ const { foreignModuleOf } = options;
372
395
  return {
373
396
  name: 'ecopages-react-foreign-boundary',
374
397
  environments: ['browser'],
375
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
+ }
376
410
  build.onLoad({ filter: /\?eco-variant=[\w-]+$/, exclude: /^\0|\/node_modules\// }, (loaded) => {
377
411
  const filePath = stripVariant(loaded).path;
378
412
  build.addWatchFile(filePath);
@@ -382,11 +416,13 @@ export function createForeignBoundaryPlugin(options) {
382
416
  };
383
417
  });
384
418
  build.transform({ filter: /\.(?:[cm]?[jt]sx?|mdx?)$/, exclude: /^\0|\/node_modules\// }, (code, id) => {
385
- const filePath = toRealPath(id.replace(/[?#].*$/, ''));
419
+ const filePath = id.replace(/[?#].*$/, '');
386
420
  if (options.isForeignFile(filePath))
387
421
  return undefined;
388
422
  const context = build.entrypoints ? buildContexts.get(build.entrypoints) : undefined;
389
- const reach = context && context.configs.length > 0 ? getEntryReach(context, options.projectRoot) : undefined;
423
+ const reach = context && context.configs.length > 0
424
+ ? getEntryReach(context, options.projectRoot, reactModuleSource)
425
+ : undefined;
390
426
  const inReactGraph = !reach ||
391
427
  isReactBoundaryVariant(id) ||
392
428
  reach.reactEntryFiles.has(filePath) ||
@@ -396,6 +432,8 @@ export function createForeignBoundaryPlugin(options) {
396
432
  return rewriteForeignImports(code, filePath, {
397
433
  projectRoot: options.projectRoot,
398
434
  isForeignFile: options.isForeignFile,
435
+ foreignModuleOf,
436
+ watchFile: (file) => build.addWatchFile(file),
399
437
  isSharedFile: reach
400
438
  ? (file) => reach.others.has(file) && reach.react.has(file)
401
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 is returned as `undefined`
28
- * too, since a build can hold more than one instance of the plugin. A namespace import is wrapped in a proxy.
29
- * Dynamic `import()` of a foreign module is left as it 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;
@@ -2,10 +2,11 @@
2
2
  * Source rewrite that gives a React module the boundary of every Eco Component another Integration owns.
3
3
  */
4
4
  import { fileSystem } from '@ecopages/file-system';
5
- import { parseModuleSource, resolveProjectModulePath } from '@ecopages/core/build';
5
+ import { parseModuleSource } from '@ecopages/core/build';
6
6
  import { FOREIGN_BOUNDARY_PACKAGE } from '../bundling/bootstrap-package-paths.js';
7
- import { toRealPath } from './foreign-jsx-reach.js';
8
7
  import { collectLexicalDeclarations, walkScopedReferences } from './scope-walk.js';
8
+ import { resolveLocalModulePath } from './foreign-jsx-reach.js';
9
+ import { exportSpecifierName, FOREIGN_STUB_SCHEME, toForeignStubSpecifier, } from './foreign-module.js';
9
10
  const HELPER_BINDING = '__ecoForeignBoundary';
10
11
  const NAMESPACE_HELPER_BINDING = '__ecoForeignBoundaryNamespace';
11
12
  /** The module variant a React graph imports of a module that another graph also uses and that imports a foreign Component. */
@@ -25,8 +26,7 @@ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/;
25
26
  * an export, so a barrel that re-exports a foreign Component counts as foreign for that name.
26
27
  *
27
28
  * @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.
29
+ * A file without a re-export is not parsed.
30
30
  */
31
31
  class ForeignExports {
32
32
  options;
@@ -34,11 +34,16 @@ class ForeignExports {
34
34
  constructor(options) {
35
35
  this.options = options;
36
36
  }
37
+ get projectRoot() {
38
+ return this.options.projectRoot;
39
+ }
40
+ /**
41
+ * @remarks
42
+ * An absolute path counts too: the MDX loader's attribution imports the Components of plain modules by
43
+ * absolute path before this rewrite runs.
44
+ */
37
45
  resolve(importer, specifier) {
38
- const resolved = resolveProjectModulePath(this.options.projectRoot, importer, specifier, {
39
- preserveBarrel: true,
40
- });
41
- return resolved ? toRealPath(resolved) : undefined;
46
+ return resolveLocalModulePath(this.options.projectRoot, importer, specifier);
42
47
  }
43
48
  getReexports(filePath) {
44
49
  let nodes = this.reexports.get(filePath);
@@ -91,7 +96,7 @@ class ForeignExports {
91
96
  const target = this.resolve(filePath, node.source.value);
92
97
  if (!target)
93
98
  continue;
94
- if (node.type === 'ImportDeclaration' && this.valueImportOf(node, target)) {
99
+ if (node.type === 'ImportDeclaration' ? this.valueImportOf(node, target) : this.staticModule(target)) {
95
100
  result = true;
96
101
  break;
97
102
  }
@@ -218,6 +223,23 @@ class ForeignExports {
218
223
  (name === undefined || moduleName(specifier.exported) === name) &&
219
224
  this.isForeign(target, moduleName(specifier.local), seen));
220
225
  }
226
+ /** The exports of `filePath` when it is a foreign file with static Components, whose stub React can load. */
227
+ staticModule(filePath) {
228
+ if (!this.options.foreignModuleOf || !this.options.isForeignFile(filePath))
229
+ return undefined;
230
+ const module = this.options.foreignModuleOf(filePath);
231
+ return module && module.identities.size > 0 ? module : undefined;
232
+ }
233
+ /**
234
+ * {@link staticModule} for a rewrite that uses it: the file is reported to `watchFile`, since a change to its
235
+ * exports changes the rewrite.
236
+ */
237
+ stubbedModule(filePath) {
238
+ const module = this.staticModule(filePath);
239
+ if (module)
240
+ this.options.watchFile?.(filePath);
241
+ return module;
242
+ }
221
243
  /** Whether the export `name` of `filePath` is declared by a foreign file; `undefined` asks about any export. */
222
244
  isForeign(filePath, name, seen = new Set()) {
223
245
  if (this.options.isForeignFile(filePath))
@@ -241,71 +263,197 @@ function importSourceOf(node, target, foreignExports) {
241
263
  ? `${specifier}?${VARIANT_QUERY}`
242
264
  : specifier;
243
265
  }
244
- /** The helper that wraps the export `imported` of `target`, or `undefined` when it is not foreign. */
266
+ /**
267
+ * The helper that wraps the export `imported` of `target`, or `undefined` when it is not foreign.
268
+ *
269
+ * @remarks
270
+ * A static Component a barrel re-exports from a stub module is already a boundary; wrapping it again returns it
271
+ * unchanged, since a boundary carries no identity.
272
+ */
245
273
  function boundaryHelperOf(foreignExports, target, imported) {
246
274
  if (foreignExports.isForeign(target, imported))
247
275
  return HELPER_BINDING;
248
276
  return foreignExports.isForeignNamespace(target, imported) ? NAMESPACE_HELPER_BINDING : undefined;
249
277
  }
278
+ /** Adds one named or default specifier of a rewritten import: wrapped when it needs the boundary, kept otherwise. */
279
+ function rewriteNamedSpecifier(specifier, target, foreignExports, uid, valueReads, rewrite) {
280
+ const local = specifier.local.name;
281
+ const imported = specifier.type === 'ImportDefaultSpecifier' ? 'default' : moduleName(specifier.imported);
282
+ const wrapper = valueReads.has(local) ? boundaryHelperOf(foreignExports, target, imported) : undefined;
283
+ if (!wrapper) {
284
+ rewrite.imports.push(`${JSON.stringify(imported)} as ${local}`);
285
+ return;
286
+ }
287
+ rewrite.foreign = true;
288
+ const temporary = `__eco_foreign_${uid()}`;
289
+ rewrite.imports.push(`${JSON.stringify(imported)} as ${temporary}`);
290
+ rewrite.bindings.push(`const ${local} = ${wrapper}(${temporary});`);
291
+ }
292
+ /** Adds a namespace specifier of a rewritten import: wrapped in the proxy when read, kept otherwise. */
293
+ function rewriteNamespaceSpecifier(local, target, from, foreignExports, uid, valueReads, rewrite) {
294
+ if (!valueReads.has(local) || !foreignExports.isForeign(target, undefined)) {
295
+ rewrite.extra.push(`import * as ${local} from ${from};`);
296
+ return;
297
+ }
298
+ rewrite.foreign = true;
299
+ const temporary = `__eco_foreign_${uid()}`;
300
+ rewrite.extra.push(`import * as ${temporary} from ${from};`);
301
+ rewrite.bindings.push(`const ${local} = ${NAMESPACE_HELPER_BINDING}(${temporary});`);
302
+ }
303
+ /** Whether a module's namespace is all static Components, so the stub module can stand for it whole. */
304
+ function isAllStatic(module) {
305
+ return module.values.size === 0 && !module.star;
306
+ }
307
+ /**
308
+ * Rewrites an import of a foreign file with static Components: those come from its stub module, every other value
309
+ * from the file behind the runtime boundary.
310
+ *
311
+ * @remarks
312
+ * A binding that is not a static Component and that the module never reads as a value is dropped with its type
313
+ * specifiers, so an import of Components alone never loads the file. A namespace import takes the stub when the
314
+ * file exports only static Components, and the file with the namespace proxy otherwise.
315
+ */
316
+ function rewriteForeignFileImport(node, module, stubFrom, uid, valueReads) {
317
+ const realFrom = JSON.stringify(node.source.value);
318
+ const stubbed = [];
319
+ const real = [];
320
+ const lines = [];
321
+ const bindings = [];
322
+ for (const specifier of node.specifiers) {
323
+ if (specifier.importKind === 'type')
324
+ continue;
325
+ const local = specifier.local.name;
326
+ if (specifier.type === 'ImportNamespaceSpecifier') {
327
+ if (isAllStatic(module)) {
328
+ lines.push(`import * as ${local} from ${stubFrom};`);
329
+ }
330
+ else if (valueReads.has(local)) {
331
+ const temporary = `__eco_foreign_${uid()}`;
332
+ lines.push(`import * as ${temporary} from ${realFrom};`);
333
+ bindings.push(`const ${local} = ${NAMESPACE_HELPER_BINDING}(${temporary});`);
334
+ }
335
+ continue;
336
+ }
337
+ const imported = specifier.type === 'ImportDefaultSpecifier' ? 'default' : moduleName(specifier.imported);
338
+ if (module.identities.has(imported)) {
339
+ stubbed.push(`${JSON.stringify(imported)} as ${local}`);
340
+ }
341
+ else if (valueReads.has(local)) {
342
+ const temporary = `__eco_foreign_${uid()}`;
343
+ real.push(`${JSON.stringify(imported)} as ${temporary}`);
344
+ bindings.push(`const ${local} = ${HELPER_BINDING}(${temporary});`);
345
+ }
346
+ }
347
+ if (stubbed.length > 0)
348
+ lines.unshift(`import { ${stubbed.join(', ')} } from ${stubFrom};`);
349
+ if (real.length > 0)
350
+ lines.push(`import { ${real.join(', ')} } from ${realFrom};`);
351
+ return [...lines, ...bindings].join(' ');
352
+ }
250
353
  /**
251
354
  * Rewrites an import declaration so each binding that resolves to a foreign Component goes through the boundary.
252
355
  *
253
356
  * @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.
357
+ * The declaration keeps its line: the replacement holds no newline, so positions after it stay valid. An import of
358
+ * a foreign file with static Components takes them from its stub module (see {@link rewriteForeignFileImport}).
359
+ * Otherwise only a binding the module reads as a value, and that is not a static Component a barrel already
360
+ * re-exports as a boundary, is wrapped; a type or an unused binding keeps its plain import, so the bundler drops
361
+ * it as it would without the rewrite.
257
362
  */
258
363
  function rewriteImport(node, source, filePath, foreignExports, uid, valueReads) {
259
364
  if (node.importKind === 'type' || !node.specifiers?.length)
260
365
  return undefined;
261
- const target = foreignExports.resolve(filePath, node.source.value);
366
+ const specifier = node.source.value;
367
+ const target = foreignExports.resolve(filePath, specifier);
262
368
  if (!target)
263
369
  return undefined;
370
+ const module = specifier.includes('?') ? undefined : foreignExports.stubbedModule(target);
371
+ if (module) {
372
+ const stubFrom = JSON.stringify(toForeignStubSpecifier(foreignExports.projectRoot, target));
373
+ return rewriteForeignFileImport(node, module, stubFrom, uid, valueReads);
374
+ }
264
375
  const from = JSON.stringify(importSourceOf(node, target, foreignExports));
265
- const imports = [];
266
- const extra = [];
267
- const bindings = [];
268
- let foreign = false;
376
+ const rewrite = { imports: [], extra: [], bindings: [], foreign: false };
269
377
  for (const specifier of node.specifiers) {
270
378
  if (specifier.importKind === 'type') {
271
- imports.push(source.slice(specifier.start, specifier.end));
272
- continue;
379
+ rewrite.imports.push(source.slice(specifier.start, specifier.end));
273
380
  }
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;
381
+ else if (specifier.type === 'ImportNamespaceSpecifier') {
382
+ rewriteNamespaceSpecifier(specifier.local.name, target, from, foreignExports, uid, valueReads, rewrite);
285
383
  }
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;
384
+ else {
385
+ rewriteNamedSpecifier(specifier, target, foreignExports, uid, valueReads, rewrite);
291
386
  }
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
387
  }
297
- if (!foreign)
388
+ if (!rewrite.foreign)
298
389
  return undefined;
299
- const named = imports.length > 0 ? `import { ${imports.join(', ')} } from ${from};` : '';
300
- return [named, ...extra, ...bindings].filter(Boolean).join(' ');
390
+ const named = rewrite.imports.length > 0 ? `import { ${rewrite.imports.join(', ')} } from ${from};` : '';
391
+ return [named, ...rewrite.extra, ...rewrite.bindings].filter(Boolean).join(' ');
301
392
  }
302
- /** The edit one top-level node needs: wrapped bindings, or the variant id for a shared module that reaches a foreign Component. */
393
+ /** {@link rewriteReexport} for `export * from` and `export * as ns from`. */
394
+ function rewriteStarReexport(node, module, stubFrom, realFrom) {
395
+ if (node.exported) {
396
+ return isAllStatic(module)
397
+ ? `export * as ${exportSpecifierName(moduleName(node.exported))} from ${stubFrom};`
398
+ : undefined;
399
+ }
400
+ const components = [...module.identities.keys()].filter((name) => name !== 'default');
401
+ if (components.length === 0)
402
+ return undefined;
403
+ const values = [...module.values].filter((name) => name !== 'default');
404
+ return [
405
+ `export { ${components.map(exportSpecifierName).join(', ')} } from ${stubFrom};`,
406
+ ...(values.length > 0 ? [`export { ${values.map(exportSpecifierName).join(', ')} } from ${realFrom};`] : []),
407
+ ...(module.star ? [`export * from ${realFrom};`] : []),
408
+ ].join(' ');
409
+ }
410
+ /**
411
+ * Rewrites a re-export of a foreign file with static Components, so a barrel never loads the file for them: the
412
+ * Components come from its stub module, every other value from the file.
413
+ *
414
+ * @remarks
415
+ * `export * from` re-exports the stub's Components by name, plus the file's other value names, and the file's own
416
+ * `export *` when it has one, whose names are unknown here: an explicit name wins over a star-exported one, so the
417
+ * file's star does not clash with the stub. `default` is never part of `export *`. `export * as ns from` takes the
418
+ * stub only when the file exports static Components alone. Type-only names are dropped, since the build erases
419
+ * them. A re-export of no static Component, or of a specifier with a query, is left as written.
420
+ */
421
+ function rewriteReexport(node, filePath, foreignExports) {
422
+ const specifier = node.source.value;
423
+ const target = specifier.includes('?') ? undefined : foreignExports.resolve(filePath, specifier);
424
+ const module = target ? foreignExports.stubbedModule(target) : undefined;
425
+ if (!target || !module)
426
+ return undefined;
427
+ const stubFrom = JSON.stringify(toForeignStubSpecifier(foreignExports.projectRoot, target));
428
+ const realFrom = JSON.stringify(specifier);
429
+ if (node.type === 'ExportAllDeclaration')
430
+ return rewriteStarReexport(node, module, stubFrom, realFrom);
431
+ const stubbed = [];
432
+ const real = [];
433
+ for (const exported of node.specifiers) {
434
+ if (exported.exportKind === 'type')
435
+ continue;
436
+ const local = moduleName(exported.local);
437
+ const text = `${exportSpecifierName(local)} as ${exportSpecifierName(moduleName(exported.exported))}`;
438
+ (module.identities.has(local) ? stubbed : real).push(text);
439
+ }
440
+ if (stubbed.length === 0)
441
+ return undefined;
442
+ return [
443
+ `export { ${stubbed.join(', ')} } from ${stubFrom};`,
444
+ ...(real.length > 0 ? [`export { ${real.join(', ')} } from ${realFrom};`] : []),
445
+ ].join(' ');
446
+ }
447
+ /**
448
+ * The edit one top-level node needs: a rewritten import or re-export, or the variant id for a shared module that
449
+ * reaches a foreign Component.
450
+ */
303
451
  function planEdit(node, code, filePath, foreignExports, uid, valueReads) {
304
452
  if (!node.source || (node.importKind ?? node.exportKind) === 'type')
305
453
  return undefined;
306
454
  const replacement = node.type === 'ImportDeclaration'
307
455
  ? rewriteImport(node, code, filePath, foreignExports, uid, valueReads)
308
- : undefined;
456
+ : rewriteReexport(node, filePath, foreignExports);
309
457
  if (replacement !== undefined)
310
458
  return { start: node.start, end: node.end, replacement };
311
459
  const specifier = node.source.value;
@@ -326,13 +474,16 @@ function planEdit(node, code, filePath, foreignExports, uid, valueReads) {
326
474
  *
327
475
  * @remarks
328
476
  * 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.
477
+ * to the same output as before and ships no boundary code. A module already rewritten, one that imports the
478
+ * boundary package or a stub module, is returned as `undefined` too, since a build can hold more than one
479
+ * instance of the plugin and a second pass would duplicate re-exports. Dynamic `import()` of a foreign module is
480
+ * left as it is.
332
481
  */
333
482
  export function rewriteForeignImports(code, filePath, options) {
334
483
  if (!/\bimport\b|\bexport\b/.test(code) || code.includes(FOREIGN_BOUNDARY_PACKAGE))
335
484
  return undefined;
485
+ if (code.includes(FOREIGN_STUB_SCHEME))
486
+ return undefined;
336
487
  const lang = /\.(?:mdx?)$/.test(filePath) ? 'jsx' : undefined;
337
488
  const { program } = parseModuleSource(filePath, code, lang ? { lang } : {});
338
489
  let counter = 0;
@@ -5,6 +5,16 @@ export type ForeignJsxReachOptions = {
5
5
  /** Every other entry file of the build. */
6
6
  otherEntryFiles: Iterable<string>;
7
7
  isForeignFile: (filePath: string) => boolean;
8
+ /**
9
+ * The source of a module as React's graph compiles it, or `undefined` to keep it; applied on the walks from
10
+ * React entry files only.
11
+ *
12
+ * @remarks
13
+ * React's rewrite points an import of a foreign file's static Components at the file's stub module, which this
14
+ * walk does not follow, so a walk that read the original source would count that file and its imports as reached
15
+ * by React.
16
+ */
17
+ reactModuleSource?: (filePath: string, source: string) => string | undefined;
8
18
  };
9
19
  export type ForeignJsxReach = {
10
20
  /** Foreign files a React entry file reaches. */
@@ -14,12 +24,21 @@ export type ForeignJsxReach = {
14
24
  };
15
25
  /** `filePath` with symbolic links resolved, so paths from the build and from the scan compare equal. */
16
26
  export declare function toRealPath(filePath: string): string;
27
+ /**
28
+ * Resolves a specifier to a local file: a relative or tsconfig path import of the app's own files, or an absolute
29
+ * file path that exists.
30
+ *
31
+ * @remarks
32
+ * Core's grouped content-script entries import each script by its absolute path, so without the absolute case a
33
+ * script reached only through such an entry would be absent from the scan.
34
+ */
35
+ export declare function resolveLocalModulePath(projectRoot: string, fromFile: string, specifier: string): string | undefined;
17
36
  /**
18
37
  * Finds which foreign JSX files React entry files reach and which other entries reach, from static imports.
19
38
  *
20
39
  * @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
40
+ * It runs before any module loads, so the answer does not depend on load order. Only relative, tsconfig path
41
+ * and absolute path imports of the app's own files are followed; packages are never scanned. A walk from another entry stops at a
23
42
  * React entry file, since React's bootstrap entries import their Page or island module.
24
43
  */
25
44
  export declare function scanForeignJsxReach(options: ForeignJsxReachOptions): ForeignJsxReach;