@ecopages/core 0.7.1 → 0.9.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 (146) hide show
  1. package/README.md +2 -2
  2. package/package.json +14 -4
  3. package/src/adapters/node/create-app.d.ts +1 -1
  4. package/src/adapters/node/create-app.js +1 -1
  5. package/src/adapters/node/server-adapter.d.ts +1 -0
  6. package/src/adapters/node/server-adapter.js +4 -1
  7. package/src/adapters/shared/hmr/hmr-manager.d.ts +2 -0
  8. package/src/adapters/shared/hmr/hmr-manager.js +8 -4
  9. package/src/adapters/shared/http/api-request-pipeline.d.ts +16 -3
  10. package/src/adapters/shared/http/api-request-pipeline.js +16 -11
  11. package/src/adapters/shared/http/explicit-static-route-matcher.js +8 -4
  12. package/src/adapters/shared/runtime/render-context.d.ts +2 -0
  13. package/src/adapters/shared/runtime/render-context.js +4 -0
  14. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +2 -2
  15. package/src/adapters/shared/runtime/server-request-pipeline.js +4 -3
  16. package/src/adapters/shared/runtime/server-static-builder.js +4 -1
  17. package/src/adapters/shared/runtime/unattached-scripts.d.ts +17 -0
  18. package/src/adapters/shared/runtime/unattached-scripts.js +57 -0
  19. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +3 -2
  20. package/src/adapters/shared/ws/ws-pattern-matcher.d.ts +14 -1
  21. package/src/adapters/shared/ws/ws-pattern-matcher.js +14 -13
  22. package/src/assets/app-browser-client-build.js +3 -0
  23. package/src/assets/asset-processing-service/asset-processing.service.d.ts +9 -0
  24. package/src/assets/asset-processing-service/asset-processing.service.js +19 -0
  25. package/src/assets/asset-processing-service/processed-asset-ledger.d.ts +16 -2
  26. package/src/assets/asset-processing-service/processed-asset-ledger.js +31 -3
  27. package/src/assets/asset-processing-service/processors/stylesheet/import-order.js +5 -3
  28. package/src/build/build-graph.d.ts +19 -2
  29. package/src/build/build-graph.js +19 -18
  30. package/src/build/cache/pages-unified-graph-build.d.ts +4 -6
  31. package/src/build/cache/pages-unified-graph-build.js +14 -51
  32. package/src/build/cache/server-module-entries.d.ts +5 -9
  33. package/src/build/cache/server-module-entries.js +5 -58
  34. package/src/build/contracts/build-contracts.d.ts +15 -0
  35. package/src/build/contracts.d.ts +1 -1
  36. package/src/build/contracts.js +1 -1
  37. package/src/build/production-asset-ledger.d.ts +1 -1
  38. package/src/build/production-asset-ledger.js +4 -2
  39. package/src/build/rolldown/file-role-grammar-plugin.d.ts +11 -0
  40. package/src/build/rolldown/file-role-grammar-plugin.js +32 -0
  41. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +11 -0
  42. package/src/build/rolldown/rolldown-adapter-helpers.js +79 -10
  43. package/src/build/rolldown/ssr-script-entries-plugin.d.ts +31 -0
  44. package/src/build/rolldown/ssr-script-entries-plugin.js +104 -0
  45. package/src/build/server/server-modules-manifest.d.ts +6 -1
  46. package/src/build/server/server-modules-manifest.js +10 -1
  47. package/src/build/server/view-reference.d.ts +9 -0
  48. package/src/build/server/view-reference.js +11 -0
  49. package/src/build.d.ts +2 -1
  50. package/src/build.js +2 -1
  51. package/src/cli.d.ts +14 -0
  52. package/src/cli.js +14 -0
  53. package/src/config/assembly/app-runtime.d.ts +13 -0
  54. package/src/config/assembly/app-runtime.js +2 -0
  55. package/src/config/assembly/finalize-config.js +13 -8
  56. package/src/config/internal-types.d.ts +0 -12
  57. package/src/config/resolve-eco-config-path.d.ts +2 -0
  58. package/src/config/resolve-eco-config-path.js +2 -1
  59. package/src/config/server-config-bundle.d.ts +0 -1
  60. package/src/config/server-config-bundle.js +1 -1
  61. package/src/config/user-config-types.d.ts +0 -12
  62. package/src/dev/invalidation/development-invalidation.service.d.ts +0 -2
  63. package/src/dev/invalidation/development-invalidation.service.js +1 -11
  64. package/src/dev/transform-server/dev-transform-vendor-registry.js +33 -19
  65. package/src/eco/discovered-dependencies.d.ts +5 -0
  66. package/src/eco/discovered-dependencies.js +9 -0
  67. package/src/eco/eco.browser.js +5 -5
  68. package/src/eco/eco.js +24 -5
  69. package/src/eco/migration-docs.d.ts +7 -0
  70. package/src/eco/migration-docs.js +7 -0
  71. package/src/hmr/client/hmr-runtime.js +1 -1
  72. package/src/hmr/strategies/js-hmr-strategy.d.ts +0 -2
  73. package/src/hmr/strategies/server-rendered-template-hmr-strategy.d.ts +2 -1
  74. package/src/hmr/strategies/server-rendered-template-hmr-strategy.js +4 -3
  75. package/src/html/html-rewriter.d.ts +9 -7
  76. package/src/html/html-rewriter.js +26 -41
  77. package/src/html/html-transformer.service.d.ts +2 -2
  78. package/src/html/html-transformer.service.js +21 -15
  79. package/src/html-pages/html-page-module-scripts.js +2 -1
  80. package/src/html-pages/html-pages.plugin.d.ts +1 -1
  81. package/src/html-pages/html-pages.plugin.js +1 -1
  82. package/src/integration.d.ts +1 -1
  83. package/src/integration.js +1 -1
  84. package/src/islands/island-host.d.ts +16 -5
  85. package/src/islands/island-host.js +8 -1
  86. package/src/plugins/component-import-discovery.d.ts +14 -1
  87. package/src/plugins/component-import-discovery.js +36 -16
  88. package/src/plugins/eco-component-meta-plugin.d.ts +5 -0
  89. package/src/plugins/eco-component-meta-plugin.js +39 -22
  90. package/src/plugins/ecopages-virtual-imports.d.ts +15 -0
  91. package/src/plugins/ecopages-virtual-imports.js +25 -0
  92. package/src/plugins/integration-plugin.d.ts +1 -1
  93. package/src/plugins/integration-plugin.js +1 -1
  94. package/src/plugins/tsconfig-import-resolver.d.ts +2 -0
  95. package/src/plugins/tsconfig-import-resolver.js +7 -5
  96. package/src/route-renderer/error-pages/error-page-renderer.js +3 -2
  97. package/src/route-renderer/explicit-view-render-preparation.d.ts +10 -3
  98. package/src/route-renderer/explicit-view-render-preparation.js +14 -8
  99. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +24 -9
  100. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +73 -50
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +39 -10
  102. package/src/route-renderer/orchestration/integration-renderer.js +74 -38
  103. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +32 -11
  104. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +68 -61
  105. package/src/route-renderer/page-declaration.d.ts +25 -0
  106. package/src/route-renderer/page-declaration.js +39 -0
  107. package/src/route-renderer/page-loading/component-declarations.d.ts +65 -0
  108. package/src/route-renderer/page-loading/component-declarations.js +77 -0
  109. package/src/route-renderer/page-loading/component-dependency-collection.d.ts +4 -16
  110. package/src/route-renderer/page-loading/component-dependency-collection.js +36 -105
  111. package/src/route-renderer/page-loading/declared-asset-collection.d.ts +19 -14
  112. package/src/route-renderer/page-loading/declared-asset-collection.js +66 -67
  113. package/src/route-renderer/page-loading/dependency-resolver.d.ts +18 -10
  114. package/src/route-renderer/page-loading/dependency-resolver.js +58 -99
  115. package/src/route-renderer/page-loading/lazy-entry-collection.d.ts +19 -26
  116. package/src/route-renderer/page-loading/lazy-entry-collection.js +53 -64
  117. package/src/route-renderer/page-loading/module-declaration-aggregation.d.ts +17 -3
  118. package/src/route-renderer/page-loading/module-declaration-aggregation.js +14 -13
  119. package/src/route-renderer/page-loading/page-module-loader.d.ts +10 -11
  120. package/src/route-renderer/page-loading/page-module-loader.js +30 -30
  121. package/src/router/server/pages-dir.d.ts +7 -0
  122. package/src/router/server/pages-dir.js +7 -0
  123. package/src/router/server/route-registry.d.ts +22 -10
  124. package/src/router/server/route-registry.js +54 -23
  125. package/src/router/server/segment-path-matcher.d.ts +29 -5
  126. package/src/router/server/segment-path-matcher.js +22 -19
  127. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +2 -2
  128. package/src/static-site-generator/production-page-browser-graph-prebuild.js +5 -5
  129. package/src/static-site-generator/static-site-generator.d.ts +17 -1
  130. package/src/static-site-generator/static-site-generator.js +46 -12
  131. package/src/types/contracts.d.ts +28 -28
  132. package/src/types/eco-api-types.d.ts +17 -12
  133. package/src/types/public-types.d.ts +1 -1
  134. package/src/utils/file-roles.d.ts +48 -0
  135. package/src/utils/file-roles.js +85 -0
  136. package/src/utils/node-builtin.d.ts +10 -0
  137. package/src/utils/node-builtin.js +13 -0
  138. package/src/watchers/project-watcher.js +2 -2
  139. package/src/build/contracts/server-only-specifier.d.ts +0 -8
  140. package/src/build/contracts/server-only-specifier.js +0 -11
  141. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.d.ts +0 -5
  142. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.js +0 -11
  143. package/src/route-renderer/page-loading/ecopages-virtual-imports.d.ts +0 -12
  144. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +0 -100
  145. package/src/utils/endpoint-file-extensions.d.ts +0 -11
  146. package/src/utils/endpoint-file-extensions.js +0 -13
