@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
@@ -27,7 +27,7 @@ export declare class FileScriptProcessor extends BaseScriptProcessor<FileScriptA
27
27
  * is copied to its source-relative path. A classic script inside `srcDir` is compiled and written
28
28
  * under that path with a `.js` name. A file outside `srcDir` has no such path that stays inside
29
29
  * `dist`: an unbundled or classic script is written under a content hash, and a bundled script
30
- * is emitted in `dist/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
30
+ * is emitted in `dist/client/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
31
31
  * `src` keep their stable names.
32
32
  */
33
33
  process(dep: FileScriptAsset): Promise<ProcessedAsset>;
@@ -38,7 +38,7 @@ export declare class FileScriptProcessor extends BaseScriptProcessor<FileScriptA
38
38
  * @remarks
39
39
  * The output keeps the source path and name when the file is inside `srcDir`, with a TypeScript
40
40
  * extension turned into `.js`, as a copied classic `.js` does. A file outside `srcDir` is written
41
- * under a content hash in `dist/assets`. A second source file for the same output is rejected while
41
+ * under a content hash in `dist/client/assets`. A second source file for the same output is rejected while
42
42
  * the first still exists, so a last write cannot silently win.
43
43
  *
44
44
  * @throws When the file cannot be a classic script, or another existing file is emitted to its output.
