@ecopages/mdx 0.2.0-alpha.2 → 0.2.0-alpha.21

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/CHANGELOG.md CHANGED
@@ -8,24 +8,27 @@ All notable changes to `@ecopages/mdx` are documented here.
8
8
 
9
9
  ### Features
10
10
 
11
- - **Decoupled from React** — The MDX integration now works as a standalone, runtime-agnostic integration. React dependencies have been removed; MDX routes are server-rendered without requiring the React integration (`4d5474a4`).
12
- - **Async MDX compilation** — The MDX loader plugin now compiles MDX files asynchronously, improving compatibility with async remark/rehype plugins (`9e879dbe`).
13
- - **Updated type definitions** — Plugin options are more precisely typed to clarify server-rendered MDX route configuration.
11
+ - Added standalone non-React MDX server rendering with async compilation and opt-in `.md` support.
14
12
 
15
- ### Refactoring
13
+ ### Bug Fixes
16
14
 
17
- - Removed unused HMR strategy and renderer files that were React-specific.
18
- - README updated to document standalone MDX usage without React.
19
- - Ambient module declarations cleaned up (`5f46ecc5`).
20
- - Aligned with full orchestration mode (`fc07bdb0`).
15
+ - Fixed loader registration, Node `source-map` interop, and renderer-owned mixed-boundary rendering for standalone MDX routes.
16
+ - Fixed standalone MDX boundary payload compatibility coverage and removed the plugin/renderer integration-name import cycle.
21
17
 
22
18
  ### Documentation
23
19
 
24
- - README updated to clarify the integration is now usable without the React integration.
20
+ - Updated the README for standalone non-React MDX usage, `.md` opt-in handling, and compiler configuration.
21
+
22
+ ### Tests
23
+
24
+ - Added renderer-level coverage for the boundary payload compatibility contract.
25
+
26
+ ### Refactoring
27
+
28
+ - Replaced the standalone MDX renderer factory with explicit renderer-owned compiler configuration and collected shared MDX plugin and renderer types into a dedicated module.
25
29
 
26
30
  ---
27
31
 
28
32
  ## Migration Notes
29
33
 
30
- - If you were using `@ecopages/mdx` together with `@ecopages/react` for MDX routes, the two integrations must now be registered separately. MDX handles server rendering; React handles client hydration.
31
- - The `useReact` option and React-specific HMR hooks have been removed.
34
+ - Use `reactPlugin({ mdx: { enabled: true } })` for React-backed MDX routes; the standalone `@ecopages/mdx` plugin now targets non-React JSX runtimes.
package/README.md CHANGED
@@ -1,19 +1,19 @@
1
- # Ecopages MDX Integration Plugin
1
+ # @ecopages/mdx
2
2
 
3
- The `@ecopages/mdx` package adds standalone MDX support for non-React JSX runtimes such as `@kitajs/html`. It uses the MDX compiler through Ecopages' integration system and is intended for server-rendered `.mdx` routes.
3
+ Integration plugin for standalone MDX support in Ecopages for non-React JSX runtimes such as `@kitajs/html`. Use it when MDX should render directly on the server without React hydration.
4
4
 
5
- ## Install
5
+ ## Installation
6
6
 
7
7
  ```bash
8
- bunx jsr add @ecopages/mdx
8
+ bun add @ecopages/mdx
9
9
  ```
10
10
 
11
11
  ## Usage
12
12
 
13
- Integrating MDX into your Ecopages project is made simple. Import and apply the `mdxPlugin` in your Ecopages configuration as demonstrated below:
13
+ Import and apply the `mdxPlugin` in your `eco.config.ts`:
14
14
 
