@ecopages/core 0.9.0 → 0.10.1

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 (53) hide show
  1. package/package.json +3 -3
  2. package/src/adapters/node/create-app.d.ts +4 -4
  3. package/src/adapters/shared/http/api-request-pipeline.js +8 -6
  4. package/src/adapters/shared/http/define-api-handler.d.ts +8 -8
  5. package/src/adapters/shared/http/file-route-middleware-pipeline.d.ts +10 -11
  6. package/src/adapters/shared/http/file-route-middleware-pipeline.js +5 -6
  7. package/src/adapters/shared/http/fs-server-response-matcher.js +12 -4
  8. package/src/adapters/shared/http/run-middleware-chain.d.ts +29 -2
  9. package/src/adapters/shared/http/run-middleware-chain.js +108 -10
  10. package/src/adapters/shared/runtime/render-context.js +2 -21
  11. package/src/build/runtime/build-request-policy.js +4 -1
  12. package/src/build.d.ts +1 -0
  13. package/src/build.js +1 -0
  14. package/src/declarations.d.ts +2 -0
  15. package/src/eco/eco.browser.js +6 -26
  16. package/src/eco/eco.js +5 -16
  17. package/src/eco/page-data-hooks.d.ts +27 -0
  18. package/src/eco/page-data-hooks.js +64 -0
  19. package/src/eco/page-layout-normalization.d.ts +2 -2
  20. package/src/index.d.ts +1 -0
  21. package/src/index.js +1 -0
  22. package/src/integration.d.ts +1 -1
  23. package/src/integration.js +1 -1
  24. package/src/middleware/create-middleware.d.ts +41 -0
  25. package/src/middleware/create-middleware.js +72 -0
  26. package/src/plugins/eco-component-meta-plugin.d.ts +33 -0
  27. package/src/plugins/eco-component-meta-plugin.js +170 -23
  28. package/src/route-renderer/error-pages/error-page-renderer.js +29 -1
  29. package/src/route-renderer/explicit-view-render-preparation.d.ts +18 -0
  30. package/src/route-renderer/explicit-view-render-preparation.js +53 -7
  31. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.d.ts +15 -5
  32. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.js +27 -15
  33. package/src/route-renderer/orchestration/integration-renderer.d.ts +3 -1
  34. package/src/route-renderer/orchestration/integration-renderer.js +10 -6
  35. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.builder.js +0 -3
  36. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +4 -0
  37. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +6 -1
  38. package/src/route-renderer/page-loading/page-module-loader.d.ts +27 -7
  39. package/src/route-renderer/page-loading/page-module-loader.js +46 -15
  40. package/src/route-renderer/page-loading/resolved-page-dependencies.js +14 -9
  41. package/src/static-site-generator/static-site-generator.d.ts +0 -1
  42. package/src/static-site-generator/static-site-generator.js +6 -6
  43. package/src/types/contracts.d.ts +196 -140
  44. package/src/types/eco-api-types.d.ts +76 -46
  45. package/src/types/locals-brand.d.ts +9 -0
  46. package/src/types/locals-brand.js +9 -0
  47. package/src/types/middleware-types.d.ts +143 -0
  48. package/src/types/middleware-types.js +1 -0
  49. package/src/types/public-types.d.ts +3 -2
  50. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.d.ts +0 -4
  51. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.js +0 -30
  52. package/src/utils/locals-utils.d.ts +0 -15
  53. package/src/utils/locals-utils.js +0 -34
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "Core package for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@clack/prompts": "^1.7.0",
27
- "@ecopages/file-system": "0.9.0",
27
+ "@ecopages/file-system": "0.10.1",
28
28
  "@ecopages/logger": "^0.2.3",
29
29
  "@ecopages/scripts-injector": "^0.1.5",
30
30
  "@jridgewell/remapping": "^2.3.5",
@@ -37,7 +37,7 @@
37
37
  "ws": "^8.20.1"
38
38
  },
39
39
  "peerDependencies": {
40
- "@ecopages/dev-toolbar": "0.9.0"
40
+ "@ecopages/dev-toolbar": "0.10.1"
41
41
  },
