@ecopages/core 0.8.0 → 0.9.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 (145) hide show
  1. package/README.md +2 -2
  2. package/package.json +14 -4
  3. package/src/adapters/node/create-app.d.ts +1 -1
  4. package/src/adapters/node/create-app.js +1 -1
  5. package/src/adapters/node/server-adapter.d.ts +1 -0
  6. package/src/adapters/node/server-adapter.js +4 -1
  7. package/src/adapters/shared/hmr/hmr-manager.d.ts +2 -0
  8. package/src/adapters/shared/hmr/hmr-manager.js +8 -4
  9. package/src/adapters/shared/http/api-request-pipeline.d.ts +16 -3
  10. package/src/adapters/shared/http/api-request-pipeline.js +16 -11
  11. package/src/adapters/shared/http/explicit-static-route-matcher.js +8 -4
  12. package/src/adapters/shared/runtime/render-context.d.ts +2 -0
  13. package/src/adapters/shared/runtime/render-context.js +4 -0
  14. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +2 -2
  15. package/src/adapters/shared/runtime/server-request-pipeline.js +4 -3
  16. package/src/adapters/shared/runtime/server-static-builder.js +4 -1
  17. package/src/adapters/shared/runtime/unattached-scripts.d.ts +17 -0
  18. package/src/adapters/shared/runtime/unattached-scripts.js +57 -0
  19. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +3 -2
  20. package/src/adapters/shared/ws/ws-pattern-matcher.d.ts +14 -1
  21. package/src/adapters/shared/ws/ws-pattern-matcher.js +14 -13
  22. package/src/assets/app-browser-client-build.js +3 -0
  23. package/src/assets/asset-processing-service/asset-processing.service.d.ts +9 -0
  24. package/src/assets/asset-processing-service/asset-processing.service.js +19 -0
  25. package/src/assets/asset-processing-service/processed-asset-ledger.d.ts +16 -2
  26. package/src/assets/asset-processing-service/processed-asset-ledger.js +31 -3
  27. package/src/build/build-graph.d.ts +19 -2
  28. package/src/build/build-graph.js +19 -18
  29. package/src/build/cache/pages-unified-graph-build.d.ts +4 -6
  30. package/src/build/cache/pages-unified-graph-build.js +14 -51
  31. package/src/build/cache/server-module-entries.d.ts +5 -9
  32. package/src/build/cache/server-module-entries.js +5 -58
  33. package/src/build/contracts/build-contracts.d.ts +15 -0
  34. package/src/build/contracts.d.ts +1 -1
  35. package/src/build/contracts.js +1 -1
  36. package/src/build/production-asset-ledger.d.ts +1 -1
  37. package/src/build/production-asset-ledger.js +4 -2
  38. package/src/build/rolldown/file-role-grammar-plugin.d.ts +11 -0
  39. package/src/build/rolldown/file-role-grammar-plugin.js +32 -0
  40. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +11 -0
  41. package/src/build/rolldown/rolldown-adapter-helpers.js +79 -10
  42. package/src/build/rolldown/ssr-script-entries-plugin.d.ts +31 -0
  43. package/src/build/rolldown/ssr-script-entries-plugin.js +104 -0
  44. package/src/build/server/server-modules-manifest.d.ts +6 -1
  45. package/src/build/server/server-modules-manifest.js +10 -1
  46. package/src/build/server/view-reference.d.ts +9 -0
  47. package/src/build/server/view-reference.js +11 -0
  48. package/src/build.d.ts +2 -1
  49. package/src/build.js +2 -1
  50. package/src/cli.d.ts +14 -0
  51. package/src/cli.js +14 -0
  52. package/src/config/assembly/app-runtime.d.ts +13 -0
  53. package/src/config/assembly/app-runtime.js +2 -0
  54. package/src/config/assembly/finalize-config.js +13 -8
  55. package/src/config/internal-types.d.ts +0 -12
  56. package/src/config/resolve-eco-config-path.d.ts +2 -0
  57. package/src/config/resolve-eco-config-path.js +2 -1
  58. package/src/config/server-config-bundle.d.ts +0 -1
  59. package/src/config/server-config-bundle.js +1 -1
  60. package/src/config/user-config-types.d.ts +0 -12
  61. package/src/dev/invalidation/development-invalidation.service.d.ts +0 -2
  62. package/src/dev/invalidation/development-invalidation.service.js +1 -11
  63. package/src/dev/transform-server/dev-transform-vendor-registry.js +33 -19
  64. package/src/eco/discovered-dependencies.d.ts +5 -0
  65. package/src/eco/discovered-dependencies.js +9 -0
  66. package/src/eco/eco.browser.js +5 -5
  67. package/src/eco/eco.js +24 -5
  68. package/src/eco/migration-docs.d.ts +7 -0
  69. package/src/eco/migration-docs.js +7 -0
  70. package/src/hmr/client/hmr-runtime.js +1 -1
  71. package/src/hmr/strategies/js-hmr-strategy.d.ts +0 -2
  72. package/src/hmr/strategies/server-rendered-template-hmr-strategy.d.ts +2 -1
  73. package/src/hmr/strategies/server-rendered-template-hmr-strategy.js +4 -3
  74. package/src/html/html-rewriter.d.ts +9 -7
  75. package/src/html/html-rewriter.js +26 -41
  76. package/src/html/html-transformer.service.d.ts +2 -2
  77. package/src/html/html-transformer.service.js +21 -15
  78. package/src/html-pages/html-page-module-scripts.js +2 -1
  79. package/src/html-pages/html-pages.plugin.d.ts +1 -1
  80. package/src/html-pages/html-pages.plugin.js +1 -1
  81. package/src/integration.d.ts +1 -1
  82. package/src/integration.js +1 -1
  83. package/src/islands/island-host.d.ts +16 -5
  84. package/src/islands/island-host.js +8 -1
  85. package/src/plugins/component-import-discovery.d.ts +14 -1
  86. package/src/plugins/component-import-discovery.js +36 -16
  87. package/src/plugins/eco-component-meta-plugin.d.ts +5 -0
  88. package/src/plugins/eco-component-meta-plugin.js +39 -22
  89. package/src/plugins/ecopages-virtual-imports.d.ts +15 -0
  90. package/src/plugins/ecopages-virtual-imports.js +25 -0
  91. package/src/plugins/integration-plugin.d.ts +1 -1
  92. package/src/plugins/integration-plugin.js +1 -1
  93. package/src/plugins/tsconfig-import-resolver.d.ts +2 -0
  94. package/src/plugins/tsconfig-import-resolver.js +7 -5
  95. package/src/route-renderer/error-pages/error-page-renderer.js +3 -2
  96. package/src/route-renderer/explicit-view-render-preparation.d.ts +10 -3
  97. package/src/route-renderer/explicit-view-render-preparation.js +14 -8
  98. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +24 -9
  99. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +73 -50
  100. package/src/route-renderer/orchestration/integration-renderer.d.ts +39 -10
  101. package/src/route-renderer/orchestration/integration-renderer.js +74 -38
  102. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +32 -11
  103. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +68 -61
  104. package/src/route-renderer/page-declaration.d.ts +25 -0
  105. package/src/route-renderer/page-declaration.js +39 -0
  106. package/src/route-renderer/page-loading/component-declarations.d.ts +65 -0
  107. package/src/route-renderer/page-loading/component-declarations.js +77 -0
  108. package/src/route-renderer/page-loading/component-dependency-collection.d.ts +4 -16
  109. package/src/route-renderer/page-loading/component-dependency-collection.js +36 -105
  110. package/src/route-renderer/page-loading/declared-asset-collection.d.ts +19 -14
  111. package/src/route-renderer/page-loading/declared-asset-collection.js +66 -67
  112. package/src/route-renderer/page-loading/dependency-resolver.d.ts +18 -10
  113. package/src/route-renderer/page-loading/dependency-resolver.js +58 -99
  114. package/src/route-renderer/page-loading/lazy-entry-collection.d.ts +19 -26
  115. package/src/route-renderer/page-loading/lazy-entry-collection.js +53 -64
  116. package/src/route-renderer/page-loading/module-declaration-aggregation.d.ts +17 -3
  117. package/src/route-renderer/page-loading/module-declaration-aggregation.js +14 -13
  118. package/src/route-renderer/page-loading/page-module-loader.d.ts +10 -11
  119. package/src/route-renderer/page-loading/page-module-loader.js +30 -30
  120. package/src/router/server/pages-dir.d.ts +7 -0
  121. package/src/router/server/pages-dir.js +7 -0
  122. package/src/router/server/route-registry.d.ts +22 -10
  123. package/src/router/server/route-registry.js +54 -23
  124. package/src/router/server/segment-path-matcher.d.ts +29 -5
  125. package/src/router/server/segment-path-matcher.js +22 -19
  126. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +2 -2
  127. package/src/static-site-generator/production-page-browser-graph-prebuild.js +5 -5
  128. package/src/static-site-generator/static-site-generator.d.ts +17 -1
  129. package/src/static-site-generator/static-site-generator.js +46 -12
  130. package/src/types/contracts.d.ts +28 -28
  131. package/src/types/eco-api-types.d.ts +17 -12
  132. package/src/types/public-types.d.ts +1 -1
  133. package/src/utils/file-roles.d.ts +48 -0
  134. package/src/utils/file-roles.js +85 -0
  135. package/src/utils/node-builtin.d.ts +10 -0
  136. package/src/utils/node-builtin.js +13 -0
  137. package/src/watchers/project-watcher.js +2 -2
  138. package/src/build/contracts/server-only-specifier.d.ts +0 -8
  139. package/src/build/contracts/server-only-specifier.js +0 -11
  140. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.d.ts +0 -5
  141. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.js +0 -11
  142. package/src/route-renderer/page-loading/ecopages-virtual-imports.d.ts +0 -12
  143. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +0 -100
  144. package/src/utils/endpoint-file-extensions.d.ts +0 -11
  145. package/src/utils/endpoint-file-extensions.js +0 -13
