@ecopages/react 0.2.0-beta.2 → 0.2.0-beta.21

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 (30) hide show
  1. package/README.md +12 -0
  2. package/package.json +21 -4
  3. package/src/layout-compose.d.ts +58 -0
  4. package/src/layout-compose.js +98 -0
  5. package/src/react-hmr-strategy.d.ts +16 -0
  6. package/src/react-hmr-strategy.js +142 -113
  7. package/src/react-renderer.d.ts +34 -13
  8. package/src/react-renderer.js +187 -84
  9. package/src/react.plugin.js +6 -27
  10. package/src/serialize-page-data-script.d.ts +8 -0
  11. package/src/serialize-page-data-script.js +10 -0
  12. package/src/services/react-bundle.service.d.ts +3 -2
  13. package/src/services/react-bundle.service.js +17 -8
  14. package/src/services/react-mdx-config-dependency.service.js +5 -7
  15. package/src/services/react-page-module.service.d.ts +4 -43
  16. package/src/services/react-page-module.service.js +0 -90
  17. package/src/services/react-page-payload.service.js +2 -2
  18. package/src/services/react-runtime-bundle.service.d.ts +5 -1
  19. package/src/services/react-runtime-bundle.service.js +8 -2
  20. package/src/utils/client-graph-ast-transform.d.ts +18 -0
  21. package/src/utils/client-graph-ast-transform.js +335 -0
  22. package/src/utils/client-graph-boundary-plugin.d.ts +1 -12
  23. package/src/utils/client-graph-boundary-plugin.js +8 -454
  24. package/src/utils/client-graph-reachability.d.ts +75 -0
  25. package/src/utils/client-graph-reachability.js +148 -0
  26. package/src/utils/component-config-traversal.js +4 -2
  27. package/src/utils/hydration-scripts.d.ts +2 -0
  28. package/src/utils/hydration-scripts.js +27 -14
  29. package/src/utils/react-mdx-loader-plugin.d.ts +2 -3
  30. package/src/utils/react-mdx-loader-plugin.js +5 -39
@@ -2,8 +2,8 @@
2
2
  * This module contains the React renderer
3
3
  * @module
4
4
  */
