@ecopages/core 0.4.0 → 0.6.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 (163) hide show
  1. package/README.md +19 -15
  2. package/package.json +13 -4
  3. package/src/adapters/create-app.js +9 -5
  4. package/src/adapters/node/create-app.d.ts +18 -16
  5. package/src/adapters/node/create-app.js +26 -30
  6. package/src/adapters/node/server-adapter.d.ts +26 -9
  7. package/src/adapters/node/server-adapter.js +38 -8
  8. package/src/adapters/shared/hmr/hmr-manager.js +3 -2
  9. package/src/adapters/shared/http/api-request-pipeline.js +2 -2
  10. package/src/adapters/shared/http/dist-file-handler.js +25 -7
  11. package/src/adapters/shared/runtime/render-context.d.ts +2 -1
  12. package/src/adapters/shared/runtime/render-context.js +18 -21
  13. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +4 -3
  14. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +6 -4
  15. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +6 -1
  16. package/src/adapters/shared/runtime/server-request-pipeline.js +11 -10
  17. package/src/adapters/shared/runtime/server-route-handler.js +4 -4
  18. package/src/adapters/shared/runtime/server-static-builder.d.ts +11 -11
  19. package/src/adapters/shared/runtime/server-static-builder.js +37 -18
  20. package/src/assets/app-browser-client-build.js +8 -21
  21. package/src/assets/app-browser-client-manifest.d.ts +1 -4
  22. package/src/assets/app-browser-client-manifest.js +6 -78
  23. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +2 -2
  24. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +2 -2
  25. package/src/assets/browser-asset-output.d.ts +1 -1
  26. package/src/assets/browser-asset-output.js +1 -1
  27. package/src/build/app-build-manifest-runtime.d.ts +11 -1
  28. package/src/build/app-build-manifest-runtime.js +17 -3
  29. package/src/build/cache/pages-unified-graph-build.d.ts +32 -35
  30. package/src/build/cache/pages-unified-graph-build.js +206 -124
  31. package/src/build/cache/server-module-entries.d.ts +35 -0
  32. package/src/build/cache/server-module-entries.js +109 -0
  33. package/src/build/contracts/build-contracts.d.ts +5 -0
  34. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  35. package/src/build/contracts/content-virtual-modules.js +11 -5
  36. package/src/build/contracts.d.ts +1 -1
  37. package/src/build/contracts.js +1 -1
  38. package/src/build/copy-server-files.d.ts +10 -0
  39. package/src/build/copy-server-files.js +37 -0
  40. package/src/build/preserve-import-meta-transform.d.ts +1 -1
  41. package/src/build/preserve-import-meta-transform.js +1 -1
  42. package/src/build/production-build-id.d.ts +9 -0
  43. package/src/build/production-build-id.js +19 -0
  44. package/src/build/production-dist-complete.d.ts +5 -0
  45. package/src/build/production-dist-complete.js +101 -0
  46. package/src/build/production-route-list.d.ts +26 -0
  47. package/src/build/production-route-list.js +78 -0
  48. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +2 -2
  49. package/src/build/rolldown/rolldown-adapter-helpers.js +56 -4
  50. package/src/build/rolldown/rolldown-build-adapter.js +1 -1
  51. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  52. package/src/build/runtime/build-request-identity.js +2 -1
  53. package/src/build/runtime/build-request-policy.d.ts +3 -2
  54. package/src/build/runtime/build-request-policy.js +5 -3
  55. package/src/build/server/import-view-module.d.ts +11 -0
  56. package/src/build/server/import-view-module.js +21 -0
  57. package/src/build/server/imported-view-plugin.d.ts +16 -0
  58. package/src/build/server/imported-view-plugin.js +59 -0
  59. package/src/build/server/page-module-import.service.d.ts +19 -20
  60. package/src/build/server/page-module-import.service.js +65 -36
  61. package/src/build/server/resolve-static-view.d.ts +9 -0
  62. package/src/build/server/resolve-static-view.js +28 -0
  63. package/src/build/server/route-module-build-cache-registry.d.ts +5 -3
  64. package/src/build/server/route-module-build-cache-registry.js +5 -3
  65. package/src/build/server/server-modules-manifest.d.ts +51 -0
  66. package/src/build/server/server-modules-manifest.js +129 -0
  67. package/src/build/server/view-reference.d.ts +38 -0
  68. package/src/build/server/view-reference.js +112 -0
  69. package/src/build/server-bundle-deploy-manifest.d.ts +9 -9
  70. package/src/build/server-bundle-deploy-manifest.js +24 -28
  71. package/src/build.d.ts +4 -2
  72. package/src/build.js +4 -2
  73. package/src/config/assembly/app-runtime.d.ts +15 -2
  74. package/src/config/assembly/app-runtime.js +3 -1
  75. package/src/config/assembly/finalize-config.js +64 -13
  76. package/src/config/index.d.ts +1 -0
  77. package/src/config/index.js +1 -0
  78. package/src/config/internal-types.d.ts +6 -0
  79. package/src/config/load-eco-config.d.ts +1 -0
  80. package/src/config/load-eco-config.js +11 -2
  81. package/src/config/resolve-eco-config-path.d.ts +2 -1
  82. package/src/config/resolve-eco-config-path.js +21 -15
  83. package/src/config/user-config-types.d.ts +9 -2
  84. package/src/dev/transform-server/dev-transform-server.js +1 -1
  85. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  86. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  87. package/src/errors/http-error.d.ts +9 -0
  88. package/src/errors/http-error.js +11 -0
  89. package/src/html/html-transformer.service.d.ts +0 -21
  90. package/src/html/html-transformer.service.js +0 -32
  91. package/src/html-pages/html-page-module.d.ts +19 -0
  92. package/src/html-pages/html-page-module.js +66 -13
  93. package/src/html-pages/html-page-renderer.d.ts +6 -1
  94. package/src/html-pages/html-page-renderer.js +14 -6
  95. package/src/html-pages/html-pages.plugin.d.ts +10 -0
  96. package/src/html-pages/html-pages.plugin.js +7 -1
  97. package/src/index.d.ts +2 -0
  98. package/src/index.js +2 -0
  99. package/src/integration.d.ts +2 -2
  100. package/src/integration.js +1 -1
  101. package/src/islands/island-host.d.ts +1 -2
  102. package/src/islands/island-host.js +1 -2
  103. package/src/page-cache/page-cache-service.d.ts +8 -0
  104. package/src/page-cache/page-cache-service.js +12 -0
  105. package/src/plugins/integration-plugin.d.ts +34 -7
  106. package/src/plugins/integration-plugin.js +14 -2
  107. package/src/plugins/processor.d.ts +18 -1
  108. package/src/plugins/processor.js +20 -1
  109. package/src/plugins/server-dom.d.ts +29 -0
  110. package/src/plugins/server-dom.js +36 -0
  111. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  112. package/src/plugins/tsconfig-import-resolver.js +4 -2
  113. package/src/processor.d.ts +1 -1
  114. package/src/route-renderer/error-pages/error-page-renderer.d.ts +6 -4
  115. package/src/route-renderer/error-pages/error-page-renderer.js +9 -5
  116. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  117. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  118. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  119. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  120. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  121. package/src/route-renderer/orchestration/integration-renderer.d.ts +21 -44
  122. package/src/route-renderer/orchestration/integration-renderer.js +69 -117
  123. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  124. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  125. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  126. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  127. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  128. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.d.ts +21 -0
  129. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.js +31 -0
  130. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +58 -24
  131. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.d.ts +12 -0
  132. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.js +55 -0
  133. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  134. package/src/router/server/route-registry.d.ts +23 -1
  135. package/src/router/server/route-registry.js +41 -14
  136. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +8 -2
  137. package/src/static-site-generator/production-page-browser-graph-prebuild.js +14 -13
  138. package/src/static-site-generator/static-site-generator.d.ts +19 -3
  139. package/src/static-site-generator/static-site-generator.js +78 -40
  140. package/src/types/build-types.d.ts +6 -0
  141. package/src/types/contracts.d.ts +26 -35
  142. package/src/types/eco-api-types.d.ts +1 -1
  143. package/src/types/public-types.d.ts +1 -0
  144. package/src/types/view-reference.d.ts +31 -0
  145. package/src/types/view-reference.js +15 -0
  146. package/src/utils/additional-watch-paths.d.ts +3 -3
  147. package/src/utils/additional-watch-paths.js +3 -1
  148. package/src/utils/resolve-entry-file.d.ts +4 -2
  149. package/src/utils/resolve-entry-file.js +4 -2
  150. package/src/utils/root-relative-path.d.ts +4 -0
  151. package/src/utils/root-relative-path.js +8 -0
  152. package/src/utils/server-bundle-context.d.ts +14 -0
  153. package/src/utils/server-bundle-context.js +45 -0
  154. package/src/watchers/project-watcher-ignore.d.ts +2 -5
  155. package/src/watchers/project-watcher-ignore.js +2 -5
  156. package/src/watchers/project-watcher.d.ts +9 -7
  157. package/src/watchers/project-watcher.js +100 -52
  158. package/src/watchers/workspace-package-watch-roots.d.ts +4 -4
  159. package/src/watchers/workspace-package-watch-roots.js +41 -25
  160. package/src/build/server/view-module-loader.d.ts +0 -10
  161. package/src/build/server/view-module-loader.js +0 -46
  162. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  163. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