@@ -9,13 +9,15 @@ import { resolveAssetProcessingIntegration } from '../../assets/asset-processing
9
9
  import { getAssetDependencyKey } from '../../assets/asset-processing-service/asset-dependency-keys.js';
10
10
  import { HtmlTransformerService } from '../../html/html-transformer.service.js';
11
11
  import { fileSystem } from '@ecopages/file-system';
12
- import { hasProductionServerModule } from '../../build/server/server-modules-manifest.js';
12
+ import { hasProductionServerModule, MissingProductionServerModuleError, } from '../../build/server/server-modules-manifest.js';
13
13
  import { invariant } from '../../utils/invariant.js';
14
14
  import { toRootRelativePath } from '../../utils/root-relative-path.js';
15
15
  import { HttpError } from '../../errors/http-error.js';
16
16
  import { DependencyResolverService } from '../page-loading/dependency-resolver.js';
17
17
  import { PageModuleLoaderService } from '../page-loading/page-module-loader.js';
18
18
  import { getComponentIdentity } from '../../eco/component-identity.js';
19
+ import { isPathInside } from '../../utils/path-containment.js';
20
+ import { createLiteralPageDeclarationError, isPageDeclaredIn, isUnattributedPage } from '../page-declaration.js';
19
21
  import { OwnershipValidationService } from './ownership-graph/ownership-validation.service.js';
20
22
  import {} from './ownership-graph/component-graph.js';
21
23
  import { collectComponentGraphWatchPaths } from './ownership-graph/component-graph-collectors.js';
@@ -27,16 +29,15 @@ import { createRenderSession } from './foreign-child/render-session.js';
27
29
  import { RouteRenderOrchestrator, } from './route-pipeline/route-render-orchestrator.js';
28
30
  import { buildRouteHtmlFinalization } from './route-pipeline/route-html-finalization.service.js';
