@ecopages/core 0.5.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 (128) hide show
  1. package/README.md +17 -13
  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/dist-file-handler.js +25 -7
  10. package/src/adapters/shared/runtime/render-context.d.ts +2 -1
  11. package/src/adapters/shared/runtime/render-context.js +18 -21
  12. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +4 -3
  13. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +6 -4
  14. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +6 -1
  15. package/src/adapters/shared/runtime/server-request-pipeline.js +10 -10
  16. package/src/adapters/shared/runtime/server-static-builder.d.ts +11 -11
  17. package/src/adapters/shared/runtime/server-static-builder.js +37 -18
  18. package/src/assets/app-browser-client-manifest.d.ts +1 -3
  19. package/src/assets/app-browser-client-manifest.js +5 -58
  20. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +2 -2
  21. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +2 -2
  22. package/src/assets/browser-asset-output.d.ts +1 -1
  23. package/src/assets/browser-asset-output.js +1 -1
  24. package/src/build/app-build-manifest-runtime.d.ts +11 -1
  25. package/src/build/app-build-manifest-runtime.js +17 -3
  26. package/src/build/cache/pages-unified-graph-build.d.ts +32 -35
  27. package/src/build/cache/pages-unified-graph-build.js +206 -124
  28. package/src/build/cache/server-module-entries.d.ts +35 -0
  29. package/src/build/cache/server-module-entries.js +109 -0
  30. package/src/build/contracts/build-contracts.d.ts +5 -0
  31. package/src/build/copy-server-files.d.ts +10 -0
  32. package/src/build/copy-server-files.js +37 -0
  33. package/src/build/preserve-import-meta-transform.d.ts +1 -1
  34. package/src/build/preserve-import-meta-transform.js +1 -1
  35. package/src/build/production-build-id.d.ts +9 -0
  36. package/src/build/production-build-id.js +19 -0
  37. package/src/build/production-dist-complete.d.ts +5 -0
  38. package/src/build/production-dist-complete.js +101 -0
  39. package/src/build/production-route-list.d.ts +26 -0
  40. package/src/build/production-route-list.js +78 -0
  41. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +2 -2
  42. package/src/build/rolldown/rolldown-adapter-helpers.js +56 -4
  43. package/src/build/rolldown/rolldown-build-adapter.js +1 -1
  44. package/src/build/runtime/build-request-identity.js +2 -1
  45. package/src/build/runtime/build-request-policy.d.ts +3 -2
  46. package/src/build/runtime/build-request-policy.js +5 -3
  47. package/src/build/server/import-view-module.d.ts +11 -0
  48. package/src/build/server/import-view-module.js +21 -0
  49. package/src/build/server/imported-view-plugin.d.ts +16 -0
  50. package/src/build/server/imported-view-plugin.js +59 -0
  51. package/src/build/server/page-module-import.service.d.ts +19 -20
  52. package/src/build/server/page-module-import.service.js +65 -36
  53. package/src/build/server/resolve-static-view.d.ts +9 -0
  54. package/src/build/server/resolve-static-view.js +28 -0
  55. package/src/build/server/route-module-build-cache-registry.d.ts +5 -3
  56. package/src/build/server/route-module-build-cache-registry.js +5 -3
  57. package/src/build/server/server-modules-manifest.d.ts +51 -0
  58. package/src/build/server/server-modules-manifest.js +129 -0
  59. package/src/build/server/view-reference.d.ts +38 -0
  60. package/src/build/server/view-reference.js +112 -0
  61. package/src/build/server-bundle-deploy-manifest.d.ts +9 -9
  62. package/src/build/server-bundle-deploy-manifest.js +24 -28
  63. package/src/build.d.ts +3 -1
  64. package/src/build.js +3 -1
  65. package/src/config/assembly/app-runtime.d.ts +15 -2
  66. package/src/config/assembly/app-runtime.js +3 -1
  67. package/src/config/assembly/finalize-config.js +64 -13
  68. package/src/config/index.d.ts +1 -0
  69. package/src/config/index.js +1 -0
  70. package/src/config/internal-types.d.ts +6 -0
  71. package/src/config/load-eco-config.d.ts +1 -0
  72. package/src/config/load-eco-config.js +11 -2
  73. package/src/config/resolve-eco-config-path.d.ts +2 -1
  74. package/src/config/resolve-eco-config-path.js +21 -15
  75. package/src/config/user-config-types.d.ts +9 -2
  76. package/src/html-pages/html-page-module.d.ts +19 -0
  77. package/src/html-pages/html-page-module.js +66 -13
  78. package/src/html-pages/html-page-renderer.d.ts +4 -0
  79. package/src/html-pages/html-page-renderer.js +9 -3
  80. package/src/html-pages/html-pages.plugin.d.ts +10 -0
  81. package/src/html-pages/html-pages.plugin.js +7 -1
  82. package/src/index.d.ts +2 -0
  83. package/src/index.js +2 -0
  84. package/src/integration.d.ts +2 -1
  85. package/src/integration.js +1 -0
  86. package/src/page-cache/page-cache-service.d.ts +8 -0
  87. package/src/page-cache/page-cache-service.js +12 -0
  88. package/src/plugins/integration-plugin.d.ts +33 -6
  89. package/src/plugins/integration-plugin.js +14 -2
  90. package/src/plugins/processor.d.ts +17 -0
  91. package/src/plugins/processor.js +20 -1
  92. package/src/plugins/server-dom.d.ts +29 -0
  93. package/src/plugins/server-dom.js +36 -0
  94. package/src/route-renderer/error-pages/error-page-renderer.d.ts +6 -4
  95. package/src/route-renderer/error-pages/error-page-renderer.js +9 -5
  96. package/src/route-renderer/orchestration/integration-renderer.d.ts +1 -0
  97. package/src/route-renderer/orchestration/integration-renderer.js +17 -2
  98. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.d.ts +21 -0
  99. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.js +31 -0
  100. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +58 -24
  101. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.d.ts +12 -0
  102. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.js +55 -0
  103. package/src/router/server/route-registry.d.ts +22 -2
  104. package/src/router/server/route-registry.js +39 -15
  105. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +8 -2
  106. package/src/static-site-generator/production-page-browser-graph-prebuild.js +14 -9
  107. package/src/static-site-generator/static-site-generator.d.ts +19 -3
  108. package/src/static-site-generator/static-site-generator.js +78 -40
  109. package/src/types/contracts.d.ts +20 -31
  110. package/src/types/public-types.d.ts +1 -0
  111. package/src/types/view-reference.d.ts +31 -0
  112. package/src/types/view-reference.js +15 -0
  113. package/src/utils/additional-watch-paths.d.ts +3 -3
  114. package/src/utils/additional-watch-paths.js +3 -1
  115. package/src/utils/resolve-entry-file.d.ts +4 -2
  116. package/src/utils/resolve-entry-file.js +4 -2
  117. package/src/utils/root-relative-path.d.ts +4 -0
  118. package/src/utils/root-relative-path.js +8 -0
  119. package/src/utils/server-bundle-context.d.ts +14 -0
  120. package/src/utils/server-bundle-context.js +45 -0
  121. package/src/watchers/project-watcher-ignore.d.ts +2 -5
  122. package/src/watchers/project-watcher-ignore.js +2 -5
  123. package/src/watchers/project-watcher.d.ts +9 -7
  124. package/src/watchers/project-watcher.js +100 -52
  125. package/src/watchers/workspace-package-watch-roots.d.ts +4 -4
  126. package/src/watchers/workspace-package-watch-roots.js +41 -25
  127. package/src/build/server/view-module-loader.d.ts +0 -10
  128. package/src/build/server/view-module-loader.js +0 -46
