@ecopages/core 0.2.0-rc.6 → 0.2.0-rc.8

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 (63) hide show
  1. package/README.md +2 -0
  2. package/package.json +27 -3
  3. package/src/adapters/abstract/segment-path-matcher.js +56 -38
  4. package/src/adapters/bun/create-app.d.ts +4 -0
  5. package/src/adapters/bun/create-app.js +46 -31
  6. package/src/adapters/shared/runtime/server-adapter.d.ts +1 -0
  7. package/src/adapters/shared/runtime/server-adapter.js +9 -22
  8. package/src/build/rolldown/rolldown-adapter-helpers.js +41 -25
  9. package/src/build/rolldown/rolldown-plugin-bridge.js +25 -21
  10. package/src/declarations.d.ts +10 -1
  11. package/src/eco/README.md +3 -1
  12. package/src/eco/lazy-injector-map.js +57 -41
  13. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -0
  14. package/src/hmr/strategies/js-hmr-strategy.js +24 -16
  15. package/src/islands/README.md +5 -1
  16. package/src/plugins/component-import-discovery.js +115 -77
  17. package/src/plugins/eco-component-meta-plugin.js +47 -30
  18. package/src/route-renderer/README.md +3 -2
  19. package/src/route-renderer/orchestration/custom-element-scripts/README.md +9 -0
  20. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preload-invalidation.d.ts +16 -0
  21. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preload-invalidation.js +34 -0
  22. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preloader.d.ts +68 -0
  23. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preloader.js +183 -0
  24. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-server-module-importer.d.ts +9 -0
  25. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-server-module-importer.js +22 -0
  26. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-ssr-preload-entrypoint.d.ts +10 -0
  27. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-ssr-preload-entrypoint.js +46 -0
  28. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +7 -2
  29. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +2 -0
  30. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +3 -2
  31. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +1 -1
  32. package/src/route-renderer/orchestration/integration-renderer.d.ts +7 -3
  33. package/src/route-renderer/orchestration/integration-renderer.js +34 -20
  34. package/src/route-renderer/orchestration/ownership-graph/component-graph-collectors.d.ts +1 -1
  35. package/src/route-renderer/orchestration/ownership-graph/component-graph-collectors.js +2 -2
  36. package/src/route-renderer/orchestration/ownership-graph/component-graph.js +55 -39
  37. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.d.ts +6 -0
  38. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +59 -36
  39. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +3 -2
  40. package/src/route-renderer/orchestration/string-markup-renderer.d.ts +1 -1
  41. package/src/route-renderer/orchestration/string-markup-renderer.js +2 -1
  42. package/src/route-renderer/page-loading/component-dependency-collection.js +95 -74
  43. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +41 -28
  44. package/src/route-renderer/page-loading/file-scoped-dependency-components.d.ts +0 -3
  45. package/src/route-renderer/page-loading/file-scoped-dependency-components.js +37 -34
  46. package/src/route-renderer/page-loading/page-dependency-bundling.js +14 -8
  47. package/src/router/README.md +7 -1
  48. package/src/router/server/route-registry.d.ts +13 -0
  49. package/src/router/server/route-registry.js +46 -32
  50. package/src/services/README.md +2 -0
  51. package/src/services/assets/asset-processing-service/browser-runtime-entry-resolution.d.ts +6 -0
  52. package/src/services/assets/asset-processing-service/browser-runtime-entry-resolution.js +24 -5
  53. package/src/services/assets/asset-processing-service/page-package.js +42 -39
  54. package/src/services/module-loading/page-module-import.service.d.ts +6 -0
  55. package/src/services/module-loading/page-module-import.service.js +60 -27
  56. package/src/services/validation/schema-validation-service.d.ts +1 -0
  57. package/src/services/validation/schema-validation-service.js +23 -36
  58. package/src/static-site-generator/static-site-generator.d.ts +4 -0
  59. package/src/static-site-generator/static-site-generator.js +75 -48
  60. package/src/types/internal-types.d.ts +5 -1
  61. package/src/utils/parse-cli-args.js +29 -22
  62. package/src/watchers/project-watcher.d.ts +5 -0
  63. package/src/watchers/project-watcher.js +46 -32
