@ecopages/core 0.3.2 → 0.4.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.
- package/README.md +17 -1
- package/package.json +3 -3
- package/src/adapters/node/create-app.d.ts +19 -19
- package/src/adapters/node/create-app.js +26 -40
- package/src/adapters/node/dev-session.d.ts +3 -1
- package/src/adapters/node/dev-session.js +4 -1
- package/src/adapters/node/server-adapter.js +5 -1
- package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
- package/src/adapters/shared/http/define-api-handler.js +15 -1
- package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
- package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
- package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
- package/src/adapters/shared/runtime/server-request-pipeline.js +45 -12
- package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
- package/src/adapters/shared/runtime/server-route-handler.js +12 -6
- package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
- package/src/adapters/shared/runtime/server-static-builder.js +13 -2
- package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
- package/src/build/server-bundle-deploy-manifest.js +1 -1
- package/src/config/assembly/finalize-config.js +5 -0
- package/src/index.d.ts +1 -1
- package/src/index.js +1 -1
- package/src/router/server/route-registry.d.ts +18 -9
- package/src/router/server/route-registry.js +49 -30
- package/src/router/server/segment-path-matcher.d.ts +8 -0
- package/src/router/server/segment-path-matcher.js +15 -0
- package/src/static-site-generator/static-site-generator.js +1 -1
- package/src/types/contracts.d.ts +87 -61
- package/src/types/contracts.js +4 -1
- package/src/types/public-types.d.ts +1 -1
- package/src/utils/endpoint-file-extensions.d.ts +11 -0
- package/src/utils/endpoint-file-extensions.js +13 -0
|
@@ -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
|
|
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
|
-
*
|
|
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
|
-
*
|
|
78
|
-
*
|
|
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
|
-
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
const sharedLength = Math.min(
|
|
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(
|
|
87
|
-
const rightIsDynamic = this.isDynamicRouteSegment(
|
|
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
|
|
93
|
-
return
|
|
97
|
+
const lengthDifference = rightSegments.length - leftSegments.length;
|
|
98
|
+
return lengthDifference !== 0 ? lengthDifference : left.pathname.localeCompare(right.pathname);
|
|
94
99
|
}
|
|
95
|
-
|
|
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,7 +107,7 @@ export class RouteRegistry {
|
|
|
102
107
|
}
|
|
103
108
|
async listStaticPathExpansions(input) {
|
|
104
109
|
const expansions = [];
|
|
105
|
-
for (const route of this.
|
|
110
|
+
for (const route of this.pageRoutes) {
|
|
106
111
|
if (route.kind === 'exact') {
|
|
107
112
|
continue;
|
|
108
113
|
}
|
|
@@ -132,7 +137,7 @@ export class RouteRegistry {
|
|
|
132
137
|
async listStaticGenerationRoutes(input) {
|
|
133
138
|
const staticPathExpansions = await this.listStaticPathExpansions(input);
|
|
134
139
|
return [
|
|
135
|
-
...this.
|
|
140
|
+
...this.pageRoutes
|
|
136
141
|
.filter((route) => route.kind === 'exact')
|
|
137
142
|
.map((route) => ({
|
|
138
143
|
requestUrl: `${input.runtimeOrigin}${route.pathname}`,
|
|
@@ -152,29 +157,41 @@ export class RouteRegistry {
|
|
|
152
157
|
if (!fileSystem.exists(this.pagesDir)) {
|
|
153
158
|
return [];
|
|
154
159
|
}
|
|
155
|
-
const scannedFiles = await fileSystem.glob(this.templatesExt.map((ext) => `**/*${ext}`), {
|
|
160
|
+
const scannedFiles = await fileSystem.glob([...this.templatesExt, ...ENDPOINT_FILE_EXTENSIONS].map((ext) => `**/*${ext}`), {
|
|
156
161
|
cwd: this.pagesDir,
|
|
157
162
|
});
|
|
158
163
|
const templateRoutes = [];
|
|
159
|
-
const
|
|
164
|
+
const routesByKey = new Map();
|
|
160
165
|
for await (const file of scannedFiles) {
|
|
161
166
|
if (file.includes('.ecopages-node.')) {
|
|
162
167
|
continue;
|
|
163
168
|
}
|
|
164
|
-
const
|
|
169
|
+
const endpointExtension = findEndpointFileExtension(file);
|
|
170
|
+
const role = endpointExtension ? 'endpoint' : 'page';
|
|
171
|
+
const routePathname = this.getRoutePath(file, endpointExtension);
|
|
165
172
|
const filePath = path.join(this.pagesDir, file);
|
|
166
173
|
const kind = this.classifyRouteKind(file);
|
|
167
|
-
const
|
|
168
|
-
|
|
174
|
+
const routeKey = segmentPathPatternKey(routePathname, 'filesystem');
|
|
175
|
+
const duplicate = routesByKey.get(routeKey);
|
|
176
|
+
if (duplicate?.filePath === filePath) {
|
|
169
177
|
continue;
|
|
170
178
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
179
|
+
if (duplicate) {
|
|
180
|
+
const route = duplicate.pathname === routePathname
|
|
181
|
+
? `the route "${routePathname}"`
|
|
182
|
+
: `the same route, "${duplicate.pathname}" and "${routePathname}"`;
|
|
183
|
+
invariant(false, `${duplicate.filePath} and ${filePath} both define ${route}. Keep one of them.`);
|
|
184
|
+
}
|
|
185
|
+
routesByKey.set(routeKey, { pathname: routePathname, filePath });
|
|
186
|
+
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.`);
|
|
187
|
+
const owner = role === 'page' && kind !== 'exact'
|
|
188
|
+
? findIntegrationForFile(this.appConfig.integrations, filePath)
|
|
189
|
+
: undefined;
|
|
174
190
|
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
191
|
templateRoutes.push({
|
|
176
192
|
pathname: routePathname,
|
|
177
193
|
kind,
|
|
194
|
+
role,
|
|
178
195
|
filePath,
|
|
179
196
|
paramNames: this.getParamNames(routePathname),
|
|
180
197
|
});
|
|
@@ -184,8 +201,8 @@ export class RouteRegistry {
|
|
|
184
201
|
if (priorityDifference !== 0) {
|
|
185
202
|
return priorityDifference;
|
|
186
203
|
}
|
|
187
|
-
if (left.kind
|
|
188
|
-
return this.
|
|
204
|
+
if (left.kind !== 'exact') {
|
|
205
|
+
return this.compareSpecificity(left, right);
|
|
189
206
|
}
|
|
190
207
|
if (left.pathname === '/') {
|
|
191
208
|
return -1;
|
|
@@ -199,10 +216,12 @@ export class RouteRegistry {
|
|
|
199
216
|
/**
|
|
200
217
|
* @remarks
|
|
201
218
|
* 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.
|
|
219
|
+
* `.kita` part when `.tsx` is also registered, and `my.html-tips.html` keeps its name. An
|
|
220
|
+
* endpoint strips its whole marker, so `users.api.tsx` is `/users` even when `.tsx` is a
|
|
221
|
+
* template extension.
|
|
203
222
|
*/
|
|
204
|
-
getRoutePath(file) {
|
|
205
|
-
const extension = findLongestExtension(this.templatesExt, file) ?? '';
|
|
223
|
+
getRoutePath(file, endpointExtension) {
|
|
224
|
+
const extension = endpointExtension ?? findLongestExtension(this.templatesExt, file) ?? '';
|
|
206
225
|
const cleanedRoute = file.slice(0, file.length - extension.length).replace(/\/?index$/, '');
|
|
207
226
|
return normalizePathname(`/${cleanedRoute}`);
|
|
208
227
|
}
|
|
@@ -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') {
|
|
@@ -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) => ({
|
package/src/types/contracts.d.ts
CHANGED
|
@@ -1137,27 +1137,19 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
|
|
|
1137
1137
|
*/
|
|
1138
1138
|
services: ApiHandlerServices;
|
|
1139
1139
|
/**
|
|
1140
|
-
*
|
|
1140
|
+
* Request body validated by `schema.body`.
|
|
1141
1141
|
*
|
|
1142
|
-
* - Without schema
|
|
1143
|
-
* - With schema
|
|
1142
|
+
* - Without `schema.body`: `undefined`
|
|
1143
|
+
* - With `schema.body`: the validated body, typed from the schema
|
|
1144
1144
|
*
|
|
1145
1145
|
* For raw access to the request body stream, use `ctx.request.body`.
|
|
1146
1146
|
*
|
|
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
1147
|
* @example With validation
|
|
1156
1148
|
* ```typescript
|
|
1157
1149
|
* import { z } from 'zod';
|
|
1158
1150
|
*
|
|
1159
1151
|
* app.post('/posts', async (ctx) => {
|
|
1160
|
-
* const { title, author } = ctx.body; //
|
|
1152
|
+
* const { title, author } = ctx.body; // { title: string; author: string }
|
|
1161
1153
|
* return ctx.json({ title, author });
|
|
1162
1154
|
* }, {
|
|
1163
1155
|
* schema: {
|
|
@@ -1172,8 +1164,8 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
|
|
|
1172
1164
|
/**
|
|
1173
1165
|
* Parsed and optionally validated query parameters.
|
|
1174
1166
|
*
|
|
1175
|
-
* - Without schema
|
|
1176
|
-
* - With schema
|
|
1167
|
+
* - Without `schema.query`: query params as strings, or arrays when a key is repeated
|
|
1168
|
+
* - With `schema.query`: the validated query, typed from the schema
|
|
1177
1169
|
*
|
|
1178
1170
|
* Repeated query keys are represented as arrays, matching `PageQuery` on page props.
|
|
1179
1171
|
*
|
|
@@ -1211,12 +1203,12 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
|
|
|
1211
1203
|
* });
|
|
1212
1204
|
* ```
|
|
1213
1205
|
*/
|
|
1214
|
-
query
|
|
1206
|
+
query: PageQuery;
|
|
1215
1207
|
/**
|
|
1216
|
-
*
|
|
1208
|
+
* Request headers validated by `schema.headers`.
|
|
1217
1209
|
*
|
|
1218
|
-
* - Without schema
|
|
1219
|
-
* - With schema
|
|
1210
|
+
* - Without `schema.headers`: `undefined`
|
|
1211
|
+
* - With `schema.headers`: the validated headers, typed from the schema
|
|
1220
1212
|
*
|
|
1221
1213
|
* For raw access to headers, use `ctx.request.headers`.
|
|
1222
1214
|
*
|
|
@@ -1278,15 +1270,15 @@ export interface ApiHandlerContext<TRequest extends Request = Request, TServer =
|
|
|
1278
1270
|
*
|
|
1279
1271
|
* Page middleware can mutate locals, short-circuit the request, and use the
|
|
1280
1272
|
* response helpers, but final document rendering stays owned by the page route
|
|
1281
|
-
* execution path.
|
|
1273
|
+
* execution path. The query string is not parsed for page middleware; read it from `request.url`.
|
|
1282
1274
|
*/
|
|
1283
|
-
export interface FileRouteMiddlewareContext<TRequest extends Request = Request, TServer = any> extends Omit<ApiHandlerContext<TRequest, TServer>, 'render' | 'renderPartial' | 'importServerModule' | 'renderServerModule'> {
|
|
1275
|
+
export interface FileRouteMiddlewareContext<TRequest extends Request = Request, TServer = any> extends Omit<ApiHandlerContext<TRequest, TServer>, 'render' | 'renderPartial' | 'importServerModule' | 'renderServerModule' | 'query'> {
|
|
1284
1276
|
}
|
|
1285
1277
|
/**
|
|
1286
1278
|
* Next function for middleware chain.
|
|
1287
1279
|
* Call to continue to the next middleware or final handler.
|
|
1288
1280
|
*/
|
|
1289
|
-
type MiddlewareNext = () => Promise<Response>;
|
|
1281
|
+
export type MiddlewareNext = () => Promise<Response>;
|
|
1290
1282
|
/**
|
|
1291
1283
|
* Middleware function signature.
|
|
1292
1284
|
* Receives the request context and a next function to continue the chain.
|
|
@@ -1342,6 +1334,11 @@ export type FileRouteMiddleware<TRequest extends Request = Request, TServer = an
|
|
|
1342
1334
|
* ```
|
|
1343
1335
|
*/
|
|
1344
1336
|
export type EcoMiddleware<TContext extends ApiHandlerContext<any, any>> = TContext extends ApiHandlerContext<infer TRequest, infer TServer> ? Middleware<TRequest, TServer, TContext> : never;
|
|
1337
|
+
/**
|
|
1338
|
+
* The request methods an `ApiHandler` answers, in the order an endpoint's `Allow` header lists them.
|
|
1339
|
+
*/
|
|
1340
|
+
export declare const API_HANDLER_METHODS: readonly ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD", "QUERY"];
|
|
1341
|
+
export type ApiHandlerMethod = (typeof API_HANDLER_METHODS)[number];
|
|
1345
1342
|
/**
|
|
1346
1343
|
* Represents an API handler in EcoPages.
|
|
1347
1344
|
* Defines the path, method, handler function, optional middleware, and validation schemas.
|
|
@@ -1403,11 +1400,15 @@ export type EcoMiddleware<TContext extends ApiHandlerContext<any, any>> = TConte
|
|
|
1403
1400
|
* ```
|
|
1404
1401
|
*/
|
|
1405
1402
|
export interface ApiHandler<TPath extends string = string, TRequest extends Request = Request, TServer = any> {
|
|
1403
|
+
/**
|
|
1404
|
+
* The URL pattern. `''` for a handler built without `path`, which an endpoint file exports;
|
|
1405
|
+
* its Template Route gives the URL.
|
|
1406
|
+
*/
|
|
1406
1407
|
path: TPath;
|
|
1407
|
-
method:
|
|
1408
|
+
method: ApiHandlerMethod;
|
|
1408
1409
|
handler: (context: ApiHandlerContext<TRequest, TServer>) => Promise<Response> | Response;
|
|
1409
1410
|
/** Optional middleware chain executed before the handler */
|
|
1410
|
-
middleware?:
|
|
1411
|
+
middleware?: MiddlewareList<TRequest, TServer>;
|
|
1411
1412
|
/** Optional validation schemas for request body, query parameters, and headers */
|
|
1412
1413
|
schema?: {
|
|
1413
1414
|
body?: StandardSchema;
|
|
@@ -1424,11 +1425,38 @@ export interface ApiHandler<TPath extends string = string, TRequest extends Requ
|
|
|
1424
1425
|
export type ErrorHandler<TRequest extends Request = Request, TServer = any> = (error: unknown, context: ApiHandlerContext<TRequest, TServer>) => Promise<Response> | Response;
|
|
1425
1426
|
/**
|
|
1426
1427
|
* Options for route handlers.
|
|
1428
|
+
*
|
|
1429
|
+
* @typeParam TMiddleware - The route's middleware; inferred as a tuple so the handler sees what each one adds
|
|
1430
|
+
* @typeParam TSchema - The route's schema; each field it declares types the matching context field
|
|
1427
1431
|
*/
|
|
1428
|
-
export interface RouteOptions<TRequest extends Request = Request, TServer = any,
|
|
1429
|
-
middleware?:
|
|
1430
|
-
schema?:
|
|
1432
|
+
export interface RouteOptions<TRequest extends Request = Request, TServer = any, TSchema extends RouteSchema = RouteSchema, TMiddleware extends MiddlewareList<TRequest, TServer> = MiddlewareList<TRequest, TServer>> {
|
|
1433
|
+
middleware?: TMiddleware;
|
|
1434
|
+
schema?: TSchema;
|
|
1431
1435
|
}
|
|
1436
|
+
/**
|
|
1437
|
+
* A middleware list, whatever context each middleware declares.
|
|
1438
|
+
*
|
|
1439
|
+
* @remarks
|
|
1440
|
+
* Each element is a method signature, so its context parameter is checked bivariantly: a middleware typed with
|
|
1441
|
+
* the wider context it adds, such as `EcoMiddleware<AuthContext>`, still fits. An inline middleware function in
|
|
1442
|
+
* the list is typed with the base context, also inside a group; type it as `EcoMiddleware` to read what the
|
|
1443
|
+
* group middleware adds. A list holding an unannotated inline function is inferred only after the arguments before it, so a handler
|
|
1444
|
+
* written before the list (`app.get(path, handler, options)`, or `handler` before `middleware` in a define call)
|
|
1445
|
+
* sees none of the list's contexts. Put `middleware` first, or declare the inline function as a `Middleware` constant.
|
|
1446
|
+
*/
|
|
1447
|
+
export type MiddlewareList<TRequest extends Request = Request, TServer = any> = readonly {
|
|
1448
|
+
middleware(context: ApiHandlerContext<TRequest, TServer>, next: MiddlewareNext): Promise<Response> | Response;
|
|
1449
|
+
}['middleware'][];
|
|
1450
|
+
/**
|
|
1451
|
+
* The context a list of middleware adds: the intersection of the context each one declares.
|
|
1452
|
+
*
|
|
1453
|
+
* @remarks
|
|
1454
|
+
* Inferring one parameter from the union of the middleware types, a contravariant position, yields the
|
|
1455
|
+
* intersection of their contexts. An empty list adds nothing.
|
|
1456
|
+
*/
|
|
1457
|
+
export type MiddlewareContext<TMiddleware extends readonly unknown[]> = [TMiddleware[number]] extends [
|
|
1458
|
+
(context: infer TAdded, next: never) => unknown
|
|
1459
|
+
] ? [TAdded] extends [never] ? unknown : TAdded : unknown;
|
|
1432
1460
|
export interface RouteSchema {
|
|
1433
1461
|
body?: StandardSchema;
|
|
1434
1462
|
query?: StandardSchema;
|
|
@@ -1436,51 +1464,49 @@ export interface RouteSchema {
|
|
|
1436
1464
|
params?: StandardSchema;
|
|
1437
1465
|
}
|
|
1438
1466
|
/**
|
|
1439
|
-
*
|
|
1467
|
+
* The context a handler receives: the base or middleware context, with each field the schema declares
|
|
1468
|
+
* replaced by that schema's output.
|
|
1469
|
+
*
|
|
1470
|
+
* @remarks
|
|
1471
|
+
* A field the schema omits keeps the type it has on `TContext`, so a schema with only `body` still
|
|
1472
|
+
* gives `params` as {@link PageParams}. `params` is typed only by `TSchema['params']`; the route's
|
|
1473
|
+
* path string never narrows it.
|
|
1440
1474
|
*/
|
|
1441
|
-
type
|
|
1475
|
+
export type RouteHandlerContext<TSchema extends RouteSchema, TContext extends ApiHandlerContext<any, any>> = Omit<TContext, RouteSchemaField> & {
|
|
1476
|
+
[K in RouteSchemaField]: TSchema[K] extends StandardSchema ? InferOutput<TSchema[K]> : TContext[K];
|
|
1477
|
+
};
|
|
1442
1478
|
/**
|
|
1443
|
-
*
|
|
1444
|
-
*
|
|
1445
|
-
*
|
|
1479
|
+
* @remarks
|
|
1480
|
+
* Mapping over this alias instead of `keyof RouteSchema` keeps the mapped type from copying the optional
|
|
1481
|
+
* modifiers of {@link RouteSchema}, so each field is required and an optional schema still types its
|
|
1482
|
+
* output with `undefined`.
|
|
1446
1483
|
*/
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1484
|
+
type RouteSchemaField = keyof RouteSchema;
|
|
1485
|
+
/**
|
|
1486
|
+
* Registers an inline route: the handler is typed from the route's `schema` and from the context every
|
|
1487
|
+
* one of its `middleware` adds on top of `TContext`.
|
|
1488
|
+
*
|
|
1489
|
+
* @typeParam TReturn - What the call returns, for chaining
|
|
1490
|
+
* @typeParam TContext - The context the route starts from: the base context, or the group's
|
|
1491
|
+
*
|
|
1492
|
+
* @remarks
|
|
1493
|
+
* `TRouteContext` has no inference site; passing it explicitly types a context that the route's
|
|
1494
|
+
* middleware list does not declare.
|
|
1495
|
+
*/
|
|
1496
|
+
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;
|
|
1453
1497
|
/**
|
|
1454
|
-
* Builder
|
|
1498
|
+
* Builder for defining routes within a group, one method per HTTP method.
|
|
1455
1499
|
* Provides chainable methods for registering routes with shared prefix and middleware.
|
|
1456
1500
|
*
|
|
1457
1501
|
* @typeParam TRequest - The request type
|
|
1458
1502
|
* @typeParam TServer - The server type
|
|
1459
1503
|
* @typeParam TContext - Extended context type from group middleware
|
|
1504
|
+
*
|
|
1505
|
+
* @remarks `query` registers the HTTP QUERY method, not a handler for `ctx.query`.
|
|
1460
1506
|
*/
|
|
1461
|
-
export
|
|
1462
|
-
|
|
1463
|
-
|
|
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
|
-
}
|
|
1507
|
+
export type RouteGroupBuilder<TRequest extends Request = Request, TServer = any, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = {
|
|
1508
|
+
[M in ApiHandler['method'] as Lowercase<M>]: RouteMethod<RouteGroupBuilder<TRequest, TServer, TContext>, TRequest, TServer, TContext>;
|
|
1509
|
+
};
|
|
1484
1510
|
/**
|
|
1485
1511
|
* A function that dynamically imports a view module.
|
|
1486
1512
|
* Used by `app.static()` and the HTML error-page helpers (`app.notFound()`,
|
package/src/types/contracts.js
CHANGED
|
@@ -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,
|
|
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
|
+
}
|