29
31
  import { resolvePageDependenciesFromContext, } from '../page-loading/resolved-page-dependencies.js';
30
- import { normalizeUnresolvedMarkerArtifactHtml } from './route-pipeline/marker-artifact.utils.js';
31
32
  import { isMarkupNodeLike } from '../../eco/component-render-output.js';
32
- import { getForeignSubtreeResolutionContextKey, getForeignSubtreeTokenPrefix, resolveOwningIntegrationRenderer, } from './foreign-child/owning-renderer-resolution.js';
33
+ import { getForeignSubtreeResolutionContextKey, resolveOwningIntegrationRenderer, } from './foreign-child/owning-renderer-resolution.js';
33
34
  import { keepsLastGoodOutput, showAssetFailure } from '../../assets/asset-processing-service/last-good-output.js';
34
35
  import { ensureIntegrationRuntimeReady } from '../../build/app-build-manifest-runtime.js';
35
36
  import { assignSsrPreloadScripts, CustomElementScriptPreloader, } from './custom-element-scripts/custom-element-script-preloader.js';
36
37
  import { createQueuedRuntime, executeComponentRender, getQueuedRuntimeContext, resolveQueuedHtml, resolveStringQueuedHtml, } from './foreign-child/foreign-subtree-execution.service.js';
37
38
  import { renderPageDocumentShell, } from './document-shell/document-shell-render.service.js';
38
39
  import { resolveInnermostPageLayout, resolvePageLayoutComponents, resolveDocumentShellLayouts, } from './document-shell/layout-shell-props.service.js';
39
- import { finalizeIslandComponentRender } from '../../islands/island-host.js';
40
+ import { stampIslandHost } from '../../islands/island-host.js';
40
41
  import { requireAppRuntime } from '../../utils/app-runtime.js';
41
42
  import { prepareAssetDependencies } from '../../assets/asset-processing-service/asset-processing.service.js';
42
43
  import { isBundleableScript } from '../../assets/asset-processing-service/bundleable-script.js';
@@ -155,7 +156,7 @@ export class IntegrationRenderer {
155
156
  file: routeInstance.routeFile,
156
157
  params: routeInstance.params,
157
158
  query: routeInstance.query,
158
- skipStaticProps: routeInstance.skipStaticProps,
159
+ skipPropsHook: routeInstance.skipPropsHook,
159
160
  };
