@ecopages/core 0.3.2 → 0.5.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 (79) hide show
  1. package/README.md +19 -3
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +19 -19
  4. package/src/adapters/node/create-app.js +26 -40
  5. package/src/adapters/node/dev-session.d.ts +3 -1
  6. package/src/adapters/node/dev-session.js +4 -1
  7. package/src/adapters/node/server-adapter.js +5 -1
  8. package/src/adapters/shared/http/api-request-pipeline.js +2 -2
  9. package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
  10. package/src/adapters/shared/http/define-api-handler.js +15 -1
  11. package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
  12. package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
  13. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
  14. package/src/adapters/shared/runtime/server-request-pipeline.js +46 -12
  15. package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
  16. package/src/adapters/shared/runtime/server-route-handler.js +16 -10
  17. package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
  18. package/src/adapters/shared/runtime/server-static-builder.js +13 -2
  19. package/src/assets/app-browser-client-build.js +8 -21
  20. package/src/assets/app-browser-client-manifest.d.ts +0 -1
  21. package/src/assets/app-browser-client-manifest.js +1 -20
  22. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  23. package/src/build/contracts/content-virtual-modules.js +11 -5
  24. package/src/build/contracts.d.ts +1 -1
  25. package/src/build/contracts.js +1 -1
  26. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  27. package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
  28. package/src/build/server-bundle-deploy-manifest.js +1 -1
  29. package/src/build.d.ts +1 -1
  30. package/src/build.js +1 -1
  31. package/src/config/assembly/finalize-config.js +5 -0
  32. package/src/dev/transform-server/dev-transform-server.js +1 -1
  33. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  34. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  35. package/src/errors/http-error.d.ts +9 -0
  36. package/src/errors/http-error.js +11 -0
  37. package/src/html/html-transformer.service.d.ts +0 -21
  38. package/src/html/html-transformer.service.js +0 -32
  39. package/src/html-pages/html-page-renderer.d.ts +2 -1
  40. package/src/html-pages/html-page-renderer.js +5 -3
  41. package/src/index.d.ts +1 -1
  42. package/src/index.js +1 -1
  43. package/src/integration.d.ts +1 -2
  44. package/src/integration.js +0 -1
  45. package/src/islands/island-host.d.ts +1 -2
  46. package/src/islands/island-host.js +1 -2
  47. package/src/plugins/integration-plugin.d.ts +1 -1
  48. package/src/plugins/processor.d.ts +1 -1
  49. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  50. package/src/plugins/tsconfig-import-resolver.js +4 -2
  51. package/src/processor.d.ts +1 -1
  52. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  53. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  54. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  55. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  56. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  57. package/src/route-renderer/orchestration/integration-renderer.d.ts +20 -44
  58. package/src/route-renderer/orchestration/integration-renderer.js +52 -115
  59. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  60. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  61. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  62. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  63. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  64. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  65. package/src/router/server/route-registry.d.ts +20 -9
  66. package/src/router/server/route-registry.js +52 -30
  67. package/src/router/server/segment-path-matcher.d.ts +8 -0
  68. package/src/router/server/segment-path-matcher.js +15 -0
  69. package/src/static-site-generator/production-page-browser-graph-prebuild.js +0 -4
  70. package/src/static-site-generator/static-site-generator.js +1 -1
  71. package/src/types/build-types.d.ts +6 -0
  72. package/src/types/contracts.d.ts +93 -65
  73. package/src/types/contracts.js +4 -1
  74. package/src/types/eco-api-types.d.ts +1 -1
  75. package/src/types/public-types.d.ts +1 -1
  76. package/src/utils/endpoint-file-extensions.d.ts +11 -0
  77. package/src/utils/endpoint-file-extensions.js +13 -0
  78. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  79. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
@@ -2,10 +2,12 @@ import path from 'node:path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
3
  import { appLogger } from '../../global/app-logger.js';
4
4
  import { invariant } from '../../utils/invariant.js';
5
+ import { hasKnownStaticExtension } from '../../utils/static-file-extensions.js';
6
+ import { ENDPOINT_FILE_EXTENSIONS, findEndpointFileExtension } from '../../utils/endpoint-file-extensions.js';
5
7
  import { normalizePathname } from '../../utils/path-pattern.js';
6
8
  import { parseSearchParams } from './parse-search-params.js';
7
9
  import { findIntegrationForFile, findLongestExtension } from '../../plugins/find-integration-for-file.js';
