@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
@@ -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();
@@ -108,6 +133,7 @@ export class ServerRequestPipeline {
108
133
  return {
109
134
  staticPaths: pageComponent?.staticPaths ?? module.getStaticPaths,
110
135
  staticProps: pageComponent?.staticProps ?? module.getStaticProps,
136
+ cache: pageComponent?.cache,
111
137
  };
112
138
  },
113
139
  };
@@ -127,6 +153,7 @@ export class ServerRequestPipeline {
127
153
  this.routeHandler = new ServerRouteHandler({
128
154
  router: this.router,
129
155
  fileSystemResponseMatcher: this.fileSystemResponseMatcher,
156
+ endpointRouteHandler: this.endpointRouteHandler,
130
157
  explicitStaticRouteMatcher,
131
158
  });
132
159
  }
@@ -185,15 +212,17 @@ export class ServerRequestPipeline {
185
212
  return this.fileSystemResponseMatcher?.getCacheService() ?? null;
186
213
  }
187
214
  getRenderContext() {
188
- const moduleLoader = requireAppRuntime(this.appConfig).moduleLoader;
189
215
  return createRenderContext({
190
216
  integrations: this.appConfig.integrations,
191
217
  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
- }),
218
+ importServerModule: (filePath) => this.importServerModule(filePath),
219
+ });
220
+ }
221
+ async importServerModule(filePath) {
222
+ return await requireAppRuntime(this.appConfig).moduleLoader.importModule({
223
+ filePath,
224
+ outdir: path.join(resolveInternalExecutionDir(this.appConfig), '.server-modules'),
225
+ externalPackages: true,
197
226
  });
198
227
  }
199
228
  async tryHandleSharedDevClientRequest(request) {
@@ -225,7 +254,11 @@ export class ServerRequestPipeline {
225
254
  return this.watchMode && isHtmlResponse(response) ? withUncachedDevHtml(response) : response;
226
255
  }
227
256
  getStaticBuildContext() {
228
- return { router: this.router, routeRendererFactory: this.routeRendererFactory };
257
+ return {
258
+ router: this.router,
259
+ routeRendererFactory: this.routeRendererFactory,
260
+ importServerModule: this.importEndpointModule,
261
+ };
229
262
  }
230
263
  async listStaticGenerationRoutes(input) {
231
264
  return await this.router.listStaticGenerationRoutes(input);
@@ -236,7 +269,8 @@ export class ServerRequestPipeline {
236
269
  * 1. Resolves static Hot Module Replacement runtime blobs if development.
237
270
  * 2. Checks if the incoming request matches any parsed API route schemas.
238
271
  * - Routes through `ApiRequestPipeline` which performs strict validation.
239
- * 3. Falls through to standard `ServerRouteHandler` for React/Lit filesystem pages.
272
+ * 3. Falls through to standard `ServerRouteHandler` for explicit static routes, then filesystem
273
+ * Pages and endpoint files.
240
274
  *
241
275
  * The Node host maps its native HTTP request into a Web Request before calling this method.
242
276
  */
@@ -265,7 +299,7 @@ export class ServerRequestPipeline {
265
299
  if (apiResponse) {
266
300
  return await this.injectSharedHmrHtmlResponse(apiResponse);
267
301
  }
268
- const routeResponse = await this.routeHandler.handleResponse(request, parsedPathSegments);
302
+ const routeResponse = await this.routeHandler.handleResponse(request, context, parsedPathSegments);
269
303
  return await this.injectSharedHmrHtmlResponse(routeResponse);
270
304
  })));
271
305
  }
@@ -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,13 +57,16 @@ 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
- if (error instanceof HttpError) {
63
- return error.toResponse();
68
+ if (HttpError.isHttpError(error)) {
69
+ return HttpError.responseFor(error);
64
70
  }
65
71
  throw error;
66
72
  }
@@ -82,8 +88,8 @@ export class ServerRouteHandler {
82
88
  return await this.fileSystemResponseMatcher.handleNoMatch(pathname, request);
83
89
  }