15
15
  ```ts
16
- import { ConfigBuilder } from '@ecopages/core';
16
+ import { ConfigBuilder } from '@ecopages/core/config-builder';
17
17
  import { mdxPlugin } from '@ecopages/mdx';
18
18
 
19
19
  const config = await new ConfigBuilder()
@@ -29,11 +29,55 @@ By default, the standalone plugin uses:
29
29
  - `jsxImportSource: '@kitajs/html'`
30
30
  - `jsxRuntime: 'automatic'`
31
31
 
32
- You can override MDX compiler options, but React runtimes are intentionally not supported here.
32
+ ## What This Integration Owns
33
33
 
34
- ## Using MDX with React Router
34
+ - `.mdx` route files.
35
+ - Optional `.md` routes when you opt them into `extensions`.
36
+ - MDX compilation against a non-React JSX runtime.
35
37
 
36
- If you are using `@ecopages/react` with a client-side router, enable MDX directly within the React plugin instead of using this standalone plugin. This ensures unified routing, hydration, and HMR for both `.tsx` and `.mdx` pages:
38
+ ## Configure Markdown Extensions
39
+
40
+ Use `extensions` when both `.mdx` and `.md` files should run through the MDX loader.
41
+
42
+ ```ts
43
+ import { mdxPlugin } from '@ecopages/mdx';
44
+
45
+ mdxPlugin({
46
+ extensions: ['.mdx', '.md'],
47
+ });
48
+ ```
49
+
50
+ ## Compiler Options
51
+
52
+ Pass `compilerOptions` to add remark, rehype, or recma plugins while keeping the non-React JSX runtime managed by the integration.
53
+
54
+ ```ts
55
+ import { mdxPlugin } from '@ecopages/mdx';
56
+
57
+ mdxPlugin({
58
+ compilerOptions: {
59
+ remarkPlugins: [],
60
+ rehypePlugins: [],
61
+ },
62
+ });
63
+ ```
64
+
65
+ > [!WARNING]
66
+ > React runtimes are intentionally rejected by this standalone plugin.
67
+
68
+ ## Mixed Rendering
69
+
70
+ Standalone MDX can own the page shell or nested MDX component boundaries in a mixed-renderer app. When another integration reaches an MDX-owned boundary, Ecopages hands that boundary back to the MDX renderer so the MDX runtime can finish serialization before the outer renderer resumes.
71
+
72
+ Important:
73
+
74
+ - Components that may render foreign children must declare those children in `config.dependencies.components`.
75
+ - Ecopages validates mixed-renderer ownership from declared dependencies during render preparation rather than inferring every boundary from rendered HTML alone.
76
+ - Standalone MDX keeps its own page normalization and non-React JSX runtime behavior.
77
+
78
+ ## Using MDX with React
79
+
80
+ If you are using `@ecopages/react` and building a full React application, **do not** use this standalone MDX plugin. Instead, enable MDX directly within the React plugin configuration to ensure unified hydration, client-side routing, and HMR:
37
81
 
38
82
  ```ts
39
83
  import { reactPlugin } from '@ecopages/react';
@@ -44,9 +88,3 @@ reactPlugin({
44
88
  mdx: { enabled: true },
45
89
  });
46
90
  ```
47
-
48
- See the `@ecopages/react` documentation for details.
49
-
50
- ## React runtimes are not supported here
51
-
52
- Standalone `mdxPlugin()` rejects `jsxImportSource: 'react'` and related React JSX runtimes. For React-backed MDX, use [@ecopages/react](../react/README.md) with `mdx.enabled`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/mdx",
3
- "version": "0.2.0-alpha.2",
3
+ "version": "0.2.0-alpha.21",
4
4
  "description": "MDX plugin for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -37,7 +37,7 @@
37
37
  "directory": "packages/integrations/mdx"
38
38
  },
39
39
  "peerDependencies": {
40
- "@ecopages/core": "0.2.0-alpha.2",
40
+ "@ecopages/core": "0.2.0-alpha.21",
41
41
  "@kitajs/html": "^4.1.0",
42
42
  "@mdx-js/mdx": "^3.1.0"
43
43
  },
@@ -1,8 +1,15 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { compile } from "@mdx-js/mdx";
4
- import { SourceMapGenerator } from "source-map";
4
+ import sourceMap from "source-map";
5
5
  import { VFile } from "vfile";
6
+ function resolveCompileFormat(filePath, compilerOptions) {
7
+ const configuredFormat = compilerOptions?.format;
8
+ if (configuredFormat && configuredFormat !== "detect") {
9
+ return configuredFormat;
10
+ }
11
+ return path.extname(filePath).toLowerCase() === ".md" ? "mdx" : configuredFormat;
12
+ }
6
13
  function createMdxLoaderPlugin(compilerOptions) {
7
14
  const mdxExtensions = compilerOptions?.mdxExtensions ?? [".mdx"];
8
15
  const mdExtensions = compilerOptions?.mdExtensions ?? [".md"];
@@ -18,13 +25,14 @@ function createMdxLoaderPlugin(compilerOptions) {
18
25
  const file = new VFile({ path: filePath, value: source });
19
26
  const compiled = await compile(file, {
20
27
  ...compilerOptions,
21
- SourceMapGenerator
28
+ format: resolveCompileFormat(filePath, compilerOptions),
29
+ SourceMapGenerator: sourceMap.SourceMapGenerator
22
30
  });
23
- const sourceMap = compiled.map ? `
31
+ const inlineSourceMap = compiled.map ? `
24
32
  //# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(compiled.map)).toString("base64")}
25
33
  ` : "";
26
34
  return {
27
- contents: `${String(compiled.value)}${sourceMap}`,
35
+ contents: `${String(compiled.value)}${inlineSourceMap}`,
28
36
  loader: compilerOptions?.jsx ? "jsx" : "js",
29
37
  resolveDir: path.dirname(args.path)
30
38
  };
@@ -2,50 +2,31 @@
2
2
  * This module contains the MDX renderer
3
3
  * @module
4
4
  */
