@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
package/README.md CHANGED
@@ -134,7 +134,7 @@ Use this package README as the top-level map, then drill into the focused subsys
134
134
  - `src/dev/invalidation/README.md`: file-change classification and dirty-marking for bounded watcher batches
135
135
  - `src/hmr/README.md`: HMR strategy, update-layer ownership, and build error presentation
136
136
  - `src/dev-toolbar/README.md`: toolbar enablement, custom clients, and build error event contract
137
- - `src/router/README.md`: route discovery, matching, browser navigation coordination, persistence-aware body morphing, and the shared client navigation pipeline
137
+ - `src/router/README.md`: route discovery (Pages and `*.api.{ts,tsx,js,jsx}` endpoint files), matching, browser navigation coordination, persistence-aware body morphing, and the shared client navigation pipeline
138
138
  - `src/route-renderer/README.md`: rendering orchestration, semantic error pages, dependency resolution, and HTML cache source paths
139
139
  - `src/static-site-generator/README.md`: static build execution, collected Page render failures, and sitemap eligibility from successful route-render metadata
140
140
  - `src/eco/README.md`: `eco` authoring APIs for pages, layouts, and components, including the `LayoutOptions` type contract
@@ -257,6 +257,8 @@ export const helloWorldAlt = defineApiHandler({
257
257
  });
258
258
  ```
259
259
 
260
+ `defineQuery`, `app.query()` and `api.query` handle the HTTP QUERY method (RFC 10008): a safe, idempotent read whose request body carries the query. It takes a `schema.body` like `definePost`, and Ecopages adds no caching, `Accept-Query` or `Vary`; set them on the response if you want them. QUERY here is the method, not the handler context's `query` field (the URL's search parameters).
261
+
260
262
  Group related routes with `defineGroupHandler`. Prefer `api.get` / `api.post` helpers inside the `routes` callback:
261
263
 
262
264
  ```typescript
@@ -281,6 +283,20 @@ Standalone response helpers (`json`, `html`, `redirect`) share the same body emi
281
283
 
282
284
  Register a prebuilt handler with `app.add()`. Use `app.get(path, handler)` only when defining the route inline in `app.ts`.
283
285
 
286
+ The method helpers also accept a handler without `path`, for an export of an endpoint file (`*.api.ts`, `.api.tsx`, `.api.js` or `.api.jsx`), whose path under the pages directory gives the URL. The `api.get` / `api.post` group helpers still require `path`, and `app.add()` and `app.group()` throw for a handler without one.
287
+
288
+ The filesystem form of the same handler is an endpoint file. `src/pages/api/hello.api.ts` answers `/api/hello` with no `app.add()` call:
289
+
290
+ ```typescript
291
+ import { defineGet } from '@ecopages/core';
292
+
293
+ export const GET = defineGet({
294
+ handler: async ({ response }) => response.json({ message: 'Hello World' }),
295
+ });
296
+ ```
297
+
298
+ The file's rules (405 and `Allow`, load errors, `app.ts` routes on the same URL) are in the [Routing docs](https://ecopages.app/docs/core/routing#endpoint-files); the contracts are in `src/router/README.md` and `src/adapters/README.md`. A build of an app with an endpoint file checks each file's exports, then emits the server bundle (`dist/.server/`) even when nothing else registers a handler, so `ecopages start` serves it.
299
+
284
300
  ### 6. Error pages
285
301
 
286
302
  Filesystem `src/pages/404.*` and `500.*` take precedence. For explicit-route apps, register views on the app:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Core package for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@clack/prompts": "^1.7.0",
24
- "@ecopages/file-system": "0.3.1",
24
+ "@ecopages/file-system": "0.4.0",
25
25
  "@ecopages/logger": "^0.2.3",
26
26
  "@ecopages/scripts-injector": "^0.1.5",
27
27
  "@jridgewell/remapping": "^2.3.5",
@@ -35,7 +35,7 @@
35
35
  "ws": "^8.20.1"
36
36
  },
37
37
  "peerDependencies": {
38
- "@ecopages/dev-toolbar": "0.3.1"
38
+ "@ecopages/dev-toolbar": "0.4.0"
39
39
  },