8
- import { buildSegmentPath, matchParsedSegmentPath, parseSegmentPath, } from './segment-path-matcher.js';
10
+ import { buildSegmentPath, matchParsedSegmentPath, parseSegmentPath, segmentPathPatternKey, } from './segment-path-matcher.js';
9
11
  const ROUTE_PRIORITY = {
10
12
  exact: 0,
11
13
  dynamic: 1,
@@ -34,6 +36,9 @@ export class RouteRegistry {
34
36
  get templateRoutes() {
35
37
  return this.templateRouteList;
36
38
  }
39
+ get pageRoutes() {
40
+ return this.templateRouteList.filter((route) => route.role === 'page');
41
+ }
37
42
  async init() {
38
43
  this.templateRouteList = await this.scanTemplateRoutes();
39
44
  appLogger.debug('RouteRegistry initialized', this.templateRouteList);
@@ -69,30 +74,30 @@ export class RouteRegistry {
69
74
  return null;
70
75
  }
71
76
  /**
72
- * Orders overlapping catch-all routes by the specificity of their prefix.
77
+ * Orders two dynamic or two catch-all routes by the specificity of their
78
+ * pattern segments, the catch-all segment itself left out.
73
79
  *
74
80
  * @remarks
75
- * Prefix segments are compared from left to right because an earlier static
81
+ * Segments are compared from left to right because an earlier literal
76
82
  * segment constrains a request more strongly than a later one. A longer
77
- * prefix wins only after the shared segment pattern ties. The pathname tie
78
- * breaker keeps equal patterns deterministic without depending on discovery
79
- * order.
83
+ * pattern wins only after the shared segments tie. The pathname tie breaker
84
+ * keeps equal patterns deterministic without depending on discovery order.
80
85
  */
81
- compareCatchAllSpecificity(left, right) {
82
- const leftPrefix = this.getCatchAllPrefix(left.pathname);
83
- const rightPrefix = this.getCatchAllPrefix(right.pathname);
84
- const sharedLength = Math.min(leftPrefix.length, rightPrefix.length);
86
+ compareSpecificity(left, right) {
87
+ const leftSegments = this.getSpecificitySegments(left.pathname);
88
+ const rightSegments = this.getSpecificitySegments(right.pathname);
89
+ const sharedLength = Math.min(leftSegments.length, rightSegments.length);
85
90
  for (let index = 0; index < sharedLength; index += 1) {
86
- const leftIsDynamic = this.isDynamicRouteSegment(leftPrefix[index]);
87
- const rightIsDynamic = this.isDynamicRouteSegment(rightPrefix[index]);
91
+ const leftIsDynamic = this.isDynamicRouteSegment(leftSegments[index]);
92
+ const rightIsDynamic = this.isDynamicRouteSegment(rightSegments[index]);
88
93
  if (leftIsDynamic !== rightIsDynamic) {
89
94
  return leftIsDynamic ? 1 : -1;
90
95
  }
91
96
  }
92
- const prefixLengthDifference = rightPrefix.length - leftPrefix.length;
93
- return prefixLengthDifference !== 0 ? prefixLengthDifference : left.pathname.localeCompare(right.pathname);
97
+ const lengthDifference = rightSegments.length - leftSegments.length;
98
+ return lengthDifference !== 0 ? lengthDifference : left.pathname.localeCompare(right.pathname);
94
99
  }
95
- getCatchAllPrefix(pathname) {
100
+ getSpecificitySegments(pathname) {
96
101
  const segments = pathname.split('/').filter(Boolean);
97
102
  const catchAllIndex = segments.findIndex((segment) => segment.startsWith('[...') && segment.endsWith(']'));
98
103
  return catchAllIndex === -1 ? segments : segments.slice(0, catchAllIndex);
@@ -102,11 +107,14 @@ export class RouteRegistry {
102
107
  }
103
108
  async listStaticPathExpansions(input) {
104
109
  const expansions = [];
105
- for (const route of this.templateRouteList) {
110
+ for (const route of this.pageRoutes) {
106
111
  if (route.kind === 'exact') {
107
112
  continue;
108
113
  }
109
114
  const pageModule = await this.pageModuleAdapter.loadPageModule(route.filePath);
115
+ if (pageModule.cache === 'dynamic') {
116
+ continue;
117
+ }
110
118
  const staticPaths = pageModule.staticPaths;
111
119
  if (this.buildMode) {
112
120
  invariant(staticPaths !== undefined, `[ecopages] Missing getStaticPaths in ${route.filePath}`);
@@ -132,7 +140,7 @@ export class RouteRegistry {
132
140
  async listStaticGenerationRoutes(input) {
133
141
  const staticPathExpansions = await this.listStaticPathExpansions(input);
134
142
  return [
135
- ...this.templateRouteList
143
+ ...this.pageRoutes
136
144
  .filter((route) => route.kind === 'exact')
137
145
  .map((route) => ({
138
146
  requestUrl: `${input.runtimeOrigin}${route.pathname}`,
@@ -152,29 +160,41 @@ export class RouteRegistry {
152
160
  if (!fileSystem.exists(this.pagesDir)) {
153
161
  return [];
154
162
  }
155
- const scannedFiles = await fileSystem.glob(this.templatesExt.map((ext) => `**/*${ext}`), {
163
+ const scannedFiles = await fileSystem.glob([...this.templatesExt, ...ENDPOINT_FILE_EXTENSIONS].map((ext) => `**/*${ext}`), {
156
164
  cwd: this.pagesDir,
157
165
  });
158
166
  const templateRoutes = [];
159
- const routeFiles = new Map();
167
+ const routesByKey = new Map();
160
168
  for await (const file of scannedFiles) {
161
169
  if (file.includes('.ecopages-node.')) {
162
170
  continue;
163
171
  }
164
- const routePathname = this.getRoutePath(file);
172
+ const endpointExtension = findEndpointFileExtension(file);
173
+ const role = endpointExtension ? 'endpoint' : 'page';
174
+ const routePathname = this.getRoutePath(file, endpointExtension);
165
175
  const filePath = path.join(this.pagesDir, file);
166
176
  const kind = this.classifyRouteKind(file);
167
- const duplicateFile = routeFiles.get(routePathname);
168
- if (duplicateFile === filePath) {
177
+ const routeKey = segmentPathPatternKey(routePathname, 'filesystem');
178
+ const duplicate = routesByKey.get(routeKey);
179
+ if (duplicate?.filePath === filePath) {
169
180
  continue;
170
181
  }
171
- invariant(duplicateFile === undefined, `${duplicateFile} and ${filePath} both define the route "${routePathname}". Keep one of them.`);
172
- routeFiles.set(routePathname, filePath);
173
- const owner = kind === 'exact' ? undefined : findIntegrationForFile(this.appConfig.integrations, filePath);
182
+ if (duplicate) {
183
+ const route = duplicate.pathname === routePathname
184
+ ? `the route "${routePathname}"`
185
+ : `the same route, "${duplicate.pathname}" and "${routePathname}"`;
186
+ invariant(false, `${duplicate.filePath} and ${filePath} both define ${route}. Keep one of them.`);
187
+ }
188
+ routesByKey.set(routeKey, { pathname: routePathname, filePath });
189
+ invariant(role === 'page' || !hasKnownStaticExtension(routePathname), `${filePath}: the endpoint "${routePathname}" ends in a static file extension, so no request reaches it. Register that URL in app.ts instead.`);
190
+ const owner = role === 'page' && kind !== 'exact'
191
+ ? findIntegrationForFile(this.appConfig.integrations, filePath)
192
+ : undefined;
174
193
  invariant(owner?.acceptsParams !== false, `${filePath}: ${findLongestExtension(owner?.extensions ?? [], filePath)} Pages cannot receive Params, so they cannot use dynamic route segments. Rename the file, or use an eco.page() Page from an Integration that supports staticPaths.`);
175
194
  templateRoutes.push({
176
195
  pathname: routePathname,
177
196
  kind,
197
+ role,
178
198
  filePath,
179
199
  paramNames: this.getParamNames(routePathname),
180
200
  });
@@ -184,8 +204,8 @@ export class RouteRegistry {
184
204
  if (priorityDifference !== 0) {
185
205
  return priorityDifference;
186
206
  }
187
- if (left.kind === 'catch-all' && right.kind === 'catch-all') {
188
- return this.compareCatchAllSpecificity(left, right);
207
+ if (left.kind !== 'exact') {
208
+ return this.compareSpecificity(left, right);
189
209
  }
190
210
  if (left.pathname === '/') {
191
211
  return -1;
@@ -199,10 +219,12 @@ export class RouteRegistry {
199
219
  /**
200
220
  * @remarks
201
221
  * Strips the longest template extension the file ends with, so `about.kita.tsx` keeps no
202
- * `.kita` part when `.tsx` is also registered, and `my.html-tips.html` keeps its name.
222
+ * `.kita` part when `.tsx` is also registered, and `my.html-tips.html` keeps its name. An
223
+ * endpoint strips its whole marker, so `users.api.tsx` is `/users` even when `.tsx` is a
224
+ * template extension.
203
225
  */
204
- getRoutePath(file) {
205
- const extension = findLongestExtension(this.templatesExt, file) ?? '';
226
+ getRoutePath(file, endpointExtension) {
227
+ const extension = endpointExtension ?? findLongestExtension(this.templatesExt, file) ?? '';
206
228
  const cleanedRoute = file.slice(0, file.length - extension.length).replace(/\/?index$/, '');
207
229
  return normalizePathname(`/${cleanedRoute}`);
208
230
  }
@@ -35,5 +35,13 @@ export declare function matchSegmentPath(pattern: string, pathname: string, synt
35
35
  * catch-all with no values disappears from the pathname.
36
36
  */
37
37
  export declare function buildSegmentPath(pattern: string, params: SegmentPathParams, syntax: SegmentPathSyntax): string;
38
+ /**
39
+ * Returns a key that two patterns share when they match the same pathnames.
40
+ *
41
+ * @remarks
42
+ * Parameter names and syntax are dropped, so `/blog/:slug` and `/blog/[id]` share a key, and a
43
+ * catch-all shares one with a wildcard, since both take every remaining segment.
44
+ */
45
+ export declare function segmentPathPatternKey(pattern: string, syntax: SegmentPathSyntax): string;
38
46
  export declare function scoreSegmentPathPattern(pattern: string, syntax: 'api'): number;
39
47
  export declare function scoreSegmentPathPattern(pattern: string, syntax: 'websocket'): number;
@@ -162,6 +162,21 @@ export function buildSegmentPath(pattern, params, syntax) {
162
162
  .filter((segment) => segment !== '');
163
163
  return normalizePathname(segments.join('/'));
164
164
  }
165
+ /**
166
+ * Returns a key that two patterns share when they match the same pathnames.
167
+ *
168
+ * @remarks
169
+ * Parameter names and syntax are dropped, so `/blog/:slug` and `/blog/[id]` share a key, and a
170
+ * catch-all shares one with a wildcard, since both take every remaining segment.
171
+ */
172
+ export function segmentPathPatternKey(pattern, syntax) {
173
+ const segments = parsePattern(pattern, syntax).map((segment) => {
174
+ if (segment.kind === 'literal')
175
+ return encodeURIComponent(segment.value);
176
+ return segment.kind === 'parameter' ? '[]' : '[...]';
177
+ });
178
+ return `/${segments.join('/')}`;
179
+ }
165
180
  export function scoreSegmentPathPattern(pattern, syntax) {
166
181
  const segments = parsePattern(pattern, syntax);
167
182
  if (syntax === 'websocket') {
@@ -144,10 +144,6 @@ function restoreManifestRouteAssets(appConfig, renderer, entry, instance) {
144
144
  instance.prebuiltGroupedAssets = restoreAppBrowserClientAssets(appConfig, entry.groupedAssets);
145
145
  instance.prebuiltPageClientBrowserAssets = {
146
146
  processedAssets: restoreAppBrowserClientAssets(appConfig, entry.pageClientAssets.processedAssets),
147
- islandRenderAssetsByFile: new Map(entry.pageClientAssets.islandRenderAssetsByFile.map(([filePath, assets]) => [
148
- resolveAppBrowserClientManifestPath(appConfig, filePath),
149
- restoreAppBrowserClientAssets(appConfig, assets),
150
- ])),
151
147
  fallbackDependencies: restoreFallbackDependencies(appConfig.rootDir, entry, instance),
152
148
  };
153
149
  }
@@ -293,7 +293,7 @@ export class StaticSiteGenerator {
293
293
  async executeStaticGenerationBody(input) {
294
294
  if (shouldPrebuildProductionPageBrowserGraphs() && input.routeRendererFactory) {
295
295
  const dynamicRouteTemplates = (input.router.templateRoutes ?? [])
296
- .filter((route) => route.kind !== 'exact')
296
+ .filter((route) => route.kind !== 'exact' && route.role === 'page')
297
297
  .map((route) => ({ routeFile: route.filePath, skipStaticProps: true, isRouteTemplate: true }));
298
298
  await prebuildProductionPageBrowserGraphs(this.appConfig, [
299
299
  ...input.routes.map((route) => ({
@@ -1,3 +1,7 @@
1
+ /**
2
+ * How a module refers to the specifier being resolved.
3
+ */
4
+ export type EcoBuildImportKind = 'import-statement' | 'dynamic-import' | 'require-call' | 'import-rule' | 'url-token' | 'new-url' | 'hot-accept';
1
5
  /**
2
6
  * Arguments passed to a build plugin `onResolve` callback.
3
7
  */
@@ -5,6 +9,8 @@ export type EcoBuildOnResolveArgs = {
5
9
  path: string;
6
10
  importer?: string;
7
11
  namespace?: string;
12
+ /** Absent for an entry point. */
13
+ kind?: EcoBuildImportKind;
8
14
  };
9
15
  /**
10
16
  * Result returned by a build plugin `onResolve` callback.
@@ -894,12 +894,10 @@ export type PageClientPlan = {
894
894
  };
895
895
  export type PageClientBrowserAssets = {
896
896
  processedAssets: ProcessedAsset[];
897
- islandRenderAssetsByFile: Map<string, ProcessedAsset[]>;
898
897
  lazyTriggers: ResolvedLazyTrigger[];
899
898
  };
900
899
  export type PageClientBuildEntry = {
901
900
  dependency: AssetDefinition;
902
- islandFile?: string;
903
901
  };
904
902
  /**
905
903
  * The options for the integration renderer.
@@ -924,7 +922,7 @@ export type IntegrationRendererRenderOptions<C = EcoPagesElement> = RouteRendere
924
922
  export type InternalIntegrationRendererRenderOptions<C = EcoPagesElement> = IntegrationRendererRenderOptions<C> & {
925
923
  sourceDependencyPaths?: readonly string[];
926
924
  pageClientPlan?: PageClientPlan;
927
- islandRenderAssetsByFile?: Map<string, ProcessedAsset[]>;
925
+ preparedGraphComponents?: ReadonlyMap<string, boolean>;
928
926
  };
929
927
  /**
930
928
  * Structured page asset package produced after dependency resolution.
@@ -1035,12 +1033,16 @@ export interface ComponentRenderInput<TIntegrationContext extends BaseIntegratio
1035
1033
  children?: unknown;
1036
1034
  integrationContext?: TIntegrationContext;
1037
1035
  }
1036
+ /**
1037
+ * @remarks
1038
+ * A render carries no assets. Route preparation builds the page package from the
1039
+ * prepared component graph before any component renders.
1040
+ */
1038
1041
  export interface ComponentRenderResult {
1039
1042
  html: string;
1040
1043
  canAttachAttributes: boolean;
1041
1044
  integrationName: string;
1042
1045
  rootAttributes?: Record<string, string>;
1043
- assets?: ProcessedAsset[];
1044
1046
  }
1045
1047
  /**
1046
1048
  * Services available to API handlers.
@@ -1137,27 +1139,19 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
1137
1139
  */
1138
1140
  services: ApiHandlerServices;
1139
1141
  /**
1140
- * Parsed and optionally validated request body.
1142
+ * Request body validated by `schema.body`.
1141
1143
  *
1142
- * - Without schema: Contains the parsed JSON body as `unknown`
1143
- * - With schema: Contains the validated and type-safe body data
1144
+ * - Without `schema.body`: `undefined`
1145
+ * - With `schema.body`: the validated body, typed from the schema
1144
1146
  *
1145
1147
  * For raw access to the request body stream, use `ctx.request.body`.
1146
1148
  *
1147
- * @example Without validation
1148
- * ```typescript
1149
- * app.post('/posts', async (ctx) => {
1150
- * const data = ctx.body; // [unknown] - parsed JSON
1151
- * return ctx.json({ received: data });
1152
- * });
1153
- * ```
1154
- *
1155
1149
  * @example With validation
1156
1150
  * ```typescript
1157
1151
  * import { z } from 'zod';
1158
1152
  *
1159
1153
  * app.post('/posts', async (ctx) => {
1160
- * const { title, author } = ctx.body; // [type-safe]
1154
+ * const { title, author } = ctx.body; // { title: string; author: string }
1161
1155
  * return ctx.json({ title, author });
1162
1156
  * }, {
1163
1157
  * schema: {
@@ -1172,8 +1166,8 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
1172
1166
  /**
1173
1167
  * Parsed and optionally validated query parameters.
1174
1168
  *
1175
- * - Without schema: Contains query params as strings, or arrays when a key is repeated
1176
- * - With schema: Contains the validated and type-safe query data
1169
+ * - Without `schema.query`: query params as strings, or arrays when a key is repeated
1170
+ * - With `schema.query`: the validated query, typed from the schema
1177
1171
  *
1178
1172
  * Repeated query keys are represented as arrays, matching `PageQuery` on page props.
1179
1173
  *
@@ -1211,12 +1205,12 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
1211
1205
  * });
1212
1206
  * ```
1213
1207
  */
1214
- query?: unknown;
1208
+ query: PageQuery;
1215
1209
  /**
1216
- * Parsed and optionally validated request headers.
1210
+ * Request headers validated by `schema.headers`.
1217
1211
  *
1218
- * - Without schema: Contains the parsed headers as a string record
1219
- * - With schema: Contains the validated and type-safe header data
1212
+ * - Without `schema.headers`: `undefined`
1213
+ * - With `schema.headers`: the validated headers, typed from the schema
1220
1214
  *
1221
1215
  * For raw access to headers, use `ctx.request.headers`.
1222
1216
  *
@@ -1278,15 +1272,15 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
1278
1272
  *
1279
1273
  * Page middleware can mutate locals, short-circuit the request, and use the
1280
1274
  * response helpers, but final document rendering stays owned by the page route
1281
- * execution path.
1275
+ * execution path. The query string is not parsed for page middleware; read it from `request.url`.
1282
1276
  */
1283
- export interface FileRouteMiddlewareContext<TRequest extends Request = Request, TServer = any> extends Omit<ApiHandlerContext<TRequest, TServer>, 'render' | 'renderPartial' | 'importServerModule' | 'renderServerModule'> {
1277
+ export interface FileRouteMiddlewareContext<TRequest extends Request = Request, TServer = any> extends Omit<ApiHandlerContext<TRequest, TServer>, 'render' | 'renderPartial' | 'importServerModule' | 'renderServerModule' | 'query'> {
1284
1278
  }
1285
1279
  /**
1286
1280
  * Next function for middleware chain.
1287
1281
  * Call to continue to the next middleware or final handler.
1288
1282
  */
1289
- type MiddlewareNext = () => Promise<Response>;
1283
+ export type MiddlewareNext = () => Promise<Response>;
1290
1284
  /**
1291
1285
  * Middleware function signature.
1292
1286
  * Receives the request context and a next function to continue the chain.
@@ -1342,6 +1336,11 @@ export type FileRouteMiddleware<TRequest extends Request = Request, TServer = an
1342
1336
  * ```
1343
1337
  */
1344
1338
  export type EcoMiddleware<TContext extends ApiHandlerContext<any, any>> = TContext extends ApiHandlerContext<infer TRequest, infer TServer> ? Middleware<TRequest, TServer, TContext> : never;
1339
+ /**
1340
+ * The request methods an `ApiHandler` answers, in the order an endpoint's `Allow` header lists them.
1341
+ */
1342
+ export declare const API_HANDLER_METHODS: readonly ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD", "QUERY"];
1343
+ export type ApiHandlerMethod = (typeof API_HANDLER_METHODS)[number];
1345
1344
  /**
1346
1345
  * Represents an API handler in EcoPages.
1347
1346
  * Defines the path, method, handler function, optional middleware, and validation schemas.
@@ -1403,11 +1402,15 @@ export type EcoMiddleware<TContext extends ApiHandlerContext<any, any>> = TConte
1403
1402
  * ```
1404
1403
  */
1405
1404
  export interface ApiHandler<TPath extends string = string, TRequest extends Request = Request, TServer = any> {
1405
+ /**
1406
+ * The URL pattern. `''` for a handler built without `path`, which an endpoint file exports;
1407
+ * its Template Route gives the URL.
1408
+ */
1406
1409
  path: TPath;
1407
- method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD';
1410
+ method: ApiHandlerMethod;
1408
1411
  handler: (context: ApiHandlerContext<TRequest, TServer>) => Promise<Response> | Response;
1409
1412
  /** Optional middleware chain executed before the handler */
1410
- middleware?: Middleware<TRequest, TServer, any>[];
1413
+ middleware?: MiddlewareList<TRequest, TServer>;
1411
1414
  /** Optional validation schemas for request body, query parameters, and headers */
1412
1415
  schema?: {
1413
1416
  body?: StandardSchema;
@@ -1424,11 +1427,38 @@ export interface ApiHandler<TPath extends string = string, TRequest extends Requ
1424
1427
  export type ErrorHandler<TRequest extends Request = Request, TServer = any> = (error: unknown, context: ApiHandlerContext<TRequest, TServer>) => Promise<Response> | Response;
1425
1428
  /**
1426
1429
  * Options for route handlers.
1430
+ *
1431
+ * @typeParam TMiddleware - The route's middleware; inferred as a tuple so the handler sees what each one adds
1432
+ * @typeParam TSchema - The route's schema; each field it declares types the matching context field
1427
1433
  */
1428
- export interface RouteOptions<TRequest extends Request = Request, TServer = any, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> {
1429
- middleware?: Middleware<TRequest, TServer, TContext>[];
1430
- schema?: RouteSchema;
1434
+ export interface RouteOptions<TRequest extends Request = Request, TServer = any, TSchema extends RouteSchema = RouteSchema, TMiddleware extends MiddlewareList<TRequest, TServer> = MiddlewareList<TRequest, TServer>> {
1435
+ middleware?: TMiddleware;
1436
+ schema?: TSchema;
1431
1437
  }
1438
+ /**
1439
+ * A middleware list, whatever context each middleware declares.
1440
+ *
1441
+ * @remarks
1442
+ * Each element is a method signature, so its context parameter is checked bivariantly: a middleware typed with
1443
+ * the wider context it adds, such as `EcoMiddleware<AuthContext>`, still fits. An inline middleware function in
1444
+ * the list is typed with the base context, also inside a group; type it as `EcoMiddleware` to read what the
1445
+ * group middleware adds. A list holding an unannotated inline function is inferred only after the arguments before it, so a handler
1446
+ * written before the list (`app.get(path, handler, options)`, or `handler` before `middleware` in a define call)
1447
+ * sees none of the list's contexts. Put `middleware` first, or declare the inline function as a `Middleware` constant.
1448
+ */
1449
+ export type MiddlewareList<TRequest extends Request = Request, TServer = any> = readonly {
1450
+ middleware(context: ApiHandlerContext<TRequest, TServer>, next: MiddlewareNext): Promise<Response> | Response;
1451
+ }['middleware'][];
1452
+ /**
1453
+ * The context a list of middleware adds: the intersection of the context each one declares.
1454
+ *
1455
+ * @remarks
1456
+ * Inferring one parameter from the union of the middleware types, a contravariant position, yields the
1457
+ * intersection of their contexts. An empty list adds nothing.
1458
+ */
1459
+ export type MiddlewareContext<TMiddleware extends readonly unknown[]> = [TMiddleware[number]] extends [
1460
+ (context: infer TAdded, next: never) => unknown
1461
+ ] ? [TAdded] extends [never] ? unknown : TAdded : unknown;
1432
1462
  export interface RouteSchema {
1433
1463
  body?: StandardSchema;
1434
1464
  query?: StandardSchema;
@@ -1436,51 +1466,49 @@ export interface RouteSchema {
1436
1466
  params?: StandardSchema;
1437
1467
  }
1438
1468
  /**
1439
- * Helper type to extract inferred types from a schema, with fallback to unknown.
1469
+ * The context a handler receives: the base or middleware context, with each field the schema declares
1470
+ * replaced by that schema's output.
1471
+ *
1472
+ * @remarks
1473
+ * A field the schema omits keeps the type it has on `TContext`, so a schema with only `body` still
1474
+ * gives `params` as {@link PageParams}. `params` is typed only by `TSchema['params']`; the route's
1475
+ * path string never narrows it.
1440
1476
  */
1441
- type InferSchemaOutput<T> = T extends StandardSchema ? InferOutput<T> : unknown;
1477
+ export type RouteHandlerContext<TSchema extends RouteSchema, TContext extends ApiHandlerContext<any, any>> = Omit<TContext, RouteSchemaField> & {
1478
+ [K in RouteSchemaField]: TSchema[K] extends StandardSchema ? InferOutput<TSchema[K]> : TContext[K];
1479
+ };
1442
1480
  /**
1443
- * Context type that combines schema-typed fields with an extended base context.
1444
- * Used by RouteGroupBuilder to merge schema validation types with middleware-extended context.
1445
- * Note: Path parameter typing (e.g., :id -> params.id) comes from the TContext.request type.
1481
+ * @remarks
1482
+ * Mapping over this alias instead of `keyof RouteSchema` keeps the mapped type from copying the optional
1483
+ * modifiers of {@link RouteSchema}, so each field is required and an optional schema still types its
1484
+ * output with `undefined`.
1446
1485
  */
1447
- export type TypedGroupHandlerContext<TSchema extends RouteSchema, TContext extends ApiHandlerContext<any, any>> = Omit<TContext, 'body' | 'query' | 'headers' | 'params'> & {
1448
- body: InferSchemaOutput<TSchema['body']>;
1449
- query: InferSchemaOutput<TSchema['query']>;
1450
- headers: InferSchemaOutput<TSchema['headers']>;
1451
- params: InferSchemaOutput<TSchema['params']>;
1452
- };
1486
+ type RouteSchemaField = keyof RouteSchema;
1453
1487
  /**
1454
- * Builder interface for defining routes within a group.
1488
+ * Registers an inline route: the handler is typed from the route's `schema` and from the context every
1489
+ * one of its `middleware` adds on top of `TContext`.
1490
+ *
1491
+ * @typeParam TReturn - What the call returns, for chaining
1492
+ * @typeParam TContext - The context the route starts from: the base context, or the group's
1493
+ *
1494
+ * @remarks
1495
+ * `TRouteContext` has no inference site; passing it explicitly types a context that the route's
1496
+ * middleware list does not declare.
1497
+ */
1498
+ export type RouteMethod<TReturn, TRequest extends Request = Request, TServer = any, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = <TSchema extends RouteSchema = RouteSchema, TRouteContext extends TContext = TContext, const TMiddleware extends MiddlewareList<TRequest, TServer> = MiddlewareList<TRequest, TServer>>(path: string, handler: (context: RouteHandlerContext<TSchema, TRouteContext & MiddlewareContext<TMiddleware>>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TSchema, TMiddleware>) => TReturn;
1499
+ /**
1500
+ * Builder for defining routes within a group, one method per HTTP method.
1455
1501
  * Provides chainable methods for registering routes with shared prefix and middleware.
1456
1502
  *
1457
1503
  * @typeParam TRequest - The request type
1458
1504
  * @typeParam TServer - The server type
1459
1505
  * @typeParam TContext - Extended context type from group middleware
1506
+ *
1507
+ * @remarks `query` registers the HTTP QUERY method, not a handler for `ctx.query`.
1460
1508
  */
1461
- export interface RouteGroupBuilder<TRequest extends Request = Request, TServer = any, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> {
1462
- get<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1463
- schema?: TSchema;
1464
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1465
- post<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1466
- schema?: TSchema;
1467
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1468
- put<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1469
- schema?: TSchema;
1470
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1471
- delete<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1472
- schema?: TSchema;
1473
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1474
- patch<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1475
- schema?: TSchema;
1476
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1477
- options<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1478
- schema?: TSchema;
1479
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1480
- head<P extends string, TSchema extends RouteSchema = RouteSchema>(path: P, handler: (context: TypedGroupHandlerContext<TSchema, TContext>) => Promise<Response> | Response, options?: RouteOptions<TRequest, TServer, TContext> & {
1481
- schema?: TSchema;
1482
- }): RouteGroupBuilder<TRequest, TServer, TContext>;
1483
- }
1509
+ export type RouteGroupBuilder<TRequest extends Request = Request, TServer = any, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = {
1510
+ [M in ApiHandler['method'] as Lowercase<M>]: RouteMethod<RouteGroupBuilder<TRequest, TServer, TContext>, TRequest, TServer, TContext>;
1511
+ };
1484
1512
  /**
1485
1513
  * A function that dynamically imports a view module.
1486
1514
  * Used by `app.static()` and the HTML error-page helpers (`app.notFound()`,
@@ -1 +1,4 @@
1
- export {};
1
+ /**
2
+ * The request methods an `ApiHandler` answers, in the order an endpoint's `Allow` header lists them.
3
+ */
4
+ export const API_HANDLER_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD', 'QUERY'];
@@ -72,7 +72,7 @@ export interface ComponentOptions<P, E = EcoPagesElement> {
72
72
  dependencies?: EcoComponentDependencies;
73
73
  render: (props: P) => E | Promise<E>;
74
74
  }
75
- export type HtmlOptions<E = EcoPagesElement> = ComponentOptions<HtmlTemplateProps, E>;
75
+ export type HtmlOptions<E = EcoPagesElement> = ComponentOptions<HtmlTemplateProps<E>, E>;
76
76
  export type LayoutOptions<E = EcoPagesElement> = ComponentOptions<LayoutProps<E>, E>;
77
77
  /**
78
78
  * Base options shared by all page variants
@@ -1,3 +1,3 @@
1
- export type { ApiHandler, ApiHandlerContext, EcoComponent, EcoComponentConfig, EcoComponentDependencies, DependencyAttributes, EcoChildren, EcoFunctionComponent, EcoPageComponent, EcoPageFile, EcoPagesAppConfig, EcoPagesElement, EcoPageLayoutEntry, EcoPageLayoutSpec, EcoPageLayouts, EcoHtmlComponent, EcoLayoutComponent, EcoMiddleware, ErrorHandler, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesSocket, EcopagesWebSocketHandler, FileRouteMiddleware, FileRouteMiddlewareContext, FileOwnedDependencyContribution, GetPageDependencies, GetPageDependenciesContext, GetMetadata, GetMetadataContext, GetStaticPaths, GetStaticProps, HtmlTemplateProps, LayoutProps, LayoutPropsContext, Middleware, OutgoingWebSocketMessage, IncomingWebSocketMessage, PageHeadProps, PageMetadataProps, PageParams, PageQuery, PageDependenciesInput, PageDependenciesResult, PageProps, PagePropsFor, PageRequires, PageRobotsMetadata, RequestLocals, RequestPageContext, RenderContext, RenderOptions, RouteGroupBuilder, RouteOptions, RouteSchema, SitemapConfig, StandardSchema, StandardSchemaFailureResult, StandardSchemaIssue, StandardSchemaResult, StandardSchemaSuccessResult, StandardSchemaV1, StaticPageContext, StaticPath, TypedGroupHandlerContext, WebSocketCloseInfo, WithLocals, } from './contracts.js';
1
+ export type { ApiHandler, ApiHandlerContext, EcoComponent, EcoComponentConfig, EcoComponentDependencies, DependencyAttributes, EcoChildren, EcoFunctionComponent, EcoPageComponent, EcoPageFile, EcoPagesAppConfig, EcoPagesElement, EcoPageLayoutEntry, EcoPageLayoutSpec, EcoPageLayouts, EcoHtmlComponent, EcoLayoutComponent, EcoMiddleware, ErrorHandler, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesSocket, EcopagesWebSocketHandler, FileRouteMiddleware, FileRouteMiddlewareContext, FileOwnedDependencyContribution, GetPageDependencies, GetPageDependenciesContext, GetMetadata, GetMetadataContext, GetStaticPaths, GetStaticProps, HtmlTemplateProps, LayoutProps, LayoutPropsContext, Middleware, MiddlewareList, MiddlewareNext, OutgoingWebSocketMessage, IncomingWebSocketMessage, PageHeadProps, PageMetadataProps, PageParams, PageQuery, PageDependenciesInput, PageDependenciesResult, PageProps, PagePropsFor, PageRequires, PageRobotsMetadata, RequestLocals, RequestPageContext, RenderContext, RenderOptions, RouteGroupBuilder, RouteHandlerContext, RouteMethod, RouteOptions, RouteSchema, SitemapConfig, StandardSchema, StandardSchemaFailureResult, StandardSchemaIssue, StandardSchemaResult, StandardSchemaSuccessResult, StandardSchemaV1, StaticPageContext, StaticPath, WebSocketCloseInfo, WithLocals, } from './contracts.js';
2
2
  export type { CacheConfig, CacheStrategy } from './cache-types.js';
3
3
  export type { CallableComponentOf, ChildrenOf, ComponentOptions, Eco, EcoEmbedProps, EmbedPropsOf, HtmlOptions, LayoutOptions, LazyTrigger, PageOptions, PageOptionsBase, PagePropsForWithLocals, PropsOf, ResultOf, } from './eco-api-types.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Suffixes that mark a file under the pages directory as an endpoint rather than a Page: `.api.`
3
+ * followed by a script extension the server-module loader compiles.
4
+ *
5
+ * @remarks
6
+ * Never a template extension: an endpoint has no Integration owner, Layout or Cache Strategy, so
7
+ * config assembly rejects an Integration whose extensions end in one of these.
8
+ */
9
+ export declare const ENDPOINT_FILE_EXTENSIONS: readonly string[];
10
+ /** Returns the endpoint marker `file` ends with, or `undefined` for any other file. */
11
+ export declare function findEndpointFileExtension(file: string): string | undefined;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Suffixes that mark a file under the pages directory as an endpoint rather than a Page: `.api.`
3
+ * followed by a script extension the server-module loader compiles.
4
+ *
5
+ * @remarks
6
+ * Never a template extension: an endpoint has no Integration owner, Layout or Cache Strategy, so
7
+ * config assembly rejects an Integration whose extensions end in one of these.
8
+ */
9
+ export const ENDPOINT_FILE_EXTENSIONS = ['.api.ts', '.api.tsx', '.api.js', '.api.jsx'];
10
+ /** Returns the endpoint marker `file` ends with, or `undefined` for any other file. */
11
+ export function findEndpointFileExtension(file) {
12
+ return ENDPOINT_FILE_EXTENSIONS.find((extension) => file.endsWith(extension));
13
+ }
@@ -1,12 +0,0 @@
1
- import { type ProcessedAsset } from '../../../assets/asset-processing-service/index.js';
2
- import type { PageBrowserGraphResult, PagePackageResult } from '../../../types/contracts.js';
3
- /**
4
- * Merges a page browser graph into an existing page package (or processed dependencies).
5
- *
6
- * Deduplicates entry/chunk assets against the existing package and rebuilds the
7
- * package so downstream HTML finalization sees one canonical graph.
8
- */
9
- export declare function mergePageBrowserGraph(currentPagePackage: PagePackageResult | undefined, processedDependencies: ProcessedAsset[], pageBrowserGraph: PageBrowserGraphResult): {
10
- pagePackage: PagePackageResult;
11
- mergedGraph: PageBrowserGraphResult;
12
- };
@@ -1,32 +0,0 @@
1
- import { createPagePackage } from '../../../assets/asset-processing-service/index.js';
2
- import { buildProcessedAssetDedupeKey, dedupeProcessedAssets } from '../../../assets/processed-asset-dedupe.js';
3
- /**
4
- * Merges a page browser graph into an existing page package (or processed dependencies).
5
- *
6
- * Deduplicates entry/chunk assets against the existing package and rebuilds the
7
- * package so downstream HTML finalization sees one canonical graph.
8
- */
9
- export function mergePageBrowserGraph(currentPagePackage, processedDependencies, pageBrowserGraph) {
10
- const mergedGraph = currentPagePackage?.pageBrowserGraph
11
- ? {
12
- entryAssets: dedupeProcessedAssets([
13
- ...currentPagePackage.pageBrowserGraph.entryAssets,
14
- ...pageBrowserGraph.entryAssets,
15
- ]),
16
- chunkAssets: dedupeProcessedAssets([
17
- ...currentPagePackage.pageBrowserGraph.chunkAssets,
18
- ...pageBrowserGraph.chunkAssets,
19
- ]),
20
- }
21
- : pageBrowserGraph;
22
- const pageBrowserGraphAssetKeys = new Set([...mergedGraph.entryAssets, ...mergedGraph.chunkAssets].map((asset) => buildProcessedAssetDedupeKey(asset)));
23
- const baseAssets = currentPagePackage
24
- ? currentPagePackage.assets.filter((asset) => !pageBrowserGraphAssetKeys.has(buildProcessedAssetDedupeKey(asset)))
25
- : processedDependencies;
26
- return {
27
- pagePackage: createPagePackage(dedupeProcessedAssets(baseAssets), {
28
- pageBrowserGraph: mergedGraph,
29
- }),
30
- mergedGraph,
31
- };
32
- }