5
- import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
6
- import { IntegrationRenderer, type HtmlDocumentContribution, type HtmlDocumentContributionContext, type PageBrowserGraphContributionContext, type RenderToResponseContext, type RouteModuleLoadOptions } from '@ecopages/core/route-renderer/integration-renderer';
5
+ import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, IntegrationRendererRenderOptions, PageMetadataProps, RouteRendererBody } from '@ecopages/core';
6
+ import { IntegrationRenderer, type HtmlDocumentContribution, type HtmlDocumentContributionContext, type PageBrowserGraphContributionContext, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
7
7
  import type { AssetDefinition, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
8
8
  import type { ReactNode } from 'react';
9
9
  import type { ReactRendererConfig } from './react.types.js';
@@ -12,10 +12,12 @@ import { ReactMdxConfigDependencyService } from './services/react-mdx-config-dep
12
12
  import { ReactPageModuleService } from './services/react-page-module.service.js';
13
13
  import { ReactPagePayloadService } from './services/react-page-payload.service.js';
14
14
  import { ReactHydrationAssetService } from './services/react-hydration-asset.service.js';
15
+ import { type DocumentShellLayoutInput } from '@ecopages/core/route-renderer/orchestration/document-shell-render.service';
16
+ import { type ReactRuntime } from './layout-compose.js';
15
17
  export type { ReactRendererConfig } from './react.types.js';
16
18
  type ReactRuntimeModules = {
17
- react: Pick<typeof import('react'), 'createElement' | 'Fragment'>;
18
- reactDomServer: Pick<typeof import('react-dom/server'), 'renderToReadableStream' | 'renderToString'>;
19
+ react: ReactRuntime;
20
+ reactDomServer: typeof import('react-dom/server');
19
21
  };
20
22
  export type ReactRendererOptions = ConstructorParameters<typeof IntegrationRenderer>[0] & {
21
23
  reactConfig?: ReactRendererConfig;
@@ -128,8 +130,8 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
128
130
  * @returns Serialized component HTML with resolved child markup preserved.
129
131
  */
130
132
  private renderComponentHtml;
133
+ private toReactNode;
131
134
  /**
132
- * Restores raw child HTML that was temporarily replaced by a token during React SSR.
133
135
  *
134
136
  * Queued foreign-subtree resolution may render children through a fragment path before all
135
137
  * nested integration tokens are resolved. When that happens, React must never see
@@ -149,13 +151,9 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
149
151
  private renderQueuedChildrenToHtml;
150
152
  /**
151
153
  * Resolves queued renderer-owned foreign-subtree tokens produced during React component rendering.
152
- *
153
- * React components can enqueue nested foreign subtrees while the parent HTML is being
154
- * rendered. This delegates to the shared renderer-owned queue resolver but keeps
155
- * the React-specific child rendering behavior local so raw child HTML and React's
156
- * fragment rendering semantics stay coordinated.
157
154
  */
158
- private resolveQueuedForeignSubtreeHtml;
155
+ private renderReactQueuedForeignSubtreeChildren;
156
+ private resolveReactQueuedForeignSubtreeHtml;
159
157
  private buildHydrationProps;
160
158
  /**
161
159
  * Builds shared document html contributions for router-backed React pages rendered
@@ -203,13 +201,30 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
203
201
  * @returns True if the file is an MDX file
204
202
  */
205
203
  isMdxFile(filePath: string): boolean;
206
- protected usesIntegrationPageImporter(file: string): boolean;
207
- protected importIntegrationPageFile(file: string, options?: RouteModuleLoadOptions): Promise<EcoPageFile>;
208
204
  protected normalizeImportedPageFile<TPageModule extends EcoPageFile>(file: string, pageModule: TPageModule): TPageModule;
209
205
  protected collectPageBrowserGraphContribution(context: PageBrowserGraphContributionContext): Promise<{
210
206
  dependencies?: AssetDefinition[];
211
207
  assets?: ProcessedAsset[];
212
208
  }>;
209
+ /**
210
+ * Composes page and layout tiers as one React element tree for SSR.
211
+ */
212
+ private composeReactLayoutPageChildren;
213
+ private composeReactLayoutPageTree;
214
+ private shouldUseUnifiedReactLayoutComposition;
215
+ protected renderPageWithDocumentShell(input: {
216
+ page: {
217
+ component: EcoComponent;
218
+ props: Record<string, unknown>;
219
+ };
220
+ layout?: DocumentShellLayoutInput;
221
+ layouts?: DocumentShellLayoutInput[];
222
+ htmlTemplate: EcoComponent;
223
+ metadata: PageMetadataProps;
224
+ pageProps: Record<string, unknown>;
225
+ documentProps?: Record<string, unknown>;
226
+ transformDocumentHtml?: (html: string) => string;
227
+ }): Promise<string>;
213
228
  /**
214
229
  * Renders a full route response for the filesystem page pipeline.
215
230
  *
@@ -221,6 +236,12 @@ export declare class ReactRenderer extends IntegrationRenderer<ReactNode> {
221
236
  render({ params, query, props, locals, pageLocals, metadata, Page, Layout, HtmlTemplate, pageProps, }: IntegrationRendererRenderOptions<ReactNode>): Promise<RouteRendererBody>;
222
237
  protected getHtmlDocumentContributions(options: HtmlDocumentContributionContext<ReactNode>): HtmlDocumentContribution[] | undefined;
223
238
  protected getDocumentAttributes(): Record<string, string> | undefined;
239
+ protected renderViewWithDocumentShell<P>(input: {
240
+ view: EcoComponent<P>;
241
+ props: P;
242
+ ctx: RenderToResponseContext;
243
+ layout?: EcoComponent;
244
+ }): Promise<Response>;
224
245
  /**
225
246
  * Renders an arbitrary React view through the application's HTML shell.
226
247
  *
@@ -2,10 +2,11 @@ import {
2
2
  IntegrationRenderer
3
3
  } from "@ecopages/core/route-renderer/integration-renderer";
4
4
  import { RESOLVED_ASSETS_DIR } from "@ecopages/core/constants";
5
- import { getAppBuildExecutor } from "@ecopages/core/build/build-adapter";
6
5
  import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from "@ecopages/core/router/navigation-coordinator";
6
+ import { ensurePageConfigLayouts } from "@ecopages/core/eco/page-layout-normalization";
7
7
  import { createRequire } from "node:module";
8
8
  import path from "node:path";
9
+ import { isValidElement } from "react";
9
10
  import { REACT_PLUGIN_NAME } from "./react.constants.js";
10
11
  import { hasSingleRootElement } from "./utils/html-boundary.js";
11
12
  import { ReactBundleService } from "./services/react-bundle.service.js";
@@ -14,6 +15,16 @@ import { ReactMdxConfigDependencyService } from "./services/react-mdx-config-dep
14
15
  import { ReactPageModuleService } from "./services/react-page-module.service.js";
15
16
  import { ReactPagePayloadService } from "./services/react-page-payload.service.js";
16
17
  import { getReactIslandComponentKey, ReactHydrationAssetService } from "./services/react-hydration-asset.service.js";
18
+ import {
19
+ composeDocumentShell,
20
+ renderPageDocumentShell
21
+ } from "@ecopages/core/route-renderer/orchestration/document-shell-render.service";
22
+ import {
23
+ composeLayoutPageTree,
24
+ composeLayoutPageTreeFromShell,
25
+ assertComposablePage,
26
+ resolveLayoutContextFromShell
27
+ } from "./layout-compose.js";
17
28
  class ReactRenderError extends Error {
18
29
  constructor(message) {
19
30
  super(message);
@@ -63,19 +74,17 @@ class ReactRenderer extends IntegrationRenderer {
63
74
  this.explicitGraphEnabled = reactConfig?.explicitGraphEnabled ?? false;
64
75
  this.bundleService = new ReactBundleService({
65
76
  rootDir: this.appConfig.rootDir,
77
+ appConfig: this.appConfig,
78
+ hostIntegrationName: this.name,
66
79
  routerAdapter: this.routerAdapter,
67
- mdxCompilerOptions: this.mdxCompilerOptions,
68
- jsxImportSource: (this.appConfig.integrations ?? []).find((integration) => integration.name === this.name)?.jsxImportSource,
69
- nonReactExtensions: (this.appConfig.integrations ?? []).filter((integration) => integration.name !== this.name).flatMap((integration) => integration.extensions)
80
+ mdxCompilerOptions: this.mdxCompilerOptions
70
81
  });
71
82
  this.pageModuleService = new ReactPageModuleService({
72
83
  rootDir: this.appConfig.rootDir,
73
84
  distDir: this.appConfig.absolutePaths.distDir,
74
85
  workDir: this.appConfig.absolutePaths.workDir,
75
- buildExecutor: getAppBuildExecutor(this.appConfig),
76
86
  layoutsDir: this.appConfig.absolutePaths.layoutsDir,
77
87
  componentsDir: this.appConfig.absolutePaths.componentsDir,
78
- mdxCompilerOptions: this.mdxCompilerOptions,
79
88
  mdxExtensions: this.mdxExtensions,
80
89
  integrationName: this.name,
81
90
  hasRouterAdapter: Boolean(this.routerAdapter)
@@ -215,6 +224,13 @@ class ReactRenderer extends IntegrationRenderer {
215
224
  reactDomServer.renderToString(react.createElement(this.asReactComponent(input.component), input.props))
216
225
  );
217
226
  }
227
+ if (isValidElement(input.children)) {
228
+ return this.normalizeUnresolvedMarkerArtifactHtml(
229
+ reactDomServer.renderToString(
230
+ react.createElement(this.asReactComponent(input.component), input.props, input.children)
231
+ )
232
+ );
233
+ }
218
234
  const resolvedChildHtml = typeof input.children === "string" ? input.children : String(input.children ?? "");
219
235
  const rawChildrenToken = `__ECO_RAW_HTML_CHILD_${context.componentInstanceId ?? "component"}__`;
220
236
  if (runtimeContext) {
@@ -226,8 +242,13 @@ class ReactRenderer extends IntegrationRenderer {
226
242
  );
227
243
  return this.normalizeUnresolvedMarkerArtifactHtml(html.split(rawChildrenToken).join(resolvedChildHtml));
228
244
  }
245
+ toReactNode(children) {
246
+ if (children === null || typeof children === "string" || typeof children === "number" || typeof children === "boolean" || isValidElement(children) || Array.isArray(children)) {
247
+ return children;
248
+ }
249
+ throw new TypeError(`[ecopages] ${this.name} renderer expected a React node child.`);
250
+ }
229
251
  /**
230
- * Restores raw child HTML that was temporarily replaced by a token during React SSR.
231
252
  *
232
253
  * Queued foreign-subtree resolution may render children through a fragment path before all
233
254
  * nested integration tokens are resolved. When that happens, React must never see
@@ -255,7 +276,7 @@ class ReactRenderer extends IntegrationRenderer {
255
276
  }
256
277
  const { react, reactDomServer } = this.getReactRuntimeModules();
257
278
  let html = this.normalizeUnresolvedMarkerArtifactHtml(
258
- reactDomServer.renderToString(react.createElement(react.Fragment, null, children))
279
+ reactDomServer.renderToString(react.createElement(react.Fragment, null, this.toReactNode(children)))
259
280
  );
260
281
  html = this.restoreRuntimeChildHtml(html, runtimeContext);
261
282
  html = await this.foreignSubtreeExecutionService.resolveQueuedTokens(
@@ -267,34 +288,34 @@ class ReactRenderer extends IntegrationRenderer {
267
288
  }
268
289
  /**
269
290
  * Resolves queued renderer-owned foreign-subtree tokens produced during React component rendering.
270
- *
271
- * React components can enqueue nested foreign subtrees while the parent HTML is being
272
- * rendered. This delegates to the shared renderer-owned queue resolver but keeps
273
- * the React-specific child rendering behavior local so raw child HTML and React's
274
- * fragment rendering semantics stay coordinated.
275
291
  */
276
- async resolveQueuedForeignSubtreeHtml(html, runtimeContext) {
277
- return this.foreignSubtreeExecutionService.resolveQueuedHtml({
278
- currentIntegrationName: this.name,
292
+ async renderReactQueuedForeignSubtreeChildren(children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) {
293
+ const renderedHtml = await this.renderQueuedChildrenToHtml(
294
+ children,
295
+ currentRuntimeContext,
296
+ queuedResolutionsByToken,
297
+ resolveToken
298
+ );
299
+ if (renderedHtml === void 0) {
300
+ return { assets: [] };
301
+ }
302
+ return {
303
+ assets: [],
304
+ html: renderedHtml
305
+ };
306
+ }
307
+ resolveReactQueuedForeignSubtreeHtml(html, runtimeContext) {
308
+ return this.resolveQueuedForeignSubtreeHtml(
279
309
  html,
280
310
  runtimeContext,
281
- queueLabel: "React",
282
- getOwningRenderer: (integrationName, rendererCache) => this.getIntegrationRendererForName(integrationName, rendererCache),
283
- applyAttributesToFirstElement: (resolvedHtml, attributes) => this.htmlTransformer.applyAttributesToFirstElement(resolvedHtml, attributes),
284
- dedupeProcessedAssets: (assets) => this.htmlTransformer.dedupeProcessedAssets(assets),
285
- renderQueuedChildren: async (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => {
286
- const renderedHtml = await this.renderQueuedChildrenToHtml(
287
- children,
288
- currentRuntimeContext,
289
- queuedResolutionsByToken,
290
- resolveToken
291
- );
292
- return {
293
- assets: [],
294
- html: renderedHtml
295
- };
296
- }
297
- });
311
+ (children, currentRuntimeContext, queuedResolutionsByToken, resolveToken) => this.renderReactQueuedForeignSubtreeChildren(
312
+ children,
313
+ currentRuntimeContext,
314
+ queuedResolutionsByToken,
315
+ resolveToken
316
+ ),
317
+ "React"
318
+ );
298
319
  }
299
320
  buildHydrationProps(props) {
300
321
  if (!props || !Object.prototype.hasOwnProperty.call(props, "locals")) {
@@ -341,7 +362,7 @@ class ReactRenderer extends IntegrationRenderer {
341
362
  const hasDependencies = Boolean(input.component.config?.dependencies);
342
363
  const canResolveAssets = typeof this.assetProcessingService?.processDependencies === "function";
343
364
  const assets = hasDependencies && canResolveAssets ? await this.processComponentDependencies([input.component]) : void 0;
344
- const queuedForeignSubtreeResolution = await this.resolveQueuedForeignSubtreeHtml(html, runtimeContext);
365
+ const queuedForeignSubtreeResolution = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
345
366
  const mergedAssets = this.htmlTransformer.dedupeProcessedAssets([
346
367
  ...assets ?? [],
347
368
  ...queuedForeignSubtreeResolution.assets
@@ -368,7 +389,7 @@ class ReactRenderer extends IntegrationRenderer {
368
389
  };
369
390
  const hasResolvedChildHtml = input.children !== void 0;
370
391
  let html = this.renderComponentHtml(input, context, runtimeContext);
371
- const queuedForeignSubtreeResolution = await this.resolveQueuedForeignSubtreeHtml(html, runtimeContext);
392
+ const queuedForeignSubtreeResolution = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
372
393
  html = queuedForeignSubtreeResolution.html;
373
394
  const canAttachAttributes = hasSingleRootElement(html);
374
395
  const rootTag = this.getRootTagName(html);
@@ -440,16 +461,11 @@ class ReactRenderer extends IntegrationRenderer {
440
461
  isMdxFile(filePath) {
441
462
  return this.pageModuleService.isMdxFile(filePath);
442
463
  }
443
- usesIntegrationPageImporter(file) {
444
- return this.pageModuleService.isMdxFile(file);
445
- }
446
- async importIntegrationPageFile(file, options) {
447
- return await this.pageModuleService.importMdxPageFile(file, options);
448
- }
449
464
  normalizeImportedPageFile(file, pageModule) {
450
465
  const reactModule = pageModule;
451
466
  const { default: Page, getMetadata, config } = reactModule;
452
467
  if (this.pageModuleService.isMdxFile(file) && config) {
468
+ ensurePageConfigLayouts(config);
453
469
  Page.config = config;
454
470
  }
455
471
  return {
@@ -492,6 +508,77 @@ class ReactRenderer extends IntegrationRenderer {
492
508
  );
493
509
  }
494
510
  }
511
+ /**
512
+ * Composes page and layout tiers as one React element tree for SSR.
513
+ */
514
+ async composeReactLayoutPageChildren(page, context) {
515
+ const pageComponent = assertComposablePage(page.component);
516
+ const shellEntries = context.layouts.map((layout) => ({
517
+ component: layout.component,
518
+ props: layout.props
519
+ }));
520
+ const { react, reactDomServer } = this.getReactRuntimeModules();
521
+ const tree = this.composeReactLayoutPageTree(pageComponent, page.props, shellEntries, {
522
+ context: resolveLayoutContextFromShell(page.props, shellEntries),
523
+ react
524
+ });
525
+ const runtimeInput = {
526
+ component: page.component,
527
+ props: page.props,
528
+ integrationContext: {
529
+ rendererCache: context.rendererCache
530
+ }
531
+ };
532
+ const runtimeContext = this.getQueuedForeignSubtreeResolutionContext(runtimeInput);
533
+ let html = this.normalizeUnresolvedMarkerArtifactHtml(reactDomServer.renderToString(tree));
534
+ const resolved = await this.resolveReactQueuedForeignSubtreeHtml(html, runtimeContext);
535
+ const primaryRender = {
536
+ html: resolved.html,
537
+ canAttachAttributes: hasSingleRootElement(resolved.html),
538
+ rootTag: this.getRootTagName(resolved.html),
539
+ integrationName: this.name,
540
+ assets: resolved.assets.length > 0 ? resolved.assets : void 0
541
+ };
542
+ return {
543
+ children: resolved.html,
544
+ layoutRenders: [],
545
+ primaryRender
546
+ };
547
+ }
548
+ composeReactLayoutPageTree(Page, pageProps, shellEntries, options) {
549
+ const hasNormalizedLayouts = Boolean(Page.config?.layoutEntries?.length) || Boolean(Page.config?.layouts?.length);
550
+ if (hasNormalizedLayouts) {
551
+ return composeLayoutPageTree(Page, pageProps, options);
552
+ }
553
+ return composeLayoutPageTreeFromShell(Page, pageProps, shellEntries, options);
554
+ }
555
+ shouldUseUnifiedReactLayoutComposition(page, shellLayouts) {
556
+ if (!this.isReactManagedComponent(page)) {
557
+ return false;
558
+ }
559
+ const composablePage = assertComposablePage(page);
560
+ const configLayouts = composablePage.config?.layouts ?? composablePage.config?.layoutEntries?.map((entry) => entry.component) ?? [];
561
+ const layoutComponents = shellLayouts.length > 0 ? shellLayouts.map((layout) => layout.component) : configLayouts;
562
+ if (layoutComponents.length === 0) {
563
+ return false;
564
+ }
565
+ return layoutComponents.every((component) => this.isReactManagedComponent(component));
566
+ }
567
+ async renderPageWithDocumentShell(input) {
568
+ const shellLayouts = input.layouts ?? (input.layout ? [input.layout] : []);
569
+ const composeChildren = this.shouldUseUnifiedReactLayoutComposition(input.page.component, shellLayouts) ? (context) => this.composeReactLayoutPageChildren(input.page, context) : void 0;
570
+ return renderPageDocumentShell(
571
+ {
572
+ renderComponentWithForeignChildren: (renderInput) => this.renderComponentWithForeignChildren(renderInput),
573
+ appendProcessedDependencies: (...assetGroups) => this.appendProcessedDependencies(...assetGroups)
574
+ },
575
+ {
576
+ ...input,
577
+ composeChildren
578
+ },
579
+ this.DOC_TYPE
580
+ );
581
+ }
495
582
  /**
496
583
  * Renders a full route response for the filesystem page pipeline.
497
584
  *
@@ -556,6 +643,59 @@ class ReactRenderer extends IntegrationRenderer {
556
643
  getDocumentAttributes() {
557
644
  return this.getRouterDocumentAttributes();
558
645
  }
646
+ async renderViewWithDocumentShell(input) {
647
+ const normalizedProps = input.props ?? {};
648
+ if (input.ctx.partial) {
649
+ const { react, reactDomServer } = this.getReactRuntimeModules();
650
+ const ViewComponent = this.asReactComponent(input.view);
651
+ return this.renderPartialViewResponse({
652
+ ...input,
653
+ renderInline: async () => await reactDomServer.renderToReadableStream(react.createElement(ViewComponent, normalizedProps))
654
+ });
655
+ }
656
+ await this.prepareViewDependencies(input.view, input.layout);
657
+ if (!input.ctx.partial) {
658
+ await this.appendHydrationAssetsForFile(input.view.config?.__eco?.file);
659
+ }
660
+ const HtmlTemplate = await this.getHtmlTemplate();
661
+ const metadata = await this.resolveViewMetadata(input.view, input.props);
662
+ const serializedPageProps = this.pagePayloadService.buildSerializedPageProps({
663
+ pageProps: normalizedProps,
664
+ params: {},
665
+ query: {},
666
+ safeLocals: this.pagePayloadService.getSerializableLocals(void 0, this.getComponentRequires(input.view))
667
+ });
668
+ const shellLayouts = input.layout ? [{ component: input.layout, props: {} }] : [];
669
+ const composeChildren = this.shouldUseUnifiedReactLayoutComposition(input.view, shellLayouts) ? (context) => this.composeReactLayoutPageChildren({ component: input.view, props: normalizedProps }, context) : void 0;
670
+ const { documentHtml } = await composeDocumentShell(
671
+ {
672
+ renderComponentWithForeignChildren: (renderInput) => this.renderComponentWithForeignChildren(renderInput),
673
+ appendProcessedDependencies: (...assetGroups) => this.appendProcessedDependencies(...assetGroups)
674
+ },
675
+ {
676
+ primaryComponent: input.view,
677
+ primaryProps: normalizedProps,
678
+ layout: input.layout ? {
679
+ component: input.layout,
680
+ props: {}
681
+ } : void 0,
682
+ layouts: shellLayouts.length > 0 ? shellLayouts : void 0,
683
+ composeChildren,
684
+ htmlTemplate: HtmlTemplate,
685
+ documentProps: {
686
+ metadata,
687
+ pageProps: serializedPageProps
688
+ }
689
+ }
690
+ );
691
+ const html = await this.finalizeResolvedHtml({
692
+ html: `${this.DOC_TYPE}${documentHtml}`,
693
+ partial: false,
694
+ documentAttributes: this.getRouterDocumentAttributes(),
695
+ htmlContributions: this.buildNonReactDocumentContributions(HtmlTemplate, serializedPageProps)
696
+ });
697
+ return this.createHtmlResponse(html, input.ctx);
698
+ }
559
699
  /**
560
700
  * Renders an arbitrary React view through the application's HTML shell.
561
701
  *
@@ -566,50 +706,13 @@ class ReactRenderer extends IntegrationRenderer {
566
706
  */
567
707
  async renderToResponse(view, props, ctx) {
568
708
  try {
569
- const { react, reactDomServer } = this.getReactRuntimeModules();
570
- const viewConfig = view.config;
571
- const Layout = viewConfig?.layout;
572
- const ViewComponent = this.asReactComponent(view);
573
- const normalizedProps = props ?? {};
574
- if (ctx.partial) {
575
- return this.renderPartialViewResponse({
576
- view,
577
- props,
578
- ctx,
579
- renderInline: async () => await reactDomServer.renderToReadableStream(
580
- react.createElement(ViewComponent, normalizedProps)
581
- )
582
- });
583
- }
584
- const HtmlTemplate = await this.getHtmlTemplate();
585
- const metadata = await this.resolveViewMetadata(view, props);
586
- await this.prepareViewDependencies(view, Layout);
587
- await this.appendHydrationAssetsForFile(viewConfig?.__eco?.file);
588
- const viewRender = await this.renderComponentWithForeignChildren({
589
- component: view,
590
- props: normalizedProps
591
- });
592
- const layoutRender = Layout ? await this.renderComponentWithForeignChildren({
593
- component: Layout,
594
- props: {},
595
- children: viewRender.html
596
- }) : void 0;
597
- const documentRender = await this.renderComponentWithForeignChildren({
598
- component: HtmlTemplate,
599
- props: {
600
- metadata,
601
- pageProps: normalizedProps
602
- },
603
- children: layoutRender?.html ?? viewRender.html
604
- });
605
- this.appendProcessedDependencies(viewRender.assets, layoutRender?.assets, documentRender.assets);
606
- const transformedHtml = await this.finalizeResolvedHtml({
607
- html: `${this.DOC_TYPE}${documentRender.html}`,
608
- partial: false,
609
- documentAttributes: this.getRouterDocumentAttributes(),
610
- htmlContributions: this.buildNonReactDocumentContributions(HtmlTemplate, normalizedProps)
709
+ const layouts = view.config?.layouts;
710
+ return await this.renderViewWithDocumentShell({
711
+ view,
712
+ props,
713
+ ctx,
714
+ layout: layouts?.[layouts.length - 1]
611
715
  });
612
- return this.createHtmlResponse(transformedHtml, ctx);
613
716
  } catch (error) {
614
717
  throw this.createRenderError("Failed to render view", error);
615
718
  }
@@ -2,42 +2,18 @@ import {
2
2
  IntegrationPlugin
3
3
  } from "@ecopages/core/plugins/integration-plugin";
4
4
  import { Logger } from "@ecopages/logger";
5
+ import path from "node:path";
5
6
  import { REACT_PLUGIN_NAME } from "./react.constants.js";
6
7
  import { ReactRenderer } from "./react-renderer.js";
7
8
  import { ReactHmrStrategy } from "./react-hmr-strategy.js";
8
9
  import { ReactRuntimeBundleService } from "./services/react-runtime-bundle.service.js";
9
10
  import { ReactHmrPageMetadataCache } from "./services/react-hmr-page-metadata-cache.js";
10
11
  import { createReactMdxLoaderPlugin } from "./utils/react-mdx-loader-plugin.js";
12
+ import { appendMdxExtensions, resolveMdxCompilerOptions } from "@ecopages/mdx/core";
11
13
  import { ClientGraphBoundaryCache } from "./utils/client-graph-boundary-cache.js";
12
14
  const appLogger = new Logger("[ReactPlugin]");
13
15
  const PLUGIN_NAME = REACT_PLUGIN_NAME;
14
- const mergePluginLists = (...lists) => {
15
- const merged = lists.flatMap((list) => list ? [...list] : []);
16
- return merged.length > 0 ? merged : void 0;
17
- };
18
- const appendMdxExtensions = (target, mdxExtensions) => {
19
- for (const extension of mdxExtensions) {
20
- if (!target.includes(extension)) {
21
- target.push(extension);
22
- }
23
- }
24
- };
25
- const resolveReactMdxCompilerOptions = (mdxOptions) => {
26
- const { compilerOptions, remarkPlugins, rehypePlugins, recmaPlugins } = mdxOptions;
27
- const resolved = {
28
- ...compilerOptions,
29
- jsxImportSource: "react",
30
- jsxRuntime: "automatic",
31
- development: process.env.NODE_ENV === "development"
32
- };
33
- const mergedRemark = mergePluginLists(compilerOptions?.remarkPlugins, remarkPlugins);
34
- const mergedRehype = mergePluginLists(compilerOptions?.rehypePlugins, rehypePlugins);
35
- const mergedRecma = mergePluginLists(compilerOptions?.recmaPlugins, recmaPlugins);
36
- if (mergedRemark) resolved.remarkPlugins = mergedRemark;
37
- if (mergedRehype) resolved.rehypePlugins = mergedRehype;
38
- if (mergedRecma) resolved.recmaPlugins = mergedRecma;
39
- return resolved;
40
- };
16
+ const resolveReactMdxCompilerOptions = (mdxOptions) => resolveMdxCompilerOptions(mdxOptions, { jsxImportSource: "react" });
41
17
  const resolveReactPluginOptions = (options) => {
42
18
  const { extensions: userExtensions, router, mdx, explicitGraph, dependencies, ...baseConfig } = options ?? {};
43
19
  const extensions = [...userExtensions ?? [".tsx"]];
@@ -129,6 +105,9 @@ class ReactPlugin extends IntegrationPlugin {
129
105
  return;
130
106
  }
131
107
  this.runtimeBundleService.setRootDir(this.appConfig?.rootDir);
108
+ this.runtimeBundleService.setWorkDir(
109
+ this.appConfig?.absolutePaths?.workDir ?? (this.appConfig?.rootDir ? path.join(this.appConfig.rootDir, this.appConfig.workDir ?? ".eco") : void 0)
110
+ );
132
111
  this.integrationDependencies.unshift(...this.runtimeBundleService.getDependencies());
133
112
  this.runtimeDependenciesInitialized = true;
134
113
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Escapes page data JSON for safe embedding in HTML script bodies.
3
+ */
4
+ export declare function escapePageDataJson(pageProps: Record<string, unknown> | undefined): string;
5
+ /**
6
+ * Emits the canonical `__ECO_PAGE_DATA__` bootstrap script tag.
7
+ */
8
+ export declare function serializePageDataScript(pageProps: Record<string, unknown> | undefined): string;
@@ -0,0 +1,10 @@
1
+ function escapePageDataJson(pageProps) {
2
+ return JSON.stringify(pageProps ?? {}).replace(/</g, "\\u003c");
3
+ }
4
+ function serializePageDataScript(pageProps) {
5
+ return `<script id="__ECO_PAGE_DATA__" type="application/json">${escapePageDataJson(pageProps)}<\/script>`;
6
+ }
7
+ export {
8
+ escapePageDataJson,
9
+ serializePageDataScript
10
+ };
@@ -6,6 +6,7 @@
6
6
  *
7
7
  * @module
8
8
  */
9
+ import type { EcoPagesAppConfig } from '@ecopages/core';
9
10
  import type { ReactRouterAdapter } from '../router-adapter.js';
10
11
  import type { CompileOptions } from '@mdx-js/mdx';
11
12
  import { type ReactRuntimeImports } from './react-runtime-bundle.service.js';
@@ -14,10 +15,10 @@ import { type ReactRuntimeImports } from './react-runtime-bundle.service.js';
14
15
  */
15
16
  export interface ReactBundleServiceConfig {
16
17
  rootDir: string;
18
+ appConfig: EcoPagesAppConfig;
19
+ hostIntegrationName: string;
17
20
  routerAdapter?: ReactRouterAdapter;
18
21
  mdxCompilerOptions?: CompileOptions;
19
- nonReactExtensions?: string[];
20
- jsxImportSource?: string;
21
22
  }
22
23
  /**
23
24
  * Optional flags that adjust how a React client entry is bundled.
@@ -4,7 +4,7 @@ import {
4
4
  getReactRuntimeExternalSpecifiers
5
5
  } from "../utils/react-runtime-alias-map.js";
6
6
  import { createBrowserRuntimePlugin } from "@ecopages/core/build/browser-runtime-plugin";
7
- import { createForeignJsxOverridePlugin } from "@ecopages/core/plugins/foreign-jsx-override-plugin";
7
+ import { getHostScopedJsxOwnershipPlugins } from "@ecopages/core/build/jsx-ownership-plugins";
8
8
  import { ReactRuntimeBundleService } from "./react-runtime-bundle.service.js";
9
9
  import { createReactMdxLoaderPlugin } from "../utils/react-mdx-loader-plugin.js";
10
10
  class ReactBundleService {
@@ -61,11 +61,11 @@ class ReactBundleService {
61
61
  declaredModules,
62
62
  alwaysAllowSpecifiers: getReactClientGraphAllowSpecifiers([], this.config.routerAdapter)
63
63
  });
64
- const foreignJsxOverridePlugin = createForeignJsxOverridePlugin({
65
- name: "react-renderer-foreign-jsx-override",
66
- hostJsxImportSource: this.config.jsxImportSource ?? "react",
67
- foreignExtensions: this.config.nonReactExtensions ?? []
68
- });
64
+ const [foreignJsxOverridePlugin] = getHostScopedJsxOwnershipPlugins(
65
+ this.config.appConfig,
66
+ this.config.hostIntegrationName,
67
+ { name: "react-renderer-foreign-jsx-override" }
68
+ );
69
69
  const runtimeManifest = this.runtimeBundleService.getRuntimeManifest();
70
70
  const runtimeRewritePlugin = createBrowserRuntimePlugin({
71
71
  name: "react-renderer-runtime-import-rewrite",
@@ -74,9 +74,18 @@ class ReactBundleService {
74
74
  const runtimePlugins = bundleOptions.includeRuntime ? [] : [runtimeRewritePlugin].filter((plugin) => plugin !== null);
75
75
  if (isMdx && this.config.mdxCompilerOptions) {
76
76
  const mdxPlugin = createReactMdxLoaderPlugin(this.config.mdxCompilerOptions);
77
- options.plugins = [foreignJsxOverridePlugin, graphBoundaryPlugin, ...runtimePlugins, mdxPlugin];
77
+ options.plugins = [
78
+ ...foreignJsxOverridePlugin ? [foreignJsxOverridePlugin] : [],
79
+ graphBoundaryPlugin,
80
+ ...runtimePlugins,
81
+ mdxPlugin
82
+ ];
78
83
  } else {
79
- options.plugins = [foreignJsxOverridePlugin, graphBoundaryPlugin, ...runtimePlugins];
84
+ options.plugins = [
85
+ ...foreignJsxOverridePlugin ? [foreignJsxOverridePlugin] : [],
86
+ graphBoundaryPlugin,
87
+ ...runtimePlugins
88
+ ];
80
89
  }
81
90
  return options;
82
91
  }
@@ -23,13 +23,11 @@ class ReactMdxConfigDependencyService {
23
23
  }
24
24
  createOwnedConfigComponents(pagePath, config) {
25
25
  const components = [];
26
- const resolvedLayout = config?.layout;
27
- if (resolvedLayout?.config?.dependencies) {
28
- const layoutConfig = this.config.pageModuleService.ensureConfigFileMetadata(
29
- resolvedLayout.config,
30
- pagePath
31
- );
32
- components.push({ config: layoutConfig });
26
+ for (const layout of config?.layouts ?? []) {
27
+ if (layout?.config?.dependencies) {
28
+ const layoutConfig = this.config.pageModuleService.ensureConfigFileMetadata(layout.config, pagePath);
29
+ components.push({ config: layoutConfig });
30
+ }
33
31
  }
34
32
  if (config?.dependencies) {
35
33
  components.push({