@ecopages/core 0.3.0 → 0.3.2

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 (201) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +40 -11
  4. package/src/adapters/node/create-app.js +95 -69
  5. package/src/adapters/node/dev-session.js +0 -1
  6. package/src/adapters/node/http-request-bridge.d.ts +4 -0
  7. package/src/adapters/node/http-request-bridge.js +9 -1
  8. package/src/adapters/node/runtime-host.d.ts +28 -6
  9. package/src/adapters/node/runtime-host.js +35 -9
  10. package/src/adapters/node/server-adapter.d.ts +10 -35
  11. package/src/adapters/node/server-adapter.js +21 -58
  12. package/src/adapters/shared/hmr/hmr-manager.d.ts +21 -7
  13. package/src/adapters/shared/hmr/hmr-manager.js +58 -70
  14. package/src/adapters/shared/http/api-request-pipeline.d.ts +3 -12
  15. package/src/adapters/shared/http/api-request-pipeline.js +7 -7
  16. package/src/adapters/shared/http/dist-file-handler.d.ts +16 -0
  17. package/src/adapters/shared/http/dist-file-handler.js +172 -0
  18. package/src/adapters/shared/http/explicit-static-route-matcher.js +2 -1
  19. package/src/adapters/shared/http/fs-server-response-matcher.js +3 -2
  20. package/src/adapters/shared/runtime/bind-runtime-server.d.ts +5 -7
  21. package/src/adapters/shared/runtime/bind-runtime-server.js +8 -12
  22. package/src/adapters/shared/runtime/copy-runtime-public-dir.js +10 -9
  23. package/src/adapters/shared/runtime/port-manager.d.ts +8 -11
  24. package/src/adapters/shared/runtime/port-manager.js +19 -30
  25. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +6 -9
  26. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +2 -5
  27. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +1 -3
  28. package/src/adapters/shared/runtime/server-request-pipeline.js +1 -5
  29. package/src/adapters/shared/runtime/server-static-builder.d.ts +3 -3
  30. package/src/adapters/shared/runtime/server-static-builder.js +3 -3
  31. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +2 -1
  32. package/src/adapters/shared/ws/websocket-lifecycle.d.ts +5 -6
  33. package/src/adapters/shared/ws/websocket-lifecycle.js +1 -2
  34. package/src/assets/app-browser-client-build.js +1 -2
  35. package/src/assets/asset-processing-service/browser-runtime-entry-resolution.js +8 -8
  36. package/src/assets/asset-processing-service/browser-runtime-entry.factory.js +4 -4
  37. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +12 -8
  38. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +36 -16
  39. package/src/assets/asset-processing-service/processors/stylesheet/file-stylesheet.processor.js +11 -6
  40. package/src/assets/browser-asset-output.d.ts +19 -0
  41. package/src/assets/browser-asset-output.js +30 -0
  42. package/src/assets/hashed-browser-asset.d.ts +8 -6
  43. package/src/assets/hashed-browser-asset.js +8 -6
  44. package/src/build/build-adapter.d.ts +2 -19
  45. package/src/build/build-adapter.js +0 -21
  46. package/src/build/build-graph.js +2 -2
  47. package/src/build/cache/cache-keys.d.ts +0 -3
  48. package/src/build/cache/cache-keys.js +0 -14
  49. package/src/build/cache/pages-unified-graph-build.js +2 -17
  50. package/src/build/contracts/build-contracts.d.ts +0 -3
  51. package/src/build/preserve-import-meta-transform.js +2 -2
  52. package/src/build/rolldown/app-package-declarations.js +3 -3
  53. package/src/build/rolldown/rolldown-adapter-helpers.js +3 -3
  54. package/src/build/rolldown/rolldown-build-adapter.d.ts +0 -1
  55. package/src/build/rolldown/rolldown-build-adapter.js +1 -2
  56. package/src/build/rolldown/rolldown-build-invocation-metrics.d.ts +1 -2
  57. package/src/build/rolldown/rolldown-build-invocation-metrics.js +5 -12
  58. package/src/build/rolldown/server-side-css-shim-plugin.js +3 -3
  59. package/src/build/runtime/build-queue.d.ts +8 -13
  60. package/src/build/runtime/build-queue.js +6 -17
  61. package/src/build/server/app-module-loader.service.d.ts +1 -1
  62. package/src/build/server/app-module-loader.service.js +0 -2
  63. package/src/build/server/page-module-import.service.d.ts +2 -3
  64. package/src/build/server/page-module-import.service.js +3 -4
  65. package/src/build/server-bundle-deploy-manifest.d.ts +5 -0
  66. package/src/build/server-bundle-deploy-manifest.js +15 -1
  67. package/src/build/server-bundle-publication.js +4 -5
  68. package/src/build.d.ts +2 -2
  69. package/src/build.js +2 -2
  70. package/src/config/assembly/app-runtime.d.ts +2 -2
  71. package/src/config/assembly/app-runtime.js +2 -2
  72. package/src/config/assembly/finalize-config.d.ts +4 -4
  73. package/src/config/assembly/finalize-config.js +4 -5
  74. package/src/config/config-module-files.js +2 -3
  75. package/src/config/internal-types.d.ts +0 -7
  76. package/src/config/user-config-types.d.ts +0 -4
  77. package/src/diagnostics/request-pipeline-metrics.d.ts +3 -3
  78. package/src/diagnostics/request-pipeline-metrics.js +4 -4
  79. package/src/diagnostics/startup-trace.js +2 -5
  80. package/src/errors/http-error.d.ts +2 -2
  81. package/src/errors/http-error.js +4 -4
  82. package/src/hmr/client/hmr-runtime.js +16 -7
  83. package/src/hmr/client/module-update.d.ts +7 -0
  84. package/src/hmr/client/module-update.js +21 -4
  85. package/src/hmr/hmr-strategy.d.ts +0 -3
  86. package/src/hmr/hmr-strategy.js +0 -3
  87. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -3
  88. package/src/hmr/strategies/js-hmr-strategy.js +3 -6
  89. package/src/html-pages/html-page-module-scripts.js +4 -3
  90. package/src/html-pages/html-page-renderer.js +2 -3
  91. package/src/plugins/alias-resolver-cache.d.ts +4 -3
  92. package/src/plugins/alias-resolver-cache.js +4 -3
  93. package/src/plugins/component-import-discovery.js +4 -4
  94. package/src/plugins/eco-component-meta-plugin.d.ts +10 -1
  95. package/src/plugins/eco-component-meta-plugin.js +66 -10
  96. package/src/plugins/foreign-jsx-override-plugin.js +4 -3
  97. package/src/plugins/tsconfig-import-resolver.js +12 -12
  98. package/src/route-renderer/error-pages/default-error-pages.js +2 -1
  99. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -1
  100. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +0 -1
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +10 -5
  102. package/src/route-renderer/orchestration/integration-renderer.js +13 -14
  103. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -23
  104. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -29
  105. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +10 -32
  106. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +2 -2
  107. package/src/route-renderer/page-loading/page-dependency-bundling.js +5 -5
  108. package/src/route-renderer/page-loading/page-module-loader.js +1 -1
  109. package/src/route-renderer/route-renderer.d.ts +2 -5
  110. package/src/route-renderer/route-renderer.js +2 -4
  111. package/src/router/client/link-navigation-policy.d.ts +4 -1
  112. package/src/router/client/link-navigation-policy.js +20 -6
  113. package/src/router/server/route-registry.d.ts +0 -1
  114. package/src/router/server/route-registry.js +3 -13
  115. package/src/router/server/segment-path-matcher.d.ts +12 -0
  116. package/src/router/server/segment-path-matcher.js +30 -0
  117. package/src/static-site-generator/static-site-generator.d.ts +0 -5
  118. package/src/static-site-generator/static-site-generator.js +2 -15
  119. package/src/types/contracts.d.ts +17 -27
  120. package/src/types/public-types.d.ts +1 -1
  121. package/src/utils/format-error-chain.d.ts +9 -0
  122. package/src/utils/format-error-chain.js +20 -0
  123. package/src/utils/invariant.d.ts +6 -1
  124. package/src/utils/invariant.js +7 -2
  125. package/src/watchers/project-watcher.d.ts +20 -1
  126. package/src/watchers/project-watcher.js +40 -9
  127. package/src/watchers/workspace-package-watch-roots.js +5 -5
  128. package/src/adapters/README.md +0 -58
  129. package/src/adapters/shared/hmr/hmr-manager.test-helpers.d.ts +0 -28
  130. package/src/adapters/shared/hmr/hmr-manager.test-helpers.js +0 -53
  131. package/src/adapters/shared/runtime/runtime-host.d.ts +0 -15
  132. package/src/adapters/shared/runtime/runtime-host.js +0 -1
  133. package/src/assets/README.md +0 -35
  134. package/src/build/README.md +0 -298
  135. package/src/build/server/README.md +0 -50
  136. package/src/cache/README.md +0 -5
  137. package/src/client/README.md +0 -5
  138. package/src/client/navigation-scripts/navigation-scripts.test.browser.d.ts +0 -1
  139. package/src/client/navigation-scripts/navigation-scripts.test.browser.js +0 -111
  140. package/src/client/scroll.test.browser.d.ts +0 -1
  141. package/src/client/scroll.test.browser.js +0 -31
  142. package/src/client/view-transitions.test.browser.d.ts +0 -1
  143. package/src/client/view-transitions.test.browser.js +0 -53
  144. package/src/config/README.md +0 -58
  145. package/src/config/constants.d.ts +0 -1
  146. package/src/config/constants.js +0 -1
  147. package/src/dev/README.md +0 -61
  148. package/src/dev/invalidation/README.md +0 -11
  149. package/src/dev-toolbar/README.md +0 -66
  150. package/src/diagnostics/README.md +0 -11
  151. package/src/eco/README.md +0 -776
  152. package/src/errors/README.md +0 -5
  153. package/src/global/README.md +0 -5
  154. package/src/hmr/README.md +0 -64
  155. package/src/hmr/client/build-error-overlay.test.browser.d.ts +0 -1
  156. package/src/hmr/client/build-error-overlay.test.browser.js +0 -48
  157. package/src/hmr/client/hmr-runtime.test.browser.d.ts +0 -1
  158. package/src/hmr/client/hmr-runtime.test.browser.js +0 -32
  159. package/src/hmr/entrypoint-dependency-graph.d.ts +0 -12
  160. package/src/hmr/entrypoint-dependency-graph.js +0 -27
  161. package/src/hmr/hmr-file-change-prep.d.ts +0 -9
  162. package/src/hmr/hmr-file-change-prep.js +0 -11
  163. package/src/html/README.md +0 -15
  164. package/src/html-pages/README.md +0 -104
  165. package/src/islands/README.md +0 -44
  166. package/src/page-cache/README.md +0 -17
  167. package/src/plugins/README.md +0 -53
  168. package/src/route-renderer/GRAPH.md +0 -142
  169. package/src/route-renderer/README.md +0 -160
  170. package/src/route-renderer/error-pages/README.md +0 -11
  171. package/src/route-renderer/orchestration/custom-element-scripts/README.md +0 -15
  172. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.d.ts +0 -39
  173. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +0 -94
  174. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.d.ts +0 -35
  175. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.js +0 -69
  176. package/src/router/README.md +0 -160
  177. package/src/router/client/link-intent.test.browser.d.ts +0 -1
  178. package/src/router/client/link-intent.test.browser.js +0 -33
  179. package/src/router/client/link-navigation-policy.test.browser.d.ts +0 -1
  180. package/src/router/client/link-navigation-policy.test.browser.js +0 -142
  181. package/src/router/client/navigation-commit.test.browser.d.ts +0 -1
  182. package/src/router/client/navigation-commit.test.browser.js +0 -116
  183. package/src/router/client/navigation-document.test.browser.d.ts +0 -1
  184. package/src/router/client/navigation-document.test.browser.js +0 -77
  185. package/src/router/client/navigation-head.test.browser.d.ts +0 -1
  186. package/src/router/client/navigation-head.test.browser.js +0 -101
  187. package/src/router/client/navigation-lifecycle.test.browser.d.ts +0 -1
  188. package/src/router/client/navigation-lifecycle.test.browser.js +0 -97
  189. package/src/router/client/navigation-view-transition.test.browser.d.ts +0 -1
  190. package/src/router/client/navigation-view-transition.test.browser.js +0 -189
  191. package/src/router/client/staged-stylesheets.test-fixtures.d.ts +0 -18
  192. package/src/router/client/staged-stylesheets.test-fixtures.js +0 -31
  193. package/src/static-site-generator/README.md +0 -67
  194. package/src/static-site-generator/static-site-generator.test-utils.d.ts +0 -2
  195. package/src/static-site-generator/static-site-generator.test-utils.js +0 -41
  196. package/src/types/README.md +0 -5
  197. package/src/utils/README.md +0 -7
  198. package/src/validation/README.md +0 -9
  199. package/src/watchers/README.md +0 -15
  200. package/src/watchers/project-watcher.test-helpers.d.ts +0 -60
  201. package/src/watchers/project-watcher.test-helpers.js +0 -108