84
90
  catch (error) {
85
- if (error instanceof HttpError) {
86
- return error.toResponse();
91
+ if (HttpError.isHttpError(error)) {
92
+ return HttpError.responseFor(error);
87
93
  }
88
94
  if (error instanceof Error) {
89
95
  this.router.appConfig?.appRuntime?.hmr?.broadcast({ type: 'error', message: error.message });
@@ -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
  }
@@ -12,6 +12,7 @@ import { getServerBundleOutputPaths, writeServerBundleDeployManifest, } from '..
12
12
  import { bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME } from '../../../config/server-config-bundle.js';
13
13
  import { resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
14
14
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
15
+ import { readEndpointHandlers } from '../http/endpoint-route-handler.js';
15
16
  /**
16
17
  * Handles static site generation.
17
18
  */
@@ -85,7 +86,7 @@ export class ServerStaticBuilder {
85
86
  *
86
87
  * @remarks
87
88
  * Only invoked when the app requires a runtime server (API handlers,
88
- * websocket handlers, etc.). Static-only apps skip this step entirely.
89
+ * websocket handlers or endpoint files). Static-only apps skip this step entirely.
89
90
  * Every process bundles the entry from source.
90
91
  *
91
92
  * Source code is bundled: the app entry graph, workspace packages and
@@ -141,6 +142,12 @@ export class ServerStaticBuilder {
141
142
  * @param dependencies.router - The initialized router
142
143
  * @param dependencies.routeRendererFactory - The route renderer factory
143
144
  * @param dependencies.staticRoutes - Explicit static routes registered via app.static()
145
+ * @param dependencies.importServerModule - The server-module loader endpoint requests use
146
+ *
147
+ * @remarks
148
+ * Every endpoint file is imported and its exports checked as its first request would, before the
149
+ * server bundle and static generation, so a broken one fails the build with the request's error.
150
+ * The import is cached in this process only; `ecopages start` compiles the file again.
144
151
  */
145
152
  async build(options, dependencies) {
146
153
  const { baseUrl: explicitBaseUrl, force = false } = options ?? {};
@@ -150,7 +157,11 @@ export class ServerStaticBuilder {
150
157
  await this.prepareExport();
151
158
  }
152
159
  this.exportPrepared = false;
153
- if (this.needsServerBundle) {
160
+ const endpointRoutes = dependencies.router.templateRoutes.filter((route) => route.role === 'endpoint');
161
+ for (const route of endpointRoutes) {
162
+ readEndpointHandlers(await dependencies.importServerModule(route.filePath), route);
163
+ }
164
+ if (this.needsServerBundle || endpointRoutes.length > 0) {
154
165
  await this.bundleServerEntry();
155
166
  }
156
167
  await this.staticSiteGenerator.run({
@@ -278,7 +278,6 @@ function registerPageClientEntry(appConfig, entriesByKey, cleanupEntries, instan
278
278
  if (!canBundle(dependency)) {
279
279
  instance.prebuiltPageClientBrowserAssets ??= {
280
280
  processedAssets: [],
281
- islandRenderAssetsByFile: new Map(),
282
281
  fallbackDependencies: [],
283
282
  };
284
283
  instance.prebuiltPageClientBrowserAssets.fallbackDependencies.push({
@@ -292,12 +291,9 @@ function registerPageClientEntry(appConfig, entriesByKey, cleanupEntries, instan
292
291
  if (!entry.dependencies.some((entryDependency) => dependencyAssociationKey(entryDependency) === identity)) {
293
292
  entry.dependencies.push(dependency);
294
293
  }
295
- const association = entry.pageClientRoutes.get(identity) ?? {
296
- dependency,
297
- routes: new Map(),
298
- };
299
- association.routes.set(routeKey, clientEntry.islandFile);
300
- entry.pageClientRoutes.set(identity, association);
294
+ const routes = entry.pageClientRoutes.get(identity) ?? new Set();
295
+ routes.add(routeKey);
296
+ entry.pageClientRoutes.set(identity, routes);
301
297
  return { ...clientEntry, dependency };
302
298
  }
303
299
  function prepareRouteBuildPlan(appConfig, plan, entriesByKey, cleanupEntries) {
@@ -335,29 +331,20 @@ function prepareRouteBuildPlans(appConfig, plans, cleanupEntries) {
335
331
  const routePlans = plans.map((plan) => prepareRouteBuildPlan(appConfig, plan, entriesByKey, cleanupEntries));
336
332
  return { routePlans, entries: [...entriesByKey.values()] };
337
333
  }
338
- function attachPageClientAsset(instance, asset, islandFile) {
339
- const prebuilt = instance.prebuiltPageClientBrowserAssets ?? {
340
- processedAssets: [],
341
- islandRenderAssetsByFile: new Map(),
342
- fallbackDependencies: [],
343
- };
334
+ function attachPageClientAsset(instance, asset) {
335
+ const prebuilt = instance.prebuiltPageClientBrowserAssets ?? { processedAssets: [], fallbackDependencies: [] };
344
336
  prebuilt.processedAssets.push(asset);
345
- if (islandFile) {
346
- const islandAssets = prebuilt.islandRenderAssetsByFile.get(islandFile) ?? [];
347
- islandAssets.push(asset);
348
- prebuilt.islandRenderAssetsByFile.set(islandFile, islandAssets);
349
- }
350
337
  instance.prebuiltPageClientBrowserAssets = prebuilt;
351
338
  }
352
339
  function attachEntryAssetToRoutes(entry, dependency, asset, routePlans) {
353
- const clientAssociation = entry.pageClientRoutes.get(dependencyAssociationKey(dependency));
340
+ const pageClientRoutes = entry.pageClientRoutes.get(dependencyAssociationKey(dependency));
354
341
  for (const routePlan of routePlans) {
355
342
  for (const { instance, routeKey } of routePlan.instances) {
356
343
  if (entry.dependencyRoutes.get(dependency)?.has(routeKey)) {
357
344
  instance.prebuiltGroupedAssets = [...(instance.prebuiltGroupedAssets ?? []), asset];
358
345
  }
359
- if (clientAssociation?.routes.has(routeKey)) {
360
- attachPageClientAsset(instance, asset, clientAssociation.routes.get(routeKey));
346
+ if (pageClientRoutes?.has(routeKey)) {
347
+ attachPageClientAsset(instance, asset);
361
348
  }
362
349
  }
363
350
  }
@@ -27,7 +27,6 @@ export type AppBrowserClientManifestEntry = {
27
27
  groupedAssets: SerializedProcessedAsset[];
28
28
  pageClientAssets: {
29
29
  processedAssets: SerializedProcessedAsset[];
30
- islandRenderAssetsByFile: Array<[string, SerializedProcessedAsset[]]>;
31
30
  fallbackPageClientBuildEntryKeys: string[];
32
31
  };
33
32
  };
@@ -78,13 +78,6 @@ function isStringArray(value) {
78
78
  function isProcessedAssetArray(value) {
79
79
  return Array.isArray(value) && value.every(isProcessedAsset);
80
80
  }
81
- function isIslandRenderAssetEntries(value) {
82
- return (Array.isArray(value) &&
83
- value.every((entry) => Array.isArray(entry) &&
84
- entry.length === 2 &&
85
- typeof entry[0] === 'string' &&
86
- isProcessedAssetArray(entry[1])));
87
- }
88
81
  function isManifestEntry(value) {
89
82
  if (!isRecord(value) || !isRecord(value.pageClientAssets))
90
83
  return false;
@@ -99,8 +92,7 @@ function isManifestEntry(value) {
99
92
  isStringArray(value.pageClientBuildEntryKeys) &&
100
93
  isProcessedAssetArray(value.groupedAssets) &&
101
94
  isProcessedAssetArray(pageClientAssets.processedAssets) &&
102
- isStringArray(pageClientAssets.fallbackPageClientBuildEntryKeys) &&
103
- isIslandRenderAssetEntries(pageClientAssets.islandRenderAssetsByFile));
95
+ isStringArray(pageClientAssets.fallbackPageClientBuildEntryKeys));
104
96
  }
105
97
  function isManifest(value) {
106
98
  return (isRecord(value) &&
@@ -137,10 +129,6 @@ function serializeEntry(rootDir, plan, instance, params) {
137
129
  groupedAssets: (instance.prebuiltGroupedAssets ?? []).map((asset) => serializeProcessedAsset(rootDir, asset)),
138
130
  pageClientAssets: {
139
131
  processedAssets: (pageClientAssets?.processedAssets ?? []).map((asset) => serializeProcessedAsset(rootDir, asset)),
140
- islandRenderAssetsByFile: [...(pageClientAssets?.islandRenderAssetsByFile ?? [])].map(([filePath, assets]) => [
141
- toProjectPath(rootDir, filePath),
142
- assets.map((asset) => serializeProcessedAsset(rootDir, asset)),
143
- ]),
144
132
  fallbackPageClientBuildEntryKeys,
145
133
  },
146
134
  };
@@ -168,10 +156,6 @@ function collectInstanceSourceFilepaths(filepaths, instance) {
168
156
  for (const asset of instance.prebuiltPageClientBrowserAssets?.processedAssets ?? []) {
169
157
  addAssetSourceFilepaths(filepaths, asset);
170
158
  }
171
- for (const assets of instance.prebuiltPageClientBrowserAssets?.islandRenderAssetsByFile.values() ?? []) {
172
- for (const asset of assets)
173
- addAssetSourceFilepaths(filepaths, asset);
174
- }
175
159
  }
176
160
  function collectSourceFilepaths(plans) {
177
161
  const filepaths = new Set();
@@ -190,9 +174,6 @@ function addAssetOutputFilepaths(filepaths, assets = []) {
190
174
  function collectInstanceOutputFilepaths(filepaths, instance) {
191
175
  addAssetOutputFilepaths(filepaths, instance.prebuiltGroupedAssets);
192
176
  addAssetOutputFilepaths(filepaths, instance.prebuiltPageClientBrowserAssets?.processedAssets);
193
- for (const assets of instance.prebuiltPageClientBrowserAssets?.islandRenderAssetsByFile.values() ?? []) {
194
- addAssetOutputFilepaths(filepaths, assets);
195
- }
196
177
  }
197
178
  function addHtmlScriptOutputFilepaths(filepaths, distDir, htmlPageModuleScriptUrls) {
198
179
  for (const url of Object.values(htmlPageModuleScriptUrls)) {
@@ -4,11 +4,17 @@ export declare const CONTENT_VIRTUAL_MODULE_PREFIX = "ecopages:content";
4
4
  export declare const CONTENT_VIRTUAL_MODULE_PATTERN: RegExp;
5
5
  /** Matches `ecopages:content/<collection>/server` component resolver specifiers. */
6
6
  export declare const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN: RegExp;
7
- /** Matches browser-only `ecopages:content/<collection>/browser` component loader specifiers. */
8
- export declare const CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN: RegExp;
7
+ /**
8
+ * Matches `ecopages:content/<collection>/component` loader specifiers.
9
+ *
10
+ * @remarks
11
+ * The server graph resolves this specifier to the `/server` module and the Page Browser Graph
12
+ * resolves it to the browser-safe loader, so one import serves both sides.
13
+ */
14
+ export declare const CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN: RegExp;
9
15
  export type ParsedCollectionSpecifier = {
10
16
  collectionName: string;
11
- variant: 'entries' | 'server' | 'browser';
17
+ variant: 'entries' | 'server' | 'component';
12
18
  };
13
19
  export declare function parseCollectionSpecifier(specifier: string): ParsedCollectionSpecifier | null;
14
20
  export declare function isContentServerVirtualModule(specifier: string): boolean;
@@ -4,8 +4,14 @@ export const CONTENT_VIRTUAL_MODULE_PREFIX = 'ecopages:content';
4
4
  export const CONTENT_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]*$/;
5
5
  /** Matches `ecopages:content/<collection>/server` component resolver specifiers. */
6
6
  export const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/server$/;
7
- /** Matches browser-only `ecopages:content/<collection>/browser` component loader specifiers. */
8
- export const CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/browser$/;
7
+ /**
8
+ * Matches `ecopages:content/<collection>/component` loader specifiers.
9
+ *
10
+ * @remarks
11
+ * The server graph resolves this specifier to the `/server` module and the Page Browser Graph
12
+ * resolves it to the browser-safe loader, so one import serves both sides.
13
+ */
14
+ export const CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/component$/;
9
15
  export function parseCollectionSpecifier(specifier) {
10
16
  const normalized = specifier.startsWith(`${CONTENT_VIRTUAL_MODULE_PREFIX}/`)
11
17
  ? specifier.slice(`${CONTENT_VIRTUAL_MODULE_PREFIX}/`.length)
@@ -21,10 +27,10 @@ export function parseCollectionSpecifier(specifier) {
21
27
  variant: 'server',
22
28
  };
23
29
  }
24
- if (normalized.endsWith('/browser')) {
30
+ if (normalized.endsWith('/component')) {
25
31
  return {
26
- collectionName: normalized.slice(0, -'/browser'.length),
27
- variant: 'browser',
32
+ collectionName: normalized.slice(0, -'/component'.length),
33
+ variant: 'component',
28
34
  };
29
35
  }
30
36
  return {
@@ -1,4 +1,4 @@
1
1
  export type * from './contracts/build-contracts.js';
2
2
  export type * from './contracts/build-types.js';
3
- export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from './contracts/content-virtual-modules.js';
3
+ export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from './contracts/content-virtual-modules.js';
4
4
  export { isServerOnlyModuleSpecifier } from './contracts/server-only-specifier.js';
@@ -1,2 +1,2 @@
1
- export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, } from './contracts/content-virtual-modules.js';
1
+ export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, } from './contracts/content-virtual-modules.js';
2
2
  export { isServerOnlyModuleSpecifier } from './contracts/server-only-specifier.js';
@@ -338,7 +338,7 @@ export async function createRolldownPluginBridge(plugins, contextRoot, recordBui
338
338
  }
339
339
  }
340
340
  registrationClosed = true;
341
- const resolveIdHandler = async (source, importer) => {
341
+ const resolveIdHandler = async (source, importer, extraOptions) => {
342
342
  for (const { matches, callback, pluginName } of resolveRegistrations) {
343
343
  if (!matches(source)) {
344
344
  continue;
@@ -346,7 +346,7 @@ export async function createRolldownPluginBridge(plugins, contextRoot, recordBui
346
346
  const { namespace, path: sourcePath } = splitNamespace(source);
347
347
  let result;
348
348
  try {
349
- result = await callback({ path: sourcePath, importer, namespace });
349
+ result = await callback({ path: sourcePath, importer, namespace, kind: extraOptions?.kind });
350
350
  }
351
351
  catch (error) {
352
352
  throw new EcoBuildPluginError(error, pluginName, importer);
@@ -42,7 +42,7 @@ export declare function writeServerBundleDeployManifest(appConfig: EcoPagesAppCo
42
42
  * not, and need `--dist-dir`. Guessing between several would run a stale bundle from an earlier build
43
43
  * that used another `distDir`.
44
44
  *
45
- * Static-only apps (no API or WebSocket handlers) build no server bundle. When the selected output, or `dist`
45
+ * Static-only apps (no API handlers, WebSocket handlers or endpoint files) build no server bundle. When the selected output, or `dist`
46
46
  * when none is named, holds built HTML but no bundle, the error says so and points to `ecopages preview`
47
47
  * instead of asking for another build. A static-only build in a custom `distDir` needs `--dist-dir` to be
48
48
  * recognised.
@@ -72,7 +72,7 @@ function readServerBundleDeployManifest(serverDir) {
72
72
  * not, and need `--dist-dir`. Guessing between several would run a stale bundle from an earlier build
73
73
  * that used another `distDir`.
74
74
  *
75
- * Static-only apps (no API or WebSocket handlers) build no server bundle. When the selected output, or `dist`
75
+ * Static-only apps (no API handlers, WebSocket handlers or endpoint files) build no server bundle. When the selected output, or `dist`
76
76
  * when none is named, holds built HTML but no bundle, the error says so and points to `ecopages preview`
77
77
  * instead of asking for another build. A static-only build in a custom `distDir` needs `--dist-dir` to be
78
78
  * recognised.