@@ -127,25 +127,31 @@ function createPageDependencyPackagingPlan(dependencies, integrationName) {
127
127
  bundleableScriptFilepaths: new Set(pageScriptImports),
128
128
  };
129
129
  }
130
+ function isBundledStylesheetDependency(dependency, plan) {
131
+ return (Boolean(plan.bundledStylesheet) &&
132
+ dependency.kind === 'stylesheet' &&
133
+ dependency.source === 'file' &&
134
+ plan.bundleableStyleFilepaths.has(dependency.filepath));
135
+ }
136
+ function isBundledScriptDependency(dependency, plan) {
137
+ return (Boolean(plan.bundledScript) &&
138
+ dependency.kind === 'script' &&
139
+ dependency.source === 'file' &&
140
+ plan.bundleableScriptFilepaths.has(dependency.filepath));
141
+ }
130
142
  function applyPageDependencyPackagingPlan(dependencies, plan) {
131
143
  const unifiedDependencies = [];
132
144
  let insertedStylesheet = false;
133
145
  let insertedScript = false;
134
146
  for (const dependency of dependencies) {
135
- if (plan.bundledStylesheet &&
136
- dependency.kind === 'stylesheet' &&
137
- dependency.source === 'file' &&
138
- plan.bundleableStyleFilepaths.has(dependency.filepath)) {
147
+ if (isBundledStylesheetDependency(dependency, plan)) {
139
148
  if (!insertedStylesheet) {
140
149
  unifiedDependencies.push(plan.bundledStylesheet);
141
150
  insertedStylesheet = true;
142
151
  }
143
152
  continue;
144
153
  }
145
- if (plan.bundledScript &&
146
- dependency.kind === 'script' &&
147
- dependency.source === 'file' &&
148
- plan.bundleableScriptFilepaths.has(dependency.filepath)) {
154
+ if (isBundledScriptDependency(dependency, plan)) {
149
155
  if (!insertedScript) {
150
156
  unifiedDependencies.push(plan.bundledScript);
151
157
  insertedScript = true;
@@ -56,7 +56,11 @@ Match priority:
56
56
 
57
57
  1. `exact` — the pathname must equal the route pathname exactly.
58
58
  2. `dynamic` — the clean (bracket-stripped) prefix must appear in the pathname, and the segment counts must match.
59
- 3. `catch-all` — the clean prefix must appear in the pathname.
59
+ 3. `catch-all` — the prefix segments must match the pathname. When multiple
60
+ catch-all routes match, shared prefix segments are compared from left to right
61
+ so an earlier static segment wins over a dynamic one; when those patterns tie,
62
+ the route with the longer prefix wins, then pathname order provides a
63
+ deterministic tie-breaker.
60
64
 
61
65
  ## `client/`
62
66
 
@@ -110,6 +114,8 @@ import {
110
114
 
111
115
  This is separate from coordinator `subscribe()` events, which track runtime ownership rather than page lifecycle.
112
116
 
117
+ Scripts listening to client navigation events (`eco:after-swap`, `eco:page-load`) should be registered as client scripts (e.g., using `scripts: ['./component.script.ts']`) or guarded by `isServer` from `@ecopages/radiant/is-server` when used in Radiant projects where `document` is defined during SSR.
118
+
113
119
  ### Link Intent (`link-intent.ts`)
114
120
 
115
121
  Shared helpers for locating anchors and recovering stale navigation intent.
@@ -62,6 +62,19 @@ export declare class RouteRegistry {
62
62
  reload(): Promise<void>;
63
63
  onReload(listener: () => void): () => void;
64
64
  matchRequest(requestUrl: string): RouteMatch | null;
65
+ /**
66
+ * Orders overlapping catch-all routes by the specificity of their prefix.
67
+ *
68
+ * @remarks
69
+ * Prefix segments are compared from left to right because an earlier static
70
+ * segment constrains a request more strongly than a later one. A longer
71
+ * prefix wins only after the shared segment pattern ties. The pathname tie
72
+ * breaker keeps equal patterns deterministic without depending on discovery
73
+ * order.
74
+ */
75
+ private compareCatchAllSpecificity;
76
+ private getCatchAllPrefix;
77
+ private isDynamicRouteSegment;
65
78
  listStaticPathExpansions(input: {
66
79
  runtimeOrigin: string;
67
80
  }): Promise<readonly StaticPathExpansion[]>;
@@ -49,49 +49,60 @@ export class RouteRegistry {
49
49
  const requestedPathname = normalizePathname(url.pathname);
50
50
  const query = this.getSearchParams(url);
51
51
  for (const route of this.templateRouteList) {
52
- if (route.kind !== 'exact') {
52
+ if (route.kind === 'exact') {
53
+ if (requestedPathname === route.pathname || requestedPathname === `${route.pathname}/`) {
54
+ return {
55
+ requestedPathname,
56
+ templateRoute: route,
57
+ params: {},
58
+ query,
59
+ };
60
+ }
53
61
  continue;
54
62
  }
55
- if (requestedPathname === route.pathname || requestedPathname === `${route.pathname}/`) {
63
+ const params = this.tryExtractParams(route, requestedPathname);
64
+ if (params) {
56
65
  return {
57
66
  requestedPathname,
58
67
  templateRoute: route,
59
- params: {},
68
+ params,
60
69
  query,
61
70
  };
62
71
  }
63
72
  }
64
- for (const route of this.templateRouteList) {
65
- if (route.kind !== 'dynamic') {
66
- continue;
67
- }
68
- const params = this.tryExtractParams(route, requestedPathname);
69
- if (!params) {
70
- continue;
71
- }
72
- return {
73
- requestedPathname,
74
- templateRoute: route,
75
- params,
76
- query,
77
- };
78
- }
79
- for (const route of this.templateRouteList) {
80
- if (route.kind !== 'catch-all') {
81
- continue;
82
- }
83
- const params = this.tryExtractParams(route, requestedPathname);
84
- if (!params) {
85
- continue;
73
+ return null;
74
+ }
75
+ /**
76
+ * Orders overlapping catch-all routes by the specificity of their prefix.
77
+ *
78
+ * @remarks
79
+ * Prefix segments are compared from left to right because an earlier static
80
+ * segment constrains a request more strongly than a later one. A longer
81
+ * prefix wins only after the shared segment pattern ties. The pathname tie
82
+ * breaker keeps equal patterns deterministic without depending on discovery
83
+ * order.
84
+ */
85
+ compareCatchAllSpecificity(left, right) {
86
+ const leftPrefix = this.getCatchAllPrefix(left.pathname);
87
+ const rightPrefix = this.getCatchAllPrefix(right.pathname);
88
+ const sharedLength = Math.min(leftPrefix.length, rightPrefix.length);
89
+ for (let index = 0; index < sharedLength; index += 1) {
90
+ const leftIsDynamic = this.isDynamicRouteSegment(leftPrefix[index]);
91
+ const rightIsDynamic = this.isDynamicRouteSegment(rightPrefix[index]);
92
+ if (leftIsDynamic !== rightIsDynamic) {
93
+ return leftIsDynamic ? 1 : -1;
86
94
  }
87
- return {
88
- requestedPathname,
89
- templateRoute: route,
90
- params,
91
- query,
92
- };
93
95
  }
94
- return null;
96
+ const prefixLengthDifference = rightPrefix.length - leftPrefix.length;
97
+ return prefixLengthDifference !== 0 ? prefixLengthDifference : left.pathname.localeCompare(right.pathname);
98
+ }
99
+ getCatchAllPrefix(pathname) {
100
+ const segments = pathname.split('/').filter(Boolean);
101
+ const catchAllIndex = segments.findIndex((segment) => segment.startsWith('[...') && segment.endsWith(']'));
102
+ return catchAllIndex === -1 ? segments : segments.slice(0, catchAllIndex);
103
+ }
104
+ isDynamicRouteSegment(segment) {
105
+ return segment.startsWith('[') && segment.endsWith(']');
95
106
  }
96
107
  async listStaticPathExpansions(input) {
97
108
  const expansions = [];
@@ -168,6 +179,9 @@ export class RouteRegistry {
168
179
  if (priorityDifference !== 0) {
169
180
  return priorityDifference;
170
181
  }
182
+ if (left.kind === 'catch-all' && right.kind === 'catch-all') {
183
+ return this.compareCatchAllSpecificity(left, right);
184
+ }
171
185
  if (left.pathname === '/') {
172
186
  return -1;
173
187
  }
@@ -30,6 +30,8 @@ so shared layout styles do not need to be rebuilt for every navigated page while
30
30
 
31
31
  Browser runtime module assets resolve bare package roots through their ESM import target. For legacy packages without an `exports` map, they prefer `package.json#module` over CJS `main`; CJS resolution is only a compatibility fallback. Generated entries use `export *` for ESM files and explicit named re-exports for CJS files (so bindings such as React `jsx` exist on the vendor). A default binding is added only when the selected entry exposes one. Runtime vendors are package-root contracts: subpath imports need their own vendor declaration or remain in the consuming bundle.
32
32
 
33
+ Package entry lookup is rooted at the application directory, so a framework-local dependency with the same name cannot shadow the application's installed package. ESM export conditions are evaluated in the same order as the generated vendor import (`node`, `import`, then `default`).
34
+
33
35
  ## Design Rule
34
36
 
35
37
  If a concern affects more than one integration or more than one runtime adapter, it usually belongs here instead of in a package-specific implementation.
@@ -3,6 +3,12 @@ export type BrowserRuntimeDefaultExportPolicy = 'emit-default' | 'skip-default';
3
3
  type RequireFromRoot = ReturnType<typeof createRequire>;
4
4
  /**
5
5
  * Resolves a package specifier through Node's ESM import conditions from the app root.
6
+ *
7
+ * @remarks
8
+ * The resolver is rooted at the application directory so package lookup cannot
9
+ * accidentally use a dependency with the same name from the framework's own
10
+ * installation. The condition order matches the generated vendor import: Node
11
+ * compatibility first, then ESM import, then the package default.
6
12
  */
7
13
  export declare function resolvePackageEsmEntryPath(specifier: string, rootDir: string): string | undefined;
8
14
  /**
@@ -1,14 +1,33 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { pathToFileURL, fileURLToPath } from 'node:url';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { ResolverFactory } from 'oxc-resolver';
4
5
  import { isBarePackageImportSpecifier } from '../../../plugins/tsconfig-import-resolver.js';
5
6
  import { toPackageRootSpecifier } from '../../../plugins/package-specifier.js';
7
+ const esmEntryResolvers = new Map();
8
+ function getEsmEntryResolver(rootDir) {
9
+ const normalizedRoot = path.resolve(rootDir);
10
+ const cached = esmEntryResolvers.get(normalizedRoot);
11
+ if (cached) {
12
+ return cached;
13
+ }
14
+ const resolver = new ResolverFactory({ conditionNames: ['node', 'import', 'default'] });
15
+ esmEntryResolvers.set(normalizedRoot, resolver);
16
+ return resolver;
17
+ }
6
18
  /**
7
19
  * Resolves a package specifier through Node's ESM import conditions from the app root.
20
+ *
21
+ * @remarks
22
+ * The resolver is rooted at the application directory so package lookup cannot
23
+ * accidentally use a dependency with the same name from the framework's own
24
+ * installation. The condition order matches the generated vendor import: Node
25
+ * compatibility first, then ESM import, then the package default.
8
26
  */
9
27
  export function resolvePackageEsmEntryPath(specifier, rootDir) {
10
28
  try {
11
- return fileURLToPath(import.meta.resolve(specifier, pathToFileURL(path.join(rootDir, 'package.json')).href));
29
+ const result = getEsmEntryResolver(rootDir).sync(path.resolve(rootDir), specifier);
30
+ return result.path;
12
31
  }
13
32
  catch {
14
33
  return undefined;
@@ -56,13 +75,13 @@ export function resolveBrowserRuntimeEntryPath(options) {
56
75
  if (specifier.startsWith('.')) {
57
76
  return requireFromRoot.resolve(specifier);
58
77
  }
59
- const esmResolvedPath = isBarePackageImportSpecifier(specifier, rootDir)
60
- ? resolvePackageEsmEntryPath(specifier, rootDir)
61
- : undefined;
62
78
  const legacyModulePath = resolveLegacyPackageModuleEntry({ specifier, requireFromRoot, rootDir });
63
79
  if (legacyModulePath) {
64
80
  return legacyModulePath;
65
81
  }
82
+ const esmResolvedPath = isBarePackageImportSpecifier(specifier, rootDir)
83
+ ? resolvePackageEsmEntryPath(specifier, rootDir)
84
+ : undefined;
66
85
  if (esmResolvedPath) {
67
86
  return esmResolvedPath;
68
87
  }
@@ -10,58 +10,61 @@ function getSuppressedSourceFilepaths(assets) {
10
10
  }
11
11
  return suppressed;
12
12
  }
13
+ function classifyProcessedAsset(asset, buckets) {
14
+ if (asset.inline) {
15
+ buckets.inlineAssets.push(asset);
16
+ return;
17
+ }
18
+ if (asset.packageRole === 'dynamic-chunk') {
19
+ buckets.dynamicChunks.push(asset);
20
+ return;
21
+ }
22
+ if (!buckets.pageScript && asset.packageRole === 'page-script') {
23
+ buckets.pageScript = asset;
24
+ return;
25
+ }
26
+ if (!buckets.pageStylesheet && asset.packageRole === 'page-style') {
27
+ buckets.pageStylesheet = asset;
28
+ return;
29
+ }
30
+ if (asset.packageRole === 'keep-separate' || asset.packageRole === 'runtime') {
31
+ buckets.separateAssets.push(asset);
32
+ return;
33
+ }
34
+ if (!buckets.pageScript && asset.kind === 'script' && !asset.excludeFromHtml) {
35
+ buckets.pageScript = asset;
36
+ return;
37
+ }
38
+ if (!buckets.pageStylesheet && asset.kind === 'stylesheet') {
39
+ buckets.pageStylesheet = asset;
40
+ return;
41
+ }
42
+ buckets.separateAssets.push(asset);
43
+ }
13
44
  export function createPagePackage(assets, options = {}) {
14
45
  const allAssets = [
15
46
  ...assets,
16
47
  ...(options.pageBrowserGraph?.entryAssets ?? []),
17
48
  ...(options.pageBrowserGraph?.chunkAssets ?? []),
18
49
  ];
19
- const inlineAssets = [];
20
- const separateAssets = [];
21
- const dynamicChunks = [];
22
- let pageScript;
23
- let pageStylesheet;
50
+ const buckets = {
51
+ inlineAssets: [],
52
+ separateAssets: [],
53
+ dynamicChunks: [],
54
+ };
24
55
  const suppressedSourceFilepaths = getSuppressedSourceFilepaths(allAssets);
25
56
  for (const asset of allAssets) {
26
- if (asset.inline) {
27
- inlineAssets.push(asset);
28
- continue;
29
- }
30
- if (asset.packageRole === 'dynamic-chunk') {
31
- dynamicChunks.push(asset);
32
- continue;
33
- }
34
- if (!pageScript && asset.packageRole === 'page-script') {
35
- pageScript = asset;
36
- continue;
37
- }
38
- if (!pageStylesheet && asset.packageRole === 'page-style') {
39
- pageStylesheet = asset;
40
- continue;
41
- }
42
- if (asset.packageRole === 'keep-separate' || asset.packageRole === 'runtime') {
43
- separateAssets.push(asset);
44
- continue;
45
- }
46
- if (!pageScript && asset.kind === 'script' && !asset.excludeFromHtml) {
47
- pageScript = asset;
48
- continue;
49
- }
50
- if (!pageStylesheet && asset.kind === 'stylesheet') {
51
- pageStylesheet = asset;
52
- continue;
53
- }
54
- separateAssets.push(asset);
57
+ classifyProcessedAsset(asset, buckets);
55
58
  }
56
59
  return {
57
60
  assets: allAssets,
58
61
  pageBrowserGraph: options.pageBrowserGraph,
59
62
  htmlAssets: allAssets.filter((asset) => shouldIncludeInHtml(asset, suppressedSourceFilepaths)),
60
- pageScript,
61
- pageStylesheet,
62
- inlineAssets,
63
- separateAssets,
64
- dynamicChunks,
63
+ pageScript: buckets.pageScript,
64
+ pageStylesheet: buckets.pageStylesheet,
65
+ inlineAssets: buckets.inlineAssets,
66
+ separateAssets: buckets.separateAssets,
67
+ dynamicChunks: buckets.dynamicChunks,
65
68
  };
66
69
  }
67
70
  function shouldIncludeInHtml(asset, suppressedSourceFilepaths) {
@@ -89,6 +89,12 @@ export declare class PageModuleImportService {
89
89
  * @returns The loaded module.
90
90
  */
91
91
  importModule<T = unknown>(options: PageModuleBuildImportOptions): Promise<T>;
92
+ private createRouteModuleBuildOptions;
93
+ private createRouteModuleCacheBuildOptions;
94
+ private tryLoadCachedRouteModuleBuild;
95
+ private tryLoadPagesUnifiedGraphModule;
96
+ private resolveCompiledRouteModuleOutput;
97
+ private importCompiledRouteModule;
92
98
  private loadModule;
93
99
  private getRouteModuleBuildCache;
94
100
  }
@@ -125,12 +125,8 @@ export class PageModuleImportService {
125
125
  fileHash,
126
126
  });
127
127
  }
128
- async loadModule(options) {
129
- const { filePath, fileHash, importCacheKey } = options;
130
- const { rootDir, outdir, splitting, externalPackages, transpileErrorMessage = (details) => `Error transpiling page module: ${details}`, noOutputMessage = (targetFilePath) => `No transpiled output generated for page module: ${targetFilePath}`, } = options;
131
- const outputFileName = createRuntimeBuildOutputFileName(resolvePageModuleOutputFileName({ filePath, fileHash }), this.developmentImportGeneration);
132
- const outputNamingTemplate = outputFileName.replace(/\.mjs$/u, '.[ext]');
133
- const preferredOutputPath = path.join(outdir, outputFileName);
128
+ createRouteModuleBuildOptions(options, outputNamingTemplate) {
129
+ const { filePath, rootDir, outdir, splitting, externalPackages } = options;
134
130
  const buildOptions = this.appConfig
135
131
  ? createServerBuildRequest(this.appConfig, {
136
132
  profile: 'route-module',
@@ -156,10 +152,17 @@ export class PageModuleImportService {
156
152
  root: rootDir,
157
153
  entrypoints: [filePath],
158
154
  };
159
- const cacheBuildOptions = {
160
- ...options,
155
+ return {
156
+ buildOptions,
161
157
  rootDir: buildOptions.root ?? rootDir,
162
158
  outdir: buildOptions.outdir ?? outdir,
159
+ };
160
+ }
161
+ createRouteModuleCacheBuildOptions(options, buildOptions, resolvedRootDir, resolvedOutdir, fileHash) {
162
+ return {
163
+ ...options,
164
+ rootDir: resolvedRootDir,
165
+ outdir: resolvedOutdir,
163
166
  splitting: buildOptions.splitting,
164
167
  externalPackages: buildOptions.externalPackages,
165
168
  jsx: buildOptions.jsx,
@@ -167,32 +170,36 @@ export class PageModuleImportService {
167
170
  sourceTransforms: buildOptions.sourceTransforms,
168
171
  fileHash,
169
172
  };
170
- const routeModuleBuildCache = this.getRouteModuleBuildCache(outdir);
171
- const cachedBuild = routeModuleBuildCache.lookup(cacheBuildOptions);
172
- if (cachedBuild) {
173
- const loadedModule = (await import(/* @vite-ignore */ pathToFileURL(cachedBuild.outputPath).href));
174
- recordPageModuleLoad('disk-cache-hit');
175
- return loadedModule;
173
+ }
174
+ async tryLoadCachedRouteModuleBuild(cacheBuildOptions, outdir) {
175
+ const cachedBuild = this.getRouteModuleBuildCache(outdir).lookup(cacheBuildOptions);
176
+ if (!cachedBuild) {
177
+ return undefined;
176
178
  }
177
- if (shouldBuildPagesUnifiedGraph() && this.appConfig && isPagesUnifiedGraphPage(filePath, this.appConfig)) {
178
- const graphModule = await importPagesUnifiedGraphModule(this.appConfig, filePath);
179
- if (graphModule !== undefined) {
180
- recordPageModuleLoad('unified-graph');
181
- return graphModule;
182
- }
179
+ const loadedModule = (await import(/* @vite-ignore */ pathToFileURL(cachedBuild.outputPath).href));
180
+ recordPageModuleLoad('disk-cache-hit');
181
+ return loadedModule;
182
+ }
183
+ async tryLoadPagesUnifiedGraphModule(filePath) {
184
+ if (!shouldBuildPagesUnifiedGraph() || !this.appConfig || !isPagesUnifiedGraphPage(filePath, this.appConfig)) {
185
+ return undefined;
183
186
  }
184
- recordPageModuleBuildInvocation();
185
- const buildResult = await this.dependencies.buildModule(buildOptions, options.buildExecutor);
186
- recordPageModuleLoad('cold-build', buildResult.outputs.length);
187
- if (!buildResult.success) {
188
- const details = buildResult.logs.map((log) => log.message).join(' | ');
189
- throw new Error(transpileErrorMessage(details));
187
+ const graphModule = await importPagesUnifiedGraphModule(this.appConfig, filePath);
188
+ if (graphModule === undefined) {
189
+ return undefined;
190
190
  }
191
+ recordPageModuleLoad('unified-graph');
192
+ return graphModule;
193
+ }
194
+ resolveCompiledRouteModuleOutput(buildResult, preferredOutputPath, filePath, noOutputMessage) {
191
195
  const compiledOutput = buildResult.outputs.find((output) => output.path === preferredOutputPath)?.path ??
192
196
  buildResult.outputs.find((output) => /\.(?:[cm]?js)$/u.test(output.path))?.path;
193
197
  if (!compiledOutput) {
194
198
  throw new Error(noOutputMessage(filePath));
195
199
  }
200
+ return compiledOutput;
201
+ }
202
+ async importCompiledRouteModule(compiledOutput, filePath, fileHash, rootDir, buildResult, importCacheKey, cacheBuildOptions, outdir) {
196
203
  const dependencyModulePaths = resolveRouteModuleDependencyPaths(buildResult, filePath, rootDir);
197
204
  const dependencyHashes = this.dependencyHasher.createDependencyHashes(dependencyModulePaths);
198
205
  dependencyHashes[path.normalize(filePath)] = fileHash;
@@ -202,7 +209,7 @@ export class PageModuleImportService {
202
209
  cacheEntry.dependencyHashes = dependencyHashes;
203
210
  }
204
211
  }
205
- routeModuleBuildCache.recordBuild({
212
+ this.getRouteModuleBuildCache(outdir).recordBuild({
206
213
  ...cacheBuildOptions,
207
214
  outputPath: compiledOutput,
208
215
  dependencyModulePaths,
@@ -213,6 +220,32 @@ export class PageModuleImportService {
213
220
  }
214
221
  return (await import(/* @vite-ignore */ compiledOutputUrl.href));
215
222
  }
223
+ async loadModule(options) {
224
+ const { filePath, fileHash, importCacheKey } = options;
225
+ const { outdir, transpileErrorMessage = (details) => `Error transpiling page module: ${details}`, noOutputMessage = (targetFilePath) => `No transpiled output generated for page module: ${targetFilePath}`, } = options;
226
+ const outputFileName = createRuntimeBuildOutputFileName(resolvePageModuleOutputFileName({ filePath, fileHash }), this.developmentImportGeneration);
227
+ const outputNamingTemplate = outputFileName.replace(/\.mjs$/u, '.[ext]');
228
+ const preferredOutputPath = path.join(outdir, outputFileName);
229
+ const { buildOptions, rootDir: resolvedRootDir, outdir: resolvedOutdir, } = this.createRouteModuleBuildOptions(options, outputNamingTemplate);
230
+ const cacheBuildOptions = this.createRouteModuleCacheBuildOptions(options, buildOptions, resolvedRootDir, resolvedOutdir, fileHash);
231
+ const cachedModule = await this.tryLoadCachedRouteModuleBuild(cacheBuildOptions, resolvedOutdir);
232
+ if (cachedModule !== undefined) {
233
+ return cachedModule;
234
+ }
235
+ const unifiedGraphModule = await this.tryLoadPagesUnifiedGraphModule(filePath);
236
+ if (unifiedGraphModule !== undefined) {
237
+ return unifiedGraphModule;
238
+ }
239
+ recordPageModuleBuildInvocation();
240
+ const buildResult = await this.dependencies.buildModule(buildOptions, options.buildExecutor);
241
+ recordPageModuleLoad('cold-build', buildResult.outputs.length);
242
+ if (!buildResult.success) {
243
+ const details = buildResult.logs.map((log) => log.message).join(' | ');
244
+ throw new Error(transpileErrorMessage(details));
245
+ }
246
+ const compiledOutput = this.resolveCompiledRouteModuleOutput(buildResult, preferredOutputPath, filePath, noOutputMessage);
247
+ return await this.importCompiledRouteModule(compiledOutput, filePath, fileHash, resolvedRootDir, buildResult, importCacheKey, cacheBuildOptions, resolvedOutdir);
248
+ }
216
249
  getRouteModuleBuildCache(outdir) {
217
250
  return getSharedRouteModuleBuildCache(outdir, this.appConfig);
218
251
  }
@@ -110,6 +110,7 @@ export declare class SchemaValidationService {
110
110
  * }
111
111
  * ```
112
112
  */
113
+ private validateRequestPart;
113
114
  validateRequest(source: ValidationSource, schemas: ValidationSchemas): Promise<ValidationResult<ValidatedData>>;
114
115
  /**
115
116
  * Validates a single value against a Standard Schema.
@@ -84,45 +84,32 @@ export class SchemaValidationService {
84
84
  * }
85
85
  * ```
86
86
  */
87
+ async validateRequestPart(schema, value, assign, allErrors, shouldValidate) {
88
+ if (!schema || !shouldValidate) {
89
+ return;
90
+ }
91
+ const result = await this.validateWithSchema(schema, value);
92
+ if (!result.success) {
93
+ allErrors.push(...(result.errors || []));
94
+ return;
95
+ }
96
+ assign(result.data);
97
+ }
87
98
  async validateRequest(source, schemas) {
88
99
  const validated = {};
89
100
  const allErrors = [];
90
- if (schemas.body && source.body !== undefined) {
91
- const result = await this.validateWithSchema(schemas.body, source.body);
92
- if (!result.success) {
93
- allErrors.push(...(result.errors || []));
94
- }
95
- else {
96
- validated.body = result.data;
97
- }
98
- }
99
- if (schemas.query && source.query) {
100
- const result = await this.validateWithSchema(schemas.query, source.query);
101
- if (!result.success) {
102
- allErrors.push(...(result.errors || []));
103
- }
104
- else {
105
- validated.query = result.data;
106
- }
107
- }
108
- if (schemas.headers && source.headers) {
109
- const result = await this.validateWithSchema(schemas.headers, source.headers);
110
- if (!result.success) {
111
- allErrors.push(...(result.errors || []));
112
- }
113
- else {
114
- validated.headers = result.data;
115
- }
116
- }
117
- if (schemas.params && source.params) {
118
- const result = await this.validateWithSchema(schemas.params, source.params);
119
- if (!result.success) {
120
- allErrors.push(...(result.errors || []));
121
- }
122
- else {
123
- validated.params = result.data;
124
- }
125
- }
101
+ await this.validateRequestPart(schemas.body, source.body, (data) => {
102
+ validated.body = data;
103
+ }, allErrors, schemas.body !== undefined && source.body !== undefined);
104
+ await this.validateRequestPart(schemas.query, source.query, (data) => {
105
+ validated.query = data;
106
+ }, allErrors, !!schemas.query && !!source.query);
107
+ await this.validateRequestPart(schemas.headers, source.headers, (data) => {
108
+ validated.headers = data;
109
+ }, allErrors, !!schemas.headers && !!source.headers);
110
+ await this.validateRequestPart(schemas.params, source.params, (data) => {
111
+ validated.params = data;
112
+ }, allErrors, !!schemas.params && !!source.params);
126
113
  if (allErrors.length > 0) {
127
114
  return { success: false, errors: allErrors };
128
115
  }
@@ -92,6 +92,10 @@ export declare class StaticSiteGenerator {
92
92
  }): Promise<void>;
93
93
  private createStaticExportContext;
94
94
  private invokeStaticExportHook;
95
+ private resetStaticGenerationState;
96
+ private ensureUnifiedGraphForStaticGeneration;
97
+ private executeStaticGenerationBody;
98
+ private finalizeStaticGenerationRun;
95
99
  /**
96
100
  * Executes the full static-generation workflow for one app run.
97
101
  */