@@ -25,9 +25,9 @@ export async function serveDistFile(request, options) {
25
25
  if (!target) {
26
26
  return createBadRequestResponse(method);
27
27
  }
28
- const candidate = findDistFile(target, options);
28
+ const candidate = findDistFile(target, options, distDir);
29
29
  const response = candidate
30
- ? await createDistFileResponse(candidate, ServerUtils.getContentType(candidate), request, options.watchMode)
30
+ ? await createDistFileResponse(candidate, ServerUtils.getContentType(candidate), request, options.watchMode, distDir)
31
31
  : null;
32
32
  if (!response) {
33
33
  return await createNotFoundResponse(request, options, distDir, method);
@@ -46,7 +46,13 @@ function resolveRequestTarget(request, distDir) {
46
46
  const requestedPath = path.resolve(distDir, relativePath);
47
47
  return isPathInside(distDir, requestedPath) ? { pathname, requestedPath } : undefined;
48
48
  }
49
- function findDistFile({ pathname, requestedPath }, options) {
49
+ /**
50
+ * Resolves a requested file only when its real path remains inside the served directory.
51
+ *
52
+ * @remarks
53
+ * This keeps an in-root symbolic link working while rejecting a link to output stored beside the client directory.
54
+ */
55
+ function findDistFile({ pathname, requestedPath }, options, distDir) {
50
56
  if (options.staticFilesOnly && !ServerUtils.hasKnownStaticExtension(pathname)) {
51
57
  return undefined;
52
58
  }
@@ -55,7 +61,9 @@ function findDistFile({ pathname, requestedPath }, options) {
55
61
  : fileSystem.exists(requestedPath) && !fileSystem.isDirectory(requestedPath)
56
62
  ? requestedPath
57
63
  : undefined;
58
- return candidate && path.basename(candidate) !== HASHED_BROWSER_ASSET_INDEX_FILENAME ? candidate : undefined;
64
+ if (!candidate || path.basename(candidate) === HASHED_BROWSER_ASSET_INDEX_FILENAME)
65
+ return undefined;
66
+ return isRealPathInside(distDir, candidate) ? candidate : undefined;
59
67
  }
60
68
  async function createNotFoundResponse(request, options, distDir, method) {
61
69
  const response = options.notFound
@@ -75,7 +83,9 @@ function createBadRequestResponse(method) {
75
83
  }
76
84
  async function createDistNotFoundResponse(request, distDir) {
77
85
  const notFoundPath = path.join(distDir, '404.html');
78
- if (fileSystem.exists(notFoundPath) && !fileSystem.isDirectory(notFoundPath)) {
86
+ if (fileSystem.exists(notFoundPath) &&
87
+ !fileSystem.isDirectory(notFoundPath) &&
88
+ isRealPathInside(distDir, notFoundPath)) {
79
89
  const body = request.method === 'HEAD' ? null : fileSystem.readFileAsBuffer(notFoundPath);
80
90
  return new Response(body, {
81
91
  status: 404,
@@ -87,11 +97,19 @@ async function createDistNotFoundResponse(request, distDir) {
87
97
  headers: { 'Content-Type': 'text/plain' },
88
98
  });
89
99
  }
90
- async function createDistFileResponse(filePath, contentType, request, watchMode) {
100
+ function isRealPathInside(root, candidate) {
101
+ try {
102
+ return isPathInside(fileSystem.realpath(root), fileSystem.realpath(candidate));
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ async function createDistFileResponse(filePath, contentType, request, watchMode, distDir) {
91
109
  try {
92
110
  const gzipPath = `${filePath}.gz`;
93
111
  const gzipEligible = !watchMode && (contentType === 'text/javascript' || contentType === 'text/css');
94
- const hasGzipVariant = gzipEligible && fileSystem.exists(gzipPath);
112
+ const hasGzipVariant = gzipEligible && fileSystem.exists(gzipPath) && isRealPathInside(distDir, gzipPath);
95
113
  const useGzip = hasGzipVariant && acceptsGzip(request.headers.get('Accept-Encoding'));
96
114
  const file = fileSystem.readFileAsBuffer(useGzip ? gzipPath : filePath);
97
115
  const cacheHeaders = fileCacheHeaders(filePath, file, watchMode);
@@ -8,7 +8,8 @@ export interface CreateRenderContextOptions {
8
8
  /**
9
9
  * Creates a render context for route handlers.
10
10
  * Provides render(), renderPartial(), json(), and html() methods that can be used
11
- * within route handlers to generate responses.
11
+ * within route handlers to generate responses. Imported views resolve through
12
+ * `importServerModule` so development invalidation and the production map apply.
12
13
  *
13
14
  * @param options - Configuration options including available integrations
14
15
  * @returns A RenderContext object with methods for rendering views and creating responses
@@ -1,10 +1,7 @@
1
- import { fileURLToPath } from 'node:url';
1
+ import { isViewReference } from '../../../types/view-reference.js';
2
2
  import { getComponentOwner } from '../../../eco/component-identity.js';
3
3
  import { invariant } from '../../../utils/invariant.js';
4
4
  import { createBodyResponse } from '../http/create-body-response.js';
5
- function resolveServerModulePath(filePath) {
6
- return filePath instanceof URL ? fileURLToPath(filePath) : filePath;
7
- }
8
5
  /**
9
6
  * Merges request locals into component props as a dedicated 'locals' property.
10
7
  * This prevents naming conflicts and maintains type safety by keeping locals
@@ -33,7 +30,8 @@ function createExplicitViewContext(scope, renderOptions, partial) {
33
30
  /**
34
31
  * Creates a render context for route handlers.
35
32
  * Provides render(), renderPartial(), json(), and html() methods that can be used
36
- * within route handlers to generate responses.
33
+ * within route handlers to generate responses. Imported views resolve through
34
+ * `importServerModule` so development invalidation and the production map apply.
37
35
  *
38
36
  * @param options - Configuration options including available integrations
39
37
  * @returns A RenderContext object with methods for rendering views and creating responses
@@ -52,30 +50,29 @@ export function createRenderContext(options) {
52
50
  await options.ensureIntegrationReady?.(integrationName);
53
51
  return integration.getRenderer();
54
52
  };
53
+ const resolveView = async (view) => {
54
+ if (!isViewReference(view)) {
55
+ return view;
56
+ }
57
+ invariant(!!options.importServerModule, 'Imported views need the server-module loader.');
58
+ const module = (await options.importServerModule(view.filePath));
59
+ invariant(!!module.default, `View module ${view.filePath} has no default export.`);
60
+ return module.default;
61
+ };
55
62
  const renderContext = {
56
- importServerModule: async (filePath) => {
57
- invariant(!!options.importServerModule, 'Server module importing is not available in this render context.');
58
- return (await options.importServerModule(resolveServerModulePath(filePath)));
59
- },
60
- async renderServerModule(filePath, props, renderOptions) {
61
- const module = await renderContext.importServerModule(filePath);
62
- const view = module.default;
63
- const locals = this?.locals;
64
- const mergedProps = mergePropsWithLocals(props ?? {}, locals);
65
- const renderer = await getRendererForView(view);
66
- return await renderer.renderExplicitView(view, mergedProps, createExplicitViewContext(this, renderOptions, false));
67
- },
68
63
  async render(view, props, renderOptions) {
69
64
  const locals = this?.locals;
70
65
  const mergedProps = mergePropsWithLocals(props ?? {}, locals);
71
- const renderer = await getRendererForView(view);
72
- return renderer.renderExplicitView(view, mergedProps, createExplicitViewContext(this, renderOptions, false));
66
+ const resolvedView = await resolveView(view);
67
+ const renderer = await getRendererForView(resolvedView);
68
+ return renderer.renderExplicitView(resolvedView, mergedProps, createExplicitViewContext(this, renderOptions, false));
73
69
  },
74
70
  async renderPartial(view, props, renderOptions) {
75
71
  const locals = this?.locals;
76
72
  const mergedProps = mergePropsWithLocals(props, locals);
77
- const renderer = await getRendererForView(view);
78
- return renderer.renderExplicitView(view, mergedProps, createExplicitViewContext(this, renderOptions, true));
73
+ const resolvedView = await resolveView(view);
74
+ const renderer = await getRendererForView(resolvedView);
75
+ return renderer.renderExplicitView(resolvedView, mergedProps, createExplicitViewContext(this, renderOptions, true));
79
76
  },
80
77
  json(data, responseOptions) {
81
78
  return createBodyResponse('json', data, {
@@ -1,7 +1,7 @@
1
1
  import type { EcoPagesAppConfig, IHmrManager } from '../../../config/internal-types.js';
2
2
  import type { ProjectWatcher } from '../../../watchers/project-watcher.js';
3
3
  /**
4
- * Copies source `public/` into dist and ensures the resolved assets directory exists.
4
+ * Copies source `public/` into the client output and ensures the resolved assets directory exists.
5
5
  */
6
6
  export declare function prepareRuntimePublicDir(appConfig: EcoPagesAppConfig): void;
7
7
  /**
@@ -29,8 +29,9 @@ export declare function startDevWarmup(options: {
29
29
  *
30
30
  * @remarks
31
31
  * A server that never ran a `DevSession` passes only `appConfig`. Integration `setup()` calls still in flight
32
- * settle before any `teardown()`, so a late setup cannot recreate released resources. A failed
33
- * integration `teardown()` still clears activation state, so the next startup runs `setup()` again.
32
+ * and page-cache regenerations settle before any `teardown()`, so a late setup or revalidating cache
33
+ * render cannot recreate or use released resources. A failed integration `teardown()` still clears
34
+ * activation state, so the next startup runs `setup()` again.
34
35
  */
35
36
  export declare function disposeDevResources(options: {
36
37
  appConfig: EcoPagesAppConfig;
@@ -6,12 +6,12 @@ import { ensureIntegrationRuntimeReady, teardownAppRuntimeIntegrations, } from '
6
6
  import { appLogger } from '../../../global/app-logger.js';
7
7
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
8
8
  /**
9
- * Copies source `public/` into dist and ensures the resolved assets directory exists.
9
+ * Copies source `public/` into the client output and ensures the resolved assets directory exists.
10
10
  */
11
11
  export function prepareRuntimePublicDir(appConfig) {
12
12
  const srcPublicDir = path.join(appConfig.rootDir, appConfig.srcDir, appConfig.publicDir);
13
13
  if (fileSystem.exists(srcPublicDir)) {
14
- copyRuntimePublicDirIfChanged(srcPublicDir, path.join(appConfig.rootDir, appConfig.distDir));
14
+ copyRuntimePublicDirIfChanged(srcPublicDir, appConfig.absolutePaths.distDir);
15
15
  }
16
16
  fileSystem.ensureDir(path.join(appConfig.absolutePaths.distDir, RESOLVED_ASSETS_DIR));
17
17
  }
@@ -60,8 +60,9 @@ export async function startDevWarmup(options) {
60
60
  *
61
61
  * @remarks
62
62
  * A server that never ran a `DevSession` passes only `appConfig`. Integration `setup()` calls still in flight
63
- * settle before any `teardown()`, so a late setup cannot recreate released resources. A failed
64
- * integration `teardown()` still clears activation state, so the next startup runs `setup()` again.
63
+ * and page-cache regenerations settle before any `teardown()`, so a late setup or revalidating cache
64
+ * render cannot recreate or use released resources. A failed integration `teardown()` still clears
65
+ * activation state, so the next startup runs `setup()` again.
65
66
  */
66
67
  export async function disposeDevResources(options) {
67
68
  const runtime = requireAppRuntime(options.appConfig);
@@ -70,6 +71,7 @@ export async function disposeDevResources(options) {
70
71
  () => options.projectWatcher?.close(),
71
72
  () => hmrManager?.stop(),
72
73
  () => options.bridge?.destroy(),
74
+ () => runtime.pageCache?.waitForInFlightRegenerations(),
73
75
  () => teardownAppRuntimeIntegrations({ appConfig: options.appConfig }),
74
76
  ];
75
77
  const errors = [];
@@ -13,22 +13,27 @@ export type ServerRequestContext<TServer = unknown> = {
13
13
  errorHandler?: ErrorHandler<Request, TServer>;
14
14
  serverInstance?: TServer;
15
15
  };
16
+ /** Runs one request or prewarm. */
17
+ export type RequestBuildScope = <T>(operation: () => Promise<T>) => Promise<T>;
16
18
  export type ServerRequestPipelineOptions = {
17
19
  appConfig: EcoPagesAppConfig;
18
20
  runtime: AppRuntime;
19
21
  watch?: boolean;
22
+ /** When omitted, there is no build-queue scope and no build-input recording. */
23
+ runInRequestBuildScope?: RequestBuildScope;
20
24
  };
21
25
  export declare class ServerRequestPipeline {
22
26
  protected readonly appConfig: EcoPagesAppConfig;
23
27
  protected readonly runtime: AppRuntime;
24
28
  private readonly watchMode;
29
+ private readonly runInRequestBuildScope;
25
30
  protected router: RouteRegistry;
26
31
  protected fileSystemResponseMatcher: FileSystemResponseMatcher;
27
32
  protected routeRendererFactory: RouteRendererFactory;
28
33
  protected routeHandler: ServerRouteHandler;
29
34
  protected readonly apiRequestPipeline: ApiRequestPipeline<Request, unknown>;
30
35
  private sharedPageCacheService;
31
- /** The one endpoint loader, shared by requests and the build, so both compile a file the same way. */
36
+ /** The one endpoint loader, shared by requests and the build. Production imports the emitted module. */
32
37
  private readonly importEndpointModule;
33
38
  private readonly endpointRouteHandler;
34
39
  /** Warnings already logged, so a dev route refresh repeats none of them. */
@@ -1,9 +1,8 @@
1
1
  import path from 'node:path';
2
+ import { getServerModuleBuildCacheOutdir } from '../../../build/server/route-module-build-cache-registry.js';
2
3
  import { RouteRendererFactory } from '../../../route-renderer/route-renderer.js';
3
4
  import { RouteRegistry } from '../../../router/server/route-registry.js';
4
5
  import { startupTrace } from '../../../diagnostics/startup-trace.js';
5
- import { requireBuildQueue } from '../../../build/runtime/build-queue.js';
6
- import { runWithBuildInputIndex } from '../../../build/cache/build-input-dependency-index.js';
7
6
  import { requireAppRuntime } from '../../../utils/app-runtime.js';
8
7
  import { MemoryCacheStore } from '../../../page-cache/memory-cache-store.js';
9
8
  import { PageCacheService } from '../../../page-cache/page-cache-service.js';
@@ -17,12 +16,12 @@ import { EndpointRouteHandler, findExplicitRoutesOnEndpoints, } from '../http/en
17
16
  import { appLogger } from '../../../global/app-logger.js';
18
17
  import { parseSegmentPath } from '../../../router/server/segment-path-matcher.js';
19
18
  import { isHtmlResponse, withUncachedDevHtml } from '../hmr/hmr-html-response.js';
20
- import { resolveInternalExecutionDir } from '../../../utils/resolve-work-dir.js';
21
19
  import { ensureIntegrationRuntimeReady } from '../../../build/app-build-manifest-runtime.js';
22
20
  export class ServerRequestPipeline {
23
21
  appConfig;
24
22
  runtime;
25
23
  watchMode;
24
+ runInRequestBuildScope;
26
25
  router;
27
26
  fileSystemResponseMatcher;
28
27
  routeRendererFactory;
@@ -32,7 +31,7 @@ export class ServerRequestPipeline {
32
31
  getCacheService: () => this.getCacheService(),
33
32
  });
34
33
  sharedPageCacheService;
35
- /** The one endpoint loader, shared by requests and the build, so both compile a file the same way. */
34
+ /** The one endpoint loader, shared by requests and the build. Production imports the emitted module. */
36
35
  importEndpointModule = (filePath) => this.importServerModule(filePath);
37
36
  endpointRouteHandler = new EndpointRouteHandler({
38
37
  apiRequestPipeline: this.apiRequestPipeline,
@@ -44,6 +43,7 @@ export class ServerRequestPipeline {
44
43
  this.appConfig = options.appConfig;
45
44
  this.runtime = options.runtime;
46
45
  this.watchMode = options.watch ?? false;
46
+ this.runInRequestBuildScope = options.runInRequestBuildScope ?? ((operation) => operation());
47
47
  }
48
48
  /**
49
49
  * Renders one declared path inside the request build scope for a DevSession prewarm.
@@ -52,10 +52,10 @@ export class ServerRequestPipeline {
52
52
  * resolve as they would for a request
53
53
  */
54
54
  async renderDevPrewarmPath(pathname, runtimeOrigin, requestContext) {
55
- await requireBuildQueue(this.appConfig).withRequestScope(() => runWithBuildInputIndex(requireAppRuntime(this.appConfig).buildInputIndex, async () => {
55
+ await this.runInRequestBuildScope(async () => {
56
56
  const response = await this.routeHandler.handleResponse(new Request(new URL(pathname, runtimeOrigin).toString(), { method: 'GET' }), requestContext);
57
57
  await response.arrayBuffer();
58
- }));
58
+ });
59
59
  }
60
60
  async initializeRouteHandling(options) {
61
61
  this.ensureRouteRendererFactory();
@@ -133,6 +133,7 @@ export class ServerRequestPipeline {
133
133
  return {
134
134
  staticPaths: pageComponent?.staticPaths ?? module.getStaticPaths,
135
135
  staticProps: pageComponent?.staticProps ?? module.getStaticProps,
136
+ cache: pageComponent?.cache,
136
137
  };
137
138
  },
138
139
  };
@@ -161,7 +162,7 @@ export class ServerRequestPipeline {
161
162
  const cacheService = this.getOrCreateSharedPageCacheService();
162
163
  const fileSystemResponseMatcher = new FileSystemResponseMatcher({
163
164
  appConfig: this.appConfig,
164
- assetPrefix: path.join(this.appConfig.rootDir, this.appConfig.distDir),
165
+ assetPrefix: this.appConfig.absolutePaths.distDir,
165
166
  router: this.router,
166
167
  routeRendererFactory: this.routeRendererFactory,
167
168
  errorPageLoaders,
@@ -220,7 +221,7 @@ export class ServerRequestPipeline {
220
221
  async importServerModule(filePath) {
221
222
  return await requireAppRuntime(this.appConfig).moduleLoader.importModule({
222
223
  filePath,
223
- outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
224
+ outdir: getServerModuleBuildCacheOutdir(this.appConfig),
224
225
  externalPackages: true,
225
226
  });
226
227
  }
@@ -274,7 +275,7 @@ export class ServerRequestPipeline {
274
275
  * The Node host maps its native HTTP request into a Web Request before calling this method.
275
276
  */
276
277
  async handleSharedRequest(request, context) {
277
- return requireBuildQueue(this.appConfig).withRequestScope(() => runWithBuildInputIndex(requireAppRuntime(this.appConfig).buildInputIndex, () => startupTrace.traceFirstRequest(request, async () => {
278
+ return this.runInRequestBuildScope(() => startupTrace.traceFirstRequest(request, async () => {
278
279
  let parsedPathSegments;
279
280
  try {
280
281
  parsedPathSegments = parseSegmentPath(new URL(request.url).pathname);
@@ -300,6 +301,6 @@ export class ServerRequestPipeline {
300
301
  }
301
302
  const routeResponse = await this.routeHandler.handleResponse(request, context, parsedPathSegments);
302
303
  return await this.injectSharedHmrHtmlResponse(routeResponse);
303
- })));
304
+ }));
304
305
  }
305
306
  }
@@ -65,8 +65,8 @@ export class ServerRouteHandler {
65
65
  : this.fileSystemResponseMatcher.handleMatch(fsMatch, request));
66
66
  }
67
67
  catch (error) {
68
- if (error instanceof HttpError) {
69
- return error.toResponse();
68
+ if (HttpError.isHttpError(error)) {
69
+ return HttpError.responseFor(error);
70
70
  }
71
71
  throw error;
72
72
  }
@@ -88,8 +88,8 @@ export class ServerRouteHandler {
88
88
  return await this.fileSystemResponseMatcher.handleNoMatch(pathname, request);
89
89
  }
90
90
  catch (error) {
91
- if (error instanceof HttpError) {
92
- return error.toResponse();
91
+ if (HttpError.isHttpError(error)) {
92
+ return HttpError.responseFor(error);
93
93
  }
94
94
  if (error instanceof Error) {
95
95
  this.router.appConfig?.appRuntime?.hmr?.broadcast({ type: 'error', message: error.message });
@@ -61,18 +61,18 @@ export declare class ServerStaticBuilder {
61
61
  runtimeOrigin: string;
62
62
  }): void;
63
63
  /**
64
- * Empties `dist/` and copies the public directory into it.
64
+ * Empties the configured output directory, then copies public files into `client/`.
65
65
  *
66
66
  * @remarks
67
- * Every build renders from source in a fresh process, so nothing in a previous `dist/` is reusable.
67
+ * Every build renders from source in a fresh process, so nothing in a previous output is reusable.
68
68
  */
69
69
  private prepareExportDirectory;
70
70
  /**
71
- * Empties `dist/`, copies the public directory into it and sets the Processors up.
71
+ * Empties `dist/`, copies the public directory into `dist/client/` and sets the Processors up.
72
72
  *
73
73
  * @remarks
74
74
  * Call it before the router reads any Page, so a Page module that resolves what a Processor generates in
75
- * `setup()` finds it. Integrations are set up later, when the static site generator starts rendering. The next
75
+ * `setup()` finds it. Integrations are activated when production emit imports their modules. The next
76
76
  * {@link build} then skips this work once; a build without a prior call prepares the export itself.
77
77
  */
78
78
  prepareExport(): Promise<void>;
@@ -88,10 +88,10 @@ export declare class ServerStaticBuilder {
88
88
  * Source code is bundled: the app entry graph, workspace packages and
89
89
  * TypeScript packages such as Core. Compiled packages from `node_modules`
90
90
  * stay external (bare when the app declares them, otherwise relative to
91
- * `dist/.server/`), so native bindings load from the installed tree. The
92
- * entry is written to a staging directory, so the request passes
93
- * `runtimeOutdir` and bundled `import.meta` reads resolve against the
94
- * sources from `dist/.server/`.
91
+ * `dist/server/`), so native bindings load from the installed tree. The
92
+ * application bundle is written as `app.bundle.mjs`; `app.mjs` records the
93
+ * bundle directory before importing it, including when a host wrapper loads it.
94
+ * Production `import.meta` points at the emitted files in `dist/server/`.
95
95
  *
96
96
  * Throws if the build adapter is unavailable or bundling fails.
97
97
  *
@@ -106,9 +106,9 @@ export declare class ServerStaticBuilder {
106
106
  * @param dependencies.importServerModule - The server-module loader endpoint requests use
107
107
  *
108
108
  * @remarks
109
- * Every endpoint file is imported and its exports checked as its first request would, before the
110
- * server bundle and static generation, so a broken one fails the build with the request's error.
111
- * The import is cached in this process only; `ecopages start` compiles the file again.
109
+ * Every server entry is emitted into `dist/server/` before endpoints are checked, so a broken
110
+ * module fails the build with the error its first request would log. `ecopages start` loads those
111
+ * emitted modules and never compiles.
112
112
  */
113
113
  build(options: StaticBuildOptions | undefined, dependencies: {
114
114
  router: RouteRegistry;
@@ -5,14 +5,19 @@ import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT, RESOLVED_ASSETS_DIR }
5
5
  import { appLogger } from '../../../global/app-logger.js';
6
6
  import { setupAppRuntimePlugins } from '../../../build/build-adapter.js';
7
7
  import { createServerBundleStagingDirectory, publishServerBundleDirectory, removeServerBundleStagingDirectory, } from '../../../build/server-bundle-publication.js';
8
+ import { createImportedViewPlugin } from '../../../build/server/imported-view-plugin.js';
8
9
  import { createServerBuildRequest } from '../../../build/runtime/build-request-policy.js';
9
10
  import { buildOrThrow } from '../../../build/runtime/build-queue.js';
10
11
  import { attachHmrToIntegrations } from './runtime-server-lifecycle.js';
12
+ import { copyDeclaredServerFiles } from '../../../build/copy-server-files.js';
13
+ import { writeProductionRouteList } from '../../../build/production-route-list.js';
11
14
  import { getServerBundleOutputPaths, writeServerBundleDeployManifest, } from '../../../build/server-bundle-deploy-manifest.js';
12
15
  import { bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME } from '../../../config/server-config-bundle.js';
13
- import { resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
16
+ import { CLIENT_OUTPUT_DIR, resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
17
+ import { createServerBundleLoaderSource, SERVER_BUNDLE_IMPLEMENTATION_FILENAME, } from '../../../utils/server-bundle-context.js';
14
18
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
15
19
  import { readEndpointHandlers } from '../http/endpoint-route-handler.js';
20
+ import { emitProductionServerModules, shouldBuildPagesUnifiedGraph, } from '../../../build/cache/pages-unified-graph-build.js';
16
21
  /**
17
22
  * Handles static site generation.
18
23
  */
@@ -39,14 +44,16 @@ export class ServerStaticBuilder {
39
44
  this.serveOptions = { ...this.serveOptions, port: input.port };
40
45
  }
41
46
  /**
42
- * Empties `dist/` and copies the public directory into it.
47
+ * Empties the configured output directory, then copies public files into `client/`.
43
48
  *
44
49
  * @remarks
45
- * Every build renders from source in a fresh process, so nothing in a previous `dist/` is reusable.
50
+ * Every build renders from source in a fresh process, so nothing in a previous output is reusable.
46
51
  */
47
52
  prepareExportDirectory() {
48
- const exportDir = this.appConfig.absolutePaths?.distDir ?? path.join(this.appConfig.rootDir, this.appConfig.distDir);
49
- fileSystem.ensureDir(exportDir, true);
53
+ const { distDir: outputDir } = getServerBundleOutputPaths(this.appConfig);
54
+ const exportDir = this.appConfig.absolutePaths?.distDir ?? path.join(outputDir, CLIENT_OUTPUT_DIR);
55
+ fileSystem.ensureDir(outputDir, true);
56
+ fileSystem.ensureDir(exportDir);
50
57
  this.runtime.runtimeAssetsPrepared = false;
51
58
  const srcPublicDir = path.join(this.appConfig.rootDir, this.appConfig.srcDir ?? 'src', this.appConfig.publicDir ?? 'public');
52
59
  if (fileSystem.exists(srcPublicDir)) {
@@ -55,11 +62,11 @@ export class ServerStaticBuilder {
55
62
  fileSystem.ensureDir(path.join(exportDir, RESOLVED_ASSETS_DIR));
56
63
  }
57
64
  /**
58
- * Empties `dist/`, copies the public directory into it and sets the Processors up.
65
+ * Empties `dist/`, copies the public directory into `dist/client/` and sets the Processors up.
59
66
  *
60
67
  * @remarks
61
68
  * Call it before the router reads any Page, so a Page module that resolves what a Processor generates in
62
- * `setup()` finds it. Integrations are set up later, when the static site generator starts rendering. The next
69
+ * `setup()` finds it. Integrations are activated when production emit imports their modules. The next
63
70
  * {@link build} then skips this work once; a build without a prior call prepares the export itself.
64
71
  */
65
72
  async prepareExport() {
@@ -92,10 +99,10 @@ export class ServerStaticBuilder {
92
99
  * Source code is bundled: the app entry graph, workspace packages and
93
100
  * TypeScript packages such as Core. Compiled packages from `node_modules`
94
101
  * stay external (bare when the app declares them, otherwise relative to
95
- * `dist/.server/`), so native bindings load from the installed tree. The
96
- * entry is written to a staging directory, so the request passes
97
- * `runtimeOutdir` and bundled `import.meta` reads resolve against the
98
- * sources from `dist/.server/`.
102
+ * `dist/server/`), so native bindings load from the installed tree. The
103
+ * application bundle is written as `app.bundle.mjs`; `app.mjs` records the
104
+ * bundle directory before importing it, including when a host wrapper loads it.
105
+ * Production `import.meta` points at the emitted files in `dist/server/`.
99
106
  *
100
107
  * Throws if the build adapter is unavailable or bundling fails.
101
108
  *
@@ -121,11 +128,13 @@ export class ServerStaticBuilder {
121
128
  reportPackagesOutsideRoot: true,
122
129
  entrypoints: [entryPath],
123
130
  outdir: stagingDir,
124
- naming: SERVER_BUNDLE_FILENAME,
131
+ naming: SERVER_BUNDLE_IMPLEMENTATION_FILENAME,
125
132
  sourcemap: 'linked',
126
133
  runtimeOutdir: serverOutdir,
134
+ plugins: [createImportedViewPlugin(this.appConfig, { entryPath })],
127
135
  });
128
136
  await buildOrThrow(this.appConfig, buildOptions, 'Failed to bundle server entry file');
137
+ fileSystem.write(stagedServerEntryPath, createServerBundleLoaderSource());
129
138
  writeServerBundleDeployManifest(this.appConfig, stagedServerEntryPath, {
130
139
  emittedConfigModule: configBundle ? EMITTED_ECO_CONFIG_FILENAME : undefined,
131
140
  outputDir: stagingDir,
@@ -145,9 +154,9 @@ export class ServerStaticBuilder {
145
154
  * @param dependencies.importServerModule - The server-module loader endpoint requests use
146
155
  *
147
156
  * @remarks
148
- * Every endpoint file is imported and its exports checked as its first request would, before the
149
- * server bundle and static generation, so a broken one fails the build with the request's error.
150
- * The import is cached in this process only; `ecopages start` compiles the file again.
157
+ * Every server entry is emitted into `dist/server/` before endpoints are checked, so a broken
158
+ * module fails the build with the error its first request would log. `ecopages start` loads those
159
+ * emitted modules and never compiles.
151
160
  */
152
161
  async build(options, dependencies) {
153
162
  const { baseUrl: explicitBaseUrl, force = false } = options ?? {};
@@ -158,12 +167,22 @@ export class ServerStaticBuilder {
158
167
  }
159
168
  this.exportPrepared = false;
160
169
  const endpointRoutes = dependencies.router.templateRoutes.filter((route) => route.role === 'endpoint');
161
- for (const route of endpointRoutes) {
162
- readEndpointHandlers(await dependencies.importServerModule(route.filePath), route);
163
- }
164
170
  if (this.needsServerBundle || endpointRoutes.length > 0) {
165
171
  await this.bundleServerEntry();
166
172
  }
173
+ if (shouldBuildPagesUnifiedGraph()) {
174
+ await emitProductionServerModules({
175
+ appConfig: this.appConfig,
176
+ router: dependencies.router,
177
+ staticRoutes: dependencies.staticRoutes,
178
+ errorPageLoaders: dependencies.errorPageLoaders,
179
+ });
180
+ }
181
+ writeProductionRouteList(this.appConfig, dependencies.router.templateRoutes);
182
+ await copyDeclaredServerFiles(this.appConfig);
183
+ for (const route of endpointRoutes) {
184
+ readEndpointHandlers(await dependencies.importServerModule(route.filePath), route);
185
+ }
167
186
  await this.staticSiteGenerator.run({
168
187
  router: dependencies.router,
169
188
  baseUrl,
@@ -278,7 +278,6 @@ function registerPageClientEntry(appConfig, entriesByKey, cleanupEntries, instan
278
278
  if (!canBundle(dependency)) {
279
279
  instance.prebuiltPageClientBrowserAssets ??= {
280
280
  processedAssets: [],
281
- islandRenderAssetsByFile: new Map(),
282
281
  fallbackDependencies: [],
283
282
  };
284
283
  instance.prebuiltPageClientBrowserAssets.fallbackDependencies.push({
@@ -292,12 +291,9 @@ function registerPageClientEntry(appConfig, entriesByKey, cleanupEntries, instan
292
291
  if (!entry.dependencies.some((entryDependency) => dependencyAssociationKey(entryDependency) === identity)) {
293
292
  entry.dependencies.push(dependency);
294
293
  }
295
- const association = entry.pageClientRoutes.get(identity) ?? {
296
- dependency,
297
- routes: new Map(),
298
- };
299
- association.routes.set(routeKey, clientEntry.islandFile);
300
- entry.pageClientRoutes.set(identity, association);
294
+ const routes = entry.pageClientRoutes.get(identity) ?? new Set();
295
+ routes.add(routeKey);
296
+ entry.pageClientRoutes.set(identity, routes);
301
297
  return { ...clientEntry, dependency };
302
298
  }
303
299
  function prepareRouteBuildPlan(appConfig, plan, entriesByKey, cleanupEntries) {
@@ -335,29 +331,20 @@ function prepareRouteBuildPlans(appConfig, plans, cleanupEntries) {
335
331
  const routePlans = plans.map((plan) => prepareRouteBuildPlan(appConfig, plan, entriesByKey, cleanupEntries));
336
332
  return { routePlans, entries: [...entriesByKey.values()] };
337
333
  }
338
- function attachPageClientAsset(instance, asset, islandFile) {
339
- const prebuilt = instance.prebuiltPageClientBrowserAssets ?? {
340
- processedAssets: [],
341
- islandRenderAssetsByFile: new Map(),
342
- fallbackDependencies: [],
343
- };
334
+ function attachPageClientAsset(instance, asset) {
335
+ const prebuilt = instance.prebuiltPageClientBrowserAssets ?? { processedAssets: [], fallbackDependencies: [] };
344
336
  prebuilt.processedAssets.push(asset);
345
- if (islandFile) {
346
- const islandAssets = prebuilt.islandRenderAssetsByFile.get(islandFile) ?? [];
347
- islandAssets.push(asset);
348
- prebuilt.islandRenderAssetsByFile.set(islandFile, islandAssets);
349
- }
350
337
  instance.prebuiltPageClientBrowserAssets = prebuilt;
351
338
  }
352
339
  function attachEntryAssetToRoutes(entry, dependency, asset, routePlans) {
353
- const clientAssociation = entry.pageClientRoutes.get(dependencyAssociationKey(dependency));
340
+ const pageClientRoutes = entry.pageClientRoutes.get(dependencyAssociationKey(dependency));
354
341
  for (const routePlan of routePlans) {
355
342
  for (const { instance, routeKey } of routePlan.instances) {
356
343
  if (entry.dependencyRoutes.get(dependency)?.has(routeKey)) {
357
344
  instance.prebuiltGroupedAssets = [...(instance.prebuiltGroupedAssets ?? []), asset];
358
345
  }
359
- if (clientAssociation?.routes.has(routeKey)) {
360
- attachPageClientAsset(instance, asset, clientAssociation.routes.get(routeKey));
346
+ if (pageClientRoutes?.has(routeKey)) {
347
+ attachPageClientAsset(instance, asset);
361
348
  }
362
349
  }
363
350
  }
@@ -27,16 +27,15 @@ export type AppBrowserClientManifestEntry = {
27
27
  groupedAssets: SerializedProcessedAsset[];
28
28
  pageClientAssets: {
29
29
  processedAssets: SerializedProcessedAsset[];
30
- islandRenderAssetsByFile: Array<[string, SerializedProcessedAsset[]]>;
31
30
  fallbackPageClientBuildEntryKeys: string[];
32
31
  };
33
32
  };
34
33
  export type AppBrowserClientManifest = {
35
34
  version: 1;
35
+ buildId?: string;
36
36
  entries: AppBrowserClientManifestEntry[];
37
37
  htmlPageModuleScriptUrls: Record<string, string>;
38
38
  htmlPageModuleScriptFingerprint: string;
39
- sourceFingerprints: Record<string, string>;
40
39
  browserOutputPaths: string[];
41
40
  };
42
41
  /** Rewrites the file path inside a client dependency key so it survives moving the project root. */
@@ -62,8 +61,6 @@ export declare function assertAppBrowserClientManifestHtmlOutputsExist(appConfig
62
61
  export declare function assertAppBrowserClientOutputsExist(appConfig: EcoPagesAppConfig, relativeOutputPaths: readonly string[]): void;
63
62
  /** Resolves the project-relative asset paths in a build manifest for the current runtime. */
64
63
  export declare function restoreAppBrowserClientAssets(appConfig: EcoPagesAppConfig, assets: readonly SerializedProcessedAsset[]): ProcessedAsset[];
65
- /** Ensures the source files used by the browser build have not changed since export. */
66
- export declare function assertAppBrowserClientSourcesMatch(appConfig: EcoPagesAppConfig, sourceFingerprints: Readonly<Record<string, string>>): void;
67
64
  /** Resolves an app-relative file path stored in the build manifest. */
68
65
  export declare function resolveAppBrowserClientManifestPath(appConfig: EcoPagesAppConfig, filePath: string): string;
69
66
  export {};