package/README.md CHANGED
@@ -59,7 +59,7 @@ await app.start();
59
59
 
60
60
  ### 3. Creating Pages
61
61
 
62
- Use the `eco.page()` factory to define static routes. Place these in `src/pages/`:
62
+ Use the `eco.page()` factory to define a page. A file in `src/pages/` default-exports one:
63
63
 
64
64
  ```tsx
65
65
  import { eco } from '@ecopages/core';
@@ -239,6 +239,6 @@ Use `@ecopages/core/client` for browser navigation and client runtime helpers.
239
239
 
240
240
  ### Runtime-Loaded Entries
241
241
 
242
- `@ecopages/core/config/write-types`, `@ecopages/core/hmr/client/hmr-runtime`, and `@ecopages/core/view-reference` remain exported because Ecopages loads them by path at runtime. They are implementation entries, not general authoring surfaces. App authors import the view file, not this subpath.
242
+ `@ecopages/core/config/write-types`, `@ecopages/core/hmr/client/hmr-runtime`, and `@ecopages/core/view-reference` remain exported because Ecopages loads them by path at runtime. `@ecopages/core/cli` holds what the `ecopages` CLI reads before it starts the app, so the CLI starts without loading the bundler. They are implementation entries, not general authoring surfaces. App authors import the view file, not the `view-reference` subpath.
243
243
 
244
244
  `@ecopages/core/errors` remains an alias for the root error exports.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
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.8.0",
27
+ "@ecopages/file-system": "0.9.0",
28
28
  "@ecopages/logger": "^0.2.3",
29
29
  "@ecopages/scripts-injector": "^0.1.5",
30
30
  "@jridgewell/remapping": "^2.3.5",
@@ -33,11 +33,11 @@
33
33
  "magic-string": "^1.4.3",
34
34
  "oxc-parser": "^0.141.0",
35
35
  "oxc-resolver": "^11.24.2",
36
- "rolldown": "^1.1.0",
36
+ "rolldown": "^1.3.2",
37
37
  "ws": "^8.20.1"
38
38
  },
39
39
  "peerDependencies": {
40
- "@ecopages/dev-toolbar": "0.8.0"
40
+ "@ecopages/dev-toolbar": "0.9.0"
41
41
  },
42
42
  "peerDependenciesMeta": {
43
43
  "@ecopages/dev-toolbar": {
@@ -71,6 +71,11 @@
71
71
  "types": "./src/processor-contract.d.ts",
72
72
  "default": "./src/processor-contract.js"
73
73
  },
74
+ "./cli": {
75
+ "import": "./src/cli.js",
76
+ "types": "./src/cli.d.ts",
77
+ "default": "./src/cli.js"
78
+ },
74
79
  "./build": {
75
80
  "import": "./src/build.js",
76
81
  "types": "./src/build.d.ts",
@@ -133,6 +138,11 @@
133
138
  "types": "./src/processor-contract.d.ts",
134
139
  "default": "./src/processor-contract.js"
135
140
  },
141
+ "./cli.ts": {
142
+ "import": "./src/cli.js",
143
+ "types": "./src/cli.d.ts",
144
+ "default": "./src/cli.js"
145
+ },
136
146
  "./build.ts": {
137
147
  "import": "./src/build.js",
138
148
  "types": "./src/build.d.ts",
@@ -91,7 +91,7 @@ export declare class EcopagesApp implements AsyncDisposable {
91
91
  private registerGroup;
92
92
  /**
93
93
  * Register a view for static generation at build time.
94
- * The view must have staticPaths defined for dynamic routes.
94
+ * The view must have paths defined for dynamic routes.
95
95
  *
96
96
  * @param path - URL path pattern (e.g., '/posts/:slug')
97
97
  * @param view - An imported view, an `eco.page` component, or a view loader
@@ -147,7 +147,7 @@ export class EcopagesApp {
147
147
  }
148
148
  /**
149
149
  * Register a view for static generation at build time.
150
- * The view must have staticPaths defined for dynamic routes.
150
+ * The view must have paths defined for dynamic routes.
151
151
  *
152
152
  * @param path - URL path pattern (e.g., '/posts/:slug')
153
153
  * @param view - An imported view, an `eco.page` component, or a view loader
@@ -67,6 +67,7 @@ export declare class NodeServerAdapter {
67
67
  private phase;
68
68
  private ready;
69
69
  private apiHandlers;
70
+ private readonly apiRoutes;
70
71
  private staticRoutes;
71
72
  private errorPageLoaders;
72
73
  private errorHandler?;
@@ -11,6 +11,7 @@ import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../constant
11
11
  import { disposeDevResources, prepareRuntimePublicDir } from '../shared/runtime/runtime-server-lifecycle.js';
12
12
  import { resolveServeRuntimeOrigin } from '../shared/runtime/runtime-app-bootstrap.js';
13
13
  import { bindRuntimeServer } from '../shared/runtime/bind-runtime-server.js';
14
+ import { compileApiRoutes } from '../shared/http/api-request-pipeline.js';
14
15
  import { serveDistFile } from '../shared/http/dist-file-handler.js';
15
16
  import { applyResponseHeaders } from '../shared/http/response-headers.js';
16
17
  import { DevSession } from './dev-session.js';
@@ -45,6 +46,7 @@ export class NodeServerAdapter {
45
46
  phase = 'idle';
46
47
  ready;
47
48
  apiHandlers;
49
+ apiRoutes;
48
50
  staticRoutes;
49
51
  errorPageLoaders;
50
52
  errorHandler;
@@ -91,6 +93,7 @@ export class NodeServerAdapter {
91
93
  this.allowPortFallback = options.allowPortFallback !== false;
92
94
  this.onDevelopmentRestart = options.onDevelopmentRestart;
93
95
  this.apiHandlers = options.apiHandlers || [];
96
+ this.apiRoutes = compileApiRoutes(this.apiHandlers);
94
97
  this.staticRoutes = options.staticRoutes || [];
95
98
  this.errorPageLoaders = options.errorPageLoaders ?? {};
96
99
  this.errorHandler = options.errorHandler;
@@ -343,7 +346,7 @@ export class NodeServerAdapter {
343
346
  async handleRequestInternal(request, waitForReadiness) {
344
347
  await this.initialize();
345
348
  const context = {
346
- apiHandlers: this.apiHandlers,
349
+ apiRoutes: this.apiRoutes,
347
350
  errorHandler: this.errorHandler,
348
351
  serverInstance: this.serverInstance,
349
352
  };
@@ -109,6 +109,8 @@ export declare class HmrManager implements IHmrManager {
109
109
  * still register the entrypoint so file watchers can invalidate it on change.
110
110
  */
111
111
  getResolvedScriptOutput(entrypointPath: string): ResolvedHmrEntrypoint | undefined;
112
+ private isPageFile;
113
+ private isLayoutFile;
112
114
  getWatchedFiles(): Map<string, string>;
113
115
  getRegisteredEntrypoints(): ReadonlyMap<string, ResolvedHmrEntrypoint>;
114
116
  /**
@@ -136,8 +136,6 @@ export class HmrManager {
136
136
  getWatchedFiles: () => this.entrypointRegistry.getWatchedOutputUrls(),
137
137
  getRegisteredEntrypoints: () => this.entrypointRegistry.getRegisteredEntrypoints(),
138
138
  getSrcDir: () => this.appConfig.absolutePaths.srcDir,
139
- getPagesDir: () => this.appConfig.absolutePaths.pagesDir,
140
- getLayoutsDir: () => this.appConfig.absolutePaths.layoutsDir,
141
139
  getTemplateExtensions: () => this.appConfig.templatesExt,
142
140
  isStylesheet: (filePath) => (this.stylesheetKinds ??= getStylesheetKinds(this.appConfig)).isStylesheet(filePath),
143
141
  getEntrypointDependencyGraph: () => this.entrypointDependencyGraph,
@@ -332,6 +330,12 @@ export class HmrManager {
332
330
  }
333
331
  return registered;
334
332
  }
333
+ isPageFile(filePath) {
334
+ return requireAppRuntime(this.appConfig).router?.isPageFile(filePath) ?? false;
335
+ }
336
+ isLayoutFile(filePath) {
337
+ return requireAppRuntime(this.appConfig).layoutFiles.has(path.resolve(filePath));
338
+ }
335
339
  getWatchedFiles() {
336
340
  return this.entrypointRegistry.getWatchedOutputUrls();
337
341
  }
@@ -370,8 +374,8 @@ export class HmrManager {
370
374
  getWatchedFiles: () => this.entrypointRegistry.getWatchedOutputUrls(),
371
375
  getRegisteredEntrypoints: () => this.entrypointRegistry.getRegisteredEntrypoints(),
372
376
  getSrcDir: () => this.appConfig.absolutePaths.srcDir,
373
- getLayoutsDir: () => this.appConfig.absolutePaths.layoutsDir,
374
- getPagesDir: () => this.appConfig.absolutePaths.pagesDir,
377
+ isPageFile: (filePath) => this.isPageFile(filePath),
378
+ isLayoutFile: (filePath) => this.isLayoutFile(filePath),
375
379
  getEntrypointDependencyGraph: () => this.entrypointDependencyGraph,
376
380
  importServerModule: async (filePath) => await requireAppRuntime(this.appConfig).moduleLoader.importModule({
377
381
  filePath,
@@ -1,5 +1,18 @@
1
- import { type ParsedSegmentPath } from '../../../router/server/segment-path-matcher.js';
1
+ import { type SegmentPattern, type ParsedSegmentPath } from '../../../router/server/segment-path-matcher.js';
2
2
  import type { ApiHandler, ApiHandlerContext, CacheInvalidator, ErrorHandler, PageParams, RenderContext } from '../../../types/contracts.js';
3
+ /**
4
+ * API handlers with their patterns parsed and ordered from most to least specific.
5
+ *
6
+ * @remarks Build it with {@link compileApiRoutes} when the handlers are known, so a request only walks the
7
+ * list. Equal scores keep registration order.
8
+ */
9
+ export type ApiRoutes<TRequest extends Request = Request, TServer = unknown> = ReadonlyArray<{
10
+ handler: ApiHandler<string, TRequest, TServer>;
11
+ /** The handler's method, upper-cased; `GET` when the handler names none. */
12
+ method: string;
13
+ pattern: SegmentPattern<'api'>;
14
+ }>;
15
+ export declare function compileApiRoutes<TRequest extends Request = Request, TServer = unknown>(handlers: readonly ApiHandler<string, TRequest, TServer>[]): ApiRoutes<TRequest, TServer>;
3
16
  export type ApiRequestPipelineOptions = {
4
17
  getRenderContext: () => RenderContext;
5
18
  getCacheService: () => CacheInvalidator | null;
@@ -8,11 +21,11 @@ export declare class ApiRequestPipeline<TRequest extends Request = Request, TSer
8
21
  private readonly getRenderContext;
9
22
  private readonly getCacheService;
10
23
  constructor(options: ApiRequestPipelineOptions);
11
- match(request: TRequest, apiHandlers: ApiHandler<string, TRequest, TServer>[], parsedPathSegments?: ParsedSegmentPath): {
24
+ match(request: TRequest, apiRoutes: ApiRoutes<TRequest, TServer>, parsedPathSegments?: ParsedSegmentPath): {
12
25
  routeConfig: ApiHandler<string, TRequest, TServer>;
13
26
  params: PageParams;
14
27
  } | null;
15
- tryHandle(request: TRequest, apiHandlers: ApiHandler<string, TRequest, TServer>[], serverInstance: TServer | undefined, errorHandler?: ErrorHandler<TRequest, TServer>, parsedPathSegments?: ParsedSegmentPath): Promise<Response | null>;
28
+ tryHandle(request: TRequest, apiRoutes: ApiRoutes<TRequest, TServer>, serverInstance: TServer | undefined, errorHandler?: ErrorHandler<TRequest, TServer>, parsedPathSegments?: ParsedSegmentPath): Promise<Response | null>;
16
29
  execute(request: TRequest, params: PageParams, routeConfig: ApiHandler<string, TRequest, TServer>, serverInstance: TServer | undefined, errorHandler?: ErrorHandler<TRequest, TServer>): Promise<Response>;
17
30
  /**
18
31
  * Resolves an error that escaped a handler into a response.
@@ -2,11 +2,20 @@ import { createRequire } from '../../../utils/locals-utils.js';
2
2
  import { HttpError } from '../../../errors/http-error.js';
3
3
  import { ApiResponseBuilder } from './api-response.js';
4
4
  import { runMiddlewareChain } from './run-middleware-chain.js';
5
- import { matchParsedSegmentPath, parseSegmentPath, scoreSegmentPathPattern, } from '../../../router/server/segment-path-matcher.js';
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
+ export function compileApiRoutes(handlers) {
11
+ return handlers
12
+ .map((handler) => ({
13
+ handler,
14
+ method: (handler.method || 'GET').toUpperCase(),
15
+ pattern: compileSegmentPattern(handler.path, 'api'),
16
+ }))
17
+ .sort((a, b) => b.pattern.score - a.pattern.score);
18
+ }
10
19
  export class ApiRequestPipeline {
11
20
  getRenderContext;
12
21
  getCacheService;
@@ -14,29 +23,25 @@ export class ApiRequestPipeline {
14
23
  this.getRenderContext = options.getRenderContext;
15
24
  this.getCacheService = options.getCacheService;
16
25
  }
17
- match(request, apiHandlers, parsedPathSegments) {
26
+ match(request, apiRoutes, parsedPathSegments) {
18
27
  const pathname = new URL(request.url).pathname;
19
28
  const pathSegments = parsedPathSegments ?? parseSegmentPath(pathname);
20
29
  const method = request.method.toUpperCase();
21
- const sortedHandlers = [...apiHandlers].sort((a, b) => {
22
- return scoreSegmentPathPattern(b.path, 'api') - scoreSegmentPathPattern(a.path, 'api');
23
- });
24
- for (const routeConfig of sortedHandlers) {
25
- const routeMethod = (routeConfig.method || 'GET').toUpperCase();
30
+ for (const { handler, method: routeMethod, pattern } of apiRoutes) {
26
31
  if (routeMethod !== method) {
27
32
  continue;
28
33
  }
29
- const params = matchParsedSegmentPath(routeConfig.path, pathSegments, 'api');
34
+ const params = matchParsedSegmentPath(pattern, pathSegments);
30
35
  if (params) {
31
- return { routeConfig, params };
36
+ return { routeConfig: handler, params };
32
37
  }
33
38
  }
34
39
  return null;
35
40
  }
36
- async tryHandle(request, apiHandlers, serverInstance, errorHandler, parsedPathSegments) {
41
+ async tryHandle(request, apiRoutes, serverInstance, errorHandler, parsedPathSegments) {
37
42
  let apiMatch;
38
43
  try {
39
- apiMatch = this.match(request, apiHandlers, parsedPathSegments);
44
+ apiMatch = this.match(request, apiRoutes, parsedPathSegments);
40
45
  }
41
46
  catch (error) {
42
47
  return await this.handleError(error, { request, serverInstance, errorHandler });
@@ -3,7 +3,7 @@ import { requireAppRuntime } from '../../../utils/app-runtime.js';
3
3
  import { formatErrorChain } from '../../../utils/format-error-chain.js';
4
4
  import { shouldLogPageFailure } from '../../../errors/http-error-page-contract.js';
5
5
  import { prepareExplicitStaticRender } from '../../../route-renderer/explicit-view-render-preparation.js';
6
- import { matchParsedSegmentPath, parseSegmentPath, } from '../../../router/server/segment-path-matcher.js';
6
+ import { compileSegmentPattern, matchParsedSegmentPath, parseSegmentPath, } from '../../../router/server/segment-path-matcher.js';
7
7
  export const EXPLICIT_STATIC_ROUTE_MATCHER_ERRORS = {
8
8
  missingIntegration: (routePath) => `View at ${routePath} is missing component identity integration. Ensure it's defined with eco.page() and exported as default.`,