42
42
  "peerDependenciesMeta": {
43
43
  "@ecopages/dev-toolbar": {
@@ -1,5 +1,5 @@
1
1
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
- import type { ApiHandler, ApiHandlerContext, ErrorHandler, MiddlewareContext, MiddlewareList, RouteGroupBuilder, RouteMethod, RouteOptions, RouteSchema, RouteHandlerContext, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
2
+ import type { ApiHandler, ApiHandlerContext, ErrorHandler, WithMiddlewareLocals, MiddlewareList, NoMiddlewareList, RouteGroupBuilder, RouteMethod, RouteOptions, RouteSchema, RouteHandlerContext, 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';
@@ -34,7 +34,7 @@ export type EcopagesAppDependencies = {
34
34
  };
35
35
  export type RouteGroupDefinition<TRequest extends Request = Request, TServer = unknown> = {
36
36
  prefix: string;
37
- middleware?: MiddlewareList<TRequest, TServer>;
37
+ middleware?: MiddlewareList;
38
38
  routes: readonly ApiHandler<string, TRequest, TServer>[];
39
39
  };
40
40
  export declare class EcopagesApp implements AsyncDisposable {
@@ -77,7 +77,7 @@ export declare class EcopagesApp implements AsyncDisposable {
77
77
  readonly head: RouteMethod<this, Request, unknown>;
78
78
  /** Registers a handler for the QUERY method, not for `ctx.query`. */
79
79
  readonly query: RouteMethod<this, Request, unknown>;
80
- 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;
80
+ route<TSchema extends RouteSchema = RouteSchema, TRouteContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>, const TMiddleware extends MiddlewareList = NoMiddlewareList>(path: string, method: ApiHandler['method'], handler: (context: RouteHandlerContext<TSchema, WithMiddlewareLocals<TRouteContext, TMiddleware>>) => Promise<Response> | Response, options?: RouteOptions<TSchema, TMiddleware>): this;
81
81
  add(handler: ApiHandler<string, Request, unknown>): this;
82
82
  /**
83
83
  * @remarks
@@ -85,7 +85,7 @@ export declare class EcopagesApp implements AsyncDisposable {
85
85
  * and fills its schema fields before the handler runs.
86
86
  */
87
87
  private addRouteHandler;
88
- 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?: {
88
+ group<TContext extends ApiHandlerContext<Request, unknown> = ApiHandlerContext<Request, unknown>, const TMiddleware extends MiddlewareList = NoMiddlewareList>(prefixOrGroup: string | RouteGroupDefinition<Request, unknown>, callback?: (builder: RouteGroupBuilder<Request, unknown, WithMiddlewareLocals<TContext, TMiddleware>>) => void, options?: {
89
89
  middleware?: TMiddleware;
90
90
  }): this;
91
91
  private registerGroup;
@@ -1,16 +1,20 @@
1
- import { createRequire } from '../../../utils/locals-utils.js';
2
1
  import { HttpError } from '../../../errors/http-error.js';
3
2
  import { ApiResponseBuilder } from './api-response.js';
3
+ import { flattenMiddleware } from '../../../middleware/create-middleware.js';
4
4
  import { runMiddlewareChain } from './run-middleware-chain.js';
5
5
  import { matchParsedSegmentPath, parseSegmentPath, compileSegmentPattern, } from '../../../router/server/segment-path-matcher.js';
6
6
  import { appLogger } from '../../../global/app-logger.js';
7
7
  import { isNodeClientAbortError } from '../../node/http-request-bridge.js';
8
8
  import { validateRequest } from '../../../validation/validate-request.js';
9
9
  import { parseSearchParams } from '../../../router/server/parse-search-params.js';
10
+ function validatedMiddleware(handler) {
11
+ flattenMiddleware(handler.middleware, `route ${handler.method} ${handler.path}`);
12
+ return handler;
13
+ }
10
14
  export function compileApiRoutes(handlers) {
11
15
  return handlers
12
16
  .map((handler) => ({
13
- handler,
17
+ handler: validatedMiddleware(handler),
14
18
  method: (handler.method || 'GET').toUpperCase(),
15
19
  pattern: compileSegmentPattern(handler.path, 'api'),
16
20
  }))
@@ -96,15 +100,13 @@ export class ApiRequestPipeline {
96
100
  return new Response('Internal Server Error', { status: 500 });
97
101
  }
98
102
  createContext(request, params, serverInstance) {
99
- const locals = {};
100
103
  return {
101
104
  request,
102
105
  params,
103
106
  query: parseSearchParams(new URL(request.url).searchParams),
104
107
  response: new ApiResponseBuilder(),
105
108
  server: serverInstance,
106
- locals,
107
- require: createRequire(() => locals),
109
+ locals: {},
108
110
  services: {
109
111
  cache: this.getCacheService(),
110
112
  },
@@ -203,7 +205,7 @@ export class ApiRequestPipeline {
203
205
  }
204
206
  }
205
207
  async runMiddlewareChain(context, routeConfig) {
206
- const middleware = routeConfig.middleware ?? [];
208
+ const middleware = flattenMiddleware(routeConfig.middleware, `route ${routeConfig.method} ${routeConfig.path}`);
207
209
  return runMiddlewareChain(middleware, context, async () => await routeConfig.handler(context));
208
210
  }
209
211
  }
@@ -1,7 +1,7 @@
1
- import type { ApiHandler, ApiHandlerContext, MiddlewareContext, MiddlewareList, RenderOptions, RouteHandlerContext, RouteSchema } from '../../../types/contracts.js';
1
+ import type { ApiHandler, ApiHandlerContext, WithMiddlewareLocals, MiddlewareList, NoMiddlewareList, RenderOptions, RouteHandlerContext, RouteSchema } from '../../../types/contracts.js';
2
2
  type UniversalContext = ApiHandlerContext<Request, unknown>;
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;
3
+ type DefineApiHandlerInput<TPath extends string, TSchema extends RouteSchema, TContext extends UniversalContext, TMiddleware extends MiddlewareList> = Omit<ApiHandler<TPath, Request, unknown>, 'handler' | 'middleware' | 'schema' | 'method' | 'path'> & {
4
+ handler: (context: RouteHandlerContext<TSchema, WithMiddlewareLocals<TContext, TMiddleware>>) => Promise<Response> | Response;
5
5
  middleware?: TMiddleware;
6
6
  schema?: TSchema;
7
7
  };
@@ -14,7 +14,7 @@ type DefineApiHandlerInput<TPath extends string, TSchema extends RouteSchema, TC
14
14
  * @remarks
15
15
  * Without `path` the returned `path` is `''`, which `app.add` and `app.group` reject.
16
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 ? {
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 = NoMiddlewareList>(handler: DefineApiHandlerInput<TPath, TSchema, THandlerContext, TMiddleware> & (TPathOptional extends true ? {
18
18
  path?: TPath;
19
19
  } : {
20
20
  path: TPath;
@@ -24,7 +24,7 @@ type DefineApiMethod<TContext extends UniversalContext, TPathOptional extends bo
24
24
  * The returned handler's context is the base context: the typed one, narrowed by the schema and the
25
25
  * middleware, is erased by the cast, as `app.add` would erase it. The middleware list needs no cast.
26
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> & {
27
+ export declare function defineApiHandler<TPath extends string, TSchema extends RouteSchema = RouteSchema, TContext extends UniversalContext = UniversalContext, const TMiddleware extends MiddlewareList = NoMiddlewareList>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
28
28
  path: TPath;
29
29
  method: ApiHandler<TPath, Request, unknown>['method'];
30
30
  }): ApiHandler<TPath, Request, unknown>;
@@ -44,18 +44,18 @@ export declare function html(content: string, options?: RenderOptions): Response
44
44
  export declare function redirect(url: string, status?: number): Response;
45
45
  export interface GroupHandler<TPrefix extends string = string> {
46
46
  prefix: TPrefix;
47
- middleware?: MiddlewareList<Request, unknown>;
47
+ middleware?: MiddlewareList;
48
48
  routes: readonly ApiHandler<string, Request, unknown>[];
49
49
  }
50
50
  type GroupDefineHandler<TContext extends UniversalContext> = {
51
- <const TPath extends string, TSchema extends RouteSchema = RouteSchema, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
51
+ <const TPath extends string, TSchema extends RouteSchema = RouteSchema, const TMiddleware extends MiddlewareList = NoMiddlewareList>(handler: DefineApiHandlerInput<TPath, TSchema, TContext, TMiddleware> & {
52
52
  path: TPath;
53
53
  method: ApiHandler<TPath, Request, unknown>['method'];
54
54
  }): ApiHandler<TPath, Request, unknown>;
55
55
  } & {
56
56
  [M in ApiHandler['method'] as Lowercase<M>]: DefineApiMethod<TContext>;
57
57
  };
58
- export declare function defineGroupHandler<TPrefix extends string, const TMiddleware extends MiddlewareList<Request, unknown> = MiddlewareList<Request, unknown>, TContext extends UniversalContext = UniversalContext & MiddlewareContext<TMiddleware>>(config: {
58
+ export declare function defineGroupHandler<TPrefix extends string, const TMiddleware extends MiddlewareList = NoMiddlewareList, TContext extends UniversalContext = WithMiddlewareLocals<UniversalContext, TMiddleware>>(config: {
59
59
  prefix: TPrefix;
60
60
  middleware?: TMiddleware;
61
61
  routes: (api: GroupDefineHandler<TContext>) => readonly ApiHandler<string, Request, unknown>[];
@@ -1,5 +1,6 @@
1
- import type { FileRouteMiddleware, FileRouteMiddlewareContext, RequestLocals } from '../../../types/contracts.js';
1
+ import type { FileRouteMiddlewareContext } from '../../../types/contracts.js';
2
2
  import type { PageCacheService } from '../../../page-cache/page-cache-service.js';
3
+ import { type MiddlewareHandler } from './run-middleware-chain.js';
3
4
  export declare const FILE_ROUTE_MIDDLEWARE_PIPELINE_ERRORS: {
4
5
  readonly middlewareRequiresDynamic: (filePath: string) => string;
5
6
  };
@@ -18,17 +19,15 @@ export declare class FileRouteMiddlewarePipeline {
18
19
  * Enforces the current middleware contract for file-routed pages.
19
20
  *
20
21
  * Middleware depends on request-scoped locals and therefore must not run when
21
- * the page is treated as statically cacheable.
22
+ * the page is treated as statically cacheable. The Page itself must declare
23
+ * `cache: 'dynamic'`: an app default of `'dynamic'` does not give its `props`
24
+ * hook or layout factories the request.
22
25
  *
23
- * @param input Middleware list, effective cache strategy, and page path.
24
- * @throws LocalsAccessError When middleware is configured for a non-dynamic page.
26
+ * @throws LocalsAccessError When middleware is configured for a Page that is not a Dynamic Page.
25
27
  */
26
28
  assertValidConfiguration(input: {
27
- middleware: FileRouteMiddleware[];
28
- pageCacheStrategy: 'static' | 'dynamic' | {
29
- revalidate: number;
30
- tags?: string[];
31
- };
29
+ middleware: readonly MiddlewareHandler<FileRouteMiddlewareContext>[];
30
+ isDynamicPage: boolean;
32
31
  filePath: string;
33
32
  }): void;
34
33
  /**
@@ -43,7 +42,7 @@ export declare class FileRouteMiddlewarePipeline {
43
42
  createContext(input: {
44
43
  request: Request;
45
44
  params: Record<string, string>;
46
- locals: RequestLocals;
45
+ locals: Record<string, unknown>;
47
46
  }): FileRouteMiddlewareContext;
48
47
  /**
49
48
  * Runs the middleware chain and eventually delegates to the render callback.
@@ -55,7 +54,7 @@ export declare class FileRouteMiddlewarePipeline {
55
54
  * @returns Response from middleware or final render stage.
56
55
  */
57
56
  run(input: {
58
- middleware: FileRouteMiddleware[];
57
+ middleware: readonly MiddlewareHandler<FileRouteMiddlewareContext>[];
59
58
  context: FileRouteMiddlewareContext;
60
59
  renderResponse: () => Promise<Response>;
61
60
  }): Promise<Response>;
@@ -1,4 +1,3 @@
1
- import { createRequire } from '../../../utils/locals-utils.js';
2
1
  import { ApiResponseBuilder } from './api-response.js';
3
2
  import { runMiddlewareChain } from './run-middleware-chain.js';
4
3
  import { LocalsAccessError } from '../../../errors/locals-access-error.js';
@@ -22,13 +21,14 @@ export class FileRouteMiddlewarePipeline {
22
21
  * Enforces the current middleware contract for file-routed pages.
23
22
  *
24
23
  * Middleware depends on request-scoped locals and therefore must not run when
25
- * the page is treated as statically cacheable.
24
+ * the page is treated as statically cacheable. The Page itself must declare
25
+ * `cache: 'dynamic'`: an app default of `'dynamic'` does not give its `props`
26
+ * hook or layout factories the request.
26
27
  *
27
- * @param input Middleware list, effective cache strategy, and page path.
28
- * @throws LocalsAccessError When middleware is configured for a non-dynamic page.
28
+ * @throws LocalsAccessError When middleware is configured for a Page that is not a Dynamic Page.
29
29
  */
30
30
  assertValidConfiguration(input) {
31
- if (input.middleware.length > 0 && input.pageCacheStrategy !== 'dynamic') {
31
+ if (input.middleware.length > 0 && !input.isDynamicPage) {
32
32
  throw new LocalsAccessError(FILE_ROUTE_MIDDLEWARE_PIPELINE_ERRORS.middlewareRequiresDynamic(input.filePath));
33
33
  }
34
34
  }
@@ -51,7 +51,6 @@ export class FileRouteMiddlewarePipeline {
51
51
  cache: this.cacheService,
52
52
  },
53
53
  locals: input.locals,
54
- require: createRequire(() => context.locals),
55
54
  json: (data, options) => {
56
55
  if (options?.status)
57
56
  context.response.status(options.status);
@@ -1,5 +1,6 @@
1
1
  import { appLogger } from '../../../global/app-logger.js';
2
2
  import { PageRequestCacheCoordinator } from '../../../page-cache/page-request-cache-coordinator.service.js';
3
+ import { flattenMiddleware } from '../../../middleware/create-middleware.js';
3
4
  import { FileRouteMiddlewarePipeline } from './file-route-middleware-pipeline.js';
4
5
  import { classifyPageFailure } from '../../../errors/http-error-page-contract.js';
5
6
  import { isDevelopmentRuntime } from '../../../utils/runtime.js';
@@ -9,6 +10,7 @@ import { serveDistFile } from './dist-file-handler.js';
9
10
  import { requireAppRuntime } from '../../../utils/app-runtime.js';
10
11
  import { ensureIntegrationRuntimeReady } from '../../../build/app-build-manifest-runtime.js';
11
12
  import { findIntegrationForFile } from '../../../plugins/find-integration-for-file.js';
13
+ import { isDynamicPage } from '../../../eco/page-data-hooks.js';
12
14
  /**
13
15
  * Matches file-system routes to rendered HTML responses.
14
16
  *
@@ -72,7 +74,7 @@ export class FileSystemResponseMatcher {
72
74
  const executionPlan = await this.createExecutionPlan(match, request);
73
75
  this.fileRouteMiddlewarePipeline.assertValidConfiguration({
74
76
  middleware: executionPlan.pageMiddleware,
75
- pageCacheStrategy: executionPlan.pageCacheStrategy,
77
+ isDynamicPage: executionPlan.isDynamic,
76
78
  filePath: executionPlan.pageFilePath,
77
79
  });
78
80
  const routeRenderer = this.routeRendererFactory.getPageRenderer(executionPlan.pageFilePath);
@@ -88,6 +90,7 @@ export class FileSystemResponseMatcher {
88
90
  params: match.params,
89
91
  query: match.query,
90
92
  locals: executionPlan.localsForRender,
93
+ request: executionPlan.requestForRender,
91
94
  });
92
95
  const html = await this.pageRequestCacheCoordinator.bodyToString(result.body);
93
96
  const strategy = result.cacheStrategy ?? this.pageRequestCacheCoordinator.getDefaultCacheStrategy();
@@ -201,17 +204,22 @@ export class FileSystemResponseMatcher {
201
204
  const pageFilePath = match.templateRoute.filePath;
202
205
  const pageModule = await this.importPageModule(pageFilePath);
203
206
  const pageComponent = pageModule.default;
204
- const pageMiddleware = pageComponent.middleware ?? [];
205
- const pageCacheStrategy = pageModule.cache ?? pageComponent.cache ?? this.pageRequestCacheCoordinator.getDefaultCacheStrategy();
207
+ const pageMiddleware = flattenMiddleware(pageComponent.middleware, `page ${pageFilePath}`);
208
+ const isDynamic = isDynamicPage(pageComponent);
209
+ const pageCacheStrategy = isDynamic
210
+ ? 'dynamic'
211
+ : (pageComponent.cache ?? this.pageRequestCacheCoordinator.getDefaultCacheStrategy());
206
212
  return {
207
213
  cacheKey,
208
214
  request: resolvedRequest,
209
215
  pageFilePath,
210
216
  pageModule,
211
217
  pageMiddleware,
218
+ isDynamic,
212
219
  pageCacheStrategy,
213
220
  localsStore,
214
- localsForRender: pageCacheStrategy === 'dynamic' ? localsStore : undefined,
221
+ localsForRender: isDynamic ? localsStore : undefined,
222
+ requestForRender: isDynamic ? resolvedRequest : undefined,
215
223
  };
216
224
  }
217
225
  /**
@@ -1,5 +1,32 @@
1
- export type MiddlewareHandler<TContext> = (context: TContext, next: () => Promise<Response>) => Response | Promise<Response>;
1
+ export type MiddlewareHandler<TContext> = (context: TContext, next: (locals?: Record<string, unknown>) => Promise<Response>) => Response | Promise<Response>;
2
2
  /**
3
3
  * Runs an onion middleware chain and invokes the terminal handler when the chain completes.
4
+ *
5
+ * @remarks
6
+ * Each stage receives its own `next`, which continues the chain exactly once. A second call throws before the
7
+ * chain advances, even from inside a later stage: a shared cursor would let a stage that calls `next` twice resume
8
+ * the chain after a guard that had already answered, running everything behind the guard, including the terminal
9
+ * handler, a second time. `next` also throws once its stage has returned or thrown, so a stage that answered cannot
10
+ * start the rest of the chain later, from a timer or a callback.
11
+ *
12
+ * A stage continues with `next(locals)`. The chain defines each own key it provides on `context.locals` before the
13
+ * next stage runs, so a later stage and the handler read it, and a later key overrides an earlier one. Keys are
14
+ * defined, not assigned, so a `__proto__` key is a plain local and cannot replace the prototype of the store. A
15
+ * provided key is typed for everything after it, so when a stage continues, every key an earlier stage provided
16
+ * must still hold its value: a plain function that wrote or deleted one would leave readers with a value their
17
+ * types do not describe, so its `next` throws instead.
18
+ *
19
+ * A stage answers with whatever it returns: the response `next` resolved with, edited, or another response that
20
+ * wraps or replaces it, as an outer stage adding headers to an immutable redirect must. A stage that returns before
21
+ * the rest of the chain it started settles, or throws, waits for that rest before its own result or error
22
+ * propagates, so the handler never runs after the request has been answered.
23
+ *
24
+ * When the rest of the chain fails, the stage decides only if it looked at the promise `next` returned: awaited it,
25
+ * returned it, or called `then`, `catch` or `finally` on it. Then its own result stands, so
26
+ * `try { await next() } catch { return fallback }` answers with the fallback. A stage that never looked at that
27
+ * promise, as in `next(); return new Response('ok')`, did not handle the failure, so the chain rethrows it once the
28
+ * stage has returned, even when the failure comes after. A stage that throws propagates its own error instead.
4
29
  */
5
- export declare function runMiddlewareChain<TContext>(middleware: readonly MiddlewareHandler<TContext>[], context: TContext, terminal: () => Promise<Response>): Promise<Response>;
30
+ export declare function runMiddlewareChain<TContext extends {
31
+ readonly locals: object;
32
+ }>(middleware: readonly MiddlewareHandler<TContext>[], context: TContext, terminal: () => Promise<Response>): Promise<Response>;
@@ -1,17 +1,115 @@
1
1
  /**
2
2
  * Runs an onion middleware chain and invokes the terminal handler when the chain completes.
3
+ *
4
+ * @remarks
5
+ * Each stage receives its own `next`, which continues the chain exactly once. A second call throws before the
6
+ * chain advances, even from inside a later stage: a shared cursor would let a stage that calls `next` twice resume
7
+ * the chain after a guard that had already answered, running everything behind the guard, including the terminal
8
+ * handler, a second time. `next` also throws once its stage has returned or thrown, so a stage that answered cannot
9
+ * start the rest of the chain later, from a timer or a callback.
10
+ *
11
+ * A stage continues with `next(locals)`. The chain defines each own key it provides on `context.locals` before the
12
+ * next stage runs, so a later stage and the handler read it, and a later key overrides an earlier one. Keys are
13
+ * defined, not assigned, so a `__proto__` key is a plain local and cannot replace the prototype of the store. A
14
+ * provided key is typed for everything after it, so when a stage continues, every key an earlier stage provided
15
+ * must still hold its value: a plain function that wrote or deleted one would leave readers with a value their
16
+ * types do not describe, so its `next` throws instead.
17
+ *
18
+ * A stage answers with whatever it returns: the response `next` resolved with, edited, or another response that
19
+ * wraps or replaces it, as an outer stage adding headers to an immutable redirect must. A stage that returns before
20
+ * the rest of the chain it started settles, or throws, waits for that rest before its own result or error
21
+ * propagates, so the handler never runs after the request has been answered.
22
+ *
23
+ * When the rest of the chain fails, the stage decides only if it looked at the promise `next` returned: awaited it,
24
+ * returned it, or called `then`, `catch` or `finally` on it. Then its own result stands, so
25
+ * `try { await next() } catch { return fallback }` answers with the fallback. A stage that never looked at that
26
+ * promise, as in `next(); return new Response('ok')`, did not handle the failure, so the chain rethrows it once the
27
+ * stage has returned, even when the failure comes after. A stage that throws propagates its own error instead.
3
28
  */
4
29
  export async function runMiddlewareChain(middleware, context, terminal) {
5
- if (middleware.length === 0) {
6
- return terminal();
7
- }
8
- let index = 0;
9
- const executeNext = async () => {
10
- if (index < middleware.length) {
11
- const current = middleware[index++];
12
- return await current(context, executeNext);
30
+ const provided = new Map();
31
+ const runFrom = async (position) => {
32
+ if (position >= middleware.length) {
33
+ return terminal();
34
+ }
35
+ let finished = false;
36
+ let started = false;
37
+ let continuation;
38
+ let restSettled;
39
+ let restFailure;
40
+ const next = (locals) => {
41
+ if (finished) {
42
+ throw new Error(`[ecopages] Middleware stage ${position} called next() after it returned. Call next() before the stage returns, and return the response it resolves with.`);
43
+ }
44
+ if (started) {
45
+ throw new Error(`[ecopages] Middleware stage ${position} called next() more than once. A stage may continue the chain a single time.`);
46
+ }
47
+ started = true;
48
+ assertProvidedLocalsKept(context.locals, provided, position);
49
+ if (locals) {
50
+ defineLocals(context.locals, locals);
51
+ for (const [key, value] of Object.entries(locals))
52
+ provided.set(key, value);
53
+ }
54
+ const rest = runFrom(position + 1);
55
+ restSettled = rest.then(() => undefined, (error) => {
56
+ restFailure = { error };
57
+ });
58
+ continuation = new ContinuationPromise(rest);
59
+ return continuation;
60
+ };
61
+ let response;
62
+ try {
63
+ response = await middleware[position](context, next);
64
+ }
65
+ finally {
66
+ finished = true;
67
+ await restSettled;
68
+ }
69
+ if (restFailure && !continuation?.observed) {
70
+ throw restFailure.error;
13
71
  }
14
- return terminal();
72
+ return response;
15
73
  };
16
- return executeNext();
74
+ return runFrom(0);
75
+ }
76
+ /**
77
+ * The promise a stage's `next` returns, which records whether the stage looked at it.
78
+ *
79
+ * @remarks
80
+ * A `Promise` subclass and not an own `then` on a plain promise: `await` reads `then` only on a promise whose
81
+ * `constructor` is not `Promise`, and `catch` and `finally` call `then`, so overriding `then` sees `await`,
82
+ * `return next()` from an async stage, `Promise.resolve(next())` and `Promise.all([next()])` alike. The species is
83
+ * `Promise`, so the promises `then` derives are plain and do not count. The constructor attaches a handler that
84
+ * does not count as looking, so a promise the stage dropped does not also surface as an unhandled rejection: the
85
+ * chain reports that failure itself.
86
+ */
87
+ class ContinuationPromise extends Promise {
88
+ static get [Symbol.species]() {
89
+ return Promise;
90
+ }
91
+ #observed = false;
92
+ constructor(rest) {
93
+ super((resolve) => resolve(rest));
94
+ super.then(undefined, () => undefined);
95
+ }
96
+ get observed() {
97
+ return this.#observed;
98
+ }
99
+ then(onfulfilled, onrejected) {
100
+ this.#observed = true;
101
+ return super.then(onfulfilled, onrejected);
102
+ }
103
+ }
104
+ function assertProvidedLocalsKept(locals, provided, position) {
105
+ for (const [key, value] of provided) {
106
+ if (!Object.is(Object.getOwnPropertyDescriptor(locals, key)?.value, value)) {
107
+ throw new Error(`[ecopages] Middleware stage ${position} changed the local "${key}" that an earlier stage provided with next(). Make the stage with createMiddleware and pass the new value to next({ ${key} }) instead of writing ctx.locals.`);
108
+ }
109
+ }
110
+ }
111
+ function defineLocals(locals, provided) {
112
+ for (const [key, value] of Object.entries(provided)) {
113
+ Object.defineProperty(locals, key, { value, writable: true, enumerable: true, configurable: true });
114
+ }
17
115
  }
@@ -3,21 +3,6 @@ import { isViewReference } from '../../../types/view-reference.js';
3
3
  import { getComponentOwner } from '../../../eco/component-identity.js';
4
4
  import { invariant } from '../../../utils/invariant.js';
5
5
  import { createBodyResponse } from '../http/create-body-response.js';
6
- /**
7
- * Merges request locals into component props as a dedicated 'locals' property.
8
- * This prevents naming conflicts and maintains type safety by keeping locals
9
- * separate from other props.
10
- *
11
- * @param props - The original component props
12
- * @param locals - Optional request-scoped locals from middleware
13
- * @returns Props with locals merged in, or original props if no locals provided
14
- */
15
- function mergePropsWithLocals(props, locals) {
16
- if (!locals || typeof props !== 'object' || props === null) {
17
- return props;
18
- }
19
- return { ...props, locals };
20
- }
21
6
  function createExplicitViewContext(scope, renderOptions, partial) {
22
7
  return {
23
8
  partial,
@@ -65,18 +50,14 @@ export function createRenderContext(options) {
65
50
  };
66
51
  const renderContext = {
67
52
  async render(view, props, renderOptions) {
68
- const locals = this?.locals;
69
- const mergedProps = mergePropsWithLocals(props ?? {}, locals);
70
53
  const resolvedView = await resolveView(view);
71
54
  const renderer = await getRendererForView(resolvedView);
72
- return renderer.renderExplicitView(resolvedView, mergedProps, createExplicitViewContext(this, renderOptions, false));
55
+ return renderer.renderExplicitView(resolvedView, props ?? {}, createExplicitViewContext(this, renderOptions, false));
73
56
  },
74
57
  async renderPartial(view, props, renderOptions) {
75
- const locals = this?.locals;
76
- const mergedProps = mergePropsWithLocals(props, locals);
77
58
  const resolvedView = await resolveView(view);
78
59
  const renderer = await getRendererForView(resolvedView);
79
- return renderer.renderExplicitView(resolvedView, mergedProps, createExplicitViewContext(this, renderOptions, true));
60
+ return renderer.renderExplicitView(resolvedView, props, createExplicitViewContext(this, renderOptions, true));
80
61
  },
81
62
  json(data, responseOptions) {
82
63
  return createBodyResponse('json', data, {
@@ -66,7 +66,10 @@ export function resolveBuildPluginOrder(appConfig, environment, options) {
66
66
  const excluded = new Set(options.excludeAppBuildPlugins);
67
67
  const appPlugins = resolveAppBuildPlugins(appConfig, environment).filter((plugin) => !excluded.has(plugin.name));
68
68
  const plugins = mergeCallerBuildPlugins(appPlugins, options.callerPlugins, environment);
69
- const coreTransforms = [createEcoComponentMetaPlugin({ config: appConfig }), ...(options.coreTransforms ?? [])];
69
+ const coreTransforms = [
70
+ createEcoComponentMetaPlugin({ config: appConfig, environment }),
71
+ ...(options.coreTransforms ?? []),
72
+ ];
70
73
  const names = new Set(plugins.map((plugin) => plugin.name));
71
74
  for (const transform of coreTransforms) {
72
75
  if (names.has(transform.name)) {
package/src/build.d.ts CHANGED
@@ -13,6 +13,7 @@ export { parseModuleSource, recordModuleTransformProfile } from './cache/index.j
13
13
  export { GENERATED_BASE_PATHS, RESOLVED_ASSETS_DIR } from './constants.js';
14
14
  export { ECOPAGES_DEV_RESTART_EXIT_CODE, ECOPAGES_DEV_RESTART_REASON_ENV, ECOPAGES_ENTRY_WATCH_ENV, getDevEnvFileNames, resolveDevelopmentRecoveryWatch, } from './dev/development-restart.js';
15
15
  export { createRequestPipelineMetricsState, recordCollectionBuild, recordMdxTransform, type RequestPipelineMetricsState, } from './diagnostics/request-pipeline-metrics.js';
16
+ export { readExportedComponentIdentities } from './plugins/eco-component-meta-plugin.js';
16
17
  export { findIntegrationForFile } from './plugins/find-integration-for-file.js';
17
18
  export { toPackageRootSpecifier } from './plugins/package-specifier.js';
18
19
  export { loadTsconfigPathPrefixes, matchesTsconfigPathPrefix, resolveProjectModulePath, } from './plugins/tsconfig-import-resolver.js';
package/src/build.js CHANGED
@@ -13,6 +13,7 @@ export { parseModuleSource, recordModuleTransformProfile } from './cache/index.j
13
13
  export { GENERATED_BASE_PATHS, RESOLVED_ASSETS_DIR } from './constants.js';
14
14
  export { ECOPAGES_DEV_RESTART_EXIT_CODE, ECOPAGES_DEV_RESTART_REASON_ENV, ECOPAGES_ENTRY_WATCH_ENV, getDevEnvFileNames, resolveDevelopmentRecoveryWatch, } from './dev/development-restart.js';
15
15
  export { createRequestPipelineMetricsState, recordCollectionBuild, recordMdxTransform, } from './diagnostics/request-pipeline-metrics.js';
16
+ export { readExportedComponentIdentities } from './plugins/eco-component-meta-plugin.js';
16
17
  export { findIntegrationForFile } from './plugins/find-integration-for-file.js';
17
18
  export { toPackageRootSpecifier } from './plugins/package-specifier.js';
18
19
  export { loadTsconfigPathPrefixes, matchesTsconfigPathPrefix, resolveProjectModulePath, } from './plugins/tsconfig-import-resolver.js';
@@ -15,6 +15,8 @@ type EcoIslandRuntime = {
15
15
  type EcoPageData = {
16
16
  module: string;
17
17
  props: Record<string, unknown>;
18
+ /** The props each layout tier renders with, resolved on the server; absent when the document carries none. */
19
+ tiers?: readonly Record<string, unknown>[];
18
20
  /** Set by a react-router navigation to the document it fetched; absent otherwise. */
19
21
  document?: Document;
20
22
  };
@@ -1,4 +1,5 @@
1
1
  import { applyPageLayoutConfig, mergeLayoutDependencies, normalizePageLayouts } from './page-layout-normalization.js';
2
+ import { attachPageOptions } from './page-data-hooks.js';
2
3
  /**
3
4
  * Creates a browser component that renders inline for every caller.
4
5
  *
@@ -30,43 +31,22 @@ function layout(options) {
30
31
  return createComponentFactory(options);
31
32
  }
32
33
  function page(options) {
33
- const { layout: pageLayout, dependencies: dependenciesInput, render, paths, props, metadata, cache, requires, middleware, } = options;
34
+ const { layout: pageLayout, dependencies: dependenciesInput, render } = options;
34
35
  const layoutEntries = normalizePageLayouts(pageLayout);
35
- const resolveDependencies = typeof dependenciesInput === 'function' ? dependenciesInput : undefined;
36
36
  const staticDependencies = typeof dependenciesInput === 'function'
37
37
  ? mergeLayoutDependencies(undefined, layoutEntries)
38
38
  : mergeLayoutDependencies(dependenciesInput, layoutEntries);
39
- const pageComponent = createComponentFactory({
39
+ const componentOptions = {
40
40
  identity: options.identity,
41
41
  integration: options.integration,
42
42
  dependencies: staticDependencies,
43
43
  render,
44
- });
44
+ };
45
+ const pageComponent = createComponentFactory(componentOptions);
45
46
  if (pageComponent.config) {
46
47
  applyPageLayoutConfig(pageComponent.config, layoutEntries);
47
48
  }
48
- if (paths) {
49
- pageComponent.paths = paths;
50
- }
51
- if (props) {
52
- pageComponent.props = props;
53
- }
54
- if (metadata) {
55
- pageComponent.metadata = metadata;
56
- }
57
- if (resolveDependencies) {
58
- pageComponent.resolveDependencies = resolveDependencies;
59
- }
60
- if (cache) {
61
- pageComponent.cache = cache;
62
- }
63
- if (requires) {
64
- pageComponent.requires = requires;
65
- }
66
- if (middleware) {
67
- pageComponent.middleware = middleware;
68
- }
69
- return pageComponent;
49
+ return attachPageOptions(pageComponent, options);
70
50
  }
71
51
  export const eco = {
72
52
  component,