@ecopages/core 0.3.1 → 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.
Files changed (67) hide show
  1. package/README.md +17 -1
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +31 -20
  4. package/src/adapters/node/create-app.js +44 -43
  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/runtime-host.d.ts +5 -0
  8. package/src/adapters/node/runtime-host.js +8 -1
  9. package/src/adapters/node/server-adapter.js +5 -1
  10. package/src/adapters/shared/hmr/hmr-manager.d.ts +12 -2
  11. package/src/adapters/shared/hmr/hmr-manager.js +20 -16
  12. package/src/adapters/shared/http/define-api-handler.d.ts +41 -26
  13. package/src/adapters/shared/http/define-api-handler.js +15 -1
  14. package/src/adapters/shared/http/endpoint-route-handler.d.ts +46 -0
  15. package/src/adapters/shared/http/endpoint-route-handler.js +96 -0
  16. package/src/adapters/shared/runtime/bind-runtime-server.js +3 -1
  17. package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
  18. package/src/adapters/shared/runtime/port-manager.d.ts +6 -0
  19. package/src/adapters/shared/runtime/port-manager.js +16 -2
  20. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +20 -3
  21. package/src/adapters/shared/runtime/server-request-pipeline.js +45 -12
  22. package/src/adapters/shared/runtime/server-route-handler.d.ts +8 -3
  23. package/src/adapters/shared/runtime/server-route-handler.js +12 -6
  24. package/src/adapters/shared/runtime/server-static-builder.d.ts +14 -1
  25. package/src/adapters/shared/runtime/server-static-builder.js +13 -2
  26. package/src/assets/app-browser-client-build.js +1 -2
  27. package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
  28. package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
  29. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
  30. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
  31. package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
  32. package/src/assets/browser-asset-output.d.ts +19 -0
  33. package/src/assets/browser-asset-output.js +30 -0
  34. package/src/assets/hashed-browser-asset.d.ts +8 -6
  35. package/src/assets/hashed-browser-asset.js +8 -6
  36. package/src/build/build-graph.js +2 -2
  37. package/src/build/preserve-import-meta-transform.js +2 -2
  38. package/src/build/rolldown/app-package-declarations.js +3 -3
  39. package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
  40. package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
  41. package/src/build/server-bundle-deploy-manifest.d.ts +1 -1
  42. package/src/build/server-bundle-deploy-manifest.js +1 -1
  43. package/src/build/server-bundle-publication.js +4 -5
  44. package/src/config/assembly/finalize-config.js +5 -0
  45. package/src/config/config-module-files.js +2 -3
  46. package/src/diagnostics/startup-trace.js +2 -5
  47. package/src/html-pages/html-page-module-scripts.js +4 -3
  48. package/src/html-pages/html-page-renderer.js +2 -3
  49. package/src/index.d.ts +1 -1
  50. package/src/index.js +1 -1
  51. package/src/plugins/component-import-discovery.js +4 -4
  52. package/src/plugins/foreign-jsx-override-plugin.js +2 -2
  53. package/src/plugins/tsconfig-import-resolver.js +12 -12
  54. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +0 -17
  55. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -23
  56. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
  57. package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
  58. package/src/router/server/route-registry.d.ts +18 -9
  59. package/src/router/server/route-registry.js +50 -32
  60. package/src/router/server/segment-path-matcher.d.ts +8 -0
  61. package/src/router/server/segment-path-matcher.js +15 -0
  62. package/src/static-site-generator/static-site-generator.js +1 -1
  63. package/src/types/contracts.d.ts +87 -61
  64. package/src/types/contracts.js +4 -1
  65. package/src/types/public-types.d.ts +1 -1
  66. package/src/utils/endpoint-file-extensions.d.ts +11 -0
  67. package/src/utils/endpoint-file-extensions.js +13 -0
@@ -1,8 +1,19 @@
1
1
  import { createBodyResponse } from './create-body-response.js';
2
+ /**
3
+ * @remarks
4
+ * The returned handler's context is the base context: the typed one, narrowed by the schema and the
5
+ * middleware, is erased by the cast, as `app.add` would erase it. The middleware list needs no cast.
6
+ */
2
7
  export function defineApiHandler(handler) {
3
8
  return handler;
4
9
  }
5
- const defineApiMethod = (method) => (handler) => defineApiHandler({ ...handler, method });
10
+ function defineApiMethod(method) {
11
+ return ((handler) => ({
12
+ ...handler,
13
+ path: handler.path ?? '',
14
+ method,
15
+ }));
16
+ }
6
17
  export const defineGet = defineApiMethod('GET');
7
18
  export const definePost = defineApiMethod('POST');
8
19
  export const definePut = defineApiMethod('PUT');
@@ -10,6 +21,8 @@ export const defineDelete = defineApiMethod('DELETE');
10
21
  export const definePatch = defineApiMethod('PATCH');
11
22
  export const defineOptions = defineApiMethod('OPTIONS');
12
23
  export const defineHead = defineApiMethod('HEAD');