@@ -1,5 +0,0 @@
1
- # Core Errors
2
-
3
- **Layer:** Foundation.
4
-
5
- This directory defines errors shared across config, rendering, build, and runtime adapters. Error types should not depend on the systems that report them.
@@ -1,5 +0,0 @@
1
- # Shared Runtime Logging
2
-
3
- **Layer:** Foundation.
4
-
5
- This directory owns core-wide logging facilities used by higher layers. App-specific state belongs to `AppRuntime`, not module-global mutable state.
package/src/hmr/README.md DELETED
@@ -1,64 +0,0 @@
1
- # HMR Layer
2
-
3
- **Layer:** Development and HMR.
4
-
5
- This directory contains the framework-owned hot-update strategy contracts used by runtime adapters and integrations.
6
-
7
- ## Purpose
8
-
9
- The HMR layer separates change classification from update execution.
10
-
11
- It is responsible for:
12
-
13
- - defining the shared HMR manager and strategy contracts
14
- - letting integrations contribute framework-specific update strategies
15
- - keeping adapter transports independent from update policy
16
-
17
- ## How It Fits
18
-
19
- 1. `ProjectWatcher` observes file changes.
20
- 2. `DevelopmentInvalidationService` classifies the change.
21
- 3. The active HMR manager selects a strategy.
22
- 4. The strategy coordinates browser rebuilds, metadata reloads, and client broadcasts.
23
-
24
- Public-directory and `additionalWatchPaths` changes skip the HMR manager: the Project Watcher sends `reload` through the client bridge itself.
25
-
26
- A `source` module recorded in both a server route's and a browser entrypoint's import closures also reloads the browser. This refreshes server-rendered markup when an edited module is shared with an island; an island-only `update` would leave the server-rendered copy stale.
27
-
28
- ## Design Rule
29
-
30
- Generic invalidation policy belongs in core services.
31
- Framework-specific update behavior belongs in HMR strategies.
32
- Runtime-specific WebSocket or event-stream transport belongs in adapters.
33
-
34
- ## Registered entrypoints and dev transform
35
-
36
- `HmrManager` in `adapters/shared/hmr/` centralizes file-change handling via `handleFileChange()` and `handleFileChanges()`. A Project Watcher batch sends all HMR-eligible paths through `handleFileChanges()` once. The manager skips missing-file events and clears their entrypoint registration. It dispatches each path to its selected strategy and coalesces the results: a `reload` from any file replaces the rest, several layout updates become one soft refresh, and every other distinct update is kept, so an edit shared by two islands hot-updates both. A file whose strategy throws is reported as an `error` event and does not drop the others. Server modules are marked dirty once, by the watcher batch, before the manager runs; the manager only runs integration hooks for a registered entrypoint, rebuilds its dev-transform module, and broadcasts. A registered entrypoint's server module is imported again on the next request, not on the file event.
37
-
38
- Dev client modules are served on demand through `DevTransformServer` (`src/dev/`). `DevTransformEntrypointRegistry` tracks registered entrypoints for HMR invalidation. Registration returns a stable dev-transform URL immediately; the first request (or cache miss) runs Rolldown on demand.
39
-
40
- Each module the dev transform serves records its local imports in the per-app dependency graph owned by `HmrManager`; its reverse lookup shares the app's build-input index. `JsHmrStrategy` only claims a JavaScript or TypeScript change to a watched entrypoint, a served module, or a file a served module imports. Any other file, such as a server-only module, an HTML Page classic script, or a module that has not been served yet, is left to the other strategies; when none matches, `DefaultHmrStrategy` reloads the page. A claimed file whose importers are not watched entrypoints also ends in a reload.
41
-
42
- The HMR client and the Dev Toolbar client are two `DevClientRuntime` entries (`dev-client-runtime.ts`: URL, entry, work directory, failure policy) that `HmrManager` bundles once per `DevSession`, serves at their URLs and loads from every HTML response through `injectDevClientRuntimes()`. Only runtimes whose bundle was built are served and injected. A failed HMR bundle disables HMR, which also stops the Dev Toolbar from loading and adding its page manifest because both are gated on the manager being enabled. A failed Dev Toolbar bundle is logged and leaves HMR on. The request pipeline injects clients only while `IHmrManager.isEnabled()` is true.
43
-
44
- `BrowserBundleService` is the sole browser-plugin resolver for HMR builds. HMR managers route `hmr-runtime` and `hmr-entrypoint` rebuilds through the `hmr` lane of the app's build queue.
45
-
46
- `HmrManager` calls `prepareHmrFileChange()` for each dispatched path (`hmr/hmr-file-change-prep.ts`) so page browser graph sessions invalidate consistently with file changes. The Project Watcher sends the file paths from the batch and does not prepare the graph itself.
47
-
48
- ## Client events
49
-
50
- Before displaying an error fallback, the client dispatches the cancelable `ecopages:build-error` window event with `{ message: string }`. A toolbar client claims presentation by calling `preventDefault()` synchronously. Any non-error HMR event clears active messages and dispatches `ecopages:build-error-clear`. Clients mounting late dispatch `ecopages:build-error-request` to replay active messages and replace the fallback. Event names and the payload type are public at `@ecopages/core/client`; see [the toolbar contract](../dev-toolbar/README.md#build-error-presentation).
51
-
52
- | Event | Client behavior |
53
- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
54
- | `update` | Cache-bust and re-import the changed module URL (or reload the active page module) |
55
- | `css-update` | Refresh matching stylesheet `link` hrefs |
56
- | `layout-update` | Soft current-page reload with layout cache cleared (`persistLayouts` remounts the updated layout without a full document reload). Falls back to `location.reload()` only if no navigation owner handles it |
57
- | `reload` | Full `location.reload()` |
58
- | `error` | Logs to the console and offers the message to toolbar clients. Unclaimed messages appear once in a fixed element appended to `<html>` (`client/build-error-overlay.ts`). Any other event clears errors; Escape, Dismiss, and a click outside a text selection dismiss the fallback |
59
-
60
- `error` events also report watcher and route errors. `HmrManager` broadcasts one when the dev transform server fails to build a requested module, and sends pending ones to a socket that connects later; see [dev/README.md](../dev/README.md#build-errors-of-served-modules).
61
-
62
- Other HMR events are not queued. While no browser is connected, `HmrManager` drops a file change's events and logs that it did so at debug level. A tab opened later loads its page after the change, so its HTML and versioned module URLs are already current. A tab whose socket was reconnecting at the time keeps its old page until the next change; replaying a `reload` to cover it would also reload every freshly opened tab, because the server cannot tell the two apart.
63
-
64
- Dev-transform local imports are rewritten with a content-hash query (`?v=…`) so transitive layout/component modules get a new ESM module-map key after invalidation. Soft `layout-update` then picks up the new layout while shared outer layout persistence still applies across normal SPA navigations.
@@ -1 +0,0 @@
1
- export {};
@@ -1,48 +0,0 @@
1
- import { afterEach, describe, expect, it } from 'vitest';
2
- import { userEvent } from 'vitest/browser';
3
- import { BUILD_ERROR_OVERLAY_ID, clearBuildError, showBuildError } from './build-error-overlay.js';
4
- const getOverlay = () => document.getElementById(BUILD_ERROR_OVERLAY_ID);
5
- const getEntries = () => Array.from(getOverlay()?.querySelectorAll('pre') ?? []).map((entry) => entry.textContent);
6
- describe('build error overlay', () => {
7
- afterEach(() => {
8
- document.getSelection()?.removeAllRanges();
9
- clearBuildError();
10
- });
11
- it('lists each distinct message as text under one label', () => {
12
- showBuildError('first <b>error</b>');
13
- showBuildError('second error');
14
- showBuildError('first <b>error</b>');
15
- expect(document.querySelectorAll(`#${BUILD_ERROR_OVERLAY_ID}`)).toHaveLength(1);
16
- expect(getOverlay()?.textContent).toContain('[ecopages] Error');
17
- expect(getEntries()).toEqual(['first <b>error</b>', 'second error']);
18
- expect(getOverlay()?.querySelector('b')).toBeNull();
19
- });
20
- it('stays in the page when the body is replaced', () => {
21
- showBuildError('error');
22
- document.body.replaceWith(document.createElement('body'));
23
- expect(getOverlay()).not.toBeNull();
24
- });
25
- it('is removed by clear, the Dismiss button and Escape', async () => {
26
- showBuildError('error');
27
- clearBuildError();
28
- expect(getOverlay()).toBeNull();
29
- showBuildError('error');
30
- await userEvent.click(getOverlay().querySelector('button'));
31
- expect(getOverlay()).toBeNull();
32
- showBuildError('error');
33
- await userEvent.keyboard('{Escape}');
34
- expect(getOverlay()).toBeNull();
35
- });
36
- it('stays open when a click ends a text selection', async () => {
37
- showBuildError('selectable error');
38
- const entry = getOverlay().querySelector('pre');
39
- await userEvent.dragAndDrop(entry, entry, {
40
- sourcePosition: { x: 2, y: 5 },
41
- targetPosition: { x: 60, y: 5 },
42
- });
43
- expect(document.getSelection()?.isCollapsed).toBe(false);
44
- expect(getOverlay()).not.toBeNull();
45
- await userEvent.click(entry);
46
- expect(getOverlay()).toBeNull();
47
- });
48
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,32 +0,0 @@
1
- import { afterAll, expect, it, vi } from 'vitest';
2
- import { BUILD_ERROR_OVERLAY_ID } from './build-error-overlay.js';
3
- class FakeSocket {
4
- url;
5
- static instances = [];
6
- listeners = new Map();
7
- constructor(url) {
8
- this.url = url;
9
- FakeSocket.instances.push(this);
10
- }
11
- addEventListener(type, listener) {
12
- this.listeners.set(type, listener);
13
- }
14
- receive(payload) {
15
- this.listeners.get('message')?.({ data: JSON.stringify(payload) });
16
- }
17
- }
18
- afterAll(() => {
19
- vi.unstubAllGlobals();
20
- vi.restoreAllMocks();
21
- });
22
- it('shows an HMR error in the page and removes it on the next update', async () => {
23
- vi.spyOn(console, 'error').mockImplementation(() => undefined);
24
- vi.spyOn(console, 'log').mockImplementation(() => undefined);
25
- vi.stubGlobal('WebSocket', FakeSocket);
26
- await import('./hmr-runtime.js');
27
- const socket = FakeSocket.instances[0];
28
- socket.receive({ type: 'error', message: 'syntax error in widget.ts' });
29
- await vi.waitFor(() => expect(document.getElementById(BUILD_ERROR_OVERLAY_ID)?.textContent).toContain('syntax error in widget.ts'));
30
- socket.receive({ type: 'css-update', path: '/assets/missing.css' });
31
- await vi.waitFor(() => expect(document.getElementById(BUILD_ERROR_OVERLAY_ID)).toBeNull());
32
- });
@@ -1,12 +0,0 @@
1
- import { BuildInputDependencyIndex } from '../build/cache/build-input-dependency-index.js';
2
- /**
3
- * HMR-owned in-memory dependency graph with reverse lookups for watched entrypoints.
4
- */
5
- export declare class InMemoryEntrypointDependencyGraph {
6
- private readonly inputIndex;
7
- constructor(inputIndex?: BuildInputDependencyIndex);
8
- getDependencyEntrypoints(filePath: string): Set<string>;
9
- setEntrypointDependencies(entrypointPath: string, dependencies: string[]): void;
10
- clearEntrypointDependencies(entrypointPath: string): void;
11
- reset(): void;
12
- }
@@ -1,27 +0,0 @@
1
- import path from 'node:path';
2
- import { BuildInputDependencyIndex } from '../build/cache/build-input-dependency-index.js';
3
- /**
4
- * HMR-owned in-memory dependency graph with reverse lookups for watched entrypoints.
5
- */
6
- export class InMemoryEntrypointDependencyGraph {
7
- inputIndex;
8
- constructor(inputIndex = new BuildInputDependencyIndex()) {
9
- this.inputIndex = inputIndex;
10
- }
11
- getDependencyEntrypoints(filePath) {
12
- return new Set(this.inputIndex.resolveKeys('entrypoint', filePath));
13
- }
14
- setEntrypointDependencies(entrypointPath, dependencies) {
15
- const normalizedEntrypoint = path.resolve(entrypointPath);
16
- this.inputIndex.register({ consumer: 'entrypoint', key: normalizedEntrypoint }, [
17
- normalizedEntrypoint,
18
- ...dependencies,
19
- ]);
20
- }
21
- clearEntrypointDependencies(entrypointPath) {
22
- this.inputIndex.unregister({ consumer: 'entrypoint', key: path.resolve(entrypointPath) });
23
- }
24
- reset() {
25
- this.inputIndex.clearConsumer('entrypoint');
26
- }
27
- }
@@ -1,9 +0,0 @@
1
- import type { EcoPagesAppConfig } from '../config/internal-types.js';
2
- import { type AffectedGraphIdentity } from '../route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js';
3
- export type HmrFileChangePreparation = {
4
- affectedGraphIdentities: AffectedGraphIdentity[];
5
- };
6
- /**
7
- * Invalidates affected Page Browser Graph records before HMR strategy dispatch.
8
- */
9
- export declare function prepareHmrFileChange(appConfig: EcoPagesAppConfig, filePath: string): HmrFileChangePreparation;
@@ -1,11 +0,0 @@
1
- import path from 'node:path';
2
- import { getAffectedPageBrowserGraphIdentities, invalidatePageBrowserGraphSession, } from '../route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js';
3
- /**
4
- * Invalidates affected Page Browser Graph records before HMR strategy dispatch.
5
- */
6
- export function prepareHmrFileChange(appConfig, filePath) {
7
- const resolvedFilePath = path.resolve(filePath);
8
- const affectedGraphIdentities = getAffectedPageBrowserGraphIdentities(appConfig, resolvedFilePath);
9
- invalidatePageBrowserGraphSession(appConfig, resolvedFilePath);
10
- return { affectedGraphIdentities };
11
- }
@@ -1,15 +0,0 @@
1
- # HTML
2
-
3
- **Layer:** Foundation.
4
-
5
- Core's HTML utilities rewrite rendered documents and parse source markup for HTML Pages.
6
-
7
- ## Document rewriting
8
-
9
- `HtmlRewriter` streams markup through a focused subset of the HTMLRewriter element API. Its tag selectors and insertion methods follow the output pinned against lol-html in `html-rewriter.test.ts`.
10
-
11
- `HtmlTransformerService` injects processed assets and document contributions supplied for one render. It does not hold queued per-render dependencies, so overlapping renders cannot consume each other's head or body contributions. Generated URLs and attribute values are escaped before tags are written.
12
-
13
- ## Source parsing
14
-
15
- `html-tokenizer.ts` holds the lexical rules shared by `HtmlRewriter` and `html-source-parser.ts`. The positional parser exposes source offsets for callers that splice existing markup, including [HTML Pages](../html-pages/README.md). Entity decoding is shared with other core features through Foundation utilities; the parser keeps its one-pass decoding behavior.
@@ -1,104 +0,0 @@
1
- # HTML Pages
2
-
3
- **Layer:** Rendering.
4
-
5
- This directory owns `.html` Filesystem Routes: plain HTML files under `src/pages/` rendered inside the application's Html shell with the app's default Cache Strategy. HTML Pages need no package, plugin call, or config field.
6
-
7
- ## Ownership
8
-
9
- `finalizeEcoPagesConfig()` appends the internal `html-pages` Integration after user Integrations, unless a user Integration already declares `.html`. Appending last keeps the first-extension fallback for missing semantic templates unchanged for existing apps. There is no public plugin factory.
10
-
11
- | File | Role |
12
- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------- |
13
- | `html-pages.plugin.ts` | `HtmlPagesPlugin`: owns `.html` with `HtmlPageRenderer`, implements `compilePageModule`, sets `acceptsParams = false` |
14
- | `html-page-template.ts` | Compiles a Page or Html shell file into template parts, asset declarations, head nodes, metadata, and social tags |
15
- | `html-page-module.ts` | Builds the Page or shell module in-process and owns the built-in shell |
16
- | `html-page-renderer.ts` | `StringMarkupRenderer` subclass: emits assets in place, uses the shared shell render, reconciles the head |
17
- | `html-page-document.ts` | Reconciles Page head tags and `<html>`/`<body>` attributes onto the finalized document |
18
- | `html-page-module-scripts.ts` | Collects every HTML Page's and the shell's module scripts, then maps each script to its URL |
19
- | `html-page-classic-script.ts` | Validates a classic `<script src>` and marks it `classic`: module-only code, JSX and compile helpers are rejected |
20
-
21
- Parsing uses `html/html-source-parser.ts`, a positional parser built on the same tokenizer as `HtmlRewriter` (`html/html-tokenizer.ts`).
22
-
23
- ## Module loading
24
-
25
- Core never checks for HTML Pages by name. It finds a file's owning Integration with `findIntegrationForFile()` (the longest registered extension) and asks it:
26
-
27
- - `PageModuleImportService.loadModule()` calls the owner's `compilePageModule()` before bundling. `HtmlPagesPlugin.compilePageModule()` compiles files under the pages directory and `src/includes/html.html` with `loadHtmlPageModule()`, and throws for any other `.html` file; an Integration that implements the hook compiles every file core loads for it. Bun and Node load HTML Pages the same way, and the import cache still keys modules by file hash.
28
- - `isPagesUnifiedGraphPage()` leaves out Pages whose owner implements `compilePageModule`, so HTML Pages stay out of the production unified graph.
29
- - Route discovery rejects `[param]` filenames whose owner sets `acceptsParams` to `false`, because HTML Pages have no `staticPaths`.
30
-
31
- Each component carries its compiled template on an interned symbol, read with `getCompiledHtmlTemplate()`. Calling the component directly throws, because rendering needs the owning renderer's asset pipeline. A Page component also exposes `metadata`, built from its head tags and merged over `defaultMetadata`, so static export and the Sitemap read it like an `eco.page()` Page.
32
-
33
- The Page and `html.html` components register their local asset files as discovered watch files on their identity. `collectRenderShellSourcePaths()` adds identity watch files to rendered HTML cache dependencies, so editing a referenced stylesheet or script invalidates every route the Page or shell renders into, including routes owned by other Integrations that use `html.html`.
34
-
35
- ## Compilation
36
-
37
- A Page is read into three parts:
38
-
39
- - **Head nodes**: children of the Page `<head>`. Without one, the leading `<title>`, `<meta>`, `<link>`, `<style>`, `<script>`, `<base>` and `<template>` elements form the head, as the HTML parsing rules do: the doctype, whitespace and comments are skipped, and the first other element, `<noscript>` or text ends it. Head nodes have a singleton key for `<title>`, `<base>`, `<meta charset>`, keyed `<meta>` (by the value of the first of `name`, `property` and `http-equiv` it has, so `property="twitter:title"` and `name="twitter:title"` are the same tag), and `<link rel="canonical">`. A second `<head>` is an error. When the Page has a `<title>` or a description `<meta>`, the compiler appends `og:title`, `og:description`, `twitter:title`, and `twitter:description` from them, unless the Page writes that tag itself. Other social tags, such as `og:image`, `og:type`, and `twitter:card`, are never derived.
40
- - **Body markup**: everything outside the head (the `<head>` element or the leading head elements), with the doctype and the `<html>` and `<body>` start and end tags removed.
41
- - **Root attributes**: the attributes of the Page `<html>` and `<body>` elements.
42
-
43
- An Html shell must contain `<html>` with `<head>` and `<body>` and exactly one `<!-- eco:children -->` comment, which becomes the children slot. Its doctype is dropped because the renderer always emits one.
44
-
45
- Processed asset tags become slots:
46
-
47
- | Tag | Processing |
48
- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
- | `<link rel="stylesheet">` with a relative `href` | `FileStylesheetProcessor`; production names the file from a hash of the processed CSS |
50
- | `<style>` with no `type`, or `type="text/css"` | `ContentStylesheetProcessor` inline; `processingOrigin` is `<file>.css`; a `</style` in the output is escaped as `<\/style` |
51
- | `<script type="module">` with a relative `src` | Static production export includes every HTML Page's and shell module script in the app-wide browser build; `ecopages start` restores those URLs from the build manifest after checking the recorded browser sources and outputs; otherwise without HMR, one shared multi-entry build (`html-page-module-scripts.ts`); with HMR, `FileScriptProcessor` and the HMR manager; a side-effect `.css` import is an error (see Rendering) |
52
- | classic `<script>` with a relative `src` | `FileScriptProcessor` with `classic: true`: compiled on its own in script mode, ignoring `tsconfig.json`, and minified in production without renaming top-level names or dropping legal comments; never bundled, outside the HMR pipeline (in development, editing one reloads the page, except under `src/includes/` or `src/views/`, where edits refresh the page in place), and emitted under the source path and name (`.ts` becomes `.js`), without a content hash. JSX files, module syntax, relative `import()`, top-level `await` and code that needs a compile helper (such as a decorator) are errors |
53
- | `<link rel="preload">` or `rel="modulepreload"` with a relative `href` | Not processed itself: at render it takes the URL of the asset with the same file and the kind it preloads (`modulepreload` a module script, `as="style"` a stylesheet, `as="script"` a classic script) in the Page or the shell (the shared build's URL, or the HMR URL); with none, it stays as written and a development warning names it |
54
-
55
- With [`@ecopages/browser-router`](../../../browser-router/README.md#scripts-on-navigation), a classic script in the Page body runs again on every navigation that renders it, so its top-level `const`, `let` and `class` declarations would be declared twice and throw. Such scripts should use `var` or functions, or wrap the code in a block or an IIFE; a module script runs once per URL.
56
-
57
- `processingOrigin` sits beside the HTML file and ends in `.css` because processors resolve relative imports against it and filter by extension.
58
-
59
- Relative paths, with or without `./`, resolve against the containing file and must stay inside the source directory, except a preload `href`, which then matches no processed file; query strings and fragments are ignored for the lookup. A processed tag with `integrity` is an error, and so is a preload hint with `integrity` that matches a processed file; an unmatched one stays as written with the usual warning. Tags with external or root-relative URLs, inline scripts, and scripts with a non-JavaScript `type` stay literal.
60
-
61
- An inline `<script type="module">` that imports a relative specifier (`./` or `../`), statically, by re-export, or by a dynamic `import()` of a string literal, is a compile error naming the file and asking to move the code to a file. It is not sent through the inline content-script path (`AssetFactory.createInlineContentScript()`): that path builds each script alone from an entry file in the work directory, so a relative import would resolve against the wrong directory, and a module the script shares with the Page's module scripts would be a second copy that runs again, the duplication the shared build exists to avoid. Bare and root-relative imports, and non-literal dynamic imports, stay literal.
62
-
63
- In development, a relative URL left literal logs a warning once per file revision: `src`, `srcset`, `imagesrcset`, `href` (except on `<a>`, `<area>`, `<base>`, and preload links), `xlink:href` (except on `<a>`, `<area>`, and `<base>`), `poster`, `<object data>`, and `url()` or an `image-set()` string in a `style` attribute, outside comments. The `content` of `og:image`, `og:image:url`, `og:image:secure_url`, `twitter:image`, and `twitter:image:src` warns unless it is an absolute URL, because link preview crawlers need one.
64
-
65
- Two warnings depend on rendering and are logged by the renderer through `warnHtmlTemplateRender()`, once per URL or preload `href` and revision of the file, building the message only when it logs: a relative URL that processed `<style>` output still holds, and a preload hint that matches no processed file. The preload warning names the fix: the right `rel` or `as` when the file is processed as another kind; for a preload of a stylesheet or script, the other HTML files that load the file (found with `findHtmlFilesLoading()`, which compiles every HTML file, so it runs only in development and at most once per file revision), asking a Page to load the file too and a shell to move the preload to those Pages; otherwise a move to the public directory. Within one `emitAssets()` call, a preload and its target share one URL lookup, so the file is processed once.
66
-
67
- Compile-time warning hashes and render-time warning keys live on the owning `AppRuntime`. Each app warns once per file revision; two apps loading the same HTML file keep their warning history separate.
68
-
69
- ## Rendering
70
-
71
- `HtmlPageRenderer.renderHtmlPage()` processes the Page's asset declarations and splices each emitted URL (or processed CSS) into the tag as written, so every other attribute is preserved. A missing local file, or an asset the pipeline cannot process, throws an error naming the HTML file. A local file declared by both the shell and the Page is emitted once, by the shell; within a file, the first declaration wins. The body markup then renders through the shared document-shell composition, so an `html.html`, built-in, JSX, or React shell wraps it the same way. When the rendered shell has no `<body>` (JSX shells that leave it to Layouts), the Page markup is wrapped in one.
72
-
73
- Without HMR, module scripts are not processed one by one. The shared build includes every module script of every HTML Page and the `html.html` shell with code splitting, so a module several scripts import, on one Page or across Pages, is one chunk with one URL, and a script has the same URL on every Page; the browser runs each once, also across browser-router navigations. Static production export places those scripts in the app-wide browser build, where they share a build group with Page Browser Graph entries from other Integrations only when their bundle options are compatible. `ecopages start` restores the HTML module-script URLs from the build manifest after checking that the HTML files and all source files recorded by the browser build still match the export. Outside that export, production builds once; development reuses the build while the HTML files, scripts, and local modules visited by the stylesheet scan keep the same contents; an edit inside a package is not detected. An HTML file that does not compile is left out of the build, so only its own render fails; a script that does not build fails the build, and so every HTML Page with a module script, until the next render builds again.
74
-
75
- A module script cannot add a stylesheet to the Page: the PostCSS Processor turns a CSS file into a module exporting the CSS string, and without a CSS Processor the bundler rejects it. So `scanModuleScript()` scans a module script and the local modules it imports, statically or dynamically, for a side-effect stylesheet import: an import or re-export that binds nothing (`import './styles.css'`, `export * from './styles.css'`) of a file ending in `.css`, local or in a package (`import 'swiper/css'`). The shared build leaves such a script out, and rendering an HTML file that loads it, with or without HMR, throws an error naming the HTML file, the stylesheet, and the importing module when it is not the script itself, with paths relative to the app root. For a stylesheet under `src` it suggests `<link rel="stylesheet" href="…">` in the HTML file; for one outside `src`, as in a package, it says to copy the file under `src` and link it. Other HTML Pages still render. The scan does not follow type-only imports or scan packages, and skips the stylesheet imports the component meta transform moves into Component Dependencies. `import styles from './styles.css'`, which binds the CSS string, is allowed; without a CSS Processor it still fails the whole build. With HMR, the scan result is reused while the files it visited keep their size and modification time.
76
-
77
- When no `src/includes/html.*` exists, `HtmlPageRenderer.getHtmlTemplate()` returns the built-in shell (`lang="en"`, charset, viewport, children slot). Pages owned by other Integrations keep the existing missing-template error. A Page owned by another Integration whose shell is `html.html` delegates the shell to this renderer through the foreign-child path; `renderComponent()` renders it with its assets emitted in place.
78
-
79
- ## Head reconciliation
80
-
81
- The renderer retains the Page head for the active render and its `finalizeDocument` hook reconciles it after Integration and core head contributions are in the document. A direct `HtmlPageRenderer.render()` call, outside a route render, reconciles the HTML it returns the same way:
82
-
83
- - A Page singleton, including a derived social tag, replaces the shell tag with the same key, in place; repeated keys, such as a light and a dark `theme-color`, match in source order, and a Page copy with no shell match is appended. This includes the core robots tag built from `metadata.robots`.
84
- - A Page `<meta charset>` matching the shell is dropped; a different encoding is an error naming the Page. A Page charset or `<base>` without a shell copy is inserted at the start of `<head>`.
85
- - Every other Page head node is inserted before `</head>` in source order.
86
- - Page `<html>` and `<body>` attributes replace shell values, except `class`, whose tokens are joined.
87
-
88
- Reconciliation runs only for HTML Pages; other routes keep their head output.
89
-
90
- ## Discovery rules
91
-
92
- `RouteRegistry` rejects a dynamic `.html` filename (no `staticPaths` source). It also rejects any two Page files that produce the same Template Route, for every Integration, such as `about.html` with `about.tsx` or `about/index.html`.
93
-
94
- ## Tests
95
-
96
- - `html-page-template.test.ts`: extraction, metadata, social tags, asset classification, preload hints, relative-URL and social image warnings, CSS URL extraction, inline module scripts with relative imports, compile errors
97
- - `html-page-document.test.ts`: head reconciliation and root attribute merging
98
- - `html-page-module.test.ts`: which `.html` files core loads, warnings once per file revision, inline module script import errors, metadata merge, shell compile errors
99
- - `html-pages.plugin.test.ts`: which files `compilePageModule()` compiles or rejects
100
- - `html-page-renderer.test.ts`: built-in shell, JSX shells without `<body>`, delegated shells, asset dedupe, preload hints (Page and shell stylesheets, shared-build and HMR module script URLs, kind mismatches, `integrity`, unmatched warnings for a Page and the shell), relative `url()` in processed `<style>`, warned again after an edit, missing assets, head on a direct `render()`, the shared module-script build (one chunk per shared module, stable URLs, no other Page's code, rebuild after an edit, a fix, or a new script, a broken Page left out, entries that differ only by extension)
101
- - `html-page-classic-script.test.ts`: the classic script rule, including a real build of a TypeScript classic script run as a classic script
102
- - `html/html-source-parser.test.ts`: source offsets, raw text, implicit head close
103
- - `router/server/route-registry.test.ts`: duplicate routes and dynamic `.html` filenames
104
- - `e2e/fixtures/html-pages`: static export, Sitemap, `404.html`, browser-router navigation, and a custom element shared by several Pages' scripts defined once
@@ -1,44 +0,0 @@
1
- # Island host contract
2
-
3
- **Layer:** Foundation.
4
-
5
- Hydratable component instances stamp a small, integration-agnostic attribute set on their SSR root so devtools (and future runtime features) can discover islands without integration-specific selectors.
6
-
7
- ## Attributes
8
-
9
- | Attribute | Purpose |
10
- | ----------------------------- | ----------------------------------------------------------- |
11
- | `data-eco-island` | Marks the element as an interactive island host |
12
- | `data-eco-island-integration` | Owning integration (`react`, `lit`, `kitajs`, …) |
13
- | `data-eco-component-id` | Stable instance id from the render pipeline |
14
- | `data-eco-component-key` | Optional module key used by client hydration (React) |
15
- | `data-eco-props` | Optional props snapshot for hydration: base64 of UTF-8 JSON |
16
-
17
- `data-eco-island` is a presence marker with an empty value, rendered as
18
- `data-eco-island=""`. Select hosts with `[data-eco-island]`.
19
-
20
- React integrations may emit `<eco-island>` as the SSR host. Island and lazy-entry
21
- client modules are built together from the page client plan, in one grouped
22
- browser build, during route preparation. Island entries are components whose Integration differs from their parent's, excluding the Html shell; a component also reached by a parent of another Integration is an island whatever the order the parents were visited in, and is listed once. Hydrating integrations take Foreign Children of another page owner (`selectHydrationIslandEntries`),
23
- not the page owner's Page, Layout, or nested includes. The page owner collects that
24
- build from every island-hydrating integration on the plan, so a React island on a
25
- Kita or Lit route still gets a hydration script. Island grouped entries re-export the
26
- component module; hydration scripts import those recorded output URLs. SSR stamps those assets onto the host. The host uses
27
- `display: contents` so it does not introduce a layout box, while the host and
28
- its children remain in place as the client calls `hydrateRoot()` on that host.
29
- React island integrations may add `data-eco-hydrated` after the initial client
30
- commit for development diagnostics.
31
-
32
- ## Where stamping happens
33
-
34
- `IntegrationRenderer` calls `finalizeIslandComponentRender()` in `island-host.ts` after the component's foreign children are resolved when:
35
-
36
- 1. `integrationContext.componentInstanceId` is present
37
- 2. The render result can attach attributes to a single root element
38
- 3. The component's own assets include at least one client `script`
39
-
40
- Own assets are the scripts and stylesheets the component declares, plus those of nested components of the same Integration, excluding Foreign Children (declared in `dependencies.components` or rendered as Foreign Subtrees) and their descendants. They are passed separately from the render result: `result.assets` keeps the merged list for the Page. `IntegrationRenderer` collects them from the component's dependency declarations, so a component without scripts that wraps another Integration's island is not stamped.
41
-
42
- Integrations write `data-eco-props` through `buildIslandHostAttributes()`, which encodes the JSON as UTF-8 before base64; plain `btoa` handles Latin-1 only and throws on text such as `€`, CJK or emoji. Browser code that cannot import core (the React hydration lifecycle and the dev toolbar) keeps its own decoder; their tests and core's test use the same encoded fixture, so a format change fails them.
43
-
44
- Integrations with custom island metadata (for example React's component key) should build on `buildIslandHostAttributes()` rather than inventing per-demo selectors.
@@ -1,17 +0,0 @@
1
- # Page Cache
2
-
3
- **Layer:** Rendering.
4
-
5
- The page cache stores rendered HTML for request-time Pages. `PageCacheService` implements the configured cache strategy, including stale-while-revalidate and path, tag, and source-file invalidation. `PageRequestCacheCoordinator` applies that policy to one HTTP render and creates the response headers.
6
-
7
- Each cached entry binds the route modules, browser graph, processed assets, and render-shell inputs it used. Development invalidates entries that depend on changed files. An edit under `additionalWatchPaths` clears the HTML cache because the Pages that read those files are not known. Path invalidation also removes query and development runtime variants and releases the entry's build-input bindings.
8
-
9
- The `static` strategy reuses HTML until invalidation or the next deploy and sends `must-revalidate` with an ETag. The `immutable` Cache-Control directive applies only to content-hashed asset URLs, never to HTML responses. Page caching is off in watch mode unless `cache.enabled: true` opts in.
10
-
11
- ## Files
12
-
13
- - `page-cache-service.ts`: cache reads, writes, regeneration, and invalidation.
14
- - `page-request-cache-coordinator.service.ts`: request-time cache policy, body normalization, and response headers.
15
- - `html-page-cache-dependency-index.ts`: binds rendered HTML entries to the source files they read.
16
- - `memory-cache-store.ts`: default in-memory cache store.
17
- - `cache.types.ts`: cache strategies, entries, and store contracts.
@@ -1,53 +0,0 @@
1
- # Plugin Contracts
2
-
3
- **Layer:** Contracts.
4
-
5
- This directory contains the authoring contracts for Ecopages integrations, processors, and related plugin-facing runtime declarations.
6
-
7
- ## Purpose
8
-
9
- The plugin layer defines what packages are allowed to declare about themselves, while core retains orchestration ownership.
10
-
11
- These contracts are responsible for:
12
-
13
- - integration registration and lifecycle hooks
14
- - processor registration and asset capability declaration
15
- - shared build-plugin bridge types used by integrations and processors
16
-
17
- ## Main Files
18
-
19
- - `integration-plugin.ts`: framework-semantics contract for render integrations, with `plugins(app)`, `createRenderer(base)`, `setup(ctx)`, `hmr(ctx)`, `staticExport(ctx)`, and `teardown()` lifecycles
20
- - `integration-renderer.ts`: core-owned route renderer plus `createIntegrationRenderer()` and the optional hooks custom Integrations can supply
21
- - `define-integration.ts`: typed factory for integrations that only need declarative config and a renderer class
22
- - `find-integration-for-file.ts`: resolves the Integration that owns a file by its longest registered extension; route rendering, page-module loading, route discovery, the pages graph, and component attribution all use it
23
- - `processor.ts`: asset-transformation contract for processors, including declarative asset capabilities with optional filename filters, the optional `transformStylesheet(css, file)` called for matching stylesheet capabilities, and generated `@types` package helpers for virtual modules
24
- - `component-import-discovery.ts`: resolves direct local factory exports, named `export { X } from` barrels (imported binding only), relative CSS imports, and aliased CSS imports; records the imported module, factory file, and successful named re-export hops as watch files; excludes `export *`, type imports, package imports, and ordinary helpers.
25
- - `eco-component-meta-plugin.ts`: the component-identity attribution build plugin for `eco.*()` factories, which core adds to every build request, and `attributeMdxComponentIdentity` for compiled MDX modules
26
-
27
- ## Ownership Rules
28
-
29
- - Integrations own rendering semantics, hydration behavior, and integration-specific HMR strategy.
30
- - `createIntegrationRenderer()` supplies the shared route render path. Integrations add framework behavior through optional hooks; use a renderer subclass only when the integration needs its own renderer state or lower-level lifecycle.
31
- - An Integration whose files are not JavaScript modules can compile them itself with `compilePageModule()`, and one whose Pages cannot receive Params overrides `acceptsParams` with `false`. Core asks the owning Integration instead of checking Integration names.
32
- - Core resolves component ownership through `getComponentOwner()`: explicit `config.integration`, build-time identity, then the inherited owner. Integrations set `bundlesPageDependencies` when core may collapse their eligible Page assets into page-owned output bundles.
33
- - Processors own asset semantics, cache ownership, and processor-specific watch behavior.
34
- - A Processor's `watch.onChanges` callback runs once per debounced file batch with matching `created`, `changed`, and `deleted` paths plus the client bridge. Watch extensions select notifications; capabilities continue to declare asset ownership.
35
- - A Processor that owns pages to prewarm appends their pathnames to `appConfig.devPrewarmPaths` from `setup()`; core reads that one list and renders it in the background without delaying development server readiness.
36
- - Core owns lifecycle ordering, startup orchestration, and manifest assembly. `plugins(app)` is the only plugin method called during finalization and must be a pure read; Plugins create state in `setup()` or lazily in their build hooks.
37
- - `staticExport(context)` starts export-wide work before the first page renders and may return a release; core awaits the releases in reverse order after the export, on success or failure.
38
- - Core calls `teardown()` for activated Integrations after static-export releases and when the app shuts down or restarts; it waits for in-flight `setup()` calls first.
39
- - Integrations and Processors expose one `plugins(app)` method. Core reads it once during config finalization, and it is the only Processor method that runs then, so it does no I/O. A Processor generates files, loads configuration and warms caches in `setup()`, or lazily in its own plugin callbacks when a build can run first. Build plugins declare their server/browser environments; omitted environments apply to both. Config finalization rejects a duplicate name within one environment and names both contributors.
40
- - The transform wraps native `eco.page()`, `eco.component()`, `eco.layout()`, and `eco.html()` factory options with `bindComponentIdentity()`. Factories retain the resulting `options.identity` on `config`, and runtime consumers read it through `getComponentIdentity()`. Browser, HMR, and server builds use the same plugin, so ownership and dependency diagnostics retain stable file attribution without a loader duplicate.
41
- - MDX modules compiled by `@ecopages/mdx/core` use `attributeMdxComponentIdentity()`, which returns `{ code, map }` with the compiler map composed, to strip bare CSS imports, attach live component accessors to `config.dependencies`, keep inferred stylesheets on identity, and assign `MDXContent.config = config`. The loader requires `projectRoot` from app config. Its source map composes the MDX compiler map with identity edits. Markdown code blocks and dynamic imports within functions are distinguished and left unaffected.
42
-
43
- ## Lifecycle Summary
44
-
45
- 1. Config finalization validates registrations and reads each `plugins(app)` once. It does not call `setContext()` or runtime setup methods.
46
- 2. Core seals the app-owned build manifest from them.
47
- 3. Runtime startup gives each Processor its app config and calls its `setup()`, then activates Integrations before their renderers are created. In watch mode, core registers each Integration's `hmr(ctx)` before `setup(ctx)`. Request-only `app.fetch()` activates only the Integrations used by the requested render, including owners of foreign children; network watch startup attempts warmup for all configured Integrations before releasing requests, and logs setup failures after all attempts settle. `ecopages build` and normal `ecopages preview` empty `dist/` first, so a Page module that resolves what a Processor generates in `setup()` finds it. The Lit render worker and `preview --serve-only` skip Processor setup.
48
- 4. Request-time rendering and development invalidation reuse those finalized contracts. Each Integration lazily owns one renderer shared by route rendering, explicit views, and foreign-child handoffs. It also shares the Integration's app-owned asset-processing service, so an unchanged stylesheet or script is reused until its source changes, its output is missing, or development invalidation drops the entry.
49
- 5. `DevelopmentInvalidationService.invalidateServerModules()` advances the app module loader's development generation. A Processor that keeps compiled server artifacts outside the route-module graph, such as the content processor's collection bundles, compares `requireAppRuntime(appConfig).moduleLoader.getDevelopmentGeneration()` with the generation it built at and rebuilds on a mismatch; there is no invalidation hook.
50
-
51
- ## Discovered dependency metadata
52
-
53
- The identity transform passes a deferred Component accessor and resolved stylesheet paths to `bindComponentIdentity`. Factories attach the deferred Component accessor to `config.dependencies`; inferred stylesheets stay keyed by identity for the collector. Import bindings are read during graph traversal, after module initialization. Supported relative and aliased CSS imports are removed from all transformed outputs so the asset pipeline owns CSS delivery. Explicit styles override discovery. Discovery follows named `export { X } from` barrels for the imported binding only. The imported module, the factory file, and successful named re-export hops are recorded as watch files on the discovering identity so a child Component edit or barrel retarget invalidates HTML and Page Browser Graph caches without editing the importing Page. It does not follow `export *`, dynamic imports, namespace imports, package Components/CSS, CSS Modules, or custom import attributes. The transform uses the same discovery rules on Bun and Node. Imported source changes are reparsed through the content-keyed parser cache.