5
- import type { EcoComponent, EcoComponentConfig, EcoPageFile, EcoPagesElement, GetMetadata, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
5
+ import type { ComponentRenderInput, ComponentRenderResult, EcoComponent, EcoPageFile, EcoPagesElement, IntegrationRendererRenderOptions, RouteRendererBody } from '@ecopages/core';
6
6
  import { IntegrationRenderer, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
7
- import type { AssetProcessingService, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
7
+ import type { ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
8
8
  import type { CompileOptions } from '@mdx-js/mdx';
9
- /**
10
- * A structure representing an MDX file
11
- */
12
- export type MDXFile = {
13
- default: EcoComponent;
14
- config?: EcoComponentConfig;
15
- getMetadata: GetMetadata;
16
- };
9
+ import type { MDXRendererOptions } from './mdx.types.js';
10
+ export type { MDXFile, MDXRendererConfig, MDXRendererOptions } from './mdx.types.js';
17
11
  /**
18
12
  * Options for the MDX renderer
19
13
  */
20
- interface MDXIntegrationRendererOpions<C = EcoPagesElement> extends IntegrationRendererRenderOptions<C> {
14
+ interface MDXIntegrationRendererOptions<C = EcoPagesElement> extends IntegrationRendererRenderOptions<C> {
21
15
  }
22
16
  /**
23
17
  * A renderer for the MDX integration.
24
18
  */
25
19
  export declare class MDXRenderer extends IntegrationRenderer<EcoPagesElement> {
26
20
  name: string;
27
- compilerOptions: CompileOptions;
28
- constructor({ compilerOptions, ...options }: {
29
- appConfig: any;
30
- assetProcessingService: AssetProcessingService;
31
- resolvedIntegrationDependencies: ProcessedAsset[];
32
- runtimeOrigin: string;
33
- compilerOptions?: CompileOptions;
34
- });
21
+ readonly compilerOptions: CompileOptions;
22
+ constructor({ mdxConfig, ...options }: MDXRendererOptions);
35
23
  buildRouteRenderAssets(pagePath: string): Promise<ProcessedAsset[]>;
36
- protected importPageFile(file: string): Promise<EcoPageFile<{
37
- layout?: EcoComponent<any> | {
38
- config: EcoComponentConfig | undefined;
39
- };
40
- }>>;
41
- render({ params, query, props, locals, pageLocals, metadata, Page, HtmlTemplate, Layout, pageProps, }: MDXIntegrationRendererOpions): Promise<RouteRendererBody>;
24
+ protected normalizeImportedPageFile<TPageModule extends EcoPageFile>(_file: string, pageModule: TPageModule): TPageModule;
25
+ renderComponent(input: ComponentRenderInput): Promise<ComponentRenderResult>;
26
+ protected createComponentBoundaryRuntime(options: {
27
+ boundaryInput: ComponentRenderInput;
28
+ rendererCache: Map<string, IntegrationRenderer<any>>;
29
+ }): import("@ecopages/core").ComponentBoundaryRuntime;
30
+ render({ params, query, props, locals, pageLocals, metadata, Page, HtmlTemplate, Layout, pageProps, }: MDXIntegrationRendererOptions): Promise<RouteRendererBody>;
42
31
  renderToResponse<P = Record<string, unknown>>(view: EcoComponent<P>, props: P, ctx: RenderToResponseContext): Promise<Response>;
43
32
  }
44
- /**
45
- * Factory function to create an MDX renderer class with specific compiler options.
46
- *
47
- * @param compilerOptions - Compiler options for MDX compilation.
48
- * @returns A new MDXRenderer class extended with the provided context.
49
- */
50
- export declare function createMDXRenderer(compilerOptions: CompileOptions): typeof MDXRenderer;
51
- export {};
@@ -1,16 +1,13 @@
1
1
  import { IntegrationRenderer } from "@ecopages/core/route-renderer/integration-renderer";
2
2
  import { invariant } from "@ecopages/core/utils/invariant";
3
- import { PLUGIN_NAME } from "./mdx.plugin.js";
3
+ import { MDX_PLUGIN_NAME } from "./mdx.constants.js";
4
4
  import { rapidhash } from "@ecopages/core/hash";
5
5
  class MDXRenderer extends IntegrationRenderer {
6
- name = PLUGIN_NAME;
6
+ name = MDX_PLUGIN_NAME;
7
7
  compilerOptions;
8
- constructor({
9
- compilerOptions,
10
- ...options
11
- }) {
8
+ constructor({ mdxConfig, ...options }) {
12
9
  super(options);
13
- this.compilerOptions = compilerOptions || {};
10
+ this.compilerOptions = mdxConfig?.compilerOptions ?? {};
14
11
  }
15
12
  async buildRouteRenderAssets(pagePath) {
16
13
  const { default: pageComponent } = await this.importPageFile(pagePath);
@@ -34,19 +31,17 @@ class MDXRenderer extends IntegrationRenderer {
34
31
  }
35
32
  return await this.resolveDependencies(components);
36
33
  }
37
- async importPageFile(file) {
34
+ normalizeImportedPageFile(_file, pageModule) {
38
35
  try {
39
- const {
40
- default: Page,
41
- config,
42
- getMetadata
43
- } = await super.importPageFile(file);
36
+ const mdxModule = pageModule;
37
+ const { default: Page, config, getMetadata } = mdxModule;
44
38
  if (typeof Page !== "function") {
45
39
  throw new Error("MDX file must export a default function");
46
40
  }
47
41
  const resolvedLayout = config?.layout;
48
42
  if (config) Page.config = config;
49
43
  return {
44
+ ...pageModule,
50
45
  default: Page,
51
46
  layout: resolvedLayout,
52
47
  getMetadata
@@ -55,6 +50,18 @@ class MDXRenderer extends IntegrationRenderer {
55
50
  invariant(false, `Error importing MDX file: ${error}`);
56
51
  }
57
52
  }
53
+ async renderComponent(input) {
54
+ return this.renderStringComponentBoundaryWithQueuedForeignBoundaries(
55
+ input,
56
+ input.component
57
+ );
58
+ }
59
+ createComponentBoundaryRuntime(options) {
60
+ return this.createQueuedBoundaryRuntime({
61
+ boundaryInput: options.boundaryInput,
62
+ rendererCache: options.rendererCache
63
+ });
64
+ }
58
65
  async render({
59
66
  params,
60
67
  query,
@@ -68,58 +75,36 @@ class MDXRenderer extends IntegrationRenderer {
68
75
  pageProps
69
76
  }) {
70
77
  try {
71
- const pageContent = await Page({ params, query, ...props, locals: pageLocals });
72
- const children = typeof Layout === "function" ? await Layout({ children: pageContent, locals }) : pageContent;
73
- const body = await HtmlTemplate({
78
+ return await this.renderPageWithDocumentShell({
79
+ page: {
80
+ component: Page,
81
+ props: { params, query, ...props, locals: pageLocals }
82
+ },
83
+ layout: Layout ? {
84
+ component: Layout,
85
+ props: locals ? { locals } : {}
86
+ } : void 0,
87
+ htmlTemplate: HtmlTemplate,
74
88
  metadata,
75
- children,
76
89
  pageProps: pageProps || {}
77
90
  });
78
- return this.DOC_TYPE + body;
79
91
  } catch (error) {
80
92
  throw this.createRenderError("Error rendering page", error);
81
93
  }
82
94
  }
83
95
  async renderToResponse(view, props, ctx) {
84
96
  try {
85
- const Layout = view.config?.layout;
86
- const viewFn = view;
87
- const pageContent = await viewFn(props);
88
- let body;
89
- if (ctx.partial) {
90
- body = pageContent;
91
- } else {
92
- const children = Layout ? await Layout({ children: pageContent }) : pageContent;
93
- const HtmlTemplate = await this.getHtmlTemplate();
94
- const metadata = view.metadata ? await view.metadata({
95
- params: {},
96
- query: {},
97
- props,
98
- appConfig: this.appConfig
99
- }) : this.appConfig.defaultMetadata;
100
- body = this.DOC_TYPE + await HtmlTemplate({
101
- metadata,
102
- children,
103
- pageProps: props
104
- });
105
- }
106
- return this.createHtmlResponse(body, ctx);
97
+ return await this.renderViewWithDocumentShell({
98
+ view,
99
+ props,
100
+ ctx,
101
+ layout: view.config?.layout
102
+ });
107
103
  } catch (error) {
108
104
  throw this.createRenderError("Error rendering view", error);
109
105
  }
110
106
  }
111
107
  }
112
- function createMDXRenderer(compilerOptions) {
113
- return class extends MDXRenderer {
114
- constructor(options) {
115
- super({
116
- ...options,
117
- compilerOptions
118
- });
119
- }
120
- };
121
- }
122
108
  export {
123
- MDXRenderer,
124
- createMDXRenderer
109
+ MDXRenderer
125
110
  };
@@ -0,0 +1 @@
1
+ export declare const MDX_PLUGIN_NAME = "MDX";
@@ -0,0 +1,4 @@
1
+ const MDX_PLUGIN_NAME = "MDX";
2
+ export {
3
+ MDX_PLUGIN_NAME
4
+ };
@@ -1,15 +1,13 @@
1
1
  import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
2
2
  import type { EcoPagesElement } from '@ecopages/core';
3
- import { IntegrationPlugin, type IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
4
- import type { CompileOptions } from '@mdx-js/mdx';
3
+ import { IntegrationPlugin } from '@ecopages/core/plugins/integration-plugin';
5
4
  import { MDXRenderer } from './mdx-renderer.js';
5
+ import type { MDXPluginConfig } from './mdx.types.js';
6
+ export type { MDXPluginConfig, MDXRendererConfig, MDXRendererOptions } from './mdx.types.js';
6
7
  /**
7
8
  * The name of the MDX plugin
8
9
  */
9
10
  export declare const PLUGIN_NAME = "MDX";
10
- export type MDXPluginConfig = Partial<Omit<IntegrationPluginConfig, 'name'>> & {
11
- compilerOptions?: CompileOptions;
12
- };
13
11
  /**
14
12
  * The MDX plugin class
15
13
  * This plugin provides support for MDX components in Ecopages.
@@ -20,10 +18,25 @@ export type MDXPluginConfig = Partial<Omit<IntegrationPluginConfig, 'name'>> & {
20
18
  */
21
19
  export declare class MDXPlugin extends IntegrationPlugin<EcoPagesElement> {
22
20
  renderer: typeof MDXRenderer;
23
- private compilerOptions;
21
+ private readonly compilerOptions;
24
22
  private mdxLoaderPlugin;
25
23
  constructor({ compilerOptions, ...options }?: MDXPluginConfig);
24
+ initializeRenderer(options?: {
25
+ rendererModules?: unknown;
26
+ }): MDXRenderer;
26
27
  get plugins(): EcoBuildPlugin[];
28
+ /**
29
+ * Materializes the MDX loader once so config-time sealing and runtime setup
30
+ * can share the same loader instance.
31
+ */
32
+ private ensureLoaderPlugin;
33
+ /**
34
+ * Prepares the MDX loader contribution before config build seals the manifest.
35
+ */
36
+ prepareBuildContributions(): Promise<void>;
37
+ /**
38
+ * Runs runtime-only MDX setup after build contributions are already prepared.
39
+ */
27
40
  setup(): Promise<void>;
28
41
  }
29
42
  /**
package/src/mdx.plugin.js CHANGED
@@ -2,9 +2,10 @@ import { IntegrationPlugin } from "@ecopages/core/plugins/integration-plugin";
2
2
  import { deepMerge } from "@ecopages/core/utils/deep-merge";
3
3
  import { Logger } from "@ecopages/logger";
4
4
  import { createMdxLoaderPlugin } from "./mdx-loader-plugin.js";
5
- import { createMDXRenderer, MDXRenderer } from "./mdx-renderer.js";
5
+ import { MDX_PLUGIN_NAME } from "./mdx.constants.js";
6
+ import { MDXRenderer } from "./mdx-renderer.js";
6
7
  const appLogger = new Logger("[MDXPlugin]");
7
- const PLUGIN_NAME = "MDX";
8
+ const PLUGIN_NAME = MDX_PLUGIN_NAME;
8
9
  const defaultOptions = {
9
10
  format: "detect",
10
11
  outputFormat: "program",
@@ -12,8 +13,20 @@ const defaultOptions = {
12
13
  jsxRuntime: "automatic",
13
14
  development: process.env.NODE_ENV === "development"
14
15
  };
16
+ function splitMarkdownExtensions(extensions) {
17
+ const mdExtensions = [];
18
+ const mdxExtensions = [];
19
+ for (const extension of extensions) {
20
+ if (extension === ".md") {
21
+ mdExtensions.push(extension);
22
+ continue;
23
+ }
24
+ mdxExtensions.push(extension);
25
+ }
26
+ return { mdExtensions, mdxExtensions };
27
+ }
15
28
  class MDXPlugin extends IntegrationPlugin {
16
- renderer;
29
+ renderer = MDXRenderer;
17
30
  compilerOptions;
18
31
  mdxLoaderPlugin;
19
32
  constructor({ compilerOptions, ...options } = { extensions: [".mdx"] }) {
@@ -22,7 +35,15 @@ class MDXPlugin extends IntegrationPlugin {
22
35
  extensions: [".mdx"],
23
36
  ...options
24
37
  });
25
- const finalCompilerOptions = deepMerge({ ...defaultOptions }, compilerOptions);
38
+ const { mdExtensions, mdxExtensions } = splitMarkdownExtensions(this.extensions);
39
+ const finalCompilerOptions = deepMerge(
40
+ {
41
+ ...defaultOptions,
42
+ mdxExtensions,
43
+ mdExtensions
44
+ },
45
+ compilerOptions
46
+ );
26
47
  const jsxImportSource = finalCompilerOptions.jsxImportSource;
27
48
  if (jsxImportSource === "react" || (jsxImportSource?.startsWith("react/") ?? false)) {
28
49
  throw new Error(
@@ -30,17 +51,44 @@ class MDXPlugin extends IntegrationPlugin {
30
51
  );
31
52
  }
32
53
  this.compilerOptions = finalCompilerOptions;
33
- this.renderer = createMDXRenderer(finalCompilerOptions);
34
54
  appLogger.debug(`MDX plugin configured with jsxImportSource: ${jsxImportSource ?? "default"}`);
35
55
  }
56
+ initializeRenderer(options) {
57
+ const renderer = new this.renderer({
58
+ ...this.createRendererOptions(options),
59
+ mdxConfig: {
60
+ compilerOptions: this.compilerOptions
61
+ }
62
+ });
63
+ return this.attachRendererRuntimeServices(renderer);
64
+ }
36
65
  get plugins() {
37
66
  if (this.mdxLoaderPlugin) {
38
67
  return [this.mdxLoaderPlugin];
39
68
  }
40
69
  return [];
41
70
  }
42
- async setup() {
71
+ /**
72
+ * Materializes the MDX loader once so config-time sealing and runtime setup
73
+ * can share the same loader instance.
74
+ */
75
+ ensureLoaderPlugin() {
76
+ if (this.mdxLoaderPlugin) {
77
+ return;
78
+ }
43
79
  this.mdxLoaderPlugin = createMdxLoaderPlugin(this.compilerOptions);
80
+ }
81
+ /**
82
+ * Prepares the MDX loader contribution before config build seals the manifest.
83
+ */
84
+ async prepareBuildContributions() {
85
+ this.ensureLoaderPlugin();
86
+ }
87
+ /**
88
+ * Runs runtime-only MDX setup after build contributions are already prepared.
89
+ */
90
+ async setup() {
91
+ this.ensureLoaderPlugin();
44
92
  await super.setup();
45
93
  }
46
94
  }
@@ -0,0 +1,27 @@
1
+ import type { EcoComponent, EcoComponentConfig, GetMetadata } from '@ecopages/core';
2
+ import type { EcoPagesAppConfig } from '@ecopages/core/internal-types';
3
+ import type { IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
4
+ import type { AssetProcessingService, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
5
+ import type { CompileOptions } from '@mdx-js/mdx';
6
+ export type MDXPluginConfig = Partial<Omit<IntegrationPluginConfig, 'name'>> & {
7
+ compilerOptions?: CompileOptions;
8
+ };
9
+ export type MDXRendererConfig = {
10
+ compilerOptions?: CompileOptions;
11
+ };
12
+ export type MDXRendererOptions = {
13
+ appConfig: EcoPagesAppConfig;
14
+ assetProcessingService: AssetProcessingService;
15
+ resolvedIntegrationDependencies: ProcessedAsset[];
16
+ rendererModules?: unknown;
17
+ runtimeOrigin: string;
18
+ mdxConfig?: MDXRendererConfig;
19
+ };
20
+ /**
21
+ * A structure representing an MDX file.
22
+ */
23
+ export type MDXFile = {
24
+ default: EcoComponent;
25
+ config?: EcoComponentConfig;
26
+ getMetadata: GetMetadata;
27
+ };
File without changes
@@ -1,40 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import path from 'node:path';
3
- import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
4
- import { type CompileOptions, compile } from '@mdx-js/mdx';
5
- import { SourceMapGenerator } from 'source-map';
6
- import { VFile } from 'vfile';
7
-
8
- export function createMdxLoaderPlugin(compilerOptions?: CompileOptions): EcoBuildPlugin {
9
- const mdxExtensions = compilerOptions?.mdxExtensions ?? ['.mdx'];
10
- const mdExtensions = compilerOptions?.mdExtensions ?? ['.md'];
11
- const allExtensions = [...mdxExtensions, ...mdExtensions];
12
- const escapedExts = allExtensions.map((ext) => ext.replace('.', '\\.'));
13
- const filter = new RegExp(`(${escapedExts.join('|')})(\\?.*)?$`);
14
-
15
- return {
16
- name: 'mdx-loader',
17
- setup(build) {
18
- build.onLoad({ filter }, async (args) => {
19
- const filePath = args.path.includes('?') ? args.path.split('?')[0] : args.path;
20
- const source = readFileSync(filePath, 'utf-8');
21
- const file = new VFile({ path: filePath, value: source });
22
-
23
- const compiled = await compile(file, {
24
- ...compilerOptions,
25
- SourceMapGenerator,
26
- });
27
-
28
- const sourceMap = compiled.map
29
- ? `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(compiled.map)).toString('base64')}\n`
30
- : '';
31
-
32
- return {
33
- contents: `${String(compiled.value)}${sourceMap}`,
34
- loader: compilerOptions?.jsx ? 'jsx' : 'js',
35
- resolveDir: path.dirname(args.path),
36
- };
37
- });
38
- },
39
- };
40
- }
@@ -1,221 +0,0 @@
1
- /**
2
- * This module contains the MDX renderer
3
- * @module
4
- */
5
-
6
- import type {
7
- EcoComponent,
8
- EcoComponentConfig,
9
- EcoPageFile,
10
- EcoPagesElement,
11
- GetMetadata,
12
- IntegrationRendererRenderOptions,
13
- PageMetadataProps,
14
- RouteRendererBody,
15
- } from '@ecopages/core';
16
- import { IntegrationRenderer, type RenderToResponseContext } from '@ecopages/core/route-renderer/integration-renderer';
17
- import { invariant } from '@ecopages/core/utils/invariant';
18
- import type { AssetProcessingService, ProcessedAsset } from '@ecopages/core/services/asset-processing-service';
19
- import type { CompileOptions } from '@mdx-js/mdx';
20
- import { PLUGIN_NAME } from './mdx.plugin.ts';
21
- import { rapidhash } from '@ecopages/core/hash';
22
-
23
- /**
24
- * A structure representing an MDX file
25
- */
26
- export type MDXFile = {
27
- default: EcoComponent;
28
- config?: EcoComponentConfig;
29
- getMetadata: GetMetadata;
30
- };
31
-
32
- /**
33
- * Options for the MDX renderer
34
- */
35
- interface MDXIntegrationRendererOpions<C = EcoPagesElement> extends IntegrationRendererRenderOptions<C> {}
36
-
37
- /**
38
- * A renderer for the MDX integration.
39
- */
40
- export class MDXRenderer extends IntegrationRenderer<EcoPagesElement> {
41
- name = PLUGIN_NAME;
42
- compilerOptions: CompileOptions;
43
-
44
- constructor({
45
- compilerOptions,
46
- ...options
47
- }: {
48
- appConfig: any;
49
- assetProcessingService: AssetProcessingService;
50
- resolvedIntegrationDependencies: ProcessedAsset[];
51
- runtimeOrigin: string;
52
- compilerOptions?: CompileOptions;
53
- }) {
54
- super(options);
55
- this.compilerOptions = compilerOptions || {};
56
- }
57
-
58
- override async buildRouteRenderAssets(pagePath: string): Promise<ProcessedAsset[]> {
59
- const { default: pageComponent } = await this.importPageFile(pagePath);
60
- const config = pageComponent.config;
61
- const components: Partial<EcoComponent>[] = [];
62
-
63
- const resolvedLayout = config?.layout;
64
-
65
- if (resolvedLayout?.config?.dependencies) {
66
- components.push({ config: resolvedLayout.config });
67
- }
68
-
69
- if (config?.dependencies) {
70
- components.push({
71
- config: {
72
- ...config,
73
- __eco: {
74
- id: rapidhash(pagePath).toString(36),
75
- file: pagePath,
76
- integration: this.name,
77
- },
78
- },
79
- });
80
- }
81
-
82
- return await this.resolveDependencies(components);
83
- }
84
-
85
- protected override async importPageFile(file: string): Promise<
86
- EcoPageFile<{
87
- layout?:
88
- | EcoComponent<any>
89
- | {
90
- config: EcoComponentConfig | undefined;
91
- };
92
- }>
93
- > {
94
- try {
95
- const {
96
- default: Page,
97
- config,
98
- getMetadata,
99
- } = (await super.importPageFile(file)) as EcoPageFile<{
100
- layout?:
101
- | EcoComponent<any>
102
- | {
103
- config: EcoComponentConfig | undefined;
104
- };
105
- }> & {
106
- config?: EcoComponentConfig;
107
- };
108
-
109
- if (typeof Page !== 'function') {
110
- throw new Error('MDX file must export a default function');
111
- }
112
-
113
- const resolvedLayout = config?.layout;
114
-
115
- if (config) Page.config = config;
116
-
117
- return {
118
- default: Page,
119
- layout: resolvedLayout,
120
- getMetadata,
121
- };
122
- } catch (error) {
123
- invariant(false, `Error importing MDX file: ${error}`);
124
- }
125
- }
126
-
127
- async render({
128
- params,
129
- query,
130
- props,
131
- locals,
132
- pageLocals,
133
- metadata,
134
- Page,
135
- HtmlTemplate,
136
- Layout,
137
- pageProps,
138
- }: MDXIntegrationRendererOpions): Promise<RouteRendererBody> {
139
- try {
140
- const pageContent = await Page({ params, query, ...props, locals: pageLocals });
141
- const children =
142
- typeof Layout === 'function' ? await Layout({ children: pageContent, locals }) : pageContent;
143
-
144
- const body = await HtmlTemplate({
145
- metadata,
146
- children,
147
- pageProps: pageProps || {},
148
- });
149
-
150
- return this.DOC_TYPE + body;
151
- } catch (error) {
152
- throw this.createRenderError('Error rendering page', error);
153
- }
154
- }
155
-
156
- async renderToResponse<P = Record<string, unknown>>(
157
- view: EcoComponent<P>,
158
- props: P,
159
- ctx: RenderToResponseContext,
160
- ): Promise<Response> {
161
- try {
162
- const Layout = view.config?.layout as
163
- | ((props: { children: EcoPagesElement } & Record<string, unknown>) => Promise<EcoPagesElement>)
164
- | undefined;
165
-
166
- const viewFn = view as (props: P) => Promise<EcoPagesElement>;
167
- const pageContent = await viewFn(props);
168
-
169
- let body: string;
170
- if (ctx.partial) {
171
- body = pageContent as string;
172
- } else {
173
- const children = Layout ? await Layout({ children: pageContent }) : pageContent;
174
-
175
- const HtmlTemplate = await this.getHtmlTemplate();
176
- const metadata: PageMetadataProps = view.metadata
177
- ? await view.metadata({
178
- params: {},
179
- query: {},
180
- props: props as Record<string, unknown>,
181
- appConfig: this.appConfig,
182
- })
183
- : this.appConfig.defaultMetadata;
184
-
185
- body =
186
- this.DOC_TYPE +
187
- (await HtmlTemplate({
188
- metadata,
189
- children: children as EcoPagesElement,
190
- pageProps: props as Record<string, unknown>,
191
- }));
192
- }
193
-
194
- return this.createHtmlResponse(body, ctx);
195
- } catch (error) {
196
- throw this.createRenderError('Error rendering view', error);
197
- }
198
- }
199
- }
200
-
201
- /**
202
- * Factory function to create an MDX renderer class with specific compiler options.
203
- *
204
- * @param compilerOptions - Compiler options for MDX compilation.
205
- * @returns A new MDXRenderer class extended with the provided context.
206
- */
207
- export function createMDXRenderer(compilerOptions: CompileOptions): typeof MDXRenderer {
208
- return class extends MDXRenderer {
209
- constructor(options: {
210
- appConfig: any;
211
- assetProcessingService: AssetProcessingService;
212
- resolvedIntegrationDependencies: ProcessedAsset[];
213
- runtimeOrigin: string;
214
- }) {
215
- super({
216
- ...options,
217
- compilerOptions,
218
- });
219
- }
220
- };
221
- }
package/src/mdx.plugin.ts DELETED
@@ -1,85 +0,0 @@
1
- import type { EcoBuildPlugin } from '@ecopages/core/build/build-types';
2
- import type { EcoPagesElement } from '@ecopages/core';
3
- import { IntegrationPlugin, type IntegrationPluginConfig } from '@ecopages/core/plugins/integration-plugin';
4
- import { deepMerge } from '@ecopages/core/utils/deep-merge';
5
- import { Logger } from '@ecopages/logger';
6
- import type { CompileOptions } from '@mdx-js/mdx';
7
- import { createMdxLoaderPlugin } from './mdx-loader-plugin.ts';
8
- import { createMDXRenderer, MDXRenderer } from './mdx-renderer.ts';
9
-
10
- const appLogger = new Logger('[MDXPlugin]');
11
-
12
- /**
13
- * The name of the MDX plugin
14
- */
15
- export const PLUGIN_NAME = 'MDX';
16
-
17
- export type MDXPluginConfig = Partial<Omit<IntegrationPluginConfig, 'name'>> & {
18
- compilerOptions?: CompileOptions;
19
- };
20
-
21
- const defaultOptions: CompileOptions = {
22
- format: 'detect',
23
- outputFormat: 'program',
24
- jsxImportSource: '@kitajs/html',
25
- jsxRuntime: 'automatic',
26
- development: process.env.NODE_ENV === 'development',
27
- };
28
-
29
- /**
30
- * The MDX plugin class
31
- * This plugin provides support for MDX components in Ecopages.
32
- *
33
- * Standalone `mdxPlugin()` is intended for non-React JSX runtimes such as
34
- * `@kitajs/html`. React-backed MDX should be configured through
35
- * `reactPlugin({ mdx: { enabled: true, compilerOptions: ... } })` instead.
36
- */
37
- export class MDXPlugin extends IntegrationPlugin<EcoPagesElement> {
38
- renderer: typeof MDXRenderer;
39
- private compilerOptions: CompileOptions;
40
- private mdxLoaderPlugin: EcoBuildPlugin | undefined;
41
-
42
- constructor({ compilerOptions, ...options }: MDXPluginConfig = { extensions: ['.mdx'] }) {
43
- super({
44
- name: PLUGIN_NAME,
45
- extensions: ['.mdx'],
46
- ...options,
47
- });
48
-
49
- const finalCompilerOptions = deepMerge({ ...defaultOptions }, compilerOptions);
50
- const jsxImportSource = finalCompilerOptions.jsxImportSource;
51
-
52
- if (jsxImportSource === 'react' || (jsxImportSource?.startsWith('react/') ?? false)) {
53
- throw new Error(
54
- 'Standalone `mdxPlugin()` does not support React JSX runtimes. Use `reactPlugin({ mdx: { enabled: true, compilerOptions: ... } })` instead.',
55
- );
56
- }
57
-
58
- this.compilerOptions = finalCompilerOptions;
59
- this.renderer = createMDXRenderer(finalCompilerOptions);
60
-
61
- appLogger.debug(`MDX plugin configured with jsxImportSource: ${jsxImportSource ?? 'default'}`);
62
- }
63
-
64
- override get plugins(): EcoBuildPlugin[] {
65
- if (this.mdxLoaderPlugin) {
66
- return [this.mdxLoaderPlugin];
67
- }
68
-
69
- return [];
70
- }
71
-
72
- override async setup(): Promise<void> {
73
- this.mdxLoaderPlugin = createMdxLoaderPlugin(this.compilerOptions);
74
- await super.setup();
75
- }
76
- }
77
-
78
- /**
79
- * Factory function to create an MDX plugin instance.
80
- * @param options Configuration options for the MDX plugin
81
- * @returns A new MDXPlugin instance
82
- */
83
- export function mdxPlugin(options?: MDXPluginConfig): MDXPlugin {
84
- return new MDXPlugin(options);
85
- }