40
40
  "peerDependenciesMeta": {
41
41
  "@ecopages/dev-toolbar": {
@@ -1,5 +1,5 @@
1
1
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
- import type { ApiHandler, ApiHandlerContext, ErrorHandler, Middleware, RouteGroupBuilder, RouteOptions, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
2
+ import type { ApiHandler, ApiHandlerContext, ErrorHandler, MiddlewareContext, MiddlewareList, RouteGroupBuilder, RouteMethod, RouteOptions, RouteSchema, RouteHandlerContext, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
3
3
  import { type HttpErrorPageStatus } from '../../errors/http-error-page-contract.js';
4
4
  import type { ReturnParseCliArgs } from '../../utils/parse-cli-args.js';
5
5
  import { type RuntimeHost } from './runtime-host.js';
@@ -30,13 +30,9 @@ export type EcopagesAppDependencies = {
30
30
  runtimeHost: RuntimeHost;
31
31
  createServerAdapter?: (params: NodeServerAdapterParams) => Promise<NodeServerAdapter>;
32
32
  };
33
- /**
34
- * Handler function type for route handlers
35
- */
36
- export type RouteHandler<TRequest extends Request = Request, TServer = unknown, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = (context: TContext) => Promise<Response> | Response;
37
- export type RouteGroupDefinition<TRequest extends Request = Request, TServer = unknown, TContext extends ApiHandlerContext<TRequest, TServer> = ApiHandlerContext<TRequest, TServer>> = {
33
+ export type RouteGroupDefinition<TRequest extends Request = Request, TServer = unknown> = {
38
34
  prefix: string;
39
- middleware?: readonly Middleware<TRequest, TServer, TContext>[];
35
+ middleware?: MiddlewareList<TRequest, TServer>;
40
36
  routes: readonly ApiHandler<string, TRequest, TServer>[];
41
37
  };
42
38
  export declare class EcopagesApp implements AsyncDisposable {
@@ -58,23 +54,36 @@ export declare class EcopagesApp implements AsyncDisposable {
58
54
  /** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
59
55
  serverAdapter: NodeServerAdapter | undefined;
60
56
  private lifecycle;
57
+ /**
58
+ * Counts `stop()` calls.
59
+ *
60
+ * @remarks
61
+ * A `start()` or `fetch()` that waits for a running stop compares it after the
62
+ * wait, so a later `stop()` cancels it instead of sharing the first stop's promise
63
+ * and letting it start a new session afterwards.
64
+ */
65
+ private stopCount;
61
66
  constructor(options: EcopagesAppRuntimeOptions, dependencies: EcopagesAppDependencies);
62
- private register;
63
- get<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
64
- post<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
65
- put<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
66
- delete<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
67
- patch<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
68
- options<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
69
- head<P extends string, TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(path: P, handler: RouteHandler<Request, unknown, TContext>, options?: RouteOptions<Request, unknown, TContext>): this;
70
- route<P extends string>(path: P, method: ApiHandler['method'], handler: RouteHandler<Request, unknown>, options?: RouteOptions<Request, unknown>): this;
67
+ private method;
68
+ readonly get: RouteMethod<this, Request, unknown>;
69
+ readonly post: RouteMethod<this, Request, unknown>;
70
+ readonly put: RouteMethod<this, Request, unknown>;
71
+ readonly delete: RouteMethod<this, Request, unknown>;
72
+ readonly patch: RouteMethod<this, Request, unknown>;
73
+ readonly options: RouteMethod<this, Request, unknown>;
74
+ readonly head: RouteMethod<this, Request, unknown>;
75
+ /** Registers a handler for the QUERY method, not for `ctx.query`. */
76
+ readonly query: RouteMethod<this, Request, unknown>;
77
+ route<TSchema extends RouteSchema = RouteSchema, TRouteContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(path: string, method: ApiHandler['method'], handler: (context: RouteHandlerContext<TSchema, TRouteContext & MiddlewareContext<TMiddleware>>) => Promise<Response> | Response, options?: RouteOptions<Request, unknown, TSchema, TMiddleware>): this;
71
78
  add(handler: ApiHandler<string, Request, unknown>): this;
72
79
  /**
73
- * Internal method to add route handlers to the API handlers array
80
+ * @remarks
81
+ * The typed handler signature is erased here: the request pipeline builds one context per request
82
+ * and fills its schema fields before the handler runs.
74
83
  */
75
84
  private addRouteHandler;
76
- group<TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>>(prefixOrGroup: string | RouteGroupDefinition<Request, unknown, TContext>, callback?: (builder: RouteGroupBuilder<Request, unknown, TContext>) => void, options?: {
77
- middleware?: readonly Middleware<Request, unknown, TContext>[];
85
+ group<TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(prefixOrGroup: string | RouteGroupDefinition<Request, unknown>, callback?: (builder: RouteGroupBuilder<Request, unknown, TContext & MiddlewareContext<TMiddleware>>) => void, options?: {
86
+ middleware?: TMiddleware;
78
87
  }): this;
79
88
  private registerGroup;
80
89
  /**
@@ -173,7 +182,9 @@ export declare class EcopagesApp implements AsyncDisposable {
173
182
  *
174
183
  * @remarks
175
184
  * Resolves without a server when `stop()` is called before startup finishes;
176
- * that startup does not continue.
185
+ * that startup does not continue. It still rejects when the step in flight
186
+ * fails, such as a bind failure. A call made while `stop()` runs waits for it,
187
+ * and resolves without a server when another `stop()` arrives in that wait.
177
188
  */
178
189
  start(onAppStart?: OnAppStartCallback): Promise<NodeServerInstance | void>;
179
190
  private bootServer;
@@ -51,6 +51,15 @@ export class EcopagesApp {
51
51
  /** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
52
52
  serverAdapter;
53
53
  lifecycle = { phase: 'idle' };
54
+ /**
55
+ * Counts `stop()` calls.
56
+ *
57
+ * @remarks
58
+ * A `start()` or `fetch()` that waits for a running stop compares it after the
59
+ * wait, so a later `stop()` cancels it instead of sharing the first stop's promise
60
+ * and letting it start a new session afterwards.
61
+ */
62
+ stopCount = 0;
54
63
  constructor(options, dependencies) {
55
64
  this.runtimeLabel = resolveProcessRuntimeLabel();
56
65
  this.appConfig = options.appConfig;
@@ -61,38 +70,29 @@ export class EcopagesApp {
61
70
  dependencies.createServerAdapter ?? (async (params) => new NodeServerAdapter(params));
62
71
  startupTrace.markConfigReady();
63
72
  }
64
- register(path, method, handler, options) {
65
- return this.addRouteHandler(path, method, handler, options?.middleware, options?.schema);
66
- }
67
- get(path, handler, options) {
68
- return this.register(path, 'GET', handler, options);
69
- }
70
- post(path, handler, options) {
71
- return this.register(path, 'POST', handler, options);
72
- }
73
- put(path, handler, options) {
74
- return this.register(path, 'PUT', handler, options);
75
- }
76
- delete(path, handler, options) {
77
- return this.register(path, 'DELETE', handler, options);
78
- }
79
- patch(path, handler, options) {
80
- return this.register(path, 'PATCH', handler, options);
81
- }
82
- options(path, handler, options) {
83
- return this.register(path, 'OPTIONS', handler, options);
84
- }
85
- head(path, handler, options) {
86
- return this.register(path, 'HEAD', handler, options);
87
- }
73
+ method(method) {
74
+ return (path, handler, options) => this.addRouteHandler(path, method, handler, options?.middleware, options?.schema);
75
+ }
76
+ get = this.method('GET');
77
+ post = this.method('POST');
78
+ put = this.method('PUT');
79
+ delete = this.method('DELETE');
80
+ patch = this.method('PATCH');
81
+ options = this.method('OPTIONS');
82
+ head = this.method('HEAD');
83
+ /** Registers a handler for the QUERY method, not for `ctx.query`. */
84
+ query = this.method('QUERY');
88
85
  route(path, method, handler, options) {
89
- return this.register(path, method, handler, options);
86
+ return this.method(method)(path, handler, options);
90
87
  }
91
88
  add(handler) {
89
+ invariant(handler.path !== '', `The ${handler.method} handler has no path. Export it from an endpoint file (\`*.api.ts\`, \`.api.tsx\`, \`.api.js\` or \`.api.jsx\`) under the pages directory, or give it a \`path\` to register it with app.add().`);
92
90
  return this.addRouteHandler(handler.path, handler.method, handler.handler, handler.middleware, handler.schema);
93
91
  }
94
92
  /**
95
- * Internal method to add route handlers to the API handlers array
93
+ * @remarks
94
+ * The typed handler signature is erased here: the request pipeline builds one context per request
95
+ * and fills its schema fields before the handler runs.
96
96
  */
97
97
  addRouteHandler(path, method, handler, middleware, schema) {
98
98
  invariant(typeof path === 'string', `Invalid route path for ${method}: expected a string path starting with "/" but received ${Object.prototype.toString.call(path)}. If you're passing a prebuilt ApiHandler, use app.add(handler).`);
@@ -101,7 +101,7 @@ export class EcopagesApp {
101
101
  path,
102
102
  method,
103
103
  handler: handler,
104
- middleware: middleware,
104
+ middleware,
105
105
  schema,
106
106
  });
107
107
  return this;
@@ -111,19 +111,12 @@ export class EcopagesApp {
111
111
  return this.registerGroup(prefixOrGroup);
112
112
  }
113
113
  const normalizedPrefix = prefixOrGroup.endsWith('/') ? prefixOrGroup.slice(0, -1) : prefixOrGroup;
114
- const groupMiddleware = (options?.middleware ?? []);
115
- const createHandler = (method) => {
116
- return ((path, handler, routeOptions) => {
117
- const combinedMiddleware = [
118
- ...groupMiddleware,
119
- ...(routeOptions?.middleware ?? []),
120
- ];
121
- const fullPath = path === '/' ? normalizedPrefix : `${normalizedPrefix}${path}`;
122
- this.addRouteHandler(fullPath, method, handler, combinedMiddleware.length > 0
123
- ? combinedMiddleware
124
- : undefined, routeOptions?.schema);
125
- return builder;
126
- });
114
+ const groupMiddleware = options?.middleware ?? [];
115
+ const createHandler = (method) => (path, handler, routeOptions) => {
116
+ const combinedMiddleware = [...groupMiddleware, ...(routeOptions?.middleware ?? [])];
117
+ const fullPath = path === '/' ? normalizedPrefix : `${normalizedPrefix}${path}`;
118
+ this.addRouteHandler(fullPath, method, handler, combinedMiddleware.length > 0 ? combinedMiddleware : undefined, routeOptions?.schema);
119
+ return builder;
127
120
  };
128
121
  const builder = {
129
122
  get: createHandler('GET'),
@@ -133,6 +126,7 @@ export class EcopagesApp {
133
126
  patch: createHandler('PATCH'),
134
127
  options: createHandler('OPTIONS'),
135
128
  head: createHandler('HEAD'),
129
+ query: createHandler('QUERY'),
136
130
  };
137
131
  callback?.(builder);
138
132
  return this;
@@ -141,6 +135,7 @@ export class EcopagesApp {
141
135
  const normalizedPrefix = group.prefix.endsWith('/') ? group.prefix.slice(0, -1) : group.prefix;
142
136
  const groupMiddleware = group.middleware ?? [];
143
137
  for (const route of group.routes) {
138
+ invariant(route.path !== '', `The ${route.method} handler in group "${group.prefix}" has no path. Export it from an endpoint file (\`*.api.ts\`, \`.api.tsx\`, \`.api.js\` or \`.api.jsx\`) under the pages directory, or give it a \`path\` ("/" for the group root) to register it with app.group().`);
144
139
  const normalizedPath = route.path.startsWith('/') ? route.path : `/${route.path}`;
145
140
  const fullPath = route.path === '/' ? normalizedPrefix : `${normalizedPrefix}${normalizedPath}`;
146
141
  const combinedMiddleware = [...groupMiddleware, ...(route.middleware ?? [])];
@@ -333,7 +328,9 @@ export class EcopagesApp {
333
328
  *
334
329
  * @remarks
335
330
  * Resolves without a server when `stop()` is called before startup finishes;
336
- * that startup does not continue.
331
+ * that startup does not continue. It still rejects when the step in flight
332
+ * fails, such as a bind failure. A call made while `stop()` runs waits for it,
333
+ * and resolves without a server when another `stop()` arrives in that wait.
337
334
  */
338
335
  async start(onAppStart) {
339
336
  if (onAppStart) {
@@ -388,7 +385,10 @@ export class EcopagesApp {
388
385
  return this.isActive(session) ? session : undefined;
389
386
  }
390
387
  if (current.phase === 'stopping') {
388
+ const stopCount = this.stopCount;
391
389
  await current.stopped;
390
+ if (this.stopCount !== stopCount)
391
+ return undefined;
392
392
  return await this.getReadySession();
393
393
  }
394
394
  const ready = this.initializeSession();
@@ -412,7 +412,7 @@ export class EcopagesApp {
412
412
  const { build, preview, serveOnly, keepGoing } = this.cliArgs;
413
413
  if (preview && serveOnly) {
414
414
  const previewOrigin = await session.adapter.servePreviewOnly();
415
- if (previewOrigin)
415
+ if (previewOrigin && this.isActive(session))
416
416
  await this.notifyListening(previewOrigin);
417
417
  return;
418
418
  }
@@ -420,7 +420,7 @@ export class EcopagesApp {
420
420
  appLogger.debugTime('Building static pages');
421
421
  const previewOrigin = await session.adapter.buildStatic({ preview, keepGoing });
422
422
  appLogger.debugTimeEnd('Building static pages');
423
- if (preview && previewOrigin)
423
+ if (preview && previewOrigin && this.isActive(session))
424
424
  await this.notifyListening(previewOrigin);
425
425
  return;
426
426
  }
@@ -523,6 +523,7 @@ export class EcopagesApp {
523
523
  * releases whatever that step created.
524
524
  */
525
525
  stop(force = true) {
526
+ this.stopCount += 1;
526
527
  const current = this.lifecycle;
527
528
  if (current.phase === 'idle' || current.phase === 'stopped')
528
529
  return Promise.resolve();
@@ -1,7 +1,7 @@
1
1
  import { WebSocketServer } from 'ws';
2
2
  import type { AppRuntime } from '../../config/assembly/app-runtime.js';
3
3
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
4
- import type { EcopagesWebSocketHandler } from '../../types/contracts.js';
4
+ import type { EcopagesWebSocketHandler, ErrorHandler } from '../../types/contracts.js';
5
5
  import type { ServerRequestPipeline } from '../shared/runtime/server-request-pipeline.js';
6
6
  import type { NodeServerInstance } from './server-adapter.js';
7
7
  export type DevSessionOptions = {
@@ -9,6 +9,8 @@ export type DevSessionOptions = {
9
9
  runtime: AppRuntime;
10
10
  server: NodeServerInstance;
11
11
  requestPipeline: ServerRequestPipeline;
12
+ /** The `app.onError` handler a prewarmed endpoint's errors resolve with. */
13
+ errorHandler?: ErrorHandler;
12
14
  websocketHandlers: Map<string, EcopagesWebSocketHandler<unknown, Record<string, string>>>;
13
15
  onDevelopmentRestart?: (changedFile: string) => Promise<void>;
14
16
  configureResponseHandlers: () => void;
@@ -62,7 +62,10 @@ export class DevSession {
62
62
  this.prewarm = startDevStaticRoutePrewarm({
63
63
  pathnames: [...new Set(appConfig.devPrewarmPaths)],
64
64
  signal: this.prewarmAbort.signal,
65
- renderPath: (pathname) => this.options.requestPipeline.renderDevPrewarmPath(pathname, runtime.origin),
65
+ renderPath: (pathname) => this.options.requestPipeline.renderDevPrewarmPath(pathname, runtime.origin, {
66
+ errorHandler: this.options.errorHandler,
67
+ serverInstance: this.options.server,
68
+ }),
66
69
  });
67
70
  }
68
71
  dispose() {
@@ -45,6 +45,11 @@ export declare class NodeRuntimeHost {
45
45
  * Client disconnects are treated as normal aborts and are not logged. Other
46
46
  * failures here (the response write, or an uninitialised adapter) are logged
47
47
  * with their stack and answered with 500.
48
+ *
49
+ * The hostname is resolved to its first address before `listen()`, which is
50
+ * what Node does internally. Bun instead tries every address the name resolves
51
+ * to, so when `localhost:<port>` is taken on `::1` it binds `127.0.0.1` and
52
+ * never reports `EADDRINUSE`, leaving two servers behind one origin.
48
53
  */
49
54
  start(serveOptions: NodeRuntimeServeOptions): Promise<NodeServerInstance>;
50
55
  /**
@@ -1,3 +1,4 @@
1
+ import { lookup } from 'node:dns/promises';
1
2
  import { createServer } from 'node:http';
2
3
  import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../constants.js';
3
4
  import { appLogger } from '../../global/app-logger.js';
@@ -38,10 +39,16 @@ export class NodeRuntimeHost {
38
39
  * Client disconnects are treated as normal aborts and are not logged. Other
39
40
  * failures here (the response write, or an uninitialised adapter) are logged
40
41
  * with their stack and answered with 500.
42
+ *
43
+ * The hostname is resolved to its first address before `listen()`, which is
44
+ * what Node does internally. Bun instead tries every address the name resolves
45
+ * to, so when `localhost:<port>` is taken on `::1` it binds `127.0.0.1` and
46
+ * never reports `EADDRINUSE`, leaving two servers behind one origin.
41
47
  */
42
48
  async start(serveOptions) {
43
49
  const hostname = String(serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME);
44
50
  const port = Number(serveOptions.port ?? DEFAULT_ECOPAGES_PORT);
51
+ const { address } = await lookup(hostname);
45
52
  let server;
46
53
  server = this.serverFactory(async (req, res) => {
47
54
  try {
@@ -67,7 +74,7 @@ export class NodeRuntimeHost {
67
74
  });
68
75
  await new Promise((resolve, reject) => {
69
76
  server.once('error', reject);
70
- server.listen(port, hostname, () => {
77
+ server.listen(port, address, () => {
71
78
  server.off('error', reject);
72
79
  resolve();
73
80
  });
@@ -149,6 +149,7 @@ export class NodeServerAdapter {
149
149
  await this.requestPipeline.initializeRouteHandling({
150
150
  staticRoutes: this.staticRoutes,
151
151
  errorPageLoaders: this.errorPageLoaders,
152
+ apiHandlers: this.apiHandlers,
152
153
  });
153
154
  }
154
155
  getServerOptions() {
@@ -167,10 +168,11 @@ export class NodeServerAdapter {
167
168
  async buildStatic(options) {
168
169
  await this.initialize();
169
170
  const baseUrl = resolveServeRuntimeOrigin(this.serveOptions);
170
- const { router, routeRendererFactory } = this.requestPipeline.getStaticBuildContext();
171
+ const { router, routeRendererFactory, importServerModule } = this.requestPipeline.getStaticBuildContext();
171
172
  await this.staticBuilder.build({ baseUrl, force: options?.force, keepGoing: options?.keepGoing }, {
172
173
  router,
173
174
  routeRendererFactory,
175
+ importServerModule,
174
176
  staticRoutes: this.staticRoutes,
175
177
  errorPageLoaders: this.errorPageLoaders,
176
178
  });
@@ -350,6 +352,7 @@ export class NodeServerAdapter {
350
352
  runtime: this.runtime,
351
353
  server,
352
354
  requestPipeline: this.requestPipeline,
355
+ errorHandler: this.errorHandler,
353
356
  websocketHandlers: this.websocketHandlers,
354
357
  onDevelopmentRestart: this.onDevelopmentRestart,
355
358
  configureResponseHandlers: () => this.requestPipeline.configureResponseHandlers({
@@ -359,6 +362,7 @@ export class NodeServerAdapter {
359
362
  createWatchRefreshCallback: () => this.requestPipeline.createWatchRefreshCallback({
360
363
  staticRoutes: this.staticRoutes,
361
364
  errorPageLoaders: this.errorPageLoaders,
365
+ apiHandlers: this.apiHandlers,
362
366
  }),
363
367
  });
364
368
  await this.devSession.start();
@@ -24,6 +24,14 @@ export declare class HmrManager implements IHmrManager {
24
24
  private readonly fallbackStrategy;
25
25
  private readonly scriptEntrypointChangeHandlers;
26
26
  private readonly registeredScriptReloadRequired;
27
+ /**
28
+ * Error messages of changed files whose strategy or script-change handler threw, by file path.
29
+ *
30
+ * @remarks
31
+ * An entry stays until that file processes without error, because nothing records it again on a later
32
+ * request the way a dev-transform failure is.
33
+ */
34
+ private readonly fileChangeErrors;
27
35
  protected readonly entrypointRegistry: DevTransformEntrypointRegistry;
28
36
  protected readonly browserBundleService: BrowserBundleService;
29
37
  protected readonly invalidationService: DevelopmentInvalidationService;
@@ -98,11 +106,13 @@ export declare class HmrManager implements IHmrManager {
98
106
  getWatchedFiles(): Map<string, string>;
99
107
  getRegisteredEntrypoints(): ReadonlyMap<string, ResolvedHmrEntrypoint>;
100
108
  /**
101
- * Sends a browser that just connected the build errors of modules that still fail to transpile.
109
+ * Sends a browser that just connected the build errors of modules that still fail to transpile, and of
110
+ * changed files whose last processing failed.
102
111
  *
103
112
  * @remarks
104
113
  * A build error is broadcast while the failing module is served, which can happen before the page's HMR
105
- * socket connects. Without this replay that browser would never show the error.
114
+ * socket connects. A change error can share its batch with a `reload`, which drops the error shown before
115
+ * it. Without this replay that browser would never show the error.
106
116
  */
107
117
  sendPendingBuildErrors(client: {
108
118
  send(payload: string): void;
@@ -31,6 +31,14 @@ export class HmrManager {
31
31
  fallbackStrategy = new DefaultHmrStrategy();
32
32
  scriptEntrypointChangeHandlers = [];
33
33
  registeredScriptReloadRequired = new Set();
34
+ /**
35
+ * Error messages of changed files whose strategy or script-change handler threw, by file path.
36
+ *
37
+ * @remarks
38
+ * An entry stays until that file processes without error, because nothing records it again on a later
39
+ * request the way a dev-transform failure is.
40
+ */
41
+ fileChangeErrors = new Map();
34
42
  entrypointRegistry;
35
43
  browserBundleService;
36
44
  invalidationService;
@@ -196,10 +204,13 @@ export class HmrManager {
196
204
  for (const filePath of uniqueFilePaths) {
197
205
  try {
198
206
  events.push(...(await this.processFileChange(filePath)));
207
+ this.fileChangeErrors.delete(filePath);
199
208
  }
200
209
  catch (error) {
201
210
  appLogger.error(error instanceof Error ? error : new Error(String(error)));
202
- events.push({ type: 'error', message: error instanceof Error ? error.message : String(error) });
211
+ const message = error instanceof Error ? error.message : String(error);
212
+ this.fileChangeErrors.set(filePath, message);
213
+ events.push({ type: 'error', message });
203
214
  }
204
215
  }
205
216
  this.broadcastBatchEvents(events, options, uniqueFilePaths);
@@ -279,18 +290,8 @@ export class HmrManager {
279
290
  */
280
291
  async runRegisteredEntrypointChangeHandlers(filePath) {
281
292
  for (const handler of this.scriptEntrypointChangeHandlers) {
282
- try {
283
- const result = await handler(filePath);
284
- if (result === true) {
285
- this.registeredScriptReloadRequired.add(path.resolve(filePath));
286
- }
287
- }
288
- catch (error) {
289
- const message = error instanceof Error
290
- ? error.message
291
- : `Failed to handle registered script entrypoint change for ${filePath}: ${String(error)}`;
292
- this.broadcast({ type: 'error', message });
293
- throw error;
293
+ if ((await handler(filePath)) === true) {
294
+ this.registeredScriptReloadRequired.add(path.resolve(filePath));
294
295
  }
295
296
  }
296
297
  }
@@ -316,14 +317,16 @@ export class HmrManager {
316
317
  return this.entrypointRegistry.getRegisteredEntrypoints();
317
318
  }
318
319
  /**
319
- * Sends a browser that just connected the build errors of modules that still fail to transpile.
320
+ * Sends a browser that just connected the build errors of modules that still fail to transpile, and of
321
+ * changed files whose last processing failed.
320
322
  *
321
323
  * @remarks
322
324
  * A build error is broadcast while the failing module is served, which can happen before the page's HMR
323
- * socket connects. Without this replay that browser would never show the error.
325
+ * socket connects. A change error can share its batch with a `reload`, which drops the error shown before
326
+ * it. Without this replay that browser would never show the error.
324
327
  */
325
328
  sendPendingBuildErrors(client) {
326
- for (const message of this.devTransformServer.getFailureMessages()) {
329
+ for (const message of [...this.devTransformServer.getFailureMessages(), ...this.fileChangeErrors.values()]) {
327
330
  client.send(JSON.stringify({ type: 'error', message }));
328
331
  }
329
332
  }
@@ -355,6 +358,7 @@ export class HmrManager {
355
358
  this.readyRuntimes.clear();
356
359
  this.scriptEntrypointChangeHandlers.length = 0;
357
360
  this.registeredScriptReloadRequired.clear();
361
+ this.fileChangeErrors.clear();
358
362
  this.entrypointRegistry.clearAll();
359
363
  this.devTransformServer.reset();
360
364
  this.buildInputIndex.clearConsumer('entrypoint');
@@ -1,46 +1,61 @@
1
- import type { ApiHandler, ApiHandlerContext, Middleware, RenderOptions, RouteSchema, TypedGroupHandlerContext } from '../../../types/contracts.js';
1
+ import type { ApiHandler, ApiHandlerContext, MiddlewareContext, MiddlewareList, RenderOptions, RouteHandlerContext, RouteSchema } from '../../../types/contracts.js';
2
2
  type UniversalContext = ApiHandlerContext<Request, unknown>;
3
- type SchemaHandlerContext<TSchema extends RouteSchema | undefined, TContext extends UniversalContext> = TSchema extends RouteSchema ? TypedGroupHandlerContext<TSchema, TContext> : TContext;
4
- type DefineApiHandlerInput<TPath extends string, TSchema extends RouteSchema | undefined, TContext extends UniversalContext> = Omit<ApiHandler<TPath, Request, unknown>, 'handler' | 'middleware' | 'schema' | 'method'> & {
5
- handler: (context: SchemaHandlerContext<TSchema, TContext>) => Promise<Response> | Response;
6
- middleware?: Middleware<Request, unknown, TContext>[];
3
+ type DefineApiHandlerInput<TPath extends string, TSchema extends RouteSchema, TContext extends UniversalContext, TMiddleware extends MiddlewareList<Request, unknown>> = Omit<ApiHandler<TPath, Request, unknown>, 'handler' | 'middleware' | 'schema' | 'method' | 'path'> & {
4
+ handler: (context: RouteHandlerContext<TSchema, TContext & MiddlewareContext<TMiddleware>>) => Promise<Response> | Response;
5
+ middleware?: TMiddleware;
7
6
  schema?: TSchema;
8
7
  };
9
- export declare function defineApiHandler<TPath extends string, TSchema extends RouteSchema | undefined = undefined, TContext extends UniversalContext = UniversalContext>(handler: DefineApiHandlerInput<TPath, TSchema, TContext> & {
8
+ /**
9
+ * A define helper bound to one HTTP method.
10
+ *
11
+ * @typeParam TContext - The context the handler starts from: the base context, or the group's
12
+ * @typeParam TPathOptional - Whether `path` may be omitted, as an endpoint file export omits it
13
+ *
14
+ * @remarks
15
+ * Without `path` the returned `path` is `''`, which `app.add` and `app.group` reject.
16
+ */
17
+ type DefineApiMethod<TContext extends UniversalContext, TPathOptional extends boolean = false> = <const TPath extends string = '', TSchema extends RouteSchema = RouteSchema, THandlerContext extends TContext = TContext, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, THandlerContext, TMiddleware> & (TPathOptional extends true ? {
18
+ path?: TPath;
19
+ } : {
20
+ path: TPath;
21
+ })) => ApiHandler<TPath, Request, unknown>;
22
+ /**
23
+ * @remarks
24
+ * The returned handler's context is the base context: the typed one, narrowed by the schema and the
25
+ * middleware, is erased by the cast, as `app.add` would erase it. The middleware list needs no cast.
26
+ */
27
+ export declare function defineApiHandler<TPath extends string, TSchema extends RouteSchema = RouteSchema, TContext extends UniversalContext = UniversalContext, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
28
+ path: TPath;
10
29
  method: ApiHandler<TPath, Request, unknown>['method'];
11
30
  }): ApiHandler<TPath, Request, unknown>;
12
- declare const defineApiMethod: <M extends ApiHandler["method"]>(method: M) => <const TPath extends string, TSchema extends RouteSchema | undefined = undefined, TContext extends UniversalContext = UniversalContext>(handler: DefineApiHandlerInput<TPath, TSchema, TContext> & {
13
- path: TPath;
14
- }) => ApiHandler<TPath, Request, unknown>;
15
- export declare const defineGet: ReturnType<typeof defineApiMethod<'GET'>>;
16
- export declare const definePost: ReturnType<typeof defineApiMethod<'POST'>>;
17
- export declare const definePut: ReturnType<typeof defineApiMethod<'PUT'>>;
18
- export declare const defineDelete: ReturnType<typeof defineApiMethod<'DELETE'>>;
19
- export declare const definePatch: ReturnType<typeof defineApiMethod<'PATCH'>>;
20
- export declare const defineOptions: ReturnType<typeof defineApiMethod<'OPTIONS'>>;
21
- export declare const defineHead: ReturnType<typeof defineApiMethod<'HEAD'>>;
31
+ /** The method helper an endpoint file exports from: `path` may be omitted. */
32
+ type EndpointMethod = DefineApiMethod<UniversalContext, true>;
33
+ export declare const defineGet: EndpointMethod;
34
+ export declare const definePost: EndpointMethod;
35
+ export declare const definePut: EndpointMethod;
36
+ export declare const defineDelete: EndpointMethod;
37
+ export declare const definePatch: EndpointMethod;
38
+ export declare const defineOptions: EndpointMethod;
39
+ export declare const defineHead: EndpointMethod;
40
+ /** Defines a handler for the QUERY method, a safe, idempotent read whose request body carries the query. */
41
+ export declare const defineQuery: EndpointMethod;
22
42
  export declare function json(data: unknown, options?: RenderOptions): Response;
23
43
  export declare function html(content: string, options?: RenderOptions): Response;
24
44
  export declare function redirect(url: string, status?: number): Response;
25
45
  export interface GroupHandler<TPrefix extends string = string> {
26
46
  prefix: TPrefix;
27
- middleware?: readonly Middleware<Request, unknown, any>[];
47
+ middleware?: MiddlewareList<Request, unknown>;
28
48
  routes: readonly ApiHandler<string, Request, unknown>[];
29
49
  }
30
50
  type GroupDefineHandler<TContext extends UniversalContext> = {
31
- <const TPath extends string, TSchema extends RouteSchema | undefined = undefined>(handler: DefineApiHandlerInput<TPath, TSchema, TContext> & {
51
+ <const TPath extends string, TSchema extends RouteSchema = RouteSchema, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
32
52
  path: TPath;
33
53
  method: ApiHandler<TPath, Request, unknown>['method'];
34
54
  }): ApiHandler<TPath, Request, unknown>;
35
- get: ReturnType<typeof defineApiMethod<'GET'>>;
36
- post: ReturnType<typeof defineApiMethod<'POST'>>;
37
- put: ReturnType<typeof defineApiMethod<'PUT'>>;
38
- delete: ReturnType<typeof defineApiMethod<'DELETE'>>;
39
- patch: ReturnType<typeof defineApiMethod<'PATCH'>>;
40
- options: ReturnType<typeof defineApiMethod<'OPTIONS'>>;
41
- head: ReturnType<typeof defineApiMethod<'HEAD'>>;
55
+ } & {
56
+ [M in ApiHandler['method'] as Lowercase<M>]: DefineApiMethod<TContext>;
42
57
  };
43
- export declare function defineGroupHandler<TPrefix extends string, TMiddleware extends readonly Middleware<Request, unknown, any>[] = [], TContext extends UniversalContext = TMiddleware extends readonly Middleware<Request, unknown, infer TGroupContext>[] ? TGroupContext : UniversalContext>(config: {
58
+ export declare function defineGroupHandler<TPrefix extends string, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>, TContext extends UniversalContext = UniversalContext & MiddlewareContext<TMiddleware>>(config: {
44
59
  prefix: TPrefix;
45
60
  middleware?: TMiddleware;
46
61
  routes: (api: GroupDefineHandler<TContext>) => readonly ApiHandler<string, Request, unknown>[];