9
9
  noRendererForIntegration: (integrationName) => `No renderer found for integration: ${integrationName}`,
@@ -18,7 +18,10 @@ export class ExplicitStaticRouteMatcher {
18
18
  constructor({ appConfig, routeRendererFactory, staticRoutes }) {
19
19
  this.appConfig = appConfig;
20
20
  this.routeRendererFactory = routeRendererFactory;
21
- this.staticRoutes = staticRoutes;
21
+ this.staticRoutes = staticRoutes.map((route) => ({
22
+ route,
23
+ pattern: compileSegmentPattern(route.path, 'explicit'),
24
+ }));
22
25
  }
23
26
  /**
24
27
  * Match a request URL against explicit static routes.
@@ -26,8 +29,8 @@ export class ExplicitStaticRouteMatcher {
26
29
  */
27
30
  match(url, parsedPathSegments) {
28
31
  const pathSegments = parsedPathSegments ?? parseSegmentPath(new URL(url).pathname);
29
- for (const route of this.staticRoutes) {
30
- const params = matchParsedSegmentPath(route.path, pathSegments, 'explicit');
32
+ for (const { route, pattern } of this.staticRoutes) {
33
+ const params = matchParsedSegmentPath(pattern, pathSegments);
31
34
  if (params !== null) {
32
35
  return { route, params };
33
36
  }
@@ -46,6 +49,7 @@ export class ExplicitStaticRouteMatcher {
46
49
  const { renderer, props, view: renderableView, } = await prepareExplicitStaticRender({
47
50
  routePath: route.path,
48
51
  view,
52
+ viewFile: route.loader.filePath,
49
53
  params,
50
54
  appConfig: this.appConfig,
51
55
  runtimeOrigin: requireAppRuntime(this.appConfig).origin,
@@ -4,6 +4,8 @@ export interface CreateRenderContextOptions {
4
4
  integrations: AnyIntegrationPlugin[];
5
5
  ensureIntegrationReady?: (integrationName: string) => Promise<void>;
6
6
  importServerModule?: (filePath: string) => Promise<unknown>;
7
+ /** App root; with it, an imported view must declare its Page with a literal `eco.page()` call in its own file. */
8
+ rootDir?: string;
7
9
  }
8
10
  /**
9
11
  * Creates a render context for route handlers.
@@ -1,3 +1,4 @@
1
+ import { assertViewDeclaredIn } from '../../../route-renderer/page-declaration.js';
1
2
  import { isViewReference } from '../../../types/view-reference.js';
2
3
  import { getComponentOwner } from '../../../eco/component-identity.js';
3
4
  import { invariant } from '../../../utils/invariant.js';
@@ -57,6 +58,9 @@ export function createRenderContext(options) {
57
58
  invariant(!!options.importServerModule, 'Imported views need the server-module loader.');
58
59
  const module = (await options.importServerModule(view.filePath));
59
60
  invariant(!!module.default, `View module ${view.filePath} has no default export.`);
61
+ if (options.rootDir) {
62
+ assertViewDeclaredIn(view.filePath, module.default, options.rootDir);
63
+ }
60
64
  return module.default;
61
65
  };
62
66
  const renderContext = {
@@ -5,11 +5,11 @@ import { RouteRegistry } from '../../../router/server/route-registry.js';
5
5
  import type { StaticGenerationRoute } from '../../../router/server/route-registry.js';
6
6
  import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
7
7
  import { ServerRouteHandler } from './server-route-handler.js';
8
- import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
8
+ import { ApiRequestPipeline, type ApiRoutes } from '../http/api-request-pipeline.js';
9
9
  import { type EndpointRequestContext, type EndpointRouteHandlerOptions } from '../http/endpoint-route-handler.js';
10
10
  import type { ApiHandler, CacheInvalidator, ErrorHandler, RenderContext, StaticRoute, ErrorPageLoaders } from '../../../types/contracts.js';
11
11
  export type ServerRequestContext<TServer = unknown> = {
12
- apiHandlers: ApiHandler[];
12
+ apiRoutes: ApiRoutes;
13
13
  errorHandler?: ErrorHandler<Request, TServer>;
14
14
  serverInstance?: TServer;
15
15
  };
@@ -119,6 +119,7 @@ export class ServerRequestPipeline {
119
119
  pageModuleAdapter: this.createRouteRegistryPageModuleAdapter(),
120
120
  });
121
121
  await this.router.init();
122
+ this.runtime.router = this.router;
122
123
  startupTrace.markPhaseEnd('route-registry');
123
124
  }
124
125
  createRouteRegistryPageModuleAdapter() {
@@ -131,8 +132,7 @@ export class ServerRequestPipeline {
131
132
  const page = module.default;
132
133
  const pageComponent = page;
133
134
  return {
134
- staticPaths: pageComponent?.staticPaths,
135
- staticProps: pageComponent?.staticProps,
135
+ paths: pageComponent?.paths,
136
136
  cache: pageComponent?.cache,
137
137
  };
138
138
  },
@@ -214,6 +214,7 @@ export class ServerRequestPipeline {
214
214
  getRenderContext() {
215
215
  return createRenderContext({
216
216
  integrations: this.appConfig.integrations,
217
+ rootDir: this.appConfig.rootDir,
217
218
  ensureIntegrationReady: (integrationName) => ensureIntegrationRuntimeReady({ appConfig: this.appConfig, integrationName }),
218
219
  importServerModule: (filePath) => this.importServerModule(path.resolve(this.appConfig.rootDir, filePath)),
219
220
  });
@@ -239,7 +240,7 @@ export class ServerRequestPipeline {
239
240
  return await hmrManager.injectDevClientRuntimes(withUncachedDevHtml(response));
240
241
  }
241
242
  async tryHandleSharedApiRequest(request, context, parsedPathSegments) {
242
- return await this.apiRequestPipeline.tryHandle(request, context.apiHandlers, context.serverInstance, context.errorHandler, parsedPathSegments);
243
+ return await this.apiRequestPipeline.tryHandle(request, context.apiRoutes, context.serverInstance, context.errorHandler, parsedPathSegments);
243
244
  }
244
245
  /**
245
246
  * Resolves an error that escaped {@link handleSharedRequest} with the same
@@ -14,11 +14,13 @@ import { writeProductionAssetLedger } from '../../../build/production-asset-ledg
14
14
  import { getPrebuiltHtmlPageModuleScriptUrls } from '../../../html-pages/html-page-module-scripts.js';
15
15
  import { writeProductionRouteList } from '../../../build/production-route-list.js';
16
16
  import { getServerBundleOutputPaths, writeServerBundleDeployManifest, } from '../../../build/server-bundle-deploy-manifest.js';
17
- import { bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME } from '../../../config/server-config-bundle.js';
17
+ import { bundleEcoConfigModule } from '../../../config/server-config-bundle.js';
18
+ import { EMITTED_ECO_CONFIG_FILENAME } from '../../../config/resolve-eco-config-path.js';
18
19
  import { CLIENT_OUTPUT_DIR, resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
19
20
  import { createServerBundleLoaderSource, SERVER_BUNDLE_IMPLEMENTATION_FILENAME, } from '../../../utils/server-bundle-context.js';
20
21
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
21
22
  import { readEndpointHandlers } from '../http/endpoint-route-handler.js';
23
+ import { warnAboutUnattachedScripts } from './unattached-scripts.js';
22
24
  import { emitProductionServerModules, shouldBuildPagesUnifiedGraph, } from '../../../build/cache/pages-unified-graph-build.js';
23
25
  /**
24
26
  * Handles static site generation.
@@ -194,6 +196,7 @@ export class ServerStaticBuilder {
194
196
  router: dependencies.router,
195
197
  staticRoutes: dependencies.staticRoutes,
196
198
  errorPageLoaders: dependencies.errorPageLoaders,
199
+ onServerSources: (sources) => warnAboutUnattachedScripts(this.appConfig, sources),
197
200
  });
198
201
  }
199
202
  writeProductionRouteList(this.appConfig, dependencies.router.templateRoutes);
@@ -0,0 +1,17 @@
1
+ import type { EcoPagesAppConfig } from '../../../config/internal-types.js';
2
+ /**
3
+ * Lists the `.script` files under `srcDir` that nothing attaches to a page.
4
+ *
5
+ * @remarks
6
+ * A script is attached when a literal `dependencies.scripts` entry in a module of the server build names it, an
7
+ * HTML Page or the Html shell loads it with `<script src>`, or an attached script imports it. A module of the
8
+ * server build that imports a script also counts, since that script is then part of the build. A `src` computed at
9
+ * runtime is not found, and neither is a declaration in an MDX file, so such a script is listed here.
10
+ *
11
+ * @param serverModules Source files of the server build, whose declarations are read.
12
+ */
13
+ export declare function findUnattachedScripts(appConfig: EcoPagesAppConfig, serverModules: readonly string[]): Promise<string[]>;
14
+ /**
15
+ * Warns once per `.script` file that {@link findUnattachedScripts} lists.
16
+ */
17
+ export declare function warnAboutUnattachedScripts(appConfig: EcoPagesAppConfig, serverModules: readonly string[]): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import { appLogger } from '../../../global/app-logger.js';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { path } from '@ecopages/file-system/path';
4
+ import { collectHtmlPageModuleScriptBuildInputs, scanModuleScript, } from '../../../html-pages/html-page-module-scripts.js';
5
+ import { FILE_ROLE_SUFFIXES } from '../../../utils/file-roles.js';
6
+ import { findDeclaredScripts, scriptModuleLanguage } from '../../../build/rolldown/ssr-script-entries-plugin.js';
7
+ const SCRIPT_SUFFIXES = FILE_ROLE_SUFFIXES.filter((suffix) => suffix.startsWith('.script.'));
8
+ /**
9
+ * Lists the `.script` files under `srcDir` that nothing attaches to a page.
10
+ *
11
+ * @remarks
12
+ * A script is attached when a literal `dependencies.scripts` entry in a module of the server build names it, an
13
+ * HTML Page or the Html shell loads it with `<script src>`, or an attached script imports it. A module of the
14
+ * server build that imports a script also counts, since that script is then part of the build. A `src` computed at
15
+ * runtime is not found, and neither is a declaration in an MDX file, so such a script is listed here.
16
+ *
17
+ * @param serverModules Source files of the server build, whose declarations are read.
18
+ */
19
+ export async function findUnattachedScripts(appConfig, serverModules) {
20
+ const { srcDir } = appConfig.absolutePaths;
21
+ const patterns = SCRIPT_SUFFIXES.map((suffix) => `**/*${suffix}`);
22
+ const scripts = (await fileSystem.glob(patterns, { cwd: srcDir })).map((file) => path.resolve(srcDir, file));
23
+ if (scripts.length === 0)
24
+ return [];
25
+ const attached = new Set();
26
+ const roots = new Set();
27
+ for (const file of serverModules) {
28
+ attached.add(path.resolve(file));
29
+ const lang = scriptModuleLanguage(file);
30
+ if (!lang || !fileSystem.exists(file))
31
+ continue;
32
+ const code = fileSystem.readFileSync(file).toString();
33
+ if (!code.includes('scripts'))
34
+ continue;
35
+ for (const { src } of findDeclaredScripts(file, code, lang))
36
+ roots.add(path.resolve(path.dirname(file), src));
37
+ }
38
+ const html = collectHtmlPageModuleScriptBuildInputs(appConfig);
39
+ for (const script of html.scripts)
40
+ roots.add(path.resolve(script));
41
+ for (const file of html.files)
42
+ attached.add(path.resolve(file));
43
+ for (const root of roots) {
44
+ attached.add(root);
45
+ for (const file of scanModuleScript(appConfig, root).files)
46
+ attached.add(file);
47
+ }
48
+ return scripts.filter((script) => !attached.has(script)).sort();
49
+ }
50
+ /**
51
+ * Warns once per `.script` file that {@link findUnattachedScripts} lists.
52
+ */
53
+ export async function warnAboutUnattachedScripts(appConfig, serverModules) {
54
+ for (const script of await findUnattachedScripts(appConfig, serverModules)) {
55
+ appLogger.warn(`${path.relative(appConfig.rootDir, script)} is a browser script, but no dependencies.scripts entry or HTML <script src> attaches it, so it ships nowhere. Check the declaration's path, or delete the file.`);
56
+ }
57
+ }
@@ -3,7 +3,7 @@ import { WebSocketServer } from 'ws';
3
3
  import { HttpError } from '../../../errors/http-error.js';
4
4
  import { appLogger } from '../../../global/app-logger.js';
5
5
  import { parseSearchParams } from '../../../router/server/parse-search-params.js';
6
- import { findWebSocketRoute } from './ws-pattern-matcher.js';
6
+ import { compileWebSocketRoutes, findWebSocketRoute } from './ws-pattern-matcher.js';
7
7
  import { createEcopagesSocket, invokeWebSocketHandlerHook, toWebSocketCloseInfo } from './websocket-lifecycle.js';
8
8
  const attachedUpgradeServers = new WeakSet();
9
9
  function adaptNodeWebSocket(ws, kind, params, search, context) {
@@ -88,6 +88,7 @@ export function attachNodeHttpWebSocketUpgrades(server, options) {
88
88
  }
89
89
  attachedUpgradeServers.add(server);
90
90
  const userWss = new WebSocketServer({ noServer: true });
91
+ const websocketRoutes = compileWebSocketRoutes(options.websocketHandlers);
91
92
  server.on('upgrade', (req, socket, head) => {
92
93
  if (options.preflight?.(req, socket, head)) {
93
94
  return;
@@ -95,7 +96,7 @@ export function attachNodeHttpWebSocketUpgrades(server, options) {
95
96
  const url = new URL(req.url ?? '/', options.runtimeOrigin);
96
97
  let wsMatch;
97
98
  try {
98
- wsMatch = findWebSocketRoute(options.websocketHandlers, url.pathname);
99
+ wsMatch = findWebSocketRoute(websocketRoutes, url.pathname);
99
100
  }
100
101
  catch (error) {
101
102
  if (!HttpError.isHttpError(error) || error.status !== 400) {
@@ -1,7 +1,20 @@
1
1
  import type { EcopagesWebSocketHandler } from '../../../types/contracts.js';
2
+ import { type SegmentPattern } from '../../../router/server/segment-path-matcher.js';
2
3
  export type WebSocketRouteMatch = {
3
4
  handler: EcopagesWebSocketHandler<unknown, Record<string, string>>;
4
5
  params: Record<string, string>;
5
6
  kind: string;
6
7
  };
7
- export declare function findWebSocketRoute(handlers: Map<string, EcopagesWebSocketHandler<unknown, Record<string, string>>>, pathname: string): WebSocketRouteMatch | null;
8
+ /**
9
+ * WebSocket handlers with their patterns parsed, in registration order.
10
+ *
11
+ * @remarks Build it with {@link compileWebSocketRoutes} once the handlers are known, so an upgrade only
12
+ * compares path segments.
13
+ */
14
+ export type CompiledWebSocketRoutes = ReadonlyArray<{
15
+ pattern: string;
16
+ compiled: SegmentPattern<'websocket'>;
17
+ handler: EcopagesWebSocketHandler<unknown, Record<string, string>>;
18
+ }>;
19
+ export declare function compileWebSocketRoutes(handlers: ReadonlyMap<string, EcopagesWebSocketHandler<unknown, Record<string, string>>>): CompiledWebSocketRoutes;
20
+ export declare function findWebSocketRoute(routes: CompiledWebSocketRoutes, pathname: string): WebSocketRouteMatch | null;
@@ -1,20 +1,21 @@
1
- import { matchParsedSegmentPath, parseSegmentPath, scoreSegmentPathPattern, } from '../../../router/server/segment-path-matcher.js';
2
- export function findWebSocketRoute(handlers, pathname) {
1
+ import { compileSegmentPattern, matchParsedSegmentPath, parseSegmentPath, } from '../../../router/server/segment-path-matcher.js';
2
+ export function compileWebSocketRoutes(handlers) {
3
+ return [...handlers].map(([pattern, handler]) => ({
4
+ pattern,
5
+ compiled: compileSegmentPattern(pattern, 'websocket'),
6
+ handler,
7
+ }));
8
+ }
9
+ export function findWebSocketRoute(routes, pathname) {
3
10
  const pathSegments = parseSegmentPath(pathname);
4
11
  let best = null;
5
- let index = 0;
6
- for (const [pattern, handler] of handlers) {
7
- const params = matchParsedSegmentPath(pattern, pathSegments, 'websocket');
8
- if (params === null) {
9
- index += 1;
12
+ for (const { pattern, compiled, handler } of routes) {
13
+ const params = matchParsedSegmentPath(compiled, pathSegments);
14
+ if (params === null)
10
15
  continue;
16
+ if (best === null || compiled.score > best.score) {
17
+ best = { score: compiled.score, match: { handler, params, kind: pattern } };
11
18
  }
12
- const score = scoreSegmentPathPattern(pattern, 'websocket');
13
- const match = { handler, params, kind: pattern };
14
- if (best === null || score > best.score || (score === best.score && index < best.index)) {
15
- best = { score, match, index };
16
- }
17
- index += 1;
18
19
  }
19
20
  return best?.match ?? null;
20
21
  }
@@ -10,6 +10,8 @@ import { requireAppRuntime } from '../utils/app-runtime.js';
10
10
  import { BrowserBundleService } from './browser-bundle.service.js';
11
11
  import { getAssetDependencyKey, getDeclaredDependencyKey } from './asset-processing-service/asset-dependency-keys.js';
12
12
  import { isBundleableScript } from './asset-processing-service/bundleable-script.js';
13
+ /** Source bytes from which an installed package gets a chunk of its own in the app-wide build. */
14
+ const PACKAGE_CHUNK_MIN_SIZE = 10 * 1024;
13
15
  function hash(value) {
14
16
  return contentHash(value, 16);
15
17
  }
@@ -195,6 +197,7 @@ async function executeAppBrowserBuild(appConfig, buildEntries, htmlEntryNames) {
195
197
  splitting: true,
196
198
  naming: '[name]-[hash].[ext]',
197
199
  minify: group.options.minify ?? true,
200
+ packageChunks: { minSize: PACKAGE_CHUNK_MIN_SIZE },
198
201
  });
199
202
  assertBuildSucceeded(result, '[ecopages] Could not build the app browser client');
200
203
  for (const { path: output } of result.outputs) {
@@ -79,6 +79,15 @@ export declare class AssetProcessingService {
79
79
  * compiled or written; a dependency the ledger does not record is an error.
80
80
  */
81
81
  processDependencies(deps: AssetDefinition[], integration: AssetProcessingIntegration | undefined): Promise<ProcessedAsset[]>;
82
+ /**
83
+ * Processes `deps`, then returns the outputs the asset ledger records for them in declaration order.
84
+ *
85
+ * @remarks
86
+ * This is the order a sealed `ecopages start` returns, so an output recorded from it renders the same in the
87
+ * build and in start. A dependency processing skipped, such as a missing file, is left out until start, where
88
+ * it is an error.
89
+ */
90
+ processDependenciesInDeclarationOrder(deps: AssetDefinition[], integration: AssetProcessingIntegration | undefined): Promise<ProcessedAsset[]>;
82
91
  /**
83
92
  * Returns the emitted form of `dep` the production build recorded, if any.
84
93
  *
@@ -150,6 +150,25 @@ export class AssetProcessingService {
150
150
  await this.optimizeDependencies(results);
151
151
  return [...prebuilt, ...results];
152
152
  }
153
+ /**
154
+ * Processes `deps`, then returns the outputs the asset ledger records for them in declaration order.
155
+ *
156
+ * @remarks
157
+ * This is the order a sealed `ecopages start` returns, so an output recorded from it renders the same in the
158
+ * build and in start. A dependency processing skipped, such as a missing file, is left out until start, where
159
+ * it is an error.
160
+ */
161
+ async processDependenciesInDeclarationOrder(deps, integration) {
162
+ const processed = await this.processDependencies(deps, integration);
163
+ if (requireAppRuntime(this.config).processedAssets.isSealed)
164
+ return processed;
165
+ return prepareAssetDependencies(deps, integration, this.config.rootDir).flatMap((dep) => {
166
+ const recorded = this.lookupRecordedAsset(dep);
167
+ return recorded
168
+ ? [finalizeProcessedAsset(recorded, (asset) => this.resolveProcessedAssetSrcUrl(asset))]
169
+ : [];
170
+ });
171
+ }
153
172
  /**
154
173
  * Returns the emitted form of `dep` the production build recorded, if any.
155
174
  *