@@ -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();
@@ -162,7 +162,7 @@ export class ServerRequestPipeline {
162
162
  const cacheService = this.getOrCreateSharedPageCacheService();
163
163
  const fileSystemResponseMatcher = new FileSystemResponseMatcher({
164
164
  appConfig: this.appConfig,
165
- assetPrefix: path.join(this.appConfig.rootDir, this.appConfig.distDir),
165
+ assetPrefix: this.appConfig.absolutePaths.distDir,
166
166
  router: this.router,
167
167
  routeRendererFactory: this.routeRendererFactory,
168
168
  errorPageLoaders,
@@ -221,7 +221,7 @@ export class ServerRequestPipeline {
221
221
  async importServerModule(filePath) {
222
222
  return await requireAppRuntime(this.appConfig).moduleLoader.importModule({
223
223
  filePath,
224
- outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
224
+ outdir: getServerModuleBuildCacheOutdir(this.appConfig),
225
225
  externalPackages: true,
226
226
  });
227
227
  }
@@ -275,7 +275,7 @@ export class ServerRequestPipeline {
275
275
  * The Node host maps its native HTTP request into a Web Request before calling this method.
276
276
  */
277
277
  async handleSharedRequest(request, context) {
278
- return requireBuildQueue(this.appConfig).withRequestScope(() => runWithBuildInputIndex(requireAppRuntime(this.appConfig).buildInputIndex, () => startupTrace.traceFirstRequest(request, async () => {
278
+ return this.runInRequestBuildScope(() => startupTrace.traceFirstRequest(request, async () => {
279
279
  let parsedPathSegments;
280
280
  try {
281
281
  parsedPathSegments = parseSegmentPath(new URL(request.url).pathname);
@@ -301,6 +301,6 @@ export class ServerRequestPipeline {
301
301
  }
302
302
  const routeResponse = await this.routeHandler.handleResponse(request, context, parsedPathSegments);
303
303
  return await this.injectSharedHmrHtmlResponse(routeResponse);
304
- })));
304
+ }));
305
305
  }
306
306
  }
@@ -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,
@@ -32,10 +32,10 @@ export type AppBrowserClientManifestEntry = {
32
32
  };
33
33
  export type AppBrowserClientManifest = {
34
34
  version: 1;
35
+ buildId?: string;
35
36
  entries: AppBrowserClientManifestEntry[];
36
37
  htmlPageModuleScriptUrls: Record<string, string>;
37
38
  htmlPageModuleScriptFingerprint: string;
38
- sourceFingerprints: Record<string, string>;
39
39
  browserOutputPaths: string[];
40
40
  };
41
41
  /** Rewrites the file path inside a client dependency key so it survives moving the project root. */
@@ -61,8 +61,6 @@ export declare function assertAppBrowserClientManifestHtmlOutputsExist(appConfig
61
61
  export declare function assertAppBrowserClientOutputsExist(appConfig: EcoPagesAppConfig, relativeOutputPaths: readonly string[]): void;
62
62
  /** Resolves the project-relative asset paths in a build manifest for the current runtime. */
63
63
  export declare function restoreAppBrowserClientAssets(appConfig: EcoPagesAppConfig, assets: readonly SerializedProcessedAsset[]): ProcessedAsset[];
64
- /** Ensures the source files used by the browser build have not changed since export. */
65
- export declare function assertAppBrowserClientSourcesMatch(appConfig: EcoPagesAppConfig, sourceFingerprints: Readonly<Record<string, string>>): void;
66
64
  /** Resolves an app-relative file path stored in the build manifest. */
67
65
  export declare function resolveAppBrowserClientManifestPath(appConfig: EcoPagesAppConfig, filePath: string): string;
68
66
  export {};
@@ -1,13 +1,14 @@
1
1
  import path from 'node:path';
2
2
  import { isPathStrictlyInside } from '../utils/path-containment.js';
3
3
  import { fileSystem } from '@ecopages/file-system';
4
- import { contentHash } from '../utils/content-hash.js';
4
+ import { ensureProductionBuildId } from '../build/production-build-id.js';
5
+ import { getServerBundleOutputPaths } from '../build/server-bundle-deploy-manifest.js';
5
6
  import { collectHtmlPageModuleScriptBuildInputs, getPrebuiltHtmlPageModuleScriptUrls, } from '../html-pages/html-page-module-scripts.js';
6
7
  import { createAppBrowserClientEntryKey } from './app-browser-client-build.js';
7
8
  import { createPageDependencyInstanceKey, createRouteGraphLookupKey, } from '../route-renderer/orchestration/page-browser-graph/route-instance-key.js';
8
9
  const APP_BROWSER_CLIENT_MANIFEST_FILENAME = 'browser-client-manifest.json';
9
10
  function getManifestPath(appConfig) {
10
- return path.join(appConfig.absolutePaths.distDir, '.server', APP_BROWSER_CLIENT_MANIFEST_FILENAME);
11
+ return path.join(getServerBundleOutputPaths(appConfig).serverOutdir, APP_BROWSER_CLIENT_MANIFEST_FILENAME);
11
12
  }
12
13
  function toProjectPath(rootDir, filePath) {
13
14
  return path.relative(rootDir, filePath).split(path.sep).join('/');
@@ -97,11 +98,11 @@ function isManifestEntry(value) {
97
98
  function isManifest(value) {
98
99
  return (isRecord(value) &&
99
100
  value.version === 1 &&
101
+ isOptionalString(value, 'buildId') &&
100
102
  Array.isArray(value.entries) &&
101
103
  value.entries.every(isManifestEntry) &&
102
104
  isStringRecord(value.htmlPageModuleScriptUrls) &&
103
105
  typeof value.htmlPageModuleScriptFingerprint === 'string' &&
104
- isStringRecord(value.sourceFingerprints) &&
105
106
  isStringArray(value.browserOutputPaths));
106
107
  }
107
108
  function serializeEntry(rootDir, plan, instance, params) {
@@ -133,38 +134,6 @@ function serializeEntry(rootDir, plan, instance, params) {
133
134
  },
134
135
  };
135
136
  }
136
- function addDependencySourceFilepaths(filepaths, dependency) {
137
- if (dependency.source === 'file' && dependency.filepath)
138
- filepaths.add(path.resolve(dependency.filepath));
139
- for (const filepath of dependency.bundledSourceFilepaths ?? [])
140
- filepaths.add(path.resolve(filepath));
141
- }
142
- function addAssetSourceFilepaths(filepaths, asset) {
143
- if (asset.sourceFilepath)
144
- filepaths.add(path.resolve(asset.sourceFilepath));
145
- for (const filepath of asset.bundledSourceFilepaths ?? [])
146
- filepaths.add(path.resolve(filepath));
147
- }
148
- function collectInstanceSourceFilepaths(filepaths, instance) {
149
- for (const dependency of instance.contribution?.dependencies ?? [])
150
- addDependencySourceFilepaths(filepaths, dependency);
151
- for (const clientEntry of instance.pageClientBuildEntries ?? []) {
152
- addDependencySourceFilepaths(filepaths, clientEntry.dependency);
153
- }
154
- for (const asset of instance.prebuiltGroupedAssets ?? [])
155
- addAssetSourceFilepaths(filepaths, asset);
156
- for (const asset of instance.prebuiltPageClientBrowserAssets?.processedAssets ?? []) {
157
- addAssetSourceFilepaths(filepaths, asset);
158
- }
159
- }
160
- function collectSourceFilepaths(plans) {
161
- const filepaths = new Set();
162
- for (const plan of plans) {
163
- for (const instance of plan.instances)
164
- collectInstanceSourceFilepaths(filepaths, instance);
165
- }
166
- return filepaths;
167
- }
168
137
  function addAssetOutputFilepaths(filepaths, assets = []) {
169
138
  for (const asset of assets) {
170
139
  if (asset.filepath)
@@ -191,12 +160,6 @@ function collectOutputFilepaths(appConfig, plans, htmlPageModuleScriptUrls, brow
191
160
  addHtmlScriptOutputFilepaths(filepaths, appConfig.absolutePaths.distDir, htmlPageModuleScriptUrls);
192
161
  return filepaths;
193
162
  }
194
- function fingerprintSources(rootDir, filepaths) {
195
- return Object.fromEntries([...new Set(filepaths)]
196
- .filter((filepath) => fileSystem.exists(filepath))
197
- .sort()
198
- .map((filepath) => [toProjectPath(rootDir, filepath), contentHash(fileSystem.readFileSync(filepath))]));
199
- }
200
163
  /** Persists the browser outputs built for production routes so `ecopages start` can reuse them. */
201
164
  export async function writeAppBrowserClientManifest(appConfig, plans, routeInstances, browserBuild) {
202
165
  const paramsByRouteKey = new Map(routeInstances.map((instance) => [
@@ -223,19 +186,12 @@ export async function writeAppBrowserClientManifest(appConfig, plans, routeInsta
223
186
  url,
224
187
  ]));
225
188
  const htmlBuildInputs = collectHtmlPageModuleScriptBuildInputs(appConfig);
226
- const sourceFilepaths = collectSourceFilepaths(plans);
227
- for (const filepath of [...htmlBuildInputs.htmlFiles, ...htmlBuildInputs.files]) {
228
- sourceFilepaths.add(path.resolve(filepath));
229
- }
230
- for (const filepath of browserBuild.sourceFiles) {
231
- sourceFilepaths.add(path.resolve(filepath));
232
- }
233
189
  const manifest = {
234
190
  version: 1,
191
+ buildId: ensureProductionBuildId(appConfig),
235
192
  entries,
236
193
  htmlPageModuleScriptUrls,
237
194
  htmlPageModuleScriptFingerprint: htmlBuildInputs.fingerprint,
238
- sourceFingerprints: fingerprintSources(appConfig.rootDir, sourceFilepaths),
239
195
  browserOutputPaths: [
240
196
  ...collectOutputFilepaths(appConfig, plans, htmlPageModuleScriptUrls, browserBuild.outputPaths),
241
197
  ]
@@ -298,15 +254,6 @@ export function restoreAppBrowserClientAssets(appConfig, assets) {
298
254
  };
299
255
  });
300
256
  }
301
- /** Ensures the source files used by the browser build have not changed since export. */
302
- export function assertAppBrowserClientSourcesMatch(appConfig, sourceFingerprints) {
303
- for (const [relativePath, expectedFingerprint] of Object.entries(sourceFingerprints)) {
304
- const filepath = path.resolve(appConfig.rootDir, relativePath);
305
- if (!fileSystem.exists(filepath) || contentHash(fileSystem.readFileSync(filepath)) !== expectedFingerprint) {
306
- throw new Error(`The app browser build manifest is stale because ${relativePath} changed or is missing. Run \`ecopages build\` again.`);
307
- }
308
- }
309
- }
310
257
  /** Resolves an app-relative file path stored in the build manifest. */
311
258
  export function resolveAppBrowserClientManifestPath(appConfig, filePath) {
312
259
  return path.resolve(appConfig.rootDir, filePath);