astro/packages/integrations/markdoc/src/index.ts

56 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-02-06 16:13:57 +00:00
import type { AstroIntegration } from 'astro';
2023-02-06 16:21:17 +00:00
import type { InlineConfig } from 'vite';
2023-02-14 17:08:04 +00:00
import type { Config as _MarkdocConfig } from '@markdoc/markdoc';
2023-02-06 21:11:01 +00:00
import _Markdoc from '@markdoc/markdoc';
import { parseFrontmatter } from './utils.js';
import { fileURLToPath } from 'node:url';
import fs from 'node:fs';
const DEFAULT_MARKDOC_EXTS = ['.mdoc', '.md'];
2023-02-10 14:22:47 +00:00
export default function markdoc(): AstroIntegration {
2023-02-06 16:13:57 +00:00
return {
name: '@astrojs/markdoc',
hooks: {
'astro:config:setup': async ({ updateConfig, config, addContentEntryType, command }: any) => {
2023-02-13 19:13:02 +00:00
const contentEntryType = {
name: 'astro:markdoc',
extensions: DEFAULT_MARKDOC_EXTS,
2023-02-13 19:13:02 +00:00
async getEntryInfo({ fileUrl, contents }: { fileUrl: URL; contents: string }) {
const parsed = parseFrontmatter(contents, fileURLToPath(fileUrl));
return {
data: parsed.data,
body: parsed.content,
slug: parsed.data.slug,
rawData: parsed.matter,
};
},
contentModuleTypes: await fs.promises.readFile(
new URL('../template/content-module-types.d.ts', import.meta.url),
'utf-8'
),
};
addContentEntryType(contentEntryType);
2023-02-10 14:10:06 +00:00
2023-02-06 16:21:17 +00:00
const viteConfig: InlineConfig = {
plugins: [
{
name: '@astrojs/markdoc',
async transform(code, id) {
if (!DEFAULT_MARKDOC_EXTS.some((ext) => id.endsWith(ext))) return;
return `import { jsx as h } from 'astro/jsx-runtime';\nimport { Markdoc } from '@astrojs/markdoc';\nimport { Renderer } from '@astrojs/markdoc/components';\nexport const body = ${JSON.stringify(
2023-02-06 23:09:23 +00:00
code
2023-02-14 16:28:33 +00:00
)};\nexport function getParsed() { return Markdoc.parse(body); }\nexport function getTransformed(inlineConfig) { return Markdoc.transform(getParsed(), inlineConfig) }\nexport async function Content ({ config, components }) { return h(Renderer, { content: getTransformed(config), components }); }\nContent[Symbol.for('astro.needsHeadRendering')] = true;`;
2023-02-06 16:21:17 +00:00
},
},
],
};
updateConfig({ vite: viteConfig });
2023-02-06 16:13:57 +00:00
},
},
};
}
2023-02-06 21:11:01 +00:00
export const Markdoc = _Markdoc;
2023-02-14 17:08:04 +00:00
export type MarkdocConfig = _MarkdocConfig;