160
161
  const resolvedInputs = await this.resolveRouteRenderInputs(routeOptions, {
161
162
  skipMetadata: routeInstance.isRouteTemplate,
@@ -203,10 +204,42 @@ export class IntegrationRenderer {
203
204
  * `getStaticPaths` or `getMetadata` fails here with an error that points to the codemod.
204
205
  */
205
206
  async loadPageModule(file, options) {
207
+ return this.importRouteModule(file, options);
208
+ }
209
+ /**
210
+ * Imports a route module and fails unless it is a Page this Integration accepts.
211
+ *
212
+ * @remarks
213
+ * The legacy-export check runs first, so a module that still exports `getStaticProps` gets the codemod message.
214
+ */
215
+ async importRouteModule(file, options) {
206
216
  const pageModule = await this.importPageFile(file, options);
207
217
  this.pageModuleLoaderService.assertNoLegacyPageExports(file, pageModule);
218
+ this.assertPageModule(file, pageModule);
208
219
  return pageModule;
209
220
  }
221
+ /**
222
+ * Fails when the default export of a route module is not a Page that the file itself declares.
223
+ *
224
+ * @remarks
225
+ * A Page is a declared component whose build-time identity names this route file: an `eco.page()` result
226
+ * (also an HTML Page or an MDX module, which the Integration stamps the same way). The identity transform
227
+ * stamps the file that holds the literal `eco.page(...)` call, so a Page made by a wrapper in another file,
228
+ * or re-exported from one, names that other file and fails here. A function with a `config` that fails the
229
+ * check gets the literal-call message; anything else gets the not-a-Page message with the fixes.
230
+ * @throws When the module has no default export that is a Page declared in `file`.
231
+ */
232
+ assertPageModule(file, module) {
233
+ const page = module.default;
234
+ if (isPageDeclaredIn(file, page, this.appConfig.rootDir))
235
+ return;
236
+ if (isUnattributedPage(page))
237
+ throw createLiteralPageDeclarationError(file);
238
+ const fixes = isPathInside(path.resolve(file), this.appConfig.absolutePaths.pagesDir)
239
+ ? ' If the file is not a Page, prefix its name with "_", give it a role suffix such as .server.ts or .script.ts, or move it out of the pages directory.'
240
+ : '';
241
+ throw new Error(`[ecopages] ${file} does not default-export a Page the ${this.name} Integration renders (an eco.page() result).${fixes}`);
242
+ }
210
243
  setHmrManager(hmrManager) {
211
244
  this.hmrManager = hmrManager;
212
245
  if (this.assetProcessingService) {
@@ -349,11 +382,12 @@ export class IntegrationRenderer {
349
382
  this.assetProcessingIntegration = assetProcessingIntegration;
350
383
  this.htmlTransformer = new HtmlTransformerService();
351
384
  this.resolvedIntegrationDependencies = resolvedIntegrationDependencies || [];
352
- this.dependencyResolverService = new DependencyResolverService(appConfig, assetProcessingService, () => isProductionRuntime() && this.getActiveHmrManager()?.isEnabled() !== true, assetProcessingIntegration);
385
+ this.dependencyResolverService = new DependencyResolverService(appConfig, assetProcessingService, assetProcessingIntegration);
353
386
  this.pageModuleLoaderService = new PageModuleLoaderService(appConfig);
354
387
  this.routeRenderOrchestrator = new RouteRenderOrchestrator(appConfig, assetProcessingService, {
355
388
  ownershipValidationService: new OwnershipValidationService(appConfig),
356
389
  assetProcessingIntegration,
390
+ recordsShellDependencies: () => isProductionRuntime() && this.getActiveHmrManager()?.isEnabled() !== true,
357
391
  });
358
392
  this.integrationHooks =
359
393
  typeof hooks === 'function'
@@ -400,6 +434,9 @@ export class IntegrationRenderer {
400
434
  return;
401
435
  }
402
436
  if (requireAppRuntime(this.appConfig).staticGenerationActive) {
437
+ if (error instanceof MissingProductionServerModuleError) {
438
+ throw new Error(`The ssr script ${scriptPath} is not in the server build. \`ecopages build\` finds ssr scripts from a string literal \`src\` beside \`ssr: true\` in a Component's dependencies; declare its \`src\` as a string literal.`, { cause: error });
439
+ }
403
440
  const cause = error instanceof Error ? error.message : String(error);
404
441
  throw new Error(`Failed to preload the ssr script ${scriptPath}: ${cause}`, { cause: error });
405
442
  }
@@ -551,12 +588,11 @@ export class IntegrationRenderer {
551
588
  applyAttributesToHtmlElement: (html, attributes) => this.applyAttributesToHtmlElement(html, attributes),
552
589
  });
553
590
  }
554
- async transformRouteResponse(response, htmlContributions, renderOptions) {
555
- const transformedResponse = this.htmlTransformer.transform(response, {
591
+ async transformRouteHtml(html, htmlContributions, renderOptions) {
592
+ const body = this.htmlTransformer.transform(html, {
556
593
  contributions: htmlContributions,
557
594
  pagePackage: renderOptions.pagePackage,
558
595
  });
559
- const body = (transformedResponse.body ?? (await transformedResponse.text()));
560
596
  return this.finalizeDocument(body, renderOptions);
561
597
  }
562
598
  finalizeDocument(body, renderOptions) {
@@ -566,7 +602,7 @@ export class IntegrationRenderer {
566
602
  const resolvedPageModule = await this.pageModuleLoaderService.resolvePageModule({
567
603
  file: routeOptions.file,
568
604
  pageModule: routeOptions.pageModule,
569
- importPageFileFn: (targetFile) => this.importPageFile(targetFile),
605
+ importPageFileFn: (targetFile) => this.importRouteModule(targetFile),
570
606
  });
571
607
  const { Page, integrationSpecificProps, module: pageModule } = resolvedPageModule;
572
608
  const HtmlTemplate = await this.getHtmlTemplate();
@@ -601,12 +637,28 @@ export class IntegrationRenderer {
601
637
  async resolvePageDependenciesForRoute(context) {
602
638
  return resolvePageDependenciesFromContext(context, this.name);
603
639
  }
604
- /** Resolves a route's component assets. */
640
+ /**
641
+ * Resolves a route's component assets.
642
+ *
643
+ * @remarks `declarationOrder` returns them in the order the asset ledger records them, for a recorded shell.
644
+ */
605
645
  async resolveRouteDependencies(input) {
606
646
  return {
607
- resolvedDependencies: await this.resolveDependencies(input.components, { preparedGraph: true }),
647
+ resolvedDependencies: input.declarationOrder
648
+ ? await this.dependencyResolverService.processPreparedComponentDependencies(input.components, this.name, true)
649
+ : await this.resolveDependencies(input.components, { preparedGraph: true }),
608
650
  };
609
651
  }
652
+ /**
653
+ * Holds the lazy client entries of a route's shell components for the page client build.
654
+ *
655
+ * @remarks
656
+ * Processing the shell holds them as a side effect; a shell read from the asset ledger is not processed, so its
657
+ * lazy entries are collected here.
658
+ */
659
+ prepareRouteLazyDependencies(components) {
660
+ this.dependencyResolverService.prepareLazyClientDependencies(components, this.name);
661
+ }
610
662
  async renderRouteBody(renderOptions) {
611
663
  return this.render(renderOptions);
612
664
  }
@@ -629,9 +681,8 @@ export class IntegrationRenderer {
629
681
  * Execution flow:
630
682
  * 1. Build normalized render options (`prepareRenderOptions`).
631
683
  * 2. Render the route body once.
632
- * 3. Reject unresolved route-level eco-marker artifacts.
633
- * 4. Optionally apply document attributes for integration-owned document boundaries.
634
- * 5. Run HTML transformer with final dependency set.
684
+ * 3. Optionally apply document attributes for integration-owned document boundaries.
685
+ * 4. Run HTML transformer with final dependency set.
635
686
  *
636
687
  * Stream-safety note: the first render result is normalized to a string once,
637
688
  * then the pipeline continues with that immutable HTML value to avoid disturbed
@@ -697,7 +748,7 @@ export class IntegrationRenderer {
697
748
  *
698
749
  * @remarks
699
750
  * `file` is the view's identity file, or a stable synthetic key when the view has
700
- * none. `props` are the view's final props: its `staticProps` hook is the caller's
751
+ * none. `props` are the view's final props: its `props` hook is the caller's
701
752
  * to run, so it is not run here.
702
753
  */
703
754
  async executeExplicitView(view, props, ctx = {}) {
@@ -711,7 +762,7 @@ export class IntegrationRenderer {
711
762
  query: ctx.query,
712
763
  locals: ctx.locals,
713
764
  props: (props ?? {}),
714
- skipStaticProps: true,
765
+ skipPropsHook: true,
715
766
  });
716
767
  }
717
768
  /**
@@ -826,7 +877,6 @@ export class IntegrationRenderer {
826
877
  currentIntegrationName: this.name,
827
878
  input,
828
879
  renderComponent: (renderInput) => this.renderComponent(renderInput),
829
- normalizeComponentRenderOutput: (result) => this.normalizeComponentRenderOutput(result),
830
880
  hasForeignChildDescendants: (component, foreignChildRoots) => this.hasForeignChildDescendants(component, foreignChildRoots),
831
881
  createForeignChildRuntime: ({ renderInput, rendererCache }) => this.createForeignChildRuntime({
832
882
  renderInput,
@@ -873,31 +923,18 @@ export class IntegrationRenderer {
873
923
  });
874
924
  }
875
925
  /**
876
- * Stamps `result` as an Island Host when the component itself declares a client script.
926
+ * Stamps `result` as an Island Host when the component itself ships a client script.
877
927
  *
878
928
  * @remarks Reads the component's own declarations, excluding Foreign Children: a component without
879
929
  * scripts that wraps an island is not an island itself. Components without `dependencies` are never stamped.
880
930
  */
881
931
  finalizeIslandComponentRender(input, result) {
882
- const ownAssets = input.component.config?.dependencies
883
- ? this.dependencyResolverService.collectOwnComponentDependencies([input.component], this.name)
884
- : undefined;
885
- return finalizeIslandComponentRender(input, {
932
+ const shipsScript = input.component.config?.dependencies !== undefined &&
933
+ this.dependencyResolverService.componentShipsScript(input.component, this.name);
934
+ return stampIslandHost(input, {
886
935
  ...result,
887
936
  html: finalizeComponentRender(input.component, result.html),
888
- }, ownAssets);
889
- }
890
- normalizeComponentRenderOutput(result) {
891
- const normalizedHtml = this.normalizeUnresolvedMarkerArtifactHtml(result.html);
892
- return normalizedHtml === result.html
893
- ? result
894
- : {
895
- ...result,
896
- html: normalizedHtml,
897
- };
898
- }
899
- normalizeUnresolvedMarkerArtifactHtml(html) {
900
- return normalizeUnresolvedMarkerArtifactHtml(html);
937
+ }, shipsScript);
901
938
  }
902
939
  /**
903
940
  * @remarks
@@ -1074,8 +1111,7 @@ export class IntegrationRenderer {
1074
1111
  const runtime = createQueuedRuntime({
1075
1112
  renderInput: options.renderInput,
1076
1113
  rendererCache: options.rendererCache,
1077
- runtimeContextKey: getForeignSubtreeResolutionContextKey(this.name),
1078
- tokenPrefix: getForeignSubtreeTokenPrefix(this.name),
1114
+ integrationName: this.name,
1079
1115
  });
1080
1116
  const normalizeForeignChildProps = this.integrationHooks.normalizeForeignChildProps;
1081
1117
  if (!normalizeForeignChildProps) {
@@ -30,20 +30,21 @@ export type RouteHtmlFinalization = {
30
30
  finalizeHtml?(html: string): string;
31
31
  htmlContributions?: HtmlDocumentContribution[];
32
32
  };
33
- export type RouteRenderHost<C> = Pick<IntegrationRenderer<C>, 'name' | 'resolveRouteRenderInputs' | 'resolveRouteDependencies' | 'collectPageBrowserGraphContribution' | 'resolvePageDependenciesForRoute' | 'resolvePageDependencyContribution' | 'buildPageClientBrowserAssets' | 'getPageSsrScriptIntegrationNames' | 'renderRouteBody' | 'getRouteHtmlFinalization' | 'transformRouteResponse'>;
34
- /**
35
- * Captured route-render output in both replayable body and string HTML forms.
36
- */
37
- export interface CapturedHtmlRenderResult {
38
- body: RouteRendererBody;
39
- html: string;
40
- }
33
+ export type RouteRenderHost<C> = Pick<IntegrationRenderer<C>, 'name' | 'resolveRouteRenderInputs' | 'resolveRouteDependencies' | 'prepareRouteLazyDependencies' | 'collectPageBrowserGraphContribution' | 'resolvePageDependenciesForRoute' | 'resolvePageDependencyContribution' | 'buildPageClientBrowserAssets' | 'getPageSsrScriptIntegrationNames' | 'renderRouteBody' | 'getRouteHtmlFinalization' | 'transformRouteHtml'>;
41
34
  /**
42
35
  * Optional app-scoped collaborators used by the route render orchestrator.
43
36
  */
44
37
  export interface RouteRenderOrchestratorDependencies {
45
38
  ownershipValidationService?: OwnershipValidationService;
46
39
  assetProcessingIntegration?: AssetProcessingIntegration;
40
+ /**
41
+ * Whether processed assets are final for the life of the process, so a route's shell Dependencies are recorded in
42
+ * the asset ledger once per Page and Html template and read from it afterwards.
43
+ *
44
+ * @remarks True in production without HMR. In development an edited stylesheet changes its processed output
45
+ * without re-importing any module, so the shell Dependencies are processed on every render.
46
+ */
47
+ recordsShellDependencies?: () => boolean;
47
48
  }
48
49
  export type PreparedRouteGraphContext = {
49
50
  dependencyInstanceKey: string;
@@ -80,6 +81,7 @@ export declare class RouteRenderOrchestrator {
80
81
  private readonly ownershipValidationService;
81
82
  private readonly pageBrowserGraphService;
82
83
  private readonly requestPipelineMetrics;
84
+ private readonly recordsShellDependencies;
83
85
  constructor(appConfig: EcoPagesAppConfig, assetProcessingService: AssetProcessingService, dependencies?: RouteRenderOrchestratorDependencies);
84
86
  private validateOwnershipGraph;
85
87
  /**
@@ -96,6 +98,7 @@ export declare class RouteRenderOrchestrator {
96
98
  planning?: true;
97
99
  }): Promise<PreparedRouteGraphContext>;
98
100
  private prepareRouteShellGraph;
101
+ private recordLayoutFiles;
99
102
  private preparePageDependencyGraph;
100
103
  private collectPageDependencyNodes;
101
104
  private processPlannedPageDependencies;
@@ -115,9 +118,28 @@ export declare class RouteRenderOrchestrator {
115
118
  */
116
119
  prepareRenderOptions<C = unknown>(routeOptions: RouteRendererOptions, renderer: RouteRenderHost<C>, planned?: PlannedRoutePreparation): Promise<InternalIntegrationRendererRenderOptions<C>>;
117
120
  /**
118
- * Captures one route render body as HTML while preserving a replayable body value.
121
+ * Reads the Dependencies of the route's shell from the asset ledger, or processes them.
122
+ *
123
+ * @remarks
124
+ * A route's shell is its Html template, Layouts and Page, and the Layouts are fixed by the Page, so the identities
125
+ * of the Page and the Html template fix the result. When processed assets are final, the first preparation of a
126
+ * Page in `ecopages build` records its shell in the ledger, and every later one reads it there, including those
127
+ * of `ecopages start`, which never packages or processes a shell. Packaging the shell reads its stylesheet
128
+ * sources, which a deploy may not hold. A read shell still holds its lazy client entries for the page client
129
+ * build, which processing would have held.
130
+ */
131
+ private resolveShellDependencies;
132
+ /**
133
+ * Names a declaration the same wherever the app runs: its root-relative file and its id.
134
+ *
135
+ * @remarks
136
+ * A runtime identity, such as an HTML Page's, holds an absolute file, and the built-in Html shell has none.
137
+ */
138
+ private describeIdentity;
139
+ /**
140
+ * Reads one route render body as an HTML string.
119
141
  */
120
- captureHtmlRender(render: () => Promise<RouteRendererBody>): Promise<CapturedHtmlRenderResult>;
142
+ captureHtmlRender(render: () => Promise<RouteRendererBody>): Promise<string>;
121
143
  /**
122
144
  * Executes the full route-render flow and returns the final body plus cache strategy.
123
145
  */
@@ -140,5 +162,4 @@ export declare class RouteRenderOrchestrator {
140
162
  * closure is recorded only then. Editing any of them must miss the cached document.
141
163
  */
142
164
  private withHtmlTemplateClosure;
143
- private captureRenderedBody;
144
165
  }
@@ -2,7 +2,8 @@ import { path } from '@ecopages/file-system/path';
2
2
  import { isProductionRuntime } from '../../../utils/runtime.js';
3
3
  import { collectHtmlCacheSourceDependencyPaths } from '../../../page-cache/html-page-cache-dependency-index.js';
4
4
  import { requireAppRuntime } from '../../../utils/app-runtime.js';
5
- import { inspectUnresolvedMarkerArtifactHtml } from './marker-artifact.utils.js';
5
+ import { getComponentIdentity } from '../../../eco/component-identity.js';
6
+ import { toRootRelativePath } from '../../../utils/root-relative-path.js';
6
7
  import { createPreparedComponentGraphBuilder, } from '../ownership-graph/component-graph.js';
7
8
  import { OwnershipValidationService, throwIfOwnershipInvalid, } from '../ownership-graph/ownership-validation.service.js';
8
9
  import { collectComponentGraphWatchPaths, collectPageIntegrationDependencies, } from '../ownership-graph/component-graph-collectors.js';
@@ -28,10 +29,12 @@ export class RouteRenderOrchestrator {
28
29
  ownershipValidationService;
29
30
  pageBrowserGraphService;
30
31
  requestPipelineMetrics;
32
+ recordsShellDependencies;
31
33
  constructor(appConfig, assetProcessingService, dependencies = {}) {
32
34
  this.appConfig = appConfig;
33
35
  this.requestPipelineMetrics = requireAppRuntime(appConfig).requestPipelineMetrics;
34
36
  this.assetProcessingService = assetProcessingService;
37
+ this.recordsShellDependencies = dependencies.recordsShellDependencies ?? (() => false);
35
38
  this.ownershipValidationService =
36
39
  dependencies.ownershipValidationService ?? new OwnershipValidationService(appConfig);
37
40
  this.pageBrowserGraphService = new PageBrowserGraphService(appConfig, assetProcessingService, dependencies.assetProcessingIntegration);
@@ -90,12 +93,23 @@ export class RouteRenderOrchestrator {
90
93
  const graphBuilder = createPreparedComponentGraphBuilder(renderer.name);
91
94
  graphBuilder.addRoots(shellRoots);
92
95
  const shellGraph = graphBuilder.getGraph({ updateForeignDescendantFlags: false });
96
+ this.recordLayoutFiles(shellGraph);
93
97
  const shellDependencyComponents = shellGraph.nodes
94
98
  .filter((node) => node.dependencyCollectionVisible)
95
99
  .map((node) => node.component);
96
100
  await this.validateOwnershipGraph(shellGraph);
97
101
  return { graphBuilder, shellGraph, shellDependencyComponents };
98
102
  }
103
+ recordLayoutFiles(shellGraph) {
104
+ if (isProductionRuntime())
105
+ return;
106
+ const layoutFiles = requireAppRuntime(this.appConfig).layoutFiles;
107
+ for (const node of shellGraph.nodes) {
108
+ if (node.source === 'layout' && node.componentFile) {
109
+ layoutFiles.add(path.resolve(this.appConfig.rootDir, node.componentFile));
110
+ }
111
+ }
112
+ }
99
113
  async preparePageDependencyGraph(input) {
100
114
  const { renderer, graphContext, graphBuilder } = input;
101
115
  const resolvedPageDependencies = await renderer.resolvePageDependenciesForRoute(graphContext);
@@ -176,14 +190,12 @@ export class RouteRenderOrchestrator {
176
190
  renderer,
177
191
  });
178
192
  const { dependencyInstanceKey, graphContext: contributionContext, resolvedPageDependencies, shellDependencyComponents, graph: preparedGraph, } = graphContext;
179
- const { resolvedDependencies } = await measureRouteRenderPhase(this.requestPipelineMetrics, 'resolve-dependencies', () => renderer.resolveRouteDependencies({
180
- components: shellDependencyComponents,
181
- }));
193
+ const resolvedDependencies = await measureRouteRenderPhase(this.requestPipelineMetrics, 'resolve-dependencies', () => this.resolveShellDependencies(renderer, finalResolvedInputs, shellDependencyComponents));
182
194
  const pageBrowserGraph = await measureRouteRenderPhase(this.requestPipelineMetrics, 'page-browser-graph', () => this.pageBrowserGraphService.resolvePageBrowserGraph({
183
195
  routeFile: routeOptions.file,
184
196
  dependencyInstanceKey,
185
197
  integrationName: renderer.name,
186
- cacheable: !routeOptions.pageModule && !routeOptions.props && !routeOptions.skipStaticProps,
198
+ cacheable: !routeOptions.pageModule && !routeOptions.props && !routeOptions.skipPropsHook,
187
199
  collectContribution: async () => mergePageBrowserGraphContributions(await renderer.collectPageBrowserGraphContribution(contributionContext), resolvedPageDependencies?.contribution),
188
200
  }));
189
201
  const graphDependencyPaths = this.pageBrowserGraphService.getDependencyPathsForRoute({
@@ -240,15 +252,56 @@ export class RouteRenderOrchestrator {
240
252
  };
241
253
  }
242
254
  /**
243
- * Captures one route render body as HTML while preserving a replayable body value.
255
+ * Reads the Dependencies of the route's shell from the asset ledger, or processes them.
256
+ *
257
+ * @remarks
258
+ * A route's shell is its Html template, Layouts and Page, and the Layouts are fixed by the Page, so the identities
259
+ * of the Page and the Html template fix the result. When processed assets are final, the first preparation of a
260
+ * Page in `ecopages build` records its shell in the ledger, and every later one reads it there, including those
261
+ * of `ecopages start`, which never packages or processes a shell. Packaging the shell reads its stylesheet
262
+ * sources, which a deploy may not hold. A read shell still holds its lazy client entries for the page client
263
+ * build, which processing would have held.
264
+ */
265
+ async resolveShellDependencies(renderer, resolvedInputs, components) {
266
+ const pageIdentity = getComponentIdentity(resolvedInputs.Page);
267
+ const key = this.recordsShellDependencies() && pageIdentity
268
+ ? `${this.describeIdentity(pageIdentity)}|${this.describeIdentity(getComponentIdentity(resolvedInputs.HtmlTemplate))}`
269
+ : undefined;
270
+ const ledger = requireAppRuntime(this.appConfig).processedAssets;
271
+ const recorded = key ? ledger.lookupShell(key) : undefined;
272
+ if (recorded) {
273
+ renderer.prepareRouteLazyDependencies(components);
274
+ return recorded;
275
+ }
276
+ if (key && ledger.isSealed) {
277
+ throw new Error(`The production build did not record the shell Dependencies of ${this.describeIdentity(pageIdentity)}. Run \`ecopages build\` again.`);
278
+ }
279
+ const { resolvedDependencies } = await renderer.resolveRouteDependencies({
280
+ components,
281
+ declarationOrder: key !== undefined,
282
+ });
283
+ if (key)
284
+ ledger.recordShell(key, resolvedDependencies);
285
+ return resolvedDependencies;
286
+ }
287
+ /**
288
+ * Names a declaration the same wherever the app runs: its root-relative file and its id.
289
+ *
290
+ * @remarks
291
+ * A runtime identity, such as an HTML Page's, holds an absolute file, and the built-in Html shell has none.
292
+ */
293
+ describeIdentity(identity) {
294
+ if (!identity)
295
+ return 'built-in';
296
+ const { rootDir } = this.appConfig;
297
+ return `${toRootRelativePath(rootDir, path.resolve(rootDir, identity.file))}#${identity.id}`;
298
+ }
299
+ /**
300
+ * Reads one route render body as an HTML string.
244
301
  */
245
302
  async captureHtmlRender(render) {
246
- const renderedBody = await render();
247
- const capturedRender = await this.captureRenderedBody(renderedBody);
248
- return {
249
- body: capturedRender.body,
250
- html: capturedRender.html,
251
- };
303
+ const body = await render();
304
+ return typeof body === 'string' ? body : new Response(body).text();
252
305
  }
253
306
  /**
254
307
  * Executes the full route-render flow and returns the final body plus cache strategy.
@@ -261,37 +314,11 @@ export class RouteRenderOrchestrator {
261
314
  * Executes the route-render finalization path for already prepared render options.
262
315
  */
263
316
  async executePrepared(renderOptions, renderer) {
264
- const renderExecution = await measureRouteRenderPhase(this.requestPipelineMetrics, 'render-body', () => this.captureHtmlRender(async () => renderer.renderRouteBody(renderOptions)));
317
+ const renderedHtml = await measureRouteRenderPhase(this.requestPipelineMetrics, 'render-body', () => this.captureHtmlRender(async () => renderer.renderRouteBody(renderOptions)));
265
318
  const sourceDependencyPaths = this.withHtmlTemplateClosure(renderOptions.sourceDependencyPaths);
266
- const unresolvedArtifactInspection = inspectUnresolvedMarkerArtifactHtml(renderExecution.html);
267
319
  const htmlFinalization = renderer.getRouteHtmlFinalization(renderOptions);
268
- const hasUnresolvedMarkerHtml = unresolvedArtifactInspection.hasUnresolvedMarkerArtifacts;
269
- if (hasUnresolvedMarkerHtml) {
270
- throw new Error('[ecopages] Route render returned unresolved eco-marker artifact HTML. Full-route unresolved-marker fallback has been removed; resolve mixed foreign children inside renderComponentWithForeignChildren().');
271
- }
272
- const canReuseCapturedBody = !hasUnresolvedMarkerHtml && htmlFinalization.finalizeHtml === undefined;
273
- if (canReuseCapturedBody) {
274
- const responseBody = typeof renderExecution.body === 'string' ? renderExecution.body : renderExecution.html;
275
- const body = await measureRouteRenderPhase(this.requestPipelineMetrics, 'transform-response', () => renderer.transformRouteResponse(new Response(responseBody, {
276
- headers: {
277
- 'Content-Type': 'text/html',
278
- },
279
- }), htmlFinalization.htmlContributions, renderOptions));
280
- return {
281
- body,
282
- cacheStrategy: renderOptions.cacheStrategy,
283
- sourceDependencyPaths,
284
- metadata: renderOptions.metadata,
285
- };
286
- }
287
- const finalization = htmlFinalization.finalizeHtml
288
- ? htmlFinalization.finalizeHtml(unresolvedArtifactInspection.normalizedHtml)
289
- : unresolvedArtifactInspection.normalizedHtml;
290
- const body = await measureRouteRenderPhase(this.requestPipelineMetrics, 'transform-response', () => renderer.transformRouteResponse(new Response(finalization, {
291
- headers: {
292
- 'Content-Type': 'text/html',
293
- },
294
- }), htmlFinalization.htmlContributions, renderOptions));
320
+ const finalHtml = htmlFinalization.finalizeHtml ? htmlFinalization.finalizeHtml(renderedHtml) : renderedHtml;
321
+ const body = await measureRouteRenderPhase(this.requestPipelineMetrics, 'transform-response', () => renderer.transformRouteHtml(finalHtml, htmlFinalization.htmlContributions, renderOptions));
295
322
  return {
296
323
  body,
297
324
  cacheStrategy: renderOptions.cacheStrategy,
@@ -339,26 +366,6 @@ export class RouteRenderOrchestrator {
339
366
  });
340
367
  return [...new Set([...sourcePaths, ...templateClosure])];
341
368
  }
342
- async captureRenderedBody(body) {
343
- const response = new Response(body);
344
- if (typeof body === 'string') {
345
- return {
346
- body,
347
- html: await response.text(),
348
- };
349
- }
350
- if (!response.body) {
351
- return {
352
- body,
353
- html: await response.text(),
354
- };
355
- }
356
- const [capturedBody, replayBody] = response.body.tee();
357
- return {
358
- body: replayBody,
359
- html: await new Response(capturedBody).text(),
360
- };
361
- }
362
369
  }
363
370
  /**
364
371
  * @remarks
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Whether `page` is a declared component whose build-time identity names `file`, absolute or relative to `rootDir`.
3
+ *
4
+ * @remarks
5
+ * The identity transform stamps the file that holds the literal `eco.page(...)` call, so a Page made by a
6
+ * wrapper in another file, or re-exported from one, names that other file.
7
+ */
8
+ export declare function isPageDeclaredIn(file: string, page: unknown, rootDir: string): boolean;
9
+ /**
10
+ * Whether `page` is a function carrying a `config`, which is what a wrapped or re-exported `eco.page()` result
11
+ * looks like when {@link isPageDeclaredIn} fails.
12
+ */
13
+ export declare function isUnattributedPage(page: unknown): boolean;
14
+ /** The error for a view or route file whose Page the build did not attribute to it. */
15
+ export declare function createLiteralPageDeclarationError(file: string): Error;
16
+ /**
17
+ * Fails when a view loaded from `file` is not a Page that file declares with a literal `eco.page(...)` call.
18
+ *
19
+ * @remarks
20
+ * Applies the route-file check to views passed to `app.static()`, `app.errorPage()` and `ctx.render()`, so a view
21
+ * behaves the same however it is routed. A value that is not a declared component at all is left to the
22
+ * renderer lookup, which reports a missing integration.
23
+ * @throws When `view` carries a config that the build did not attribute to `file`.
24
+ */
25
+ export declare function assertViewDeclaredIn(file: string, view: unknown, rootDir: string): void;
@@ -0,0 +1,39 @@
1
+ import { path } from '@ecopages/file-system/path';
2
+ import { getComponentIdentity } from '../eco/component-identity.js';
3
+ import { isEcoDeclaredComponent } from '../eco/eco-declared-component.js';
4
+ /**
5
+ * Whether `page` is a declared component whose build-time identity names `file`, absolute or relative to `rootDir`.
6
+ *
7
+ * @remarks
8
+ * The identity transform stamps the file that holds the literal `eco.page(...)` call, so a Page made by a
9
+ * wrapper in another file, or re-exported from one, names that other file.
10
+ */
11
+ export function isPageDeclaredIn(file, page, rootDir) {
12
+ const identityFile = isEcoDeclaredComponent(page) ? getComponentIdentity(page)?.file : undefined;
13
+ return identityFile !== undefined && path.resolve(rootDir, identityFile) === path.resolve(rootDir, file);
14
+ }
15
+ /**
16
+ * Whether `page` is a function carrying a `config`, which is what a wrapped or re-exported `eco.page()` result
17
+ * looks like when {@link isPageDeclaredIn} fails.
18
+ */
19
+ export function isUnattributedPage(page) {
20
+ return typeof page === 'function' && typeof page.config === 'object';
21
+ }
22
+ /** The error for a view or route file whose Page the build did not attribute to it. */
23
+ export function createLiteralPageDeclarationError(file) {
24
+ return new Error(`[ecopages] ${file} default-exports an eco.page() result that the build did not attribute to this file. A route file declares its Page with a literal \`eco.page(...)\` call in that file. The build finds eco.page, eco.layout, eco.component and eco.html by their literal call, so a wrapper function, an alias such as \`const page = eco.page\`, a renamed import, or a Page declared in another file and re-exported gives the Page no identity or another file's, and server options such as props and metadata stay in the browser bundle. Call eco.page(...) directly in ${file}.`);
25
+ }
26
+ /**
27
+ * Fails when a view loaded from `file` is not a Page that file declares with a literal `eco.page(...)` call.
28
+ *
29
+ * @remarks
30
+ * Applies the route-file check to views passed to `app.static()`, `app.errorPage()` and `ctx.render()`, so a view
31
+ * behaves the same however it is routed. A value that is not a declared component at all is left to the
32
+ * renderer lookup, which reports a missing integration.
33
+ * @throws When `view` carries a config that the build did not attribute to `file`.
34
+ */
35
+ export function assertViewDeclaredIn(file, view, rootDir) {
36
+ if (isUnattributedPage(view) && !isPageDeclaredIn(file, view, rootDir)) {
37
+ throw createLiteralPageDeclarationError(file);
38
+ }
39
+ }