@@ -56,7 +56,7 @@ export class FileScriptProcessor extends BaseScriptProcessor {
56
56
  * is copied to its source-relative path. A classic script inside `srcDir` is compiled and written
57
57
  * under that path with a `.js` name. A file outside `srcDir` has no such path that stays inside
58
58
  * `dist`: an unbundled or classic script is written under a content hash, and a bundled script
59
- * is emitted in `dist/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
59
+ * is emitted in `dist/client/assets` under the bundler's `[name]-[hash]` name. Vendor runtimes inside
60
60
  * `src` keep their stable names.
61
61
  */
62
62
  async process(dep) {
@@ -151,7 +151,7 @@ export class FileScriptProcessor extends BaseScriptProcessor {
151
151
  * @remarks
152
152
  * The output keeps the source path and name when the file is inside `srcDir`, with a TypeScript
153
153
  * extension turned into `.js`, as a copied classic `.js` does. A file outside `srcDir` is written
154
- * under a content hash in `dist/assets`. A second source file for the same output is rejected while
154
+ * under a content hash in `dist/client/assets`. A second source file for the same output is rejected while
155
155
  * the first still exists, so a last write cannot silently win.
156
156
  *
157
157
  * @throws When the file cannot be a classic script, or another existing file is emitted to its output.
@@ -4,7 +4,7 @@
4
4
  * @remarks
5
5
  * `path.relative` from `srcDir` to a file outside it starts with `..`. Joining
6
6
  * that onto `dist` writes the asset outside the build. Callers then emit the file
7
- * in `dist/assets`: a bundled script under the bundler's `[name]-[hash]` name, and
7
+ * in `dist/client/assets`: a bundled script under the bundler's `[name]-[hash]` name, and
8
8
  * an unbundled script or stylesheet under a content hash.
9
9
  */
10
10
  export declare function sourceRelativeBrowserAssetPath(srcDir: string, filepath: string): string | undefined;
@@ -6,7 +6,7 @@ import { isPathInside } from '../utils/path-containment.js';
6
6
  * @remarks
7
7
  * `path.relative` from `srcDir` to a file outside it starts with `..`. Joining
8
8
  * that onto `dist` writes the asset outside the build. Callers then emit the file
9
- * in `dist/assets`: a bundled script under the bundler's `[name]-[hash]` name, and
9
+ * in `dist/client/assets`: a bundled script under the bundler's `[name]-[hash]` name, and
10
10
  * an unbundled script or stylesheet under a content hash.
11
11
  */
12
12
  export function sourceRelativeBrowserAssetPath(srcDir, filepath) {
@@ -9,15 +9,25 @@ import type { EcoPagesAppConfig } from '../config/internal-types.js';
9
9
  * runtime manifests are data, not lifecycle hooks. Runtime setup happens after finalization.
10
10
  */
11
11
  export declare function sealAppBuildManifest(appConfig: EcoPagesAppConfig): AppBuildManifest;
12
+ /**
13
+ * Gives each Processor its app config and calls `setup()`.
14
+ *
15
+ * @remarks
16
+ * When `skipProcessorSetup` is set, or this is the Lit static-render worker, each Processor
17
+ * restores from the production server-modules map instead of scanning sources.
18
+ */
12
19
  export declare function setupAppRuntimePlugins(options: {
13
20
  appConfig: EcoPagesAppConfig;
21
+ skipProcessorSetup?: boolean;
14
22
  }): Promise<void>;
15
23
  /**
16
24
  * Activates one integration's runtime setup on first use.
17
25
  *
18
26
  * @remarks
19
27
  * Concurrent callers share a single in-flight promise per integration name.
20
- * Failed activations are evicted so a later caller can retry.
28
+ * Server DOM install runs inside that promise, before `setup()`, so a second
29
+ * caller cannot skip the in-flight activation. Failed activations are evicted
30
+ * so a later caller can retry.
21
31
  */
22
32
  export declare function ensureIntegrationRuntimeReady(options: {
23
33
  appConfig: EcoPagesAppConfig;
@@ -5,6 +5,7 @@ import { requireAppRuntime } from '../utils/app-runtime.js';
5
5
  import { appLogger } from '../global/app-logger.js';
6
6
  import { startupTrace } from '../diagnostics/startup-trace.js';
7
7
  import { isLitStaticRenderWorkerThread } from './browser/lit-static-render-worker-context.js';
8
+ import { installConfiguredServerDom } from '../plugins/server-dom.js';
8
9
  /**
9
10
  * Seals the app's build manifest from its loaders, processors and integrations.
10
11
  *
@@ -32,6 +33,13 @@ export function sealAppBuildManifest(appConfig) {
32
33
  }
33
34
  return createAppBuildManifest(registrations, mergeBrowserRuntimeManifests(...browserRuntimeManifests));
34
35
  }
36
+ /**
37
+ * Gives each Processor its app config and calls `setup()`.
38
+ *
39
+ * @remarks
40
+ * When `skipProcessorSetup` is set, or this is the Lit static-render worker, each Processor
41
+ * restores from the production server-modules map instead of scanning sources.
42
+ */
35
43
  export async function setupAppRuntimePlugins(options) {
36
44
  startupTrace.markPhaseStart('setupAppRuntimePlugins');
37
45
  const runtime = requireAppRuntime(options.appConfig);
@@ -45,10 +53,13 @@ export async function setupAppRuntimePlugins(options) {
45
53
  }
46
54
  appLogger.debugTime('setupAppRuntimePlugins');
47
55
  try {
48
- const skipProcessorSetup = isLitStaticRenderWorkerThread();
56
+ const skipProcessorSetup = options.skipProcessorSetup === true || isLitStaticRenderWorkerThread();
49
57
  for (const processor of options.appConfig.processors.values()) {
50
58
  processor.setContext(options.appConfig);
51
- if (!skipProcessorSetup) {
59
+ if (skipProcessorSetup) {
60
+ await processor.restoreProductionRuntime?.();
61
+ }
62
+ else {
52
63
  await processor.setup();
53
64
  }
54
65
  }
@@ -65,7 +76,9 @@ export async function setupAppRuntimePlugins(options) {
65
76
  *
66
77
  * @remarks
67
78
  * Concurrent callers share a single in-flight promise per integration name.
68
- * Failed activations are evicted so a later caller can retry.
79
+ * Server DOM install runs inside that promise, before `setup()`, so a second
80
+ * caller cannot skip the in-flight activation. Failed activations are evicted
81
+ * so a later caller can retry.
69
82
  */
70
83
  export async function ensureIntegrationRuntimeReady(options) {
71
84
  const runtime = requireAppRuntime(options.appConfig);
@@ -79,6 +92,7 @@ export async function ensureIntegrationRuntimeReady(options) {
79
92
  return;
80
93
  }
81
94
  const activation = (async () => {
95
+ await installConfiguredServerDom(options.appConfig.integrations);
82
96
  await integration.setup({ appConfig: options.appConfig, runtime });
83
97
  })();
84
98
  runtime.integrationActivations.set(options.integrationName, activation);
@@ -1,54 +1,51 @@
1
1
  /**
2
- * Unified pages Rolldown graph (Phase A build + Phase C import).
2
+ * Unified production server-module graph.
3
3
  *
4
- * Enabled by default in production builds. Opt out with
5
- * `ECOPAGES_UNIFIED_PAGES_GRAPH=false` or `0`. Covers all static page template extensions
6
- * registered on the app config.
4
+ * `ecopages build` emits every server entry into `dist/server/` and writes
5
+ * `server-modules.json`. `ecopages start` imports those modules and never compiles.
7
6
  */
8
7
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
9
- import { type RouteModuleDependencyHashes } from '../server/route-module-dependency-hasher.js';
10
- export interface PagesUnifiedGraphCacheManifest {
11
- buildKey: string;
12
- outputs: Record<string, string>;
13
- /**
14
- * Local files reachable from the outputs through local imports, including
15
- * shared chunks. The graph is reused only while all of them exist.
16
- */
17
- outputImports: string[];
18
- /**
19
- * Content hashes for every trackable source file in the graph.
20
- *
21
- * @remarks
22
- * Compiled chunks can outlive a deleted layout or component. Reuse also
23
- * requires these hashes so a source edit or deletion rebuilds the graph.
24
- */
25
- dependencyHashes: RouteModuleDependencyHashes;
26
- /**
27
- * Memoized result of {@link isGraphManifestCurrent} for page imports.
28
- */
29
- importable?: boolean;
30
- }
8
+ import type { ErrorPageLoaders, StaticRoute } from '../../types/contracts.js';
9
+ import { type ProductionServerModulesManifest } from '../server/server-modules-manifest.js';
10
+ import { type ServerModuleEntryRouteSource } from './server-module-entries.js';
31
11
  /**
32
- * True when the unified graph should build or serve prebuilt page modules.
12
+ * True when a production build should emit the server-modules map.
33
13
  *
34
14
  * @remarks
35
15
  * Enabled by default in production builds. `ECOPAGES_UNIFIED_PAGES_GRAPH=false` or `0` opts out, which the
36
- * bench parity suite uses as its per-page build oracle.
16
+ * bench parity suite uses as its per-page build oracle. Production `ecopages start` still requires
17
+ * the emitted server-modules map from a build that did emit.
37
18
  */
38
19
  export declare function shouldBuildPagesUnifiedGraph(): boolean;
39
20
  /**
40
21
  * @remarks
41
22
  * Pages of an Integration that compiles its own modules (`compilePageModule`), such as
42
- * HTML Pages, are not bundled, so they stay out of the graph.
23
+ * HTML Pages, are not bundled, so they stay out of the Rolldown graph.
43
24
  */
44
25
  export declare function isPagesUnifiedGraphPage(filePath: string, appConfig: EcoPagesAppConfig): boolean;
26
+ export declare function importEmittedServerModule<T>(appConfig: EcoPagesAppConfig, filePath: string, outputPath: string): Promise<T>;
45
27
  /**
46
- * Builds eligible static pages in one Rolldown invocation and records outputs for this process.
28
+ * Emits every production server entry into `outdir` and writes `server-modules.json`.
29
+ *
30
+ * @remarks
31
+ * Imports the emitted Rolldown modules to discover extra `ssr: true` scripts, so
32
+ * Integrations are activated first; Core installs the configured server DOM
33
+ * before their `setup()`. A discovered script already bundled into the first
34
+ * emit maps to that output. Otherwise a second emit adds the scripts; preserved
35
+ * modules keep their output path across both emits, so a module imported after
36
+ * the first emit is not evaluated again from a second copy.
47
37
  */
48
- export declare function ensurePagesUnifiedGraphBuilt(options: {
38
+ export declare function emitProductionServerModules(options: {
49
39
  appConfig: EcoPagesAppConfig;
50
- entryPaths: readonly string[];
51
- outdir: string;
52
- force?: boolean;
53
- }): Promise<PagesUnifiedGraphCacheManifest | undefined>;
40
+ router: ServerModuleEntryRouteSource;
41
+ staticRoutes?: readonly StaticRoute[];
42
+ errorPageLoaders?: ErrorPageLoaders;
43
+ outdir?: string;
44
+ }): Promise<ProductionServerModulesManifest>;
45
+ /**
46
+ * Imports the emitted module for `filePath` from the production server-modules map.
47
+ *
48
+ * @remarks
49
+ * Resolves `undefined` when no map was emitted or it does not list the file.
50
+ */
54
51
  export declare function importPagesUnifiedGraphModule<T>(appConfig: EcoPagesAppConfig, filePath: string): Promise<T | undefined>;
@@ -1,30 +1,34 @@
1
1
  /**
2
- * Unified pages Rolldown graph (Phase A build + Phase C import).
2
+ * Unified production server-module graph.
3
3
  *
4
- * Enabled by default in production builds. Opt out with
5
- * `ECOPAGES_UNIFIED_PAGES_GRAPH=false` or `0`. Covers all static page template extensions
6
- * registered on the app config.
4
+ * `ecopages build` emits every server entry into `dist/server/` and writes
5
+ * `server-modules.json`. `ecopages start` imports those modules and never compiles.
7
6
  */
8
7
  import path from 'node:path';
9
- import { isEcopagesEnvDisabled } from '../../env.js';
10
- import { isProductionRuntime } from '../../utils/runtime.js';
11
8
  import { pathToFileURL } from 'node:url';
12
9
  import { fileSystem } from '@ecopages/file-system';
10
+ import { isEcopagesEnvDisabled } from '../../env.js';
11
+ import { isProductionRuntime } from '../../utils/runtime.js';
13
12
  import { requireAppRuntime } from '../../utils/app-runtime.js';
13
+ import { setupAppRuntimeIntegrations } from '../app-build-manifest-runtime.js';
14
14
  import { appLogger } from '../../global/app-logger.js';
15
15
  import { findIntegrationForFile } from '../../plugins/find-integration-for-file.js';
16
16
  import { buildOrThrow } from '../runtime/build-queue.js';
17
- import { createServerBuildRequest, resolveAppBuildPlugins } from '../runtime/build-request-policy.js';
18
- import { hashAppConfigFile } from './app-config-hash.js';
19
- import { collectBuildOutputImports, getBuildEntryOutput } from '../build-graph.js';
20
- import { getServerModuleBuildCacheOutdir } from '../server/route-module-build-cache-registry.js';
21
- import { RouteModuleDependencyHasher, resolveRouteModuleDependencyPaths, } from '../server/route-module-dependency-hasher.js';
17
+ import { createServerBuildRequest } from '../runtime/build-request-policy.js';
18
+ import { getBuildEntryOutput } from '../build-graph.js';
19
+ import { contentHash } from '../../utils/content-hash.js';
20
+ import { toRootRelativePath } from '../../utils/root-relative-path.js';
21
+ import { loadProductionServerModules, matchProductionModuleKey, writeProductionServerModulesManifest, } from '../server/server-modules-manifest.js';
22
+ import { getServerBundleOutputPaths } from '../server-bundle-deploy-manifest.js';
23
+ import { ensureProductionBuildId } from '../production-build-id.js';
24
+ import { collectServerModuleEntries, collectSsrScriptPaths, isRolldownServerModuleEntry, } from './server-module-entries.js';
22
25
  /**
23
- * True when the unified graph should build or serve prebuilt page modules.
26
+ * True when a production build should emit the server-modules map.
24
27
  *
25
28
  * @remarks
26
29
  * Enabled by default in production builds. `ECOPAGES_UNIFIED_PAGES_GRAPH=false` or `0` opts out, which the
27
- * bench parity suite uses as its per-page build oracle.
30
+ * bench parity suite uses as its per-page build oracle. Production `ecopages start` still requires
31
+ * the emitted server-modules map from a build that did emit.
28
32
  */
29
33
  export function shouldBuildPagesUnifiedGraph() {
30
34
  return !isEcopagesEnvDisabled('ECOPAGES_UNIFIED_PAGES_GRAPH') && isProductionRuntime();
@@ -32,151 +36,229 @@ export function shouldBuildPagesUnifiedGraph() {
32
36
  /**
33
37
  * @remarks
34
38
  * Pages of an Integration that compiles its own modules (`compilePageModule`), such as
35
- * HTML Pages, are not bundled, so they stay out of the graph.
39
+ * HTML Pages, are not bundled, so they stay out of the Rolldown graph.
36
40
  */
37
41
  export function isPagesUnifiedGraphPage(filePath, appConfig) {
38
42
  const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
39
43
  return owner !== undefined && !owner.compilePageModule;
40
44
  }
41
- function createPagesUnifiedGraphBuildKey(appConfig, outdir) {
42
- const pluginNames = resolveAppBuildPlugins(appConfig, 'server')
43
- .map((plugin) => plugin.name)
44
- .sort()
45
- .join('|');
46
- const templateExtensions = [...appConfig.templatesExt].sort().join('|');
47
- return [
48
- path.resolve(outdir),
49
- hashAppConfigFile(appConfig),
50
- templateExtensions,
51
- pluginNames,
52
- 'node',
53
- 'esm',
54
- 'external-packages',
55
- ].join('::');
56
- }
57
- function readPagesUnifiedGraphManifest(appConfig) {
58
- return requireAppRuntime(appConfig).pagesUnifiedGraphManifest ?? undefined;
59
- }
60
- function sourceDependenciesAreCurrent(manifest) {
61
- return new RouteModuleDependencyHasher().matchesStoredHashes(manifest.dependencyHashes);
62
- }
63
- function writePagesUnifiedGraphManifest(appConfig, manifest) {
64
- requireAppRuntime(appConfig).pagesUnifiedGraphManifest = manifest;
65
- }
66
- function createSafeGraphEntryKey(entryPath, rootDir) {
67
- const relativePath = path.relative(rootDir, entryPath).replace(/\.[^.]+$/u, '');
68
- const safeKey = relativePath.replace(/[^a-zA-Z0-9]+/gu, '-').replace(/^-+|-+$/gu, '');
69
- return safeKey.length > 0 ? safeKey : 'page';
70
- }
71
- /**
72
- * Whether `manifest` was built for this graph setup, every file its outputs import
73
- * still exists, and source hashes still match.
74
- */
75
- function isGraphManifestCurrent(manifest, appConfig, outdir) {
76
- return (manifest.buildKey === createPagesUnifiedGraphBuildKey(appConfig, outdir) &&
77
- manifest.outputImports.every((filePath) => fileSystem.exists(filePath)) &&
78
- sourceDependenciesAreCurrent(manifest));
79
- }
80
45
  /**
46
+ * Readable output stem unique for every source path.
47
+ *
81
48
  * @remarks
82
- * In addition to graph freshness and chunk existence on disk, the manifest must
83
- * match the exact count of active template entries so removing or adding a page
84
- * invalidates the graph.
49
+ * Sanitizing `src/pages/foo-bar` and `src/pages/foo/bar` would otherwise yield
50
+ * the same stem and overwrite one emitted module with the other.
85
51
  */
86
- function isManifestValidForEntries(manifest, appConfig, outdir, entryPaths) {
87
- return (isGraphManifestCurrent(manifest, appConfig, outdir) &&
88
- entryPaths.length === Object.keys(manifest.outputs).length &&
89
- entryPaths.every((entryPath) => {
90
- const outputPath = manifest.outputs[path.resolve(entryPath)];
91
- return outputPath ? fileSystem.exists(outputPath) : false;
92
- }));
52
+ function createSafeGraphEntryKey(entryPath, rootDir) {
53
+ const sourceKey = toRootRelativePath(rootDir, entryPath);
54
+ const relativePath = sourceKey.replace(/\.[^.]+$/u, '');
55
+ const readable = relativePath.replace(/[^a-zA-Z0-9]+/gu, '-').replace(/^-+|-+$/gu, '');
56
+ return `${readable.length > 0 ? readable : 'page'}-${contentHash(sourceKey, 8)}`;
57
+ }
58
+ function uniqueEntryPaths(entryPaths) {
59
+ return [...new Set(entryPaths.map((entryPath) => path.resolve(entryPath)))];
60
+ }
61
+ async function emitCompiledPageModule(appConfig, filePath, outdir) {
62
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
63
+ if (!owner?.compilePageModule) {
64
+ throw new Error(`No compilePageModule implementation for ${filePath}`);
65
+ }
66
+ if (!owner.serializeCompiledPageModule) {
67
+ throw new Error(`No serializeCompiledPageModule implementation for ${filePath}`);
68
+ }
69
+ const compiled = await owner.compilePageModule(filePath, appConfig);
70
+ const { contents } = owner.serializeCompiledPageModule(compiled, { rootDir: appConfig.rootDir, filePath });
71
+ const sourceKey = toRootRelativePath(appConfig.rootDir, filePath);
72
+ const relativePath = `${createSafeGraphEntryKey(filePath, appConfig.rootDir)}-html.json`;
73
+ const outputPath = path.join(outdir, relativePath);
74
+ fileSystem.ensureDir(outdir);
75
+ fileSystem.write(outputPath, contents);
76
+ return { sourceKey, relativePath, outputPath };
77
+ }
78
+ function reviveCompiledPageModuleFromDisk(appConfig, filePath, outputPath) {
79
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
80
+ if (!owner?.reviveCompiledPageModule) {
81
+ throw new Error(`No reviveCompiledPageModule implementation for ${filePath}`);
82
+ }
83
+ return owner.reviveCompiledPageModule(fileSystem.readFileSync(outputPath).toString(), {
84
+ rootDir: appConfig.rootDir,
85
+ filePath,
86
+ });
93
87
  }
94
88
  /**
95
- * {@link isGraphManifestCurrent} for page imports, memoized per manifest.
89
+ * Points `identity.file` at the current app root when the emitted module still
90
+ * names the build machine, so a copied `dist/` does not read that path.
96
91
  *
97
92
  * @remarks
98
- * Page modules can be imported before the static site generator calls
99
- * {@link ensurePagesUnifiedGraphBuilt} (for example while collecting static
100
- * paths), so the import path must not trust a graph this process has already
101
- * invalidated.
93
+ * Relative `dependencies.scripts` resolve from this directory, so the remap
94
+ * keeps the source key. Emitting the module path here breaks the asset
95
+ * pipeline (`./hello.script.ts` would resolve under `dist/server/`).
102
96
  */
103
- function isGraphImportable(manifest, appConfig) {
104
- if (manifest.importable !== undefined)
105
- return manifest.importable;
106
- const current = isGraphManifestCurrent(manifest, appConfig, getServerModuleBuildCacheOutdir(appConfig));
107
- manifest.importable = current;
108
- return current;
97
+ function remapProductionIdentityFile(identity, appConfig) {
98
+ if (!identity?.file) {
99
+ return;
100
+ }
101
+ const manifest = loadProductionServerModules(appConfig);
102
+ if (!manifest) {
103
+ return;
104
+ }
105
+ const key = matchProductionModuleKey(appConfig.rootDir, identity.file, manifest.modules);
106
+ if (key) {
107
+ identity.file = path.resolve(appConfig.rootDir, key);
108
+ }
109
109
  }
110
- /**
111
- * Builds eligible static pages in one Rolldown invocation and records outputs for this process.
112
- */
113
- export async function ensurePagesUnifiedGraphBuilt(options) {
114
- requireAppRuntime(options.appConfig);
115
- if (!shouldBuildPagesUnifiedGraph()) {
116
- return undefined;
110
+ function remapLoadedModuleIdentities(loaded, appConfig) {
111
+ for (const value of Object.values(loaded)) {
112
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) {
113
+ continue;
114
+ }
115
+ const record = value;
116
+ remapProductionIdentityFile(record.config?.identity ?? record.identity, appConfig);
117
117
  }
118
- const eligibleEntryPaths = Array.from(new Set(options.entryPaths
119
- .map((entryPath) => path.resolve(entryPath))
120
- .filter((entryPath) => isPagesUnifiedGraphPage(entryPath, options.appConfig))));
121
- if (eligibleEntryPaths.length === 0) {
122
- return undefined;
118
+ }
119
+ export async function importEmittedServerModule(appConfig, filePath, outputPath) {
120
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
121
+ if (owner?.reviveCompiledPageModule) {
122
+ return reviveCompiledPageModuleFromDisk(appConfig, filePath, outputPath);
123
+ }
124
+ const loaded = (await import(/* @vite-ignore */ pathToFileURL(outputPath).href));
125
+ if (loaded && typeof loaded === 'object') {
126
+ remapLoadedModuleIdentities(loaded, appConfig);
123
127
  }
124
- const outdir = path.resolve(options.outdir);
125
- const existingManifest = options.force ? undefined : readPagesUnifiedGraphManifest(options.appConfig);
126
- if (existingManifest &&
127
- isManifestValidForEntries(existingManifest, options.appConfig, outdir, eligibleEntryPaths)) {
128
- appLogger.debug('Reusing pages unified graph built in this process');
129
- return existingManifest;
128
+ return loaded;
129
+ }
130
+ async function emitRolldownServerModules(appConfig, entryPaths, outdir) {
131
+ if (entryPaths.length === 0) {
132
+ return { modules: {}, outputGraph: {} };
130
133
  }
131
134
  const entryRecord = {};
132
- for (const entryPath of eligibleEntryPaths) {
133
- const entryKey = createSafeGraphEntryKey(entryPath, options.appConfig.rootDir);
134
- entryRecord[entryKey] = entryPath;
135
+ for (const entryPath of entryPaths) {
136
+ entryRecord[createSafeGraphEntryKey(entryPath, appConfig.rootDir)] = entryPath;
135
137
  }
136
138
  appLogger.debugTime('pagesUnifiedGraphBuild');
137
- const buildOptions = createServerBuildRequest(options.appConfig, {
139
+ const buildOptions = createServerBuildRequest(appConfig, {
138
140
  entrypoints: entryRecord,
139
141
  outdir,
140
142
  splitting: true,
143
+ preserveModules: true,
144
+ preserveModulesRoot: appConfig.rootDir,
141
145
  naming: '[name]-[hash].[ext]',
142
146
  });
143
- const buildResult = await buildOrThrow(options.appConfig, buildOptions, 'Pages unified graph build failed').finally(() => appLogger.debugTimeEnd('pagesUnifiedGraphBuild'));
144
- const outputs = {};
145
- const outputImports = new Set();
146
- const dependencyHasher = new RouteModuleDependencyHasher();
147
- const dependencyHashes = {};
148
- for (const entryPath of eligibleEntryPaths) {
149
- const fileHash = fileSystem.hash(entryPath);
150
- const compiledOutput = getBuildEntryOutput(buildResult, entryPath, options.appConfig.rootDir);
147
+ const buildResult = await buildOrThrow(appConfig, buildOptions, 'Pages unified graph build failed').finally(() => appLogger.debugTimeEnd('pagesUnifiedGraphBuild'));
148
+ const modules = {};
149
+ for (const entryPath of entryPaths) {
150
+ const compiledOutput = getBuildEntryOutput(buildResult, entryPath, appConfig.rootDir);
151
151
  if (!compiledOutput) {
152
152
  throw new Error(`Pages unified graph build produced no output for ${entryPath}`);
153
153
  }
154
- outputs[entryPath] = compiledOutput;
155
- for (const importPath of collectBuildOutputImports(buildResult, compiledOutput))
156
- outputImports.add(importPath);
157
- const dependencyModulePaths = resolveRouteModuleDependencyPaths(buildResult, entryPath, options.appConfig.rootDir);
158
- Object.assign(dependencyHashes, dependencyHasher.createDependencyHashes(dependencyModulePaths));
159
- dependencyHashes[path.normalize(entryPath)] = fileHash;
160
- }
161
- const manifest = {
162
- buildKey: createPagesUnifiedGraphBuildKey(options.appConfig, outdir),
163
- outputs,
164
- outputImports: [...outputImports],
165
- dependencyHashes,
154
+ modules[toRootRelativePath(appConfig.rootDir, entryPath)] = toRootRelativePath(outdir, compiledOutput);
155
+ }
156
+ return { modules, outputGraph: buildResult.outputGraph };
157
+ }
158
+ function findEmittedModulePath(outputGraph, sourcePath) {
159
+ const resolvedSource = path.resolve(sourcePath);
160
+ for (const [outputPath, chunk] of Object.entries(outputGraph)) {
161
+ if (chunk.modules.includes(resolvedSource)) {
162
+ return outputPath;
163
+ }
164
+ }
165
+ return undefined;
166
+ }
167
+ async function importEmittedModules(manifest, sourceKeys) {
168
+ const modules = [];
169
+ for (const sourceKey of sourceKeys) {
170
+ const relativePath = manifest.modules[sourceKey];
171
+ if (!relativePath) {
172
+ continue;
173
+ }
174
+ modules.push(await import(/* @vite-ignore */ pathToFileURL(path.join(manifest.outdir, relativePath)).href));
175
+ }
176
+ return modules;
177
+ }
178
+ function assignProductionServerModules(appConfig, manifest) {
179
+ const runtime = requireAppRuntime(appConfig);
180
+ runtime.productionServerModules = manifest;
181
+ }
182
+ /**
183
+ * Emits every production server entry into `outdir` and writes `server-modules.json`.
184
+ *
185
+ * @remarks
186
+ * Imports the emitted Rolldown modules to discover extra `ssr: true` scripts, so
187
+ * Integrations are activated first; Core installs the configured server DOM
188
+ * before their `setup()`. A discovered script already bundled into the first
189
+ * emit maps to that output. Otherwise a second emit adds the scripts; preserved
190
+ * modules keep their output path across both emits, so a module imported after
191
+ * the first emit is not evaluated again from a second copy.
192
+ */
193
+ export async function emitProductionServerModules(options) {
194
+ const appConfig = options.appConfig;
195
+ requireAppRuntime(appConfig);
196
+ await setupAppRuntimeIntegrations({ appConfig });
197
+ const outdir = path.resolve(options.outdir ?? getServerBundleOutputPaths(appConfig).serverOutdir);
198
+ fileSystem.ensureDir(outdir);
199
+ const collected = await collectServerModuleEntries({
200
+ appConfig,
201
+ router: options.router,
202
+ staticRoutes: options.staticRoutes,
203
+ errorPageLoaders: options.errorPageLoaders,
204
+ });
205
+ const rolldownEntries = collected.filter((entryPath) => isRolldownServerModuleEntry(entryPath, appConfig));
206
+ const htmlEntries = collected.filter((entryPath) => !isRolldownServerModuleEntry(entryPath, appConfig));
207
+ const modules = {};
208
+ const initialEmit = await emitRolldownServerModules(appConfig, uniqueEntryPaths(rolldownEntries), outdir);
209
+ Object.assign(modules, initialEmit.modules);
210
+ for (const htmlEntry of uniqueEntryPaths(htmlEntries)) {
211
+ const emitted = await emitCompiledPageModule(appConfig, htmlEntry, outdir);
212
+ modules[emitted.sourceKey] = emitted.relativePath;
213
+ }
214
+ let manifest = {
215
+ outdir,
216
+ buildId: ensureProductionBuildId(appConfig),
217
+ modules,
166
218
  };
167
- writePagesUnifiedGraphManifest(options.appConfig, manifest);
168
- appLogger.debug(`Built pages unified graph for ${eligibleEntryPaths.length} entries`);
219
+ assignProductionServerModules(appConfig, manifest);
220
+ const discoveredScripts = collectSsrScriptPaths(await importEmittedModules(manifest, rolldownEntries.map((entryPath) => toRootRelativePath(appConfig.rootDir, entryPath)))).filter((scriptPath) => fileSystem.exists(scriptPath) && !(toRootRelativePath(appConfig.rootDir, scriptPath) in modules));
221
+ if (discoveredScripts.length > 0) {
222
+ const scriptsToEmit = [];
223
+ for (const scriptPath of discoveredScripts) {
224
+ const existingOutput = findEmittedModulePath(initialEmit.outputGraph, scriptPath);
225
+ if (existingOutput) {
226
+ modules[toRootRelativePath(appConfig.rootDir, scriptPath)] = toRootRelativePath(outdir, existingOutput);
227
+ }
228
+ else {
229
+ scriptsToEmit.push(scriptPath);
230
+ }
231
+ }
232
+ if (scriptsToEmit.length > 0) {
233
+ const emittedModules = await emitRolldownServerModules(appConfig, uniqueEntryPaths([...rolldownEntries, ...scriptsToEmit]), outdir);
234
+ Object.assign(modules, emittedModules.modules);
235
+ }
236
+ manifest = { outdir, buildId: ensureProductionBuildId(appConfig), modules };
237
+ assignProductionServerModules(appConfig, manifest);
238
+ }
239
+ writeProductionServerModulesManifest(manifest);
240
+ appLogger.debug(`Emitted ${Object.keys(modules).length} production server modules`);
169
241
  return manifest;
170
242
  }
243
+ /**
244
+ * Imports the emitted module for `filePath` from the production server-modules map.
245
+ *
246
+ * @remarks
247
+ * Resolves `undefined` when no map was emitted or it does not list the file.
248
+ */
171
249
  export async function importPagesUnifiedGraphModule(appConfig, filePath) {
172
- const manifest = readPagesUnifiedGraphManifest(appConfig);
173
- if (!manifest || !isGraphImportable(manifest, appConfig)) {
250
+ const manifest = loadProductionServerModules(appConfig);
251
+ if (!manifest) {
252
+ return undefined;
253
+ }
254
+ const sourceKey = toRootRelativePath(appConfig.rootDir, filePath);
255
+ const relativePath = manifest.modules[sourceKey];
256
+ if (!relativePath) {
174
257
  return undefined;
175
258
  }
176
- const resolvedFilePath = path.resolve(filePath);
177
- const outputPath = manifest.outputs[resolvedFilePath];
178
- if (!outputPath || !fileSystem.exists(outputPath)) {
259
+ const outputPath = path.join(manifest.outdir, relativePath);
260
+ if (!fileSystem.exists(outputPath)) {
179
261
  return undefined;
180
262
  }
181
- return (await import(/* @vite-ignore */ pathToFileURL(outputPath).href));
263
+ return importEmittedServerModule(appConfig, filePath, outputPath);
182
264
  }