@ecopages/content-processor 0.2.0-rc.1 → 0.2.0-rc.10

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.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Build-time content collections for Ecopages. Scans MDX (or other configured exte
15
15
  | :-------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- |
16
16
  | File discovery, frontmatter validation, manifest sort | `@ecopages/content-processor` |
17
17
  | Generated `ecopages:content/*` modules (`entries`, `getComponent`, …) | `@ecopages/content-processor` |
18
- | `ContentScanner` for build scripts (for example `llms.txt`) | `@ecopages/content-processor` |
18
+ | `ContentScanner` for app scripts that emit `llms.txt` | `@ecopages/content-processor` |
19
19
  | Routes (`eco.page`), layouts, metadata, URL shape | Your app |
20
20
  | Sidebar, breadcrumbs, pagination | Your app — derive from `entries` and frontmatter fields such as `title`, `group`, and `order` |
21
21
 
@@ -27,10 +27,12 @@ The processor gives you a typed manifest and MDX components at build time. Wire
27
27
  - **Standard Schema validation** — frontmatter schemas stay in your app; the library validates through the Standard Schema interface.
28
28
  - **Typed virtual modules** — `ecopages:content/<collection>` with generated `Entry` types.
29
29
  - **Multiple collections** — docs, blog, changelog, or any keyed collection you configure.
30
- - **`ContentScanner`** — reuse the same scan logic in one-off build scripts (for example, `llms.txt` generation).
30
+ - **`ContentScanner`** — reuse the same scan/validate path in one-off build scripts. The scanner does not write `llms.txt`; the app script does.
31
31
 
32
32
  During development, edits to an entry's MDX body invalidate its compiled server collection bundle even when its frontmatter and generated manifest are unchanged. The next request rebuilds that bundle and renders the new body.
33
33
 
34
+ Co-located non-entry files inside a collection directory (for example `survey-form.config.ts`, helper modules, or JSON data) also invalidate the compiled server collection without rewriting the generated entries manifest.
35
+
34
36
  ## Installation
35
37
 
36
38
  ```bash
@@ -83,7 +85,7 @@ export default await new ConfigBuilder()
83
85
  | `schema` | yes | Standard Schema validator for frontmatter. |
84
86
  | `entryType` | no | Frontmatter type for generated virtual-module types. Format: `./path/to/schema#TypeName`. The processor wraps it as `ContentEntry<YourFrontmatter>`. |
85
87
  | `orderBy` | no | Comparator function for manifest sort. Default: {@link compareEntriesBySlug}. Use {@link compareEntriesByField} for frontmatter fields. |
86
- | `extensions` | no | File extensions to scan. Default: `['.mdx']`. |
88
+ | `extensions` | no | File extensions to scan. Default: `['.mdx']`. Multi-dot extensions (`.radiant.mdx`, `.react.mdx`) are matched longest-first; declaration order does not matter. |
87
89
  | `routePrefix` | no | Public URL prefix for entries, e.g. `/docs`. Used with `devPrewarm`. |
88
90
  | `devPrewarm` | no | Dev prewarm: `'first'`, `'all'`, `{ slugs }`, or `{ limit }`. Core SSR-prewarms after the HMR-ready pipeline exists; prewarm schedules renders only and does not control HTML cache admission. |
89
91
  | `devPrewarmReadiness` | no | `'background'` (default) or `'beforeReady'` to block the framework ready signal until prewarm finishes (listen port may already be open). |
@@ -127,29 +129,32 @@ Add one import to the app `modules.d.ts`:
127
129
  import '@ecopages/content-processor/types';
128
130
  ```
129
131
 
130
- That declares `ecopages:content/*`. Collection modules are generated at dev/build time into
132
+ That makes `ecopages:content/*`, `/server`, and `/browser` imports resolvable immediately.
133
+ Collection-specific declarations are generated at dev/build time into
131
134
  `node_modules/@types/ecopages-content-processor`, which TypeScript loads automatically.
132
135
 
133
- Run `ecopages dev` or `ecopages build` before expecting IDE types. Restart the TypeScript server if types look stale after changing schema or collection config.
136
+ Run `ecopages dev` or `ecopages build` before expecting precise collection entry types. Restart the TypeScript server if generated types look stale after changing schema or collection config.
134
137
 
135
138
  ## Virtual module API
136
139
 
137
- Each collection exposes `ecopages:content/<collection>` for metadata and `ecopages:content/<collection>/server` for MDX components:
140
+ Each collection exposes `ecopages:content/<collection>` for metadata, `ecopages:content/<collection>/server` for server-only dependency discovery, and `ecopages:content/<collection>/browser` for a lazy MDX component loader:
138
141
 
139
142
  ```typescript
140
143
  import { entries, getEntry, getEntryBySegments } from 'ecopages:content/docs';
141
144
  import { getComponent, getEntryDependencies } from 'ecopages:content/docs/server';
145
+ import { loadComponent } from 'ecopages:content/docs/browser';
142
146
  import type { Entry } from 'ecopages:content/docs';
143
147
  ```
144
148
 
145
- | Export | Module | Description |
146
- | :----------------------------- | :------ | :-------------------------------------------------------------------------------------------------------------------------- |
147
- | `entries` | entries | Readonly manifest of all entries, sorted by `orderBy`. |
148
- | `getEntry(slug)` | entries | Lookup by joined slug, e.g. `'getting-started/intro'`. Throws `HttpError.NotFound` when missing. |
149
- | `getEntryBySegments(segments)` | entries | Lookup by segment array, e.g. `['getting-started', 'intro']`. Throws `HttpError.NotFound` when missing. |
150
- | `getComponent(slug)` | server | `Promise` of the MDX component for the entry (lazy-loaded per slug). Throws `HttpError.NotFound` when missing. |
151
- | `getEntryDependencies(slug)` | server | `Promise` of the browser dependency bag for the entry, with MDX source ownership. Throws `HttpError.NotFound` when missing. |
152
- | `Entry` | entries | **Type only.** `ContentEntry<YourFrontmatter>` — frontmatter fields plus `slug` and `segments`. |
149
+ | Export | Module | Description |
150
+ | :----------------------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------- |
151
+ | `entries` | entries | Readonly manifest of all entries, sorted by `orderBy`. |
152
+ | `getEntry(slug)` | entries | Lookup by joined slug, e.g. `'getting-started/intro'`. Throws `HttpError.NotFound` when missing. |
153
+ | `getEntryBySegments(segments)` | entries | Lookup by segment array, e.g. `['getting-started', 'intro']`. Throws `HttpError.NotFound` when missing. |
154
+ | `getComponent(slug)` | server | `Promise` of the MDX component for the entry (lazy-loaded per slug). Throws `HttpError.NotFound` when missing. |
155
+ | `getEntryDependencies(slug)` | server | Returns `{ components: [entry] }` so collection walks MDX identity. Does not copy the dependency bag. Throws `HttpError.NotFound` when missing. |
156
+ | `loadComponent(slug)` | browser | Page Browser Graph loader for one MDX entry. Pair with `createCollectionComponentCache()` when a hydratable React Page renders the component. |
157
+ | `Entry` | entries | **Type only.** `ContentEntry<YourFrontmatter>` — frontmatter fields plus `slug` and `segments`. |
153
158
 
154
159
  **Important:** `Entry` exists only in generated `.d.ts` files, not in the runtime cache module. Keep type imports on a separate `import type` line in page files that get bundled. Mixed imports like `import { entries, type Entry }` can cause the bundler to treat `Entry` as a runtime export and fail with `MISSING_EXPORT`.
155
160
 
@@ -190,25 +195,70 @@ export default eco.page<{ entry: Entry }>({
190
195
  });
191
196
  ```
192
197
 
198
+ Return `getEntryDependencies` alone when the Page has no relative assets of its own. Combine Page-local `scripts`, `stylesheets`, or `modules` with `mergePageDependencies()` so each file keeps ownership.
199
+
200
+ ### Hydratable React Pages
201
+
202
+ When a React Page must keep the MDX component in its hydrated tree, SSR fills the cache in `staticProps` with `getComponent()` and `prime()`. The Page's named `preload` export then fills it with the `/browser` loader before hydration and router navigation. The cache makes `get()` synchronous after either fill; `getEntryDependencies()` remains server-only and is stripped from the Page Browser Graph.
203
+
204
+ ```tsx
205
+ import { createCollectionComponentCache } from '@ecopages/react/collection-component-cache';
206
+ import { getEntry } from 'ecopages:content/docs';
207
+ import { loadComponent } from 'ecopages:content/docs/browser';
208
+ import { getComponent, getEntryDependencies } from 'ecopages:content/docs/server';
209
+
210
+ const docs = createCollectionComponentCache(loadComponent);
211
+
212
+ export async function preload({ entry }) {
213
+ await docs.preload(entry.slug);
214
+ }
215
+
216
+ export default eco.page({
217
+ staticProps: async ({ pathname }) => {
218
+ const entry = getEntry(pathname.params.slug);
219
+ await docs.prime(entry.slug, getComponent(entry.slug));
220
+ return { props: { entry } };
221
+ },
222
+ dependencies: ({ props }) => getEntryDependencies(props.entry.slug),
223
+ render: ({ entry }) => {
224
+ const Content = docs.get(entry.slug);
225
+ return <Content />;
226
+ },
227
+ });
228
+ ```
229
+
193
230
  Unknown slugs throw `HttpError.NotFound`, so a catch-all that matches `/docs/[...slug]` still serves the app 404 page instead of a 500.
194
231
 
195
- Content MDX entries may declare interactive demo dependencies without polluting the catch-all page shell:
232
+ Content MDX entries may import interactive demos and styles without a handwritten `config.dependencies` bag. The MDX loader discovers them:
196
233
 
197
234
  ```mdx
198
235
  import { WeatherApp } from '@/components/weather-app/weather-app';
199
-
200
- export const config = {
201
- dependencies: {
202
- components: [WeatherApp],
203
- },
204
- };
236
+ import './weather-app.css';
205
237
 
206
238
  # Weather app
207
239
 
208
240
  <WeatherApp />
209
241
  ```
210
242
 
211
- `getComponent()` lazy-loads one MDX module per slug and returns the default component with exported `config` attached. Pair that with `getEntryDependencies()` on the catch-all page so only the active entry contributes to the Page Browser Graph. The helper includes `ownerFile` so relative `scripts`, `stylesheets`, and `modules` declared in MDX resolve against the entry file, not the catch-all route.
243
+ `getComponent()` lazy-loads one MDX module per slug and returns the default component with loader-attributed `config` attached. Pair that with `getEntryDependencies()` on the catch-all page so only the active entry contributes to the Page Browser Graph.
244
+
245
+ `getEntryDependencies(slug)` returns `{ components: [entry] }`. It does not copy `config.dependencies` and does not set `ownerFile`. Relative `scripts`, `stylesheets`, and `modules` declared on the MDX module resolve from that Component's identity rather than the catch-all route.
246
+
247
+ Combine Page-local relative assets with `mergePageDependencies()`. Object-spread of the two bags copies `ownerFile` onto the other side's relative paths:
248
+
249
+ ```typescript
250
+ import { eco, mergePageDependencies } from '@ecopages/core';
251
+ import { getComponent, getEntryDependencies } from 'ecopages:content/posts/server';
252
+
253
+ export default eco.page({
254
+ dependencies: async ({ props }) =>
255
+ mergePageDependencies({ stylesheets: ['./post.css'] }, await getEntryDependencies(props.slug)),
256
+ render: async ({ slug }) => {
257
+ const Content = await getComponent(slug);
258
+ return <Content />;
259
+ },
260
+ });
261
+ ```
212
262
 
213
263
  ## Navigation (app-side)
214
264
 
@@ -310,3 +360,9 @@ import { remarkFrontmatter } from '@ecopages/content-processor/mdx';
310
360
  ```
311
361
 
312
362
  App-specific presentation plugins (syntax highlighting, GFM, table wrappers) stay in your app — for example `src/mdx/plugins.ts`.
363
+
364
+ ## Content-entry ownership
365
+
366
+ The integration that compiles an MDX entry also owns its rendering: an entry compiled with `mdx.extensions: ['.react.mdx']` on the React integration is a React component and must be rendered through a React-owned route (for example a `[...slug].react.tsx` catch-all). Calling it from a JSX (Radiant) or Kita render tree cannot serialize its output.
367
+
368
+ The generated `getComponent()` preserves this ownership at render time: invoking an entry in its owning lane renders directly, while a supported foreign-child render lane queues the entry through its owning integration. If no handoff runtime is available, it throws with the entry path, owning integration, and active integration. When both integrations compile MDX for the same collection, declare disjoint `mdx.extensions` per integration — since the React MDX loader derives its filter from the declared extensions, only `.react.mdx` files compile with React. `mdx.extensions` replaces `compilerOptions.mdxExtensions` rather than merging with it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/content-processor",
3
- "version": "0.2.0-rc.1",
3
+ "version": "0.2.0-rc.10",
4
4
  "description": "Scan MDX collections at build time and expose typed ecopages:content/* virtual modules for pages and scripts",
5
5
  "keywords": [
6
6
  "content",
@@ -11,16 +11,19 @@
11
11
  "license": "MIT",
12
12
  "main": "./src/index.js",
13
13
  "type": "module",
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
14
17
  "repository": {
15
18
  "type": "git",
16
19
  "url": "git+https://github.com/ecopages/ecopages.git",
17
20
  "directory": "packages/processors/content-processor"
18
21
  },
19
22
  "peerDependencies": {
20
- "@ecopages/core": "0.2.0-rc.1"
23
+ "@ecopages/core": "0.2.0-rc.10"
21
24
  },
22
25
  "dependencies": {
23
- "@ecopages/file-system": "0.2.0-rc.1",
26
+ "@ecopages/file-system": "0.2.0-rc.10",
24
27
  "@ecopages/logger": "^0.2.3",
25
28
  "remark-frontmatter": "^5.0.0",
26
29
  "unified": "^11.0.5",
@@ -43,6 +46,10 @@
43
46
  "default": "./src/mdx.js",
44
47
  "types": "./src/mdx.d.ts"
45
48
  },
49
+ "./ownership": {
50
+ "default": "./src/ownership.js",
51
+ "types": "./src/ownership.d.ts"
52
+ },
46
53
  "./plugin.ts": {
47
54
  "default": "./src/plugin.js",
48
55
  "types": "./src/plugin.d.ts"
@@ -53,7 +60,11 @@
53
60
  "./mdx.ts": {
54
61
  "default": "./src/mdx.js",
55
62
  "types": "./src/mdx.d.ts"
63
+ },
64
+ "./ownership.ts": {
65
+ "default": "./src/ownership.js",
66
+ "types": "./src/ownership.d.ts"
56
67
  }
57
68
  },
58
69
  "types": "./src/index.d.ts"
59
- }
70
+ }
package/src/codegen.d.ts CHANGED
@@ -12,13 +12,26 @@ export declare function renderCollectionEntriesModule(collectionName: string, ma
12
12
  *
13
13
  * @remarks
14
14
  * The emitted module caches completed components and coalesces concurrent
15
- * loads for the same slug. Keeping MDX imports here leaves the metadata
16
- * virtual module cheap to load during route preparation.
15
+ * loads for the same slug. `getEntryDependencies` returns the entry Component
16
+ * so collection can resolve assets from identity. Keeping MDX imports here
17
+ * leaves the metadata virtual module cheap to load during route preparation.
17
18
  */
18
19
  export declare function renderCollectionComponentsModule(_collectionName: string, outputDir: string, entrySources: Array<{
19
20
  entry: ContentEntry;
20
21
  filePath: string;
21
22
  }>): string;
23
+ /**
24
+ * Generates the browser-only virtual module for one content collection.
25
+ *
26
+ * @remarks
27
+ * Consumers own any synchronous-after-preload cache policy. This module only
28
+ * loads one browser-compiled MDX entry on demand and coalesces concurrent
29
+ * requests; it is not a server renderer.
30
+ */
31
+ export declare function renderCollectionBrowserModule(_collectionName: string, outputDir: string, entrySources: Array<{
32
+ entry: ContentEntry;
33
+ filePath: string;
34
+ }>): string;
22
35
  /** Generates both ambient virtual-module declarations for one collection. */
23
36
  export declare function renderCollectionTypesModule(collectionName: string, entryType?: string, typeResolution?: {
24
37
  rootDir: string;
package/src/codegen.js CHANGED
@@ -52,12 +52,37 @@ export function getEntryBySegments(segments: string[]) {
52
52
  * Generates the adapter that retains an MDX module's Ecopages component contract.
53
53
  *
54
54
  * @remarks
55
- * MDX compilers expose component metadata as module exports. The generated
56
- * server module moves that metadata onto the component returned to the route
57
- * renderer, while assigning the content file as its canonical identity.
55
+ * The loader already attributes identity and live dependency getters. This
56
+ * adapter copies that config by reference onto the callable returned to the
57
+ * route renderer. It does not re-bind or snapshot `config`.
58
58
  */
59
- function renderAttachMdxExportsHelper() {
60
- return `type ContentMdxModule = {
59
+ function renderAttachMdxExportsHelper(options) {
60
+ const ownershipImport = options?.ownershipCheck
61
+ ? `
62
+ import { invokeContentEntry } from '@ecopages/content-processor/ownership';
63
+ `
64
+ : '';
65
+ const guardBody = options?.ownershipCheck
66
+ ? `
67
+ const component = Object.assign(
68
+ (props: Record<string, unknown> = {}) =>
69
+ invokeContentEntry(
70
+ sourceFile,
71
+ module.config?.identity?.integration,
72
+ component,
73
+ Page,
74
+ props,
75
+ ),
76
+ Page,
77
+ ) as EcoComponent<Record<string, unknown>>;
78
+ `
79
+ : `
80
+ const component = Object.assign(
81
+ (props: Record<string, unknown> = {}) => Page(props),
82
+ Page,
83
+ ) as EcoComponent<Record<string, unknown>>;
84
+ `;
85
+ return `${ownershipImport}type ContentMdxModule = {
61
86
  default: EcoComponent<Record<string, unknown>>;
62
87
  config?: EcoComponent<Record<string, unknown>>['config'];
63
88
  getMetadata?: EcoComponent<Record<string, unknown>>['metadata'];
@@ -65,22 +90,12 @@ function renderAttachMdxExportsHelper() {
65
90
 
66
91
  function attachMdxExports(module: ContentMdxModule, sourceFile: string): EcoComponent<Record<string, unknown>> {
67
92
  const Page = module.default;
68
- const component = Object.assign(
69
- (props: Record<string, unknown>) => Page(props),
70
- Page,
71
- ) as EcoComponent<Record<string, unknown>>;
72
-
93
+ ${guardBody}
73
94
  if (module.config) {
74
- const moduleIdentity = getComponentIdentity(module.config);
75
- const componentIdentity = getComponentIdentity(component);
76
- component.config = bindComponentIdentity({
77
- id: moduleIdentity?.id ?? componentIdentity?.id ?? sourceFile,
78
- file: sourceFile,
79
- integration: moduleIdentity?.integration ?? componentIdentity?.integration ?? 'content',
80
- }, {
81
- ...component.config,
82
- ...module.config,
83
- });
95
+ if (!module.config.identity) {
96
+ throw new Error(\`[ecopages] MDX config for "\${sourceFile}" is missing identity; the MDX loader must attribute it.\`);
97
+ }
98
+ component.config = module.config;
84
99
  }
85
100
 
86
101
  if (module.getMetadata) {
@@ -91,15 +106,8 @@ function attachMdxExports(module: ContentMdxModule, sourceFile: string): EcoComp
91
106
  }
92
107
  `;
93
108
  }
94
- /**
95
- * Generates the server-only virtual module that lazy-loads MDX entries.
96
- *
97
- * @remarks
98
- * The emitted module caches completed components and coalesces concurrent
99
- * loads for the same slug. Keeping MDX imports here leaves the metadata
100
- * virtual module cheap to load during route preparation.
101
- */
102
- export function renderCollectionComponentsModule(_collectionName, outputDir, entrySources) {
109
+ /** Renders the per-slug MDX import and source-file maps shared by both loaders. */
110
+ function renderMdxLoaderMaps(outputDir, entrySources) {
103
111
  const loaderLines = [];
104
112
  const entrySourceFilesBySlugLines = [];
105
113
  for (const { entry, filePath } of entrySources) {
@@ -110,20 +118,32 @@ export function renderCollectionComponentsModule(_collectionName, outputDir, ent
110
118
  loaderLines.push(`\t'${entry.slug}': () => import('${escapedImportPath}'),`);
111
119
  entrySourceFilesBySlugLines.push(`\t'${entry.slug}': '${escapedSourceFile}',`);
112
120
  }
113
- return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
114
-
115
- import { bindComponentIdentity, getComponentIdentity, type EcoComponent, type PageDependenciesResult } from '@ecopages/core';
116
- import { HttpError } from '@ecopages/core/errors';
117
-
118
- ${renderAttachMdxExportsHelper()}
119
-
120
- const loadersBySlug: Record<string, () => Promise<ContentMdxModule>> = {
121
+ return `const loadersBySlug: Record<string, () => Promise<ContentMdxModule>> = {
121
122
  ${loaderLines.join('\n')}
122
123
  };
123
124
 
124
125
  const entrySourceFilesBySlug: Record<string, string> = {
125
126
  ${entrySourceFilesBySlugLines.join('\n')}
126
- };
127
+ };`;
128
+ }
129
+ /**
130
+ * Generates the server-only virtual module that lazy-loads MDX entries.
131
+ *
132
+ * @remarks
133
+ * The emitted module caches completed components and coalesces concurrent
134
+ * loads for the same slug. `getEntryDependencies` returns the entry Component
135
+ * so collection can resolve assets from identity. Keeping MDX imports here
136
+ * leaves the metadata virtual module cheap to load during route preparation.
137
+ */
138
+ export function renderCollectionComponentsModule(_collectionName, outputDir, entrySources) {
139
+ return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
140
+
141
+ import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
142
+ import { HttpError } from '@ecopages/core/errors';
143
+
144
+ ${renderAttachMdxExportsHelper({ ownershipCheck: true })}
145
+
146
+ ${renderMdxLoaderMaps(outputDir, entrySources)}
127
147
 
128
148
  const componentCache = new Map<string, EcoComponent<Record<string, unknown>>>();
129
149
  const componentLoadPromises = new Map<string, Promise<EcoComponent<Record<string, unknown>>>>();
@@ -157,20 +177,53 @@ export async function getComponent(slug: string): Promise<EcoComponent<Record<st
157
177
  return loadPromise;
158
178
  }
159
179
 
160
- export async function getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined> {
180
+ export async function getEntryDependencies(slug: string): Promise<PageDependenciesResult> {
161
181
  const component = await getComponent(slug);
162
- const dependencies = component.config?.dependencies;
163
- if (!dependencies) {
164
- return undefined;
165
- }
166
-
167
182
  return {
168
- ...dependencies,
169
- ownerFile: entrySourceFilesBySlug[slug],
183
+ components: [component],
170
184
  };
171
185
  }
172
186
  `;
173
187
  }
188
+ /**
189
+ * Generates the browser-only virtual module for one content collection.
190
+ *
191
+ * @remarks
192
+ * Consumers own any synchronous-after-preload cache policy. This module only
193
+ * loads one browser-compiled MDX entry on demand and coalesces concurrent
194
+ * requests; it is not a server renderer.
195
+ */
196
+ export function renderCollectionBrowserModule(_collectionName, outputDir, entrySources) {
197
+ return `// This file is auto-generated by @ecopages/content-processor. Do not edit.
198
+
199
+ import type { EcoComponent } from '@ecopages/core';
200
+ import { HttpError } from '@ecopages/core/errors';
201
+
202
+ ${renderAttachMdxExportsHelper()}
203
+
204
+ ${renderMdxLoaderMaps(outputDir, entrySources)}
205
+
206
+ const componentLoadPromises = new Map<string, Promise<EcoComponent<Record<string, unknown>>>>();
207
+
208
+ export function loadComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>> {
209
+ const pending = componentLoadPromises.get(slug);
210
+ if (pending) {
211
+ return pending;
212
+ }
213
+
214
+ const load = loadersBySlug[slug];
215
+ if (!load) {
216
+ ${renderUnknownContentEntryThrow()};
217
+ }
218
+
219
+ const loadPromise = load().then((module) => attachMdxExports(module, entrySourceFilesBySlug[slug]!)).finally(() => {
220
+ componentLoadPromises.delete(slug);
221
+ });
222
+ componentLoadPromises.set(slug, loadPromise);
223
+ return loadPromise;
224
+ }
225
+ `;
226
+ }
174
227
  /**
175
228
  * Resolves an app-owned frontmatter type to the specifier used in generated
176
229
  * virtual-module declarations.
@@ -219,13 +272,32 @@ function renderCollectionComponentsTypesModule(collectionName) {
219
272
 
220
273
  /** @throws HttpError 404 when the slug is not in the collection. */
221
274
  export function getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
222
- /** @throws HttpError 404 when the slug is not in the collection. */
223
- export function getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined>;
275
+ /**
276
+ * Returns { components: [entry] } so collection walks MDX identity.
277
+ *
278
+ * @remarks Does not copy config.dependencies or set ownerFile.
279
+ * Combine Page-local relative assets with mergePageDependencies().
280
+ * @throws HttpError 404 when the slug is not in the collection.
281
+ */
282
+ export function getEntryDependencies(slug: string): Promise<PageDependenciesResult>;
283
+ }`;
284
+ }
285
+ function renderCollectionBrowserTypesModule(collectionName) {
286
+ return `declare module "ecopages:content/${collectionName}/browser" {
287
+ import type { EcoComponent } from '@ecopages/core';
288
+
289
+ /**
290
+ * Loads the browser-compiled MDX component for one slug.
291
+ *
292
+ * @remarks Use only from the Page Browser Graph.
293
+ * @throws HttpError 404 when the slug is not in the collection.
294
+ */
295
+ export function loadComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
224
296
  }`;
225
297
  }
226
298
  /** Generates both ambient virtual-module declarations for one collection. */
227
299
  export function renderCollectionTypesModule(collectionName, entryType, typeResolution) {
228
- return `${renderCollectionEntriesTypesModule(collectionName, entryType, typeResolution)}\n\n${renderCollectionComponentsTypesModule(collectionName)}`;
300
+ return `${renderCollectionEntriesTypesModule(collectionName, entryType, typeResolution)}\n\n${renderCollectionComponentsTypesModule(collectionName)}\n\n${renderCollectionBrowserTypesModule(collectionName)}`;
229
301
  }
230
302
  /**
231
303
  * Generates the declaration file that gives TypeScript types for every
@@ -1,5 +1,5 @@
1
1
  /** Processor registry name and generated artifact namespace. */
2
2
  export declare const CONTENT_PROCESSOR_NAME = "ecopages-content-processor";
3
- export { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
3
+ export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
4
4
  /** Validates collection keys used in processor options and virtual module paths. */
5
5
  export declare const COLLECTION_NAME_PATTERN: RegExp;
package/src/constants.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Processor registry name and generated artifact namespace. */
2
2
  export const CONTENT_PROCESSOR_NAME = 'ecopages-content-processor';
3
- export { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
3
+ export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, parseCollectionSpecifier, } from '@ecopages/core/build/contracts/content-virtual-modules';
4
4
  /** Validates collection keys used in processor options and virtual module paths. */
5
5
  export const COLLECTION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
@@ -4,8 +4,27 @@ export type { ParsedCollectionSpecifier };
4
4
  export { parseCollectionSpecifier } from './constants.js';
5
5
  export type EnsureCollectionServerArtifact = (collectionName: string) => Promise<void>;
6
6
  export declare function parseCollectionName(specifier: string): string | null;
7
- export declare function resolveCollectionPath(specifier: string, collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>): string | null;
8
- export declare function createContentPlugin(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, ensureCollectionServerArtifact?: EnsureCollectionServerArtifact): EcoBuildPlugin;
9
- export declare function createContentPluginBundler(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>): EcoBuildPlugin;
7
+ export declare function resolveCollectionPath(specifier: string, collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>): string | null;
8
+ /**
9
+ * Creates the server graph resolver for collection virtual modules.
10
+ *
11
+ * @remarks
12
+ * Compiled `/server` modules are externalized so Node can load the collection
13
+ * artifact directly. The Page Browser Graph uses `createContentPluginBundler`,
14
+ * where the content boundary rejects `/server` and resolves `/browser` to
15
+ * browser-safe source.
16
+ */
17
+ export declare function createContentPlugin(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>, ensureCollectionServerArtifact?: EnsureCollectionServerArtifact): EcoBuildPlugin;
18
+ /**
19
+ * Creates the Page Browser Graph resolver for collection virtual modules.
20
+ *
21
+ * @remarks
22
+ * It resolves entries and `/browser` modules into browser source. `/server`
23
+ * resolution is deliberately omitted so the content server-boundary plugin can
24
+ * reject any server artifact that remains browser-reachable.
25
+ */
26
+ export declare function createContentPluginBundler(collectionModules: Record<string, string>, collectionServerModules: Record<string, string>, collectionServerCompiledModules?: Record<string, string>, collectionBrowserModules?: Record<string, string>): EcoBuildPlugin;
10
27
  export declare function getCollectionCachePath(cacheDir: string, collectionName: string): string;
11
28
  export declare function getCollectionServerCachePath(cacheDir: string, collectionName: string): string;
29
+ /** Returns the generated browser module path for one collection. */
30
+ export declare function getCollectionBrowserCachePath(cacheDir: string, collectionName: string): string;
@@ -1,12 +1,12 @@
1
1
  import path from 'node:path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
- import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, parseCollectionSpecifier, } from './constants.js';
3
+ import { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, parseCollectionSpecifier, } from './constants.js';
4
4
  export { parseCollectionSpecifier } from './constants.js';
5
5
  export function parseCollectionName(specifier) {
6
6
  const parsed = parseCollectionSpecifier(specifier);
7
7
  return parsed?.collectionName ?? null;
8
8
  }
9
- export function resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules) {
9
+ export function resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}) {
10
10
  const parsed = parseCollectionSpecifier(specifier);
11
11
  if (!parsed) {
12
12
  return null;
@@ -16,13 +16,16 @@ export function resolveCollectionPath(specifier, collectionModules, collectionSe
16
16
  collectionServerModules[parsed.collectionName] ??
17
17
  null);
18
18
  }
19
+ if (parsed.variant === 'browser') {
20
+ return collectionBrowserModules[parsed.collectionName] ?? null;
21
+ }
19
22
  return collectionModules[parsed.collectionName] ?? null;
20
23
  }
21
- function createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, ensureCollectionServerArtifact, options) {
24
+ function createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, ensureCollectionServerArtifact, options) {
22
25
  return {
23
26
  name: 'ecopages:content',
24
27
  setup(build) {
25
- const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules);
28
+ const resolveCollection = (specifier) => resolveCollectionPath(specifier, collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules);
26
29
  build.onResolve({ filter: CONTENT_VIRTUAL_MODULE_PATTERN }, (args) => {
27
30
  const modulePath = resolveCollection(args.path);
28
31
  if (!modulePath) {
@@ -61,14 +64,41 @@ function createContentResolvePlugin(collectionModules, collectionServerModules,
61
64
  return { path: modulePath };
62
65
  });
63
66
  }
67
+ build.onResolve({ filter: CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN }, (args) => {
68
+ const modulePath = resolveCollection(args.path);
69
+ if (!modulePath) {
70
+ return undefined;
71
+ }
72
+ if (options.namespace) {
73
+ return { namespace: options.namespace, path: modulePath };
74
+ }
75
+ return { path: modulePath };
76
+ });
64
77
  },
65
78
  };
66
79
  }
67
- export function createContentPlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, ensureCollectionServerArtifact) {
68
- return createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, ensureCollectionServerArtifact, { includeServerModules: true, externalizeCompiledServerModules: true });
80
+ /**
81
+ * Creates the server graph resolver for collection virtual modules.
82
+ *
83
+ * @remarks
84
+ * Compiled `/server` modules are externalized so Node can load the collection
85
+ * artifact directly. The Page Browser Graph uses `createContentPluginBundler`,
86
+ * where the content boundary rejects `/server` and resolves `/browser` to
87
+ * browser-safe source.
88
+ */
89
+ export function createContentPlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}, ensureCollectionServerArtifact) {
90
+ return createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, ensureCollectionServerArtifact, { includeServerModules: true, externalizeCompiledServerModules: true });
69
91
  }
70
- export function createContentPluginBundler(collectionModules, collectionServerModules, collectionServerCompiledModules) {
71
- const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, undefined, {
92
+ /**
93
+ * Creates the Page Browser Graph resolver for collection virtual modules.
94
+ *
95
+ * @remarks
96
+ * It resolves entries and `/browser` modules into browser source. `/server`
97
+ * resolution is deliberately omitted so the content server-boundary plugin can
98
+ * reject any server artifact that remains browser-reachable.
99
+ */
100
+ export function createContentPluginBundler(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules = {}) {
101
+ const plugin = createContentResolvePlugin(collectionModules, collectionServerModules, collectionServerCompiledModules, collectionBrowserModules, undefined, {
72
102
  namespace: 'ecopages-content',
73
103
  includeServerModules: false,
74
104
  });
@@ -89,3 +119,7 @@ export function getCollectionCachePath(cacheDir, collectionName) {
89
119
  export function getCollectionServerCachePath(cacheDir, collectionName) {
90
120
  return path.join(cacheDir, `${collectionName}.server.ts`);
91
121
  }
122
+ /** Returns the generated browser module path for one collection. */
123
+ export function getCollectionBrowserCachePath(cacheDir, collectionName) {
124
+ return path.join(cacheDir, `${collectionName}.browser.ts`);
125
+ }
@@ -4,10 +4,17 @@ import type { ContentEntry } from './types.js';
4
4
  export type ContentScannerConfig<T extends Record<string, unknown> = Record<string, unknown>> = {
5
5
  /** Absolute directory scanned for content files. */
6
6
  contentRoot: string;
7
- /** Standard Schema validator for frontmatter. */
8
- schema: StandardSchema<unknown, T>;
9
- orderBy?: EntryComparator<T>;
7
+ /**
8
+ * Extensions scanned for content entries, including multi-dot ones.
9
+ *
10
+ * @remarks
11
+ * Declaration order does not matter: extensions are matched longest-first so
12
+ * `.radiant.mdx` and `.react.mdx` strip cleanly even when a plain `.mdx`
13
+ * entry is also declared in the same collection.
14
+ */
10
15
  extensions?: string[];
16
+ orderBy?: EntryComparator<T>;
17
+ schema: StandardSchema<unknown, T>;
11
18
  };
12
19
  export type ContentEntryPathUpdateResult = 'no-op' | 'manifest' | 'structure';
13
20
  /**
@@ -15,7 +22,7 @@ export type ContentEntryPathUpdateResult = 'no-op' | 'manifest' | 'structure';
15
22
  * Used by the content processor at build time; it does not belong in page bundles.
16
23
  */
17
24
  export declare class ContentScanner<T extends Record<string, unknown> = Record<string, unknown>> {
18
- private readonly config;
25
+ private readonly contentRoot;
19
26
  private readonly extensions;
20
27
  private readonly orderBy;
21
28
  private readonly schema;
@@ -4,6 +4,13 @@ import { VFile } from 'vfile';
4
4
  import { matter } from 'vfile-matter';
5
5
  import { fileSystem } from '@ecopages/file-system';
6
6
  import { compareEntriesBySlug } from './sort.js';
7
+ /**
8
+ * Strips the longest matching declared extension from a relative path.
9
+ *
10
+ * @remarks
11
+ * `extensions` must be longest-first. `ContentScanner` sorts its configured
12
+ * extensions that way before calling this helper.
13
+ */
7
14
  function slugFromRelativePath(relativePath, extensions) {
8
15
  for (const ext of extensions) {
9
16
  if (relativePath.endsWith(ext)) {
@@ -17,14 +24,14 @@ function slugFromRelativePath(relativePath, extensions) {
17
24
  * Used by the content processor at build time; it does not belong in page bundles.
18
25
  */
19
26
  export class ContentScanner {
20
- config;
27
+ contentRoot;
21
28
  extensions;
22
29
  orderBy;
23
30
  schema;
24
31
  cachePromise;
25
32
  constructor(config) {
26
- this.config = config;
27
- this.extensions = config.extensions ?? ['.mdx'];
33
+ this.contentRoot = config.contentRoot;
34
+ this.extensions = [...(config.extensions ?? ['.mdx'])].sort((left, right) => right.length - left.length);
28
35
  this.orderBy = config.orderBy ?? compareEntriesBySlug;
29
36
  this.schema = config.schema;
30
37
  }
@@ -38,9 +45,9 @@ export class ContentScanner {
38
45
  }
39
46
  async loadCache() {
40
47
  const patterns = this.extensions.map((ext) => `**/*${ext}`);
41
- const relativePaths = await fileSystem.glob(patterns, { cwd: this.config.contentRoot });
48
+ const relativePaths = await fileSystem.glob(patterns, { cwd: this.contentRoot });
42
49
  const files = await Promise.all(relativePaths.map(async (relativePath) => {
43
- const filePath = join(this.config.contentRoot, relativePath);
50
+ const filePath = join(this.contentRoot, relativePath);
44
51
  const slug = slugFromRelativePath(relativePath, this.extensions);
45
52
  const raw = await fileSystem.readFile(filePath);
46
53
  const entry = {
@@ -100,7 +107,7 @@ export class ContentScanner {
100
107
  if (event === 'delete') {
101
108
  return this.removeEntryAtPath(cache, resolvedPath);
102
109
  }
103
- const relativePath = relative(this.config.contentRoot, resolvedPath);
110
+ const relativePath = relative(this.contentRoot, resolvedPath);
104
111
  const nextSlug = slugFromRelativePath(relativePath, this.extensions);
105
112
  const previousSlug = this.findSlugForFilePath(cache, resolvedPath);
106
113
  return this.upsertEntryAtPath(cache, resolvedPath, nextSlug, previousSlug);
@@ -1,9 +1,9 @@
1
1
  import type { EcoBuildPlugin } from '@ecopages/core/plugins/processor';
2
2
  /**
3
- * Keeps `ecopages:content/<collection>/server` out of browser bundles.
3
+ * Rejects `ecopages:content/<collection>/server` in browser bundles.
4
4
  *
5
5
  * @remarks
6
6
  * Server modules lazy-load MDX entries via dynamic `import()` for `getComponent`. Browser builds
7
- * must never follow that graph — highlighted MDX output belongs in SSR HTML only.
7
+ * must never follow that graph; browser-safe MDX is available through `/browser` instead.
8
8
  */
9
9
  export declare function createContentServerBoundaryPlugin(): EcoBuildPlugin;
@@ -1,19 +1,18 @@
1
1
  import { CONTENT_SERVER_VIRTUAL_MODULE_PATTERN } from './constants.js';
2
2
  /**
3
- * Keeps `ecopages:content/<collection>/server` out of browser bundles.
3
+ * Rejects `ecopages:content/<collection>/server` in browser bundles.
4
4
  *
5
5
  * @remarks
6
6
  * Server modules lazy-load MDX entries via dynamic `import()` for `getComponent`. Browser builds
7
- * must never follow that graph — highlighted MDX output belongs in SSR HTML only.
7
+ * must never follow that graph; browser-safe MDX is available through `/browser` instead.
8
8
  */
9
9
  export function createContentServerBoundaryPlugin() {
10
10
  return {
11
11
  name: 'ecopages:content-server-boundary',
12
12
  setup(build) {
13
- build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => ({
14
- path: args.path,
15
- external: true,
16
- }));
13
+ build.onResolve({ filter: CONTENT_SERVER_VIRTUAL_MODULE_PATTERN }, (args) => {
14
+ throw new Error(`[ecopages] Server-only content module '${args.path}' reached the browser bundle from ${args.importer || 'an entry point'}. Move this import into a server-only Page option.`);
15
+ });
17
16
  },
18
17
  };
19
18
  }
@@ -1,4 +1,8 @@
1
+ /* oxlint-disable typescript/triple-slash-reference */
2
+ /// <reference path="./content-virtual-modules.d.js" />
3
+
1
4
  export type {
5
+ ContentCollectionBrowserModule,
2
6
  ContentCollectionComponentsModule,
3
7
  ContentCollectionEntriesModule,
4
8
  ContentCollectionModule,
@@ -6,6 +10,3 @@ export type {
6
10
  EntryComparator,
7
11
  OrderBy,
8
12
  } from './types.js';
9
-
10
- declare module 'ecopages:content/*' {}
11
- declare module 'ecopages:content/*/server' {}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Fallback declarations for content virtual modules before the configured
3
+ * collection declarations are generated by `ecopages dev` or `ecopages build`.
4
+ *
5
+ * @remarks This must remain a script (without imports or exports). In an
6
+ * external module, these declarations become module augmentations and cannot
7
+ * introduce unresolved `ecopages:content/*` specifiers.
8
+ *
9
+ * Variant patterns (`/server`, `/browser`) must be declared before the catch-all
10
+ * `ecopages:content/*` pattern so TypeScript pattern matching selects them first.
11
+ */
12
+
13
+ declare module 'ecopages:content/*/server' {
14
+ import type { EcoComponent, PageDependenciesResult } from '@ecopages/core';
15
+
16
+ export function getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
17
+ /**
18
+ * Returns `{ components: [entry] }` so collection walks MDX identity.
19
+ *
20
+ * @remarks Does not copy `config.dependencies` or set `ownerFile`.
21
+ * Combine Page-local relative assets with `mergePageDependencies()`.
22
+ * @throws HttpError 404 when the slug is not in the collection.
23
+ */
24
+ export function getEntryDependencies(slug: string): Promise<PageDependenciesResult>;
25
+ }
26
+
27
+ declare module 'ecopages:content/*/browser' {
28
+ import type { EcoComponent } from '@ecopages/core';
29
+
30
+ export function loadComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
31
+ }
32
+
33
+ declare module 'ecopages:content/*' {
34
+ import type { ContentEntry } from '@ecopages/content-processor/types';
35
+
36
+ export type Entry = ContentEntry<Record<string, unknown>>;
37
+ export const entries: readonly Entry[];
38
+ export function getEntry(slug: string): Entry;
39
+ export function getEntryBySegments(segments: string[]): Entry;
40
+ }
@@ -0,0 +1,27 @@
1
+ import type { EcoComponent } from '@ecopages/core';
2
+ /**
3
+ * Throws when an MDX content entry is invoked under a different integration
4
+ * than the one that compiled it.
5
+ *
6
+ * @remarks
7
+ * Call this before invoking the entry component. Checking after render misses
8
+ * async components and lets an incompatible renderer throw first. No-ops when
9
+ * no render context is active so loaders and tests can call the component
10
+ * outside a render lane.
11
+ */
12
+ export declare function assertContentEntryOwnerLane(sourceFile: string, integration: string | undefined): void;
13
+ type OwnedContentEntryComponent = EcoComponent & ((props: Record<string, unknown>) => unknown);
14
+ /**
15
+ * Invokes an MDX content entry under its owning integration's lane.
16
+ *
17
+ * @remarks
18
+ * When a foreign render lane is active but exposes a foreign-child runtime,
19
+ * the entry is handed off to its owning renderer through the Foreign Subtree
20
+ * queue instead of failing: the owning renderer renders and hydrates the
21
+ * subtree, and the lane receives resolved HTML. The strict ownership guard
22
+ * applies only when no handoff is available, so loaders and tests can invoke
23
+ * the component outside a render lane and foreign lanes without a runtime
24
+ * fail fast with an actionable message.
25
+ */
26
+ export declare function invokeContentEntry(sourceFile: string, integration: string | undefined, component: OwnedContentEntryComponent, page: (props: Record<string, unknown>) => unknown, props?: Record<string, unknown>): unknown;
27
+ export {};
@@ -0,0 +1,65 @@
1
+ import { getComponentRenderContext, } from '@ecopages/core/route-renderer/orchestration/foreign-child/component-render-context';
2
+ /**
3
+ * Throws when an MDX content entry is invoked under a different integration
4
+ * than the one that compiled it.
5
+ *
6
+ * @remarks
7
+ * Call this before invoking the entry component. Checking after render misses
8
+ * async components and lets an incompatible renderer throw first. No-ops when
9
+ * no render context is active so loaders and tests can call the component
10
+ * outside a render lane.
11
+ */
12
+ export function assertContentEntryOwnerLane(sourceFile, integration) {
13
+ if (!integration) {
14
+ return;
15
+ }
16
+ const context = getComponentRenderContext();
17
+ if (!context || context.currentIntegration === integration) {
18
+ return;
19
+ }
20
+ throw ownershipError(sourceFile, integration, context.currentIntegration);
21
+ }
22
+ function ownershipError(sourceFile, integration, currentIntegration) {
23
+ return new Error(`[ecopages] MDX content entry "${sourceFile}" is owned by the "${integration}" integration and cannot be rendered inside a ${currentIntegration} render tree. Embed it through its owning renderer (for example eco.embed() / EcoEmbed) or render it from a route owned by "${integration}".`);
24
+ }
25
+ function isPromiseLike(value) {
26
+ return typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function';
27
+ }
28
+ /**
29
+ * Invokes an MDX content entry under its owning integration's lane.
30
+ *
31
+ * @remarks
32
+ * When a foreign render lane is active but exposes a foreign-child runtime,
33
+ * the entry is handed off to its owning renderer through the Foreign Subtree
34
+ * queue instead of failing: the owning renderer renders and hydrates the
35
+ * subtree, and the lane receives resolved HTML. The strict ownership guard
36
+ * applies only when no handoff is available, so loaders and tests can invoke
37
+ * the component outside a render lane and foreign lanes without a runtime
38
+ * fail fast with an actionable message.
39
+ */
40
+ export function invokeContentEntry(sourceFile, integration, component, page, props = {}) {
41
+ if (!integration) {
42
+ return page(props);
43
+ }
44
+ const context = getComponentRenderContext();
45
+ if (!context || context.currentIntegration === integration) {
46
+ return page(props);
47
+ }
48
+ const resolveInterception = (interception) => {
49
+ if (interception?.kind === 'resolved') {
50
+ return interception.value;
51
+ }
52
+ if (interception?.kind === 'inline') {
53
+ return page(interception.props ?? props);
54
+ }
55
+ throw ownershipError(sourceFile, integration, context.currentIntegration);
56
+ };
57
+ const interception = context.interceptForeignChild({
58
+ component,
59
+ props,
60
+ targetIntegration: integration,
61
+ });
62
+ return isPromiseLike(interception)
63
+ ? interception.then(resolveInterception)
64
+ : resolveInterception(interception);
65
+ }
package/src/plugin.d.ts CHANGED
@@ -22,6 +22,8 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
22
22
  * Absolute paths to generated server-only component resolver modules.
23
23
  */
24
24
  readonly collectionServerModules: Record<string, string>;
25
+ /** Absolute paths to generated browser-safe component loader modules. */
26
+ readonly collectionBrowserModules: Record<string, string>;
25
27
  /**
26
28
  * Absolute paths to pre-built collection server artifacts for route-module externalization.
27
29
  */
@@ -29,6 +31,7 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
29
31
  constructor(config: Omit<ProcessorConfig<ContentProcessorConfig>, 'name' | 'description'>);
30
32
  get buildPlugins(): EcoBuildPlugin[];
31
33
  get plugins(): EcoBuildPlugin[];
34
+ invalidateServerArtifacts(): void;
32
35
  private getCollectionsConfig;
33
36
  private getCollectionContentRoot;
34
37
  private writeGeneratedFile;
@@ -46,6 +49,7 @@ export declare class ContentProcessorPlugin extends Processor<ContentProcessorCo
46
49
  private regenerateCollectionEntriesModule;
47
50
  private regenerateCollections;
48
51
  private regenerateAllCollections;
52
+ private isCollectionEntryPath;
49
53
  private handleContentFileEvent;
50
54
  private initializeWatchPaths;
51
55
  private generateTypes;
package/src/plugin.js CHANGED
@@ -6,10 +6,10 @@ import path from 'node:path';
6
6
  import { fileSystem } from '@ecopages/file-system';
7
7
  import { mergeProcessorOptions, Processor, resolveGeneratedPath, writeGeneratedTypesPackage, } from '@ecopages/core/plugins/processor';
8
8
  import { Logger } from '@ecopages/logger';
9
- import { renderCollectionComponentsModule, renderCollectionEntriesModule, renderVirtualModuleTypes, } from './codegen.js';
9
+ import { renderCollectionComponentsModule, renderCollectionBrowserModule, renderCollectionEntriesModule, renderVirtualModuleTypes, } from './codegen.js';
10
10
  import { compareEntriesBySlug } from './sort.js';
11
11
  import { ContentScanner } from './content-scanner.js';
12
- import { createContentPlugin, createContentPluginBundler, getCollectionCachePath, getCollectionServerCachePath, } from './content-plugins.js';
12
+ import { createContentPlugin, createContentPluginBundler, getCollectionCachePath, getCollectionBrowserCachePath, getCollectionServerCachePath, } from './content-plugins.js';
13
13
  import { createContentServerBoundaryPlugin } from './content-server-boundary-plugin.js';
14
14
  import { COLLECTION_NAME_PATTERN, CONTENT_PROCESSOR_NAME } from './constants.js';
15
15
  import { buildContentDevPrewarmPathnames } from './dev-prewarm-paths.js';
@@ -40,6 +40,8 @@ export class ContentProcessorPlugin extends Processor {
40
40
  * Absolute paths to generated server-only component resolver modules.
41
41
  */
42
42
  collectionServerModules = {};
43
+ /** Absolute paths to generated browser-safe component loader modules. */
44
+ collectionBrowserModules = {};
43
45
  /**
44
46
  * Absolute paths to pre-built collection server artifacts for route-module externalization.
45
47
  */
@@ -47,7 +49,7 @@ export class ContentProcessorPlugin extends Processor {
47
49
  constructor(config) {
48
50
  const defaultWatchConfig = {
49
51
  paths: [],
50
- extensions: ['mdx'],
52
+ extensions: ['.mdx', '.md', '.ts', '.tsx', '.js', '.jsx', '.json'],
51
53
  onCreate: async (ctx) => this.handleContentFileEvent(ctx.path, 'create'),
52
54
  onChange: async (ctx) => this.handleContentFileEvent(ctx.path, 'change'),
53
55
  onDelete: async (ctx) => this.handleContentFileEvent(ctx.path, 'delete'),
@@ -62,14 +64,19 @@ export class ContentProcessorPlugin extends Processor {
62
64
  get buildPlugins() {
63
65
  return [
64
66
  createContentServerBoundaryPlugin(),
65
- createContentPluginBundler(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules),
67
+ createContentPluginBundler(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, this.collectionBrowserModules),
66
68
  ];
67
69
  }
68
70
  get plugins() {
69
71
  return [
70
- createContentPlugin(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, (collectionName) => this.ensureCollectionServerArtifact(collectionName)),
72
+ createContentPlugin(this.collectionModules, this.collectionServerModules, this.collectionServerCompiledModules, this.collectionBrowserModules, (collectionName) => this.ensureCollectionServerArtifact(collectionName)),
71
73
  ];
72
74
  }
75
+ invalidateServerArtifacts() {
76
+ for (const collectionName of Object.keys(this.getCollectionsConfig())) {
77
+ this.invalidateCollectionServerArtifact(collectionName);
78
+ }
79
+ }
73
80
  getCollectionsConfig() {
74
81
  if (!this.options?.collections) {
75
82
  throw new Error('Content processor requires `options.collections`');
@@ -122,18 +129,23 @@ export class ContentProcessorPlugin extends Processor {
122
129
  const manifest = entrySources.map(({ entry }) => entry);
123
130
  const outputFile = getCollectionCachePath(this.context.cache, collectionName);
124
131
  const serverOutputFile = getCollectionServerCachePath(this.context.cache, collectionName);
132
+ const browserOutputFile = getCollectionBrowserCachePath(this.context.cache, collectionName);
125
133
  const outputDir = path.dirname(outputFile);
126
134
  const entriesOutput = renderCollectionEntriesModule(collectionName, manifest);
127
135
  const componentsOutput = renderCollectionComponentsModule(collectionName, outputDir, entrySources);
136
+ const browserOutput = renderCollectionBrowserModule(collectionName, outputDir, entrySources);
128
137
  this.writeGeneratedFile(outputFile, entriesOutput);
129
138
  this.writeGeneratedFile(serverOutputFile, componentsOutput);
139
+ this.writeGeneratedFile(browserOutputFile, browserOutput);
130
140
  this.collectionModules[collectionName] = outputFile;
131
141
  this.collectionServerModules[collectionName] = serverOutputFile;
142
+ this.collectionBrowserModules[collectionName] = browserOutputFile;
132
143
  this.invalidateCollectionServerArtifact(collectionName);
133
144
  logger.debug('Generated content collection module', {
134
145
  collectionName,
135
146
  outputFile,
136
147
  serverOutputFile,
148
+ browserOutputFile,
137
149
  entryCount: manifest.length,
138
150
  });
139
151
  }
@@ -170,6 +182,13 @@ export class ContentProcessorPlugin extends Processor {
170
182
  async regenerateAllCollections() {
171
183
  await this.regenerateCollections(Object.keys(this.getCollectionsConfig()));
172
184
  }
185
+ isCollectionEntryPath(normalizedPath, configuredExtensions) {
186
+ const extensions = configuredExtensions ?? ['.mdx'];
187
+ return extensions.some((ext) => {
188
+ const dotted = ext.startsWith('.') ? ext : `.${ext}`;
189
+ return normalizedPath.endsWith(dotted);
190
+ });
191
+ }
173
192
  async handleContentFileEvent(filePath, event) {
174
193
  if (!this.context) {
175
194
  return;
@@ -184,6 +203,12 @@ export class ContentProcessorPlugin extends Processor {
184
203
  }
185
204
  let shouldRegenerateTypes = false;
186
205
  for (const collectionName of affectedCollections) {
206
+ const definition = this.getCollectionsConfig()[collectionName];
207
+ const isEntry = this.isCollectionEntryPath(normalizedPath, definition.extensions);
208
+ if (!isEntry) {
209
+ this.invalidateCollectionServerArtifact(collectionName);
210
+ continue;
211
+ }
187
212
  if (event === 'create' || event === 'delete') {
188
213
  await this.regenerateCollectionModule(collectionName);
189
214
  shouldRegenerateTypes = true;
package/src/types.d.ts CHANGED
@@ -30,15 +30,30 @@ export type ContentCollectionEntriesModule<TEntry extends Record<string, unknown
30
30
  /** Runtime shape of a generated `ecopages:content/<collection>/server` module. */
31
31
  export type ContentCollectionComponentsModule = {
32
32
  /**
33
- * Lazy-loads the MDX component for one slug.
33
+ * Lazy-loads the server-compiled MDX component for one slug.
34
34
  * @throws HttpError 404 when the slug is not in the collection.
35
35
  */
36
36
  getComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
37
37
  /**
38
- * Browser dependency bag for one slug, with MDX source ownership.
38
+ * Returns `{ components: [entry] }` so collection walks the MDX component identity.
39
+ *
40
+ * @remarks
41
+ * Does not copy `config.dependencies` or set `ownerFile`. Combine Page-local
42
+ * relative assets with `mergePageDependencies()`.
39
43
  * @throws HttpError 404 when the slug is not in the collection.
40
44
  */
41
- getEntryDependencies(slug: string): Promise<PageDependenciesResult | undefined>;
45
+ getEntryDependencies(slug: string): Promise<PageDependenciesResult>;
46
+ };
47
+ /** Runtime shape of a generated `ecopages:content/<collection>/browser` module. */
48
+ export type ContentCollectionBrowserModule = {
49
+ /**
50
+ * Lazy-loads one browser-compiled MDX component for a collection entry.
51
+ *
52
+ * @remarks
53
+ * Use this only from the Page Browser Graph. Server rendering must use
54
+ * `ContentCollectionComponentsModule.getComponent()` instead.
55
+ */
56
+ loadComponent(slug: string): Promise<EcoComponent<Record<string, unknown>>>;
42
57
  };
43
58
  /** @deprecated Import entries and server modules separately. */
44
59
  export type ContentCollectionModule<TEntry extends Record<string, unknown> = Record<string, unknown>> = ContentCollectionEntriesModule<TEntry> & ContentCollectionComponentsModule;