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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

60 lines
2 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-06 21:11:01 +00:00
import _Markdoc from '@markdoc/markdoc';
import { parseFrontmatter } from './utils.js';
import { fileURLToPath } from 'node:url';
const contentEntryType = {
extensions: ['.mdoc'],
2023-02-09 17:16: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,
};
},
};
2023-02-06 16:13:57 +00:00
export default function markdoc(partialOptions: {} = {}): AstroIntegration {
return {
name: '@astrojs/markdoc',
hooks: {
'astro:config:setup': async ({ updateConfig, config, addContentEntryType, command }: any) => {
addContentEntryType(contentEntryType);
2023-02-06 16:13:57 +00:00
console.log('Markdoc working!');
2023-02-09 17:26:21 +00:00
const markdocConfigUrl = new URL('./markdoc.config', config.srcDir);
2023-02-06 16:21:17 +00:00
const viteConfig: InlineConfig = {
plugins: [
{
name: '@astrojs/markdoc',
async transform(code, id) {
if (!id.endsWith('.mdoc')) 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
)};\nexport function getParsed() { return Markdoc.parse(body); }\nexport async function getTransformed(inlineConfig) {
2023-02-09 17:26:21 +00:00
let config = inlineConfig;
2023-02-06 23:09:23 +00:00
if (!config) {
try {
const importedConfig = await import(${JSON.stringify(markdocConfigUrl.pathname)});
2023-02-09 17:26:21 +00:00
console.log({importedConfig})
2023-02-06 23:09:23 +00:00
config = importedConfig.default.transform;
2023-02-09 17:26:21 +00:00
} catch {
config = {};
}
2023-02-06 23:09:23 +00:00
}
2023-02-09 18:25:18 +00:00
return Markdoc.transform(getParsed(), config) }\nexport async function Content ({ config, components }) { return h(Renderer, { content: await 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;