24
+ /** Defines a handler for the QUERY method, a safe, idempotent read whose request body carries the query. */
25
+ export const defineQuery = defineApiMethod('QUERY');
13
26
  export function json(data, options) {
14
27
  return createBodyResponse('json', data, {
15
28
  status: options?.status,
@@ -38,6 +51,7 @@ function createGroupApi() {
38
51
  patch: defineApiMethod('PATCH'),
39
52
  options: defineApiMethod('OPTIONS'),
40
53
  head: defineApiMethod('HEAD'),
54
+ query: defineApiMethod('QUERY'),
41
55
  });
42
56
  }
43
57
  export function defineGroupHandler(config) {
@@ -0,0 +1,46 @@
1
+ import type { RouteMatch, TemplateRoute } from '../../../router/server/route-registry.js';
2
+ import { type ApiHandler, type ApiHandlerMethod, type ErrorHandler } from '../../../types/contracts.js';
3
+ import type { ApiRequestPipeline } from './api-request-pipeline.js';
4
+ type EndpointHandler = ApiHandler<string, Request, unknown>;
5
+ /** The per-request values an endpoint needs so its errors reach `app.onError`. */
6
+ export type EndpointRequestContext = {
7
+ errorHandler?: ErrorHandler<Request, unknown>;
8
+ serverInstance?: unknown;
9
+ };
10
+ export type EndpointRouteHandlerOptions = {
11
+ apiRequestPipeline: ApiRequestPipeline<Request, unknown>;
12
+ /** The server-module loader Pages use, so a dev save drops the cached endpoint module. */
13
+ importServerModule: (filePath: string) => Promise<Record<string, unknown>>;
14
+ };
15
+ type EndpointFile = Pick<TemplateRoute, 'pathname' | 'filePath'>;
16
+ /**
17
+ * Reads the method handlers an endpoint module exports, keyed in `Allow` header order.
18
+ *
19
+ * @remarks
20
+ * Exports other than the method names are ignored. A method export that is not a method-helper
21
+ * result, is built for another method, or sets `path` fails the load: the file is the one owner of
22
+ * the URL.
23
+ */
24
+ export declare function readEndpointHandlers(module: Record<string, unknown>, { filePath, pathname }: EndpointFile): ReadonlyMap<ApiHandlerMethod, EndpointHandler>;
25
+ /**
26
+ * Lists one warning per Explicit Route registered on the same pathname as an endpoint file.
27
+ *
28
+ * @remarks
29
+ * Explicit Routes match first, so each one keeps its method and the file answers the rest.
30
+ * `:slug` and `[slug]` are the same slot, as are `*` and `[...slug]`.
31
+ */
32
+ export declare function findExplicitRoutesOnEndpoints(apiHandlers: readonly Pick<ApiHandler, 'method' | 'path'>[], templateRoutes: readonly Pick<TemplateRoute, 'pathname' | 'filePath' | 'role'>[]): string[];
33
+ /**
34
+ * Answers a request matched to an endpoint Template Route through the API pipeline.
35
+ *
36
+ * @remarks
37
+ * The module is imported on every request; the server-module loader caches it until a dev save
38
+ * invalidates it. A load error resolves like a handler error, through `app.onError`.
39
+ */
40
+ export declare class EndpointRouteHandler {
41
+ private readonly apiRequestPipeline;
42
+ private readonly importServerModule;
43
+ constructor({ apiRequestPipeline, importServerModule }: EndpointRouteHandlerOptions);
44
+ handleMatch(match: RouteMatch, request: Request, context: EndpointRequestContext): Promise<Response>;
45
+ }
46
+ export {};
@@ -0,0 +1,96 @@
1
+ import { segmentPathPatternKey } from '../../../router/server/segment-path-matcher.js';
2
+ import { API_HANDLER_METHODS, } from '../../../types/contracts.js';
3
+ import { invariant } from '../../../utils/invariant.js';
4
+ function isApiHandler(value) {
5
+ return (typeof value === 'object' &&
6
+ value !== null &&
7
+ 'handler' in value &&
8
+ typeof value.handler === 'function' &&
9
+ 'method' in value &&
10
+ typeof value.method === 'string');
11
+ }
12
+ function methodHelperName(method) {
13
+ return `define${method[0]}${method.slice(1).toLowerCase()}`;
14
+ }
15
+ /**
16
+ * Reads the method handlers an endpoint module exports, keyed in `Allow` header order.
17
+ *
18
+ * @remarks
19
+ * Exports other than the method names are ignored. A method export that is not a method-helper
20
+ * result, is built for another method, or sets `path` fails the load: the file is the one owner of
21
+ * the URL.
22
+ */
23
+ export function readEndpointHandlers(module, { filePath, pathname }) {
24
+ const handlers = new Map();
25
+ for (const method of API_HANDLER_METHODS) {
26
+ const value = module[method];
27
+ if (value === undefined) {
28
+ continue;
29
+ }
30
+ const exportName = `${filePath}: the ${method} export of the endpoint "${pathname}"`;
31
+ invariant(isApiHandler(value), `${exportName} is not a request handler. Build it with ${methodHelperName(method)}().`);
32
+ invariant(value.method === method, `${exportName} is a ${value.method} handler. Build it with ${methodHelperName(method)}().`);
33
+ invariant(!value.path, `${exportName} sets path "${value.path}". The file gives the endpoint its path; remove path.`);
34
+ handlers.set(method, value);
35
+ }
36
+ invariant(handlers.size > 0, `${filePath} defines the endpoint "${pathname}" but exports no request handler. Export at least one of ${API_HANDLER_METHODS.join(', ')}, built with defineGet() or another method helper.`);
37
+ return handlers;
38
+ }
39
+ /**
40
+ * Lists one warning per Explicit Route registered on the same pathname as an endpoint file.
41
+ *
42
+ * @remarks
43
+ * Explicit Routes match first, so each one keeps its method and the file answers the rest.
44
+ * `:slug` and `[slug]` are the same slot, as are `*` and `[...slug]`.
45
+ */
46
+ export function findExplicitRoutesOnEndpoints(apiHandlers, templateRoutes) {
47
+ const endpointsByKey = new Map(templateRoutes
48
+ .filter((route) => route.role === 'endpoint')
49
+ .map((route) => [segmentPathPatternKey(route.pathname, 'filesystem'), route]));
50
+ return apiHandlers.flatMap(({ method, path }) => {
51
+ const endpoint = endpointsByKey.get(segmentPathPatternKey(path, 'api'));
52
+ return endpoint
53
+ ? [
54
+ `The app route ${method} ${path} and the endpoint file ${endpoint.filePath} both answer "${endpoint.pathname}". The app route answers ${method}; the file answers its other methods.`,
55
+ ]
56
+ : [];
57
+ });
58
+ }
59
+ /**
60
+ * Answers a request matched to an endpoint Template Route through the API pipeline.
61
+ *
62
+ * @remarks
63
+ * The module is imported on every request; the server-module loader caches it until a dev save
64
+ * invalidates it. A load error resolves like a handler error, through `app.onError`.
65
+ */
66
+ export class EndpointRouteHandler {
67
+ apiRequestPipeline;
68
+ importServerModule;
69
+ constructor({ apiRequestPipeline, importServerModule }) {
70
+ this.apiRequestPipeline = apiRequestPipeline;
71
+ this.importServerModule = importServerModule;
72
+ }
73
+ async handleMatch(match, request, context) {
74
+ const { errorHandler, serverInstance } = context;
75
+ let handlers;
76
+ try {
77
+ const module = await this.importServerModule(match.templateRoute.filePath);
78
+ handlers = readEndpointHandlers(module, match.templateRoute);
79
+ }
80
+ catch (error) {
81
+ return await this.apiRequestPipeline.handleError(error, {
82
+ request,
83
+ params: match.params,
84
+ serverInstance,
85
+ errorHandler,
86
+ });
87
+ }
88
+ const requestMethod = request.method.toUpperCase();
89
+ const method = API_HANDLER_METHODS.find((candidate) => candidate === requestMethod);
90
+ const handler = method && handlers.get(method);
91
+ if (!handler) {
92
+ return new Response(null, { status: 405, headers: { Allow: [...handlers.keys()].join(', ') } });
93
+ }
94
+ return await this.apiRequestPipeline.execute(request, match.params, handler, serverInstance, errorHandler);
95
+ }
96
+ }
@@ -1,4 +1,5 @@
1
- import { PortManager } from './port-manager.js';
1
+ import { DEFAULT_ECOPAGES_HOSTNAME } from '../../../constants.js';
2
+ import { isPortAvailable, PortManager } from './port-manager.js';
2
3
  import { appLogger } from '../../../global/app-logger.js';
3
4
  /**
4
5
  * Starts a runtime server, optionally negotiating a fallback port via
@@ -27,6 +28,7 @@ export async function bindRuntimeServer(runtimeHost, options) {
27
28
  activeRuntimeOrigin = runtimeOrigin;
28
29
  return boundPort;
29
30
  },
31
+ probePort: (port) => isPortAvailable(port, options.serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME),
30
32
  warn: (message) => appLogger.warn(message),
31
33
  });
32
34
  const boundPort = await portManager.bind({
@@ -1,9 +1,8 @@
1
- import { lstatSync, readdirSync, readlinkSync } from 'node:fs';
2
1
  import path from 'node:path';
3
2
  import { fileSystem } from '@ecopages/file-system';
4
3
  function tryLstat(filePath) {
5
4
  try {
6
- return lstatSync(filePath);
5
+ return fileSystem.lstat(filePath);
7
6
  }
8
7
  catch (error) {
9
8
  if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
@@ -17,7 +16,7 @@ export function copyRuntimePublicFileIfChanged(sourcePath, destinationPath) {
17
16
  return;
18
17
  }
19
18
  fileSystem.ensureDir(path.dirname(destinationPath));
20
- const destinationIsSymbolicLink = tryLstat(destinationPath)?.isSymbolicLink() ?? false;
19
+ const destinationIsSymbolicLink = tryLstat(destinationPath)?.isSymbolicLink ?? false;
21
20
  if (destinationIsSymbolicLink) {
22
21
  fileSystem.remove(destinationPath);
23
22
  }
@@ -42,18 +41,20 @@ export async function copyRuntimePublicFile(sourcePath, destinationPath) {
42
41
  */
43
42
  export function copyRuntimePublicDirIfChanged(sourceDir, destinationDir) {
44
43
  fileSystem.ensureDir(destinationDir);
45
- for (const entry of readdirSync(sourceDir, { withFileTypes: true })) {
44
+ for (const entry of fileSystem.readdir(sourceDir)) {
46
45
  const sourcePath = path.join(sourceDir, entry.name);
47
46
  const destinationPath = path.join(destinationDir, entry.name);
48
- if (entry.isDirectory()) {
47
+ if (entry.isDirectory) {
49
48
  copyRuntimePublicDirIfChanged(sourcePath, destinationPath);
50
49
  continue;
51
50
  }
52
- if (entry.isSymbolicLink()) {
53
- const sourceTarget = readlinkSync(sourcePath);
51
+ if (entry.isSymbolicLink) {
52
+ const sourceTarget = fileSystem.readlink(sourcePath);
54
53
  const destinationStats = tryLstat(destinationPath);
55
54
  const destinationExists = destinationStats !== undefined;
56
- const destinationTarget = destinationStats?.isSymbolicLink() ? readlinkSync(destinationPath) : undefined;
55
+ const destinationTarget = destinationStats?.isSymbolicLink
56
+ ? fileSystem.readlink(destinationPath)
57
+ : undefined;
57
58
  if (sourceTarget === destinationTarget) {
58
59
  continue;
59
60
  }
@@ -63,7 +64,7 @@ export function copyRuntimePublicDirIfChanged(sourceDir, destinationDir) {
63
64
  fileSystem.copyFile(sourcePath, destinationPath);
64
65
  continue;
65
66
  }
66
- if (!entry.isFile()) {
67
+ if (!entry.isFile) {
67
68
  continue;
68
69
  }
69
70
  copyRuntimePublicFileIfChanged(sourcePath, destinationPath);
@@ -7,6 +7,12 @@ export declare function isPortInUseError(error: unknown): boolean;
7
7
  * short-lived Node `net.Server`.
8
8
  *
9
9
  * @remarks
10
+ * `hostname` is resolved to a single address first and the probe binds that
11
+ * address, mirroring what the server bind does. Passing the hostname straight
12
+ * to `listen()` makes some runtimes (Bun) try every resolved address, so a
13
+ * taken port can be reported as free. A hostname that does not resolve reports
14
+ * the port as unavailable.
15
+ *
10
16
  * A successful probe only guarantees the port was free at probe time; callers
11
17
  * must still handle EADDRINUSE when they actually bind, since release races
12
18
  * can flip the answer between probe and bind.
@@ -1,3 +1,4 @@
1
+ import { lookup } from 'node:dns/promises';
1
2
  import { createServer as createNetServer } from 'node:net';
2
3
  import { createClackDefaultPrompt } from './port-manager-default-prompt.js';
3
4
  /**
@@ -14,18 +15,31 @@ function sleep(ms) {
14
15
  * short-lived Node `net.Server`.
15
16
  *
16
17
  * @remarks
18
+ * `hostname` is resolved to a single address first and the probe binds that
19
+ * address, mirroring what the server bind does. Passing the hostname straight
20
+ * to `listen()` makes some runtimes (Bun) try every resolved address, so a
21
+ * taken port can be reported as free. A hostname that does not resolve reports
22
+ * the port as unavailable.
23
+ *
17
24
  * A successful probe only guarantees the port was free at probe time; callers
18
25
  * must still handle EADDRINUSE when they actually bind, since release races
19
26
  * can flip the answer between probe and bind.
20
27
  */
21
- export function isPortAvailable(port, hostname = '127.0.0.1') {
28
+ export async function isPortAvailable(port, hostname = '127.0.0.1') {
29
+ let address;
30
+ try {
31
+ ({ address } = await lookup(hostname));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
22
36
  return new Promise((resolve) => {
23
37
  const tester = createNetServer();
24
38
  tester.once('error', () => resolve(false));
25
39
  tester.once('listening', () => {
26
40
  tester.close(() => resolve(true));
27
41
  });
28
- tester.listen(port, hostname);
42
+ tester.listen(port, address);
29
43
  });
30
44
  }
31
45
  const PORT_RELEASE_RACE_RETRIES = 2;
@@ -6,6 +6,7 @@ import type { StaticGenerationRoute } from '../../../router/server/route-registr
6
6
  import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
7
7
  import { ServerRouteHandler } from './server-route-handler.js';
8
8
  import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
9
+ import { type EndpointRequestContext, type EndpointRouteHandlerOptions } from '../http/endpoint-route-handler.js';
9
10
  import type { ApiHandler, CacheInvalidator, ErrorHandler, RenderContext, StaticRoute, ErrorPageLoaders } from '../../../types/contracts.js';
10
11
  export type ServerRequestContext<TServer = unknown> = {
11
12
  apiHandlers: ApiHandler[];
@@ -27,17 +28,30 @@ export declare class ServerRequestPipeline {
27
28
  protected routeHandler: ServerRouteHandler;
28
29
  protected readonly apiRequestPipeline: ApiRequestPipeline<Request, unknown>;
29
30
  private sharedPageCacheService;
31
+ /** The one endpoint loader, shared by requests and the build, so both compile a file the same way. */
32
+ private readonly importEndpointModule;
33
+ private readonly endpointRouteHandler;
34
+ /** Warnings already logged, so a dev route refresh repeats none of them. */
35
+ private readonly loggedEndpointWarnings;
30
36
  constructor(options: ServerRequestPipelineOptions);
31
- /** Renders one declared path inside the request build scope for a DevSession prewarm. */
32
- renderDevPrewarmPath(pathname: string, runtimeOrigin: string): Promise<void>;
37
+ /**
38
+ * Renders one declared path inside the request build scope for a DevSession prewarm.
39
+ *
40
+ * @param requestContext - The `app.onError` handler and server, so a prewarmed endpoint's errors
41
+ * resolve as they would for a request
42
+ */
43
+ renderDevPrewarmPath(pathname: string, runtimeOrigin: string, requestContext: EndpointRequestContext): Promise<void>;
33
44
  initializeRouteHandling(options: {
34
45
  staticRoutes: StaticRoute[];
35
46
  errorPageLoaders?: ErrorPageLoaders;
47
+ apiHandlers: readonly ApiHandler[];
36
48
  }): Promise<void>;
49
+ private warnExplicitRoutesOnEndpoints;
37
50
  private ensureRouteRendererFactory;
38
51
  createWatchRefreshCallback(options: {
39
52
  staticRoutes: StaticRoute[];
40
53
  errorPageLoaders?: ErrorPageLoaders;
54
+ apiHandlers: readonly ApiHandler[];
41
55
  onRoutesReady?: () => Promise<void> | void;
42
56
  onError?: (error: Error) => Promise<void> | void;
43
57
  }): () => Promise<void>;
@@ -68,6 +82,7 @@ export declare class ServerRequestPipeline {
68
82
  private getOrCreateSharedPageCacheService;
69
83
  protected getCacheService(): CacheInvalidator | null;
70
84
  protected getRenderContext(): RenderContext;
85
+ private importServerModule;
71
86
  private tryHandleSharedDevClientRequest;
72
87
  private tryHandleSharedHmrRequest;
73
88
  private injectSharedHmrHtmlResponse;
@@ -80,6 +95,7 @@ export declare class ServerRequestPipeline {
80
95
  getStaticBuildContext(): {
81
96
  router: RouteRegistry;
82
97
  routeRendererFactory: RouteRendererFactory;
98
+ importServerModule: EndpointRouteHandlerOptions['importServerModule'];
83
99
  };
84
100
  listStaticGenerationRoutes(input: {
85
101
  runtimeOrigin: string;
@@ -90,7 +106,8 @@ export declare class ServerRequestPipeline {
90
106
  * 1. Resolves static Hot Module Replacement runtime blobs if development.
91
107
  * 2. Checks if the incoming request matches any parsed API route schemas.
92
108
  * - Routes through `ApiRequestPipeline` which performs strict validation.
93
- * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
109
+ * 3. Falls through to standard `ServerRouteHandler` for explicit static routes, then filesystem
110
+ * Pages and endpoint files.
94
111
  *
95
112
  * The Node host maps its native HTTP request into a Web Request before calling this method.
96
113
  */
@@ -13,6 +13,8 @@ import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js
13
13
  import { ServerRouteHandler } from './server-route-handler.js';
14
14
  import { createRenderContext } from './render-context.js';
15
15
  import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
16
+ import { EndpointRouteHandler, findExplicitRoutesOnEndpoints, } from '../http/endpoint-route-handler.js';
17
+ import { appLogger } from '../../../global/app-logger.js';
16
18
  import { parseSegmentPath } from '../../../router/server/segment-path-matcher.js';
17
19
  import { isHtmlResponse, withUncachedDevHtml } from '../hmr/hmr-html-response.js';
18
20
  import { resolveInternalExecutionDir } from '../../../utils/resolve-work-dir.js';
@@ -30,23 +32,45 @@ export class ServerRequestPipeline {
30
32
  getCacheService: () => this.getCacheService(),
31
33
  });
32
34
  sharedPageCacheService;
35
+ /** The one endpoint loader, shared by requests and the build, so both compile a file the same way. */
36
+ importEndpointModule = (filePath) => this.importServerModule(filePath);
37
+ endpointRouteHandler = new EndpointRouteHandler({
38
+ apiRequestPipeline: this.apiRequestPipeline,
39
+ importServerModule: this.importEndpointModule,
40
+ });
41
+ /** Warnings already logged, so a dev route refresh repeats none of them. */
42
+ loggedEndpointWarnings = new Set();
33
43
  constructor(options) {
34
44
  this.appConfig = options.appConfig;
35
45
  this.runtime = options.runtime;
36
46
  this.watchMode = options.watch ?? false;
37
47
  }
38
- /** Renders one declared path inside the request build scope for a DevSession prewarm. */
39
- async renderDevPrewarmPath(pathname, runtimeOrigin) {
48
+ /**
49
+ * Renders one declared path inside the request build scope for a DevSession prewarm.
50
+ *
51
+ * @param requestContext - The `app.onError` handler and server, so a prewarmed endpoint's errors
52
+ * resolve as they would for a request
53
+ */
54
+ async renderDevPrewarmPath(pathname, runtimeOrigin, requestContext) {
40
55
  await requireBuildQueue(this.appConfig).withRequestScope(() => runWithBuildInputIndex(requireAppRuntime(this.appConfig).buildInputIndex, async () => {
41
- const response = await this.routeHandler.handleResponse(new Request(new URL(pathname, runtimeOrigin).toString(), { method: 'GET' }));
56
+ const response = await this.routeHandler.handleResponse(new Request(new URL(pathname, runtimeOrigin).toString(), { method: 'GET' }), requestContext);
42
57
  await response.arrayBuffer();
43
58
  }));
44
59
  }
45
60
  async initializeRouteHandling(options) {
46
61
  this.ensureRouteRendererFactory();
47
62
  await this.initSharedRouter();
63
+ this.warnExplicitRoutesOnEndpoints(options.apiHandlers);
48
64
  this.configureResponseHandlers(options);
49
65
  }
66
+ warnExplicitRoutesOnEndpoints(apiHandlers) {
67
+ for (const warning of findExplicitRoutesOnEndpoints(apiHandlers, this.router.templateRoutes)) {
68
+ if (!this.loggedEndpointWarnings.has(warning)) {
69
+ this.loggedEndpointWarnings.add(warning);
70
+ appLogger.warn(warning);
71
+ }
72
+ }
73
+ }
50
74
  ensureRouteRendererFactory() {
51
75
  if (this.routeRendererFactory) {
52
76
  return;
@@ -61,6 +85,7 @@ export class ServerRequestPipeline {
61
85
  await this.initializeRouteHandling({
62
86
  staticRoutes: options.staticRoutes,
63
87
  errorPageLoaders: options.errorPageLoaders,
88
+ apiHandlers: options.apiHandlers,
64
89
  });
65
90
  if (options.onRoutesReady) {
66
91
  await options.onRoutesReady();
@@ -127,6 +152,7 @@ export class ServerRequestPipeline {
127
152
  this.routeHandler = new ServerRouteHandler({
128
153
  router: this.router,
129
154
  fileSystemResponseMatcher: this.fileSystemResponseMatcher,
155
+ endpointRouteHandler: this.endpointRouteHandler,
130
156
  explicitStaticRouteMatcher,
131
157
  });
132
158
  }
@@ -185,15 +211,17 @@ export class ServerRequestPipeline {
185
211
  return this.fileSystemResponseMatcher?.getCacheService() ?? null;
186
212
  }
187
213
  getRenderContext() {
188
- const moduleLoader = requireAppRuntime(this.appConfig).moduleLoader;
189
214
  return createRenderContext({
190
215
  integrations: this.appConfig.integrations,
191
216
  ensureIntegrationReady: (integrationName) => ensureIntegrationRuntimeReady({ appConfig: this.appConfig, integrationName }),
192
- importServerModule: async (filePath) => await moduleLoader.importModule({
193
- filePath,
194
- outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
195
- externalPackages: true,
196
- }),
217
+ importServerModule: (filePath) => this.importServerModule(filePath),
218
+ });
219
+ }
220
+ async importServerModule(filePath) {
221
+ return await requireAppRuntime(this.appConfig).moduleLoader.importModule({
222
+ filePath,
223
+ outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
224
+ externalPackages: true,
197
225
  });
198
226
  }
199
227
  async tryHandleSharedDevClientRequest(request) {
@@ -225,7 +253,11 @@ export class ServerRequestPipeline {
225
253
  return this.watchMode && isHtmlResponse(response) ? withUncachedDevHtml(response) : response;
226
254
  }
227
255
  getStaticBuildContext() {
228
- return { router: this.router, routeRendererFactory: this.routeRendererFactory };
256
+ return {
257
+ router: this.router,
258
+ routeRendererFactory: this.routeRendererFactory,
259
+ importServerModule: this.importEndpointModule,
260
+ };
229
261
  }
230
262
  async listStaticGenerationRoutes(input) {
231
263
  return await this.router.listStaticGenerationRoutes(input);
@@ -236,7 +268,8 @@ export class ServerRequestPipeline {
236
268
  * 1. Resolves static Hot Module Replacement runtime blobs if development.
237
269
  * 2. Checks if the incoming request matches any parsed API route schemas.
238
270
  * - Routes through `ApiRequestPipeline` which performs strict validation.
239
- * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
271
+ * 3. Falls through to standard `ServerRouteHandler` for explicit static routes, then filesystem
272
+ * Pages and endpoint files.
240
273
  *
241
274
  * The Node host maps its native HTTP request into a Web Request before calling this method.
242
275
  */
@@ -265,7 +298,7 @@ export class ServerRequestPipeline {
265
298
  if (apiResponse) {
266
299
  return await this.injectSharedHmrHtmlResponse(apiResponse);
267
300
  }
268
- const routeResponse = await this.routeHandler.handleResponse(request, parsedPathSegments);
301
+ const routeResponse = await this.routeHandler.handleResponse(request, context, parsedPathSegments);
269
302
  return await this.injectSharedHmrHtmlResponse(routeResponse);
270
303
  })));
271
304
  }
@@ -1,6 +1,7 @@
1
1
  import type { RouteRegistry } from '../../../router/server/route-registry.js';
2
2
  import type { ExplicitStaticRouteMatcher } from '../http/explicit-static-route-matcher.js';
3
3
  import type { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
4
+ import type { EndpointRequestContext, EndpointRouteHandler } from '../http/endpoint-route-handler.js';
4
5
  import { type ParsedSegmentPath } from '../../../router/server/segment-path-matcher.js';
5
6
  /**
6
7
  * Configuration parameters for ServerRouteHandler.
@@ -10,6 +11,8 @@ export interface ServerRouteHandlerParams {
10
11
  router: RouteRegistry;
11
12
  /** Matcher for handling file system route responses. */
12
13
  fileSystemResponseMatcher: FileSystemResponseMatcher;
14
+ /** Answers file system routes whose role is `endpoint`. */
15
+ endpointRouteHandler: EndpointRouteHandler;
13
16
  /** Optional matcher for explicit static routes like processed images or sitemaps. */
14
17
  explicitStaticRouteMatcher?: ExplicitStaticRouteMatcher;
15
18
  }
@@ -25,26 +28,28 @@ export interface ServerRouteHandlerParams {
25
28
  export declare class ServerRouteHandler {
26
29
  private readonly router;
27
30
  private readonly fileSystemResponseMatcher;
31
+ private readonly endpointRouteHandler;
28
32
  private readonly explicitStaticRouteMatcher?;
29
33
  /**
30
34
  * Creates a new ServerRouteHandler instance.
31
35
  *
32
36
  * @param params - Configuration parameters
33
37
  */
34
- constructor({ router, fileSystemResponseMatcher, explicitStaticRouteMatcher }: ServerRouteHandlerParams);
38
+ constructor({ router, fileSystemResponseMatcher, endpointRouteHandler, explicitStaticRouteMatcher, }: ServerRouteHandlerParams);
35
39
  /**
36
40
  * Handles HTTP requests from the router adapter.
37
41
  *
38
42
  * Priority-based routing flow:
39
43
  * 1. Check explicit static routes first (e.g., /sitemap.xml, /image.webp from plugins)
40
44
  * 2. Match file-based routes, unless the path ends in a known static file extension, so a
41
- * dotted route such as `/v1.2` still matches its Page
45
+ * dotted route such as `/v1.2` still matches its Page or endpoint
42
46
  * 3. Fall back to static file serving from disk
43
47
  *
44
48
  * @param request - The incoming HTTP request
49
+ * @param requestContext - The `app.onError` handler and server an endpoint's errors resolve with
45
50
  * @returns HTTP response for the matched route
46
51
  */
47
- handleResponse(request: Request, parsedPathSegments?: ParsedSegmentPath): Promise<Response>;
52
+ handleResponse(request: Request, requestContext: EndpointRequestContext, parsedPathSegments?: ParsedSegmentPath): Promise<Response>;
48
53
  /**
49
54
  * Handles requests that do not match any routes.
50
55
  *
@@ -14,15 +14,17 @@ import { parseSegmentPath } from '../../../router/server/segment-path-matcher.js
14
14
  export class ServerRouteHandler {
15
15
  router;
16
16
  fileSystemResponseMatcher;
17
+ endpointRouteHandler;
17
18
  explicitStaticRouteMatcher;
18
19
  /**
19
20
  * Creates a new ServerRouteHandler instance.
20
21
  *
21
22
  * @param params - Configuration parameters
22
23
  */
23
- constructor({ router, fileSystemResponseMatcher, explicitStaticRouteMatcher }) {
24
+ constructor({ router, fileSystemResponseMatcher, endpointRouteHandler, explicitStaticRouteMatcher, }) {
24
25
  this.router = router;
25
26
  this.fileSystemResponseMatcher = fileSystemResponseMatcher;
27
+ this.endpointRouteHandler = endpointRouteHandler;
26
28
  this.explicitStaticRouteMatcher = explicitStaticRouteMatcher;
27
29
  }
28
30
  /**
@@ -31,13 +33,14 @@ export class ServerRouteHandler {
31
33
  * Priority-based routing flow:
32
34
  * 1. Check explicit static routes first (e.g., /sitemap.xml, /image.webp from plugins)
33
35
  * 2. Match file-based routes, unless the path ends in a known static file extension, so a
34
- * dotted route such as `/v1.2` still matches its Page
36
+ * dotted route such as `/v1.2` still matches its Page or endpoint
35
37
  * 3. Fall back to static file serving from disk
36
38
  *
37
39
  * @param request - The incoming HTTP request
40
+ * @param requestContext - The `app.onError` handler and server an endpoint's errors resolve with
38
41
  * @returns HTTP response for the matched route
39
42
  */
40
- async handleResponse(request, parsedPathSegments) {
43
+ async handleResponse(request, requestContext, parsedPathSegments) {
41
44
  const pathname = new URL(request.url).pathname;
42
45
  try {
43
46
  const pathSegments = parsedPathSegments ?? parseSegmentPath(pathname);
@@ -54,9 +57,12 @@ export class ServerRouteHandler {
54
57
  }
55
58
  }
56
59
  const fsMatch = !ServerUtils.hasKnownStaticExtension(pathname) && this.router.matchRequest(request.url, pathSegments);
57
- return await (fsMatch
58
- ? this.fileSystemResponseMatcher.handleMatch(fsMatch, request)
59
- : this.handleNoMatch(request));
60
+ if (!fsMatch) {
61
+ return await this.handleNoMatch(request);
62
+ }
63
+ return await (fsMatch.templateRoute.role === 'endpoint'
64
+ ? this.endpointRouteHandler.handleMatch(fsMatch, request, requestContext)
65
+ : this.fileSystemResponseMatcher.handleMatch(fsMatch, request));
60
66
  }
61
67
  catch (error) {
62
68
  if (error instanceof HttpError) {
@@ -4,6 +4,7 @@ import type { ErrorPageLoaders, StaticRoute } from '../../../types/contracts.js'
4
4
  import type { RouteRegistry } from '../../../router/server/route-registry.js';
5
5
  import type { StaticSiteGenerator } from '../../../static-site-generator/static-site-generator.js';
6
6
  import type { StaticGenerationRendererResolver } from '../../../route-renderer/route-renderer.js';
7
+ import { type EndpointRouteHandlerOptions } from '../http/endpoint-route-handler.js';
7
8
  export interface StaticBuildOptions {
8
9
  baseUrl?: string;
9
10
  force?: boolean;
@@ -22,6 +23,11 @@ export interface ServerStaticBuilderParams {
22
23
  * Whether the app requires a server entry bundle for production use.
23
24
  * When `true`, the build step bundles the server entry file for `ecopages start`.
24
25
  * Defaults to `false` (static-only build, no server needed).
26
+ *
27
+ * @remarks
28
+ * Covers what the app registers: Explicit Routes and WebSocket handlers. An endpoint file under the pages
29
+ * directory is known only once the Route Registry has scanned it, so {@link ServerStaticBuilder.build} adds
30
+ * it to this decision.
25
31
  */
26
32
  needsServerBundle?: boolean;
27
33
  logger?: ServerStaticBuilderLogger;
@@ -76,7 +82,7 @@ export declare class ServerStaticBuilder {
76
82
  *
77
83
  * @remarks
78
84
  * Only invoked when the app requires a runtime server (API handlers,
79
- * websocket handlers, etc.). Static-only apps skip this step entirely.
85
+ * websocket handlers or endpoint files). Static-only apps skip this step entirely.
80
86
  * Every process bundles the entry from source.
81
87
  *
82
88
  * Source code is bundled: the app entry graph, workspace packages and
@@ -97,11 +103,18 @@ export declare class ServerStaticBuilder {
97
103
  * @param dependencies.router - The initialized router
98
104
  * @param dependencies.routeRendererFactory - The route renderer factory
99
105
  * @param dependencies.staticRoutes - Explicit static routes registered via app.static()
106
+ * @param dependencies.importServerModule - The server-module loader endpoint requests use
107
+ *
108
+ * @remarks
109
+ * Every endpoint file is imported and its exports checked as its first request would, before the
110
+ * server bundle and static generation, so a broken one fails the build with the request's error.
111
+ * The import is cached in this process only; `ecopages start` compiles the file again.
100
112
  */
101
113
  build(options: StaticBuildOptions | undefined, dependencies: {
102
114
  router: RouteRegistry;
103
115
  routeRendererFactory: StaticGenerationRendererResolver;
104
116
  staticRoutes?: StaticRoute[];
105
117
  errorPageLoaders?: ErrorPageLoaders;
118
+ importServerModule: EndpointRouteHandlerOptions['importServerModule'];
106
119
  }): Promise<void>;
107
120
  }