wip: REAL basic example

This commit is contained in:
bholmesdev 2023-05-26 16:56:59 -04:00
parent 594a3aaf51
commit 4c348b63b4
7 changed files with 151 additions and 22 deletions

View file

@ -1,14 +1,3 @@
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import Aside from './src/components/Aside.astro';
export default defineMarkdocConfig({
tags: {
aside: {
render: Aside,
attributes: {
type: { type: String },
title: { type: String },
},
},
},
});
export default defineMarkdocConfig({});

View file

@ -2,6 +2,7 @@
// Inspired by the `Aside` component from docs.astro.build
// https://github.com/withastro/docs/blob/main/src/components/Aside.astro
// TODO: InferProps util
export interface Props {
type?: 'note' | 'tip' | 'caution' | 'danger';
title?: string;

View file

@ -0,0 +1,6 @@
import { defineProps, field } from '@astrojs/markdoc/props';
export const props = defineProps({
type: field.enum(['note', 'tip', 'warning', 'danger']),
title: field.string().optional(),
});

View file

@ -22,6 +22,7 @@
"./prism": "./dist/extensions/prism.js",
"./shiki": "./dist/extensions/shiki.js",
".": "./dist/index.js",
"./props": "./dist/props.js",
"./components": "./components/index.ts",
"./runtime": "./dist/runtime.js",
"./config": "./dist/config.js",
@ -41,14 +42,15 @@
"test:match": "mocha --timeout 20000 -g"
},
"dependencies": {
"shiki": "^0.14.1",
"@astrojs/prism": "^2.1.2",
"@markdoc/markdoc": "^0.3.0",
"esbuild": "^0.17.12",
"fast-glob": "^3.2.11",
"github-slugger": "^2.0.0",
"gray-matter": "^4.0.3",
"kleur": "^4.1.5",
"zod": "^3.17.3"
"shiki": "^0.14.1",
"zod": "^3.20.6"
},
"peerDependencies": {
"astro": "workspace:^2.5.5"

View file

@ -1,6 +1,8 @@
import { isPropsDef, markdocAttributesFromZodProps, usedDefinePropsSymbol } from './props.js';
/* eslint-disable no-console */
import type { Node } from '@markdoc/markdoc';
import type { Node, Schema } from '@markdoc/markdoc';
import Markdoc from '@markdoc/markdoc';
import glob from 'fast-glob';
import type { AstroConfig, AstroIntegration, ContentEntryType, HookParameters } from 'astro';
import fs from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
@ -11,6 +13,8 @@ import { bold, red, yellow } from 'kleur/colors';
import type * as rollup from 'rollup';
import { loadMarkdocConfig, type MarkdocConfigResult } from './load-config.js';
import { setupConfig } from './runtime.js';
import path from 'node:path';
import type { Plugin } from 'vite';
type SetupHookParams = HookParameters<'astro:config:setup'> & {
// `contentEntryType` is not a public API
@ -28,6 +32,7 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
process.exit(0);
}
let markdocConfigResult: MarkdocConfigResult | undefined;
return {
name: '@astrojs/markdoc',
hooks: {
@ -37,12 +42,74 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
updateConfig,
addContentEntryType,
} = params as SetupHookParams;
const embedsVirtualModId = 'astro:markdoc-embeds';
const tagPropsModules = await glob(
fileURLToPath(new URL('./embeds/*.props.js', astroConfig.srcDir)),
{ absolute: true }
);
let componentAttrsByName: Record<string, Schema> = {};
let componentPathByName: Record<string, string> = {};
const embedsDir = new URL('embeds/', astroConfig.srcDir);
for (const tagPropsModule of tagPropsModules) {
const mod = await import(tagPropsModule);
if (typeof mod !== 'object' || mod == null) {
throw new MarkdocError({
message: `${tagPropsModule} does not export a \`props\` object.`,
});
}
const { props } = mod;
if (isPropsDef(props)) {
const compName = path
.relative(fileURLToPath(embedsDir), tagPropsModule)
.replace('.props.js', '');
componentAttrsByName[compName] = markdocAttributesFromZodProps(props);
componentPathByName[compName] = tagPropsModule.replace(/\.props\.js$/, '.astro');
} else {
throw new MarkdocError({
message: `\`props\` exports must use the \`defineProps()\` helper.`,
});
}
}
updateConfig({
vite: {
ssr: {
external: ['@astrojs/markdoc/prism', '@astrojs/markdoc/shiki'],
},
plugins: [
{
name: 'astro:markdoc-embeds',
resolveId(id) {
if (id === embedsVirtualModId) {
return '\0' + embedsVirtualModId;
}
},
async load(id) {
if (id === '\0' + embedsVirtualModId) {
const code = `${Object.entries(componentPathByName)
.map(([name, path]) => {
return `import ${name} from ${JSON.stringify(
pathToFileURL(path).pathname
)}`;
})
.join('\n')}
export const tagConfig = {
${Object.entries(componentAttrsByName)
.map(([name, attributes]) => {
return `${JSON.stringify(name)}: {
attributes: ${JSON.stringify(attributes)},
render: ${name},
}`;
})
.join(',\n')}
};`;
console.log(code);
return code;
}
},
} as Plugin,
],
},
});
@ -72,6 +139,7 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
// Variables can be configured at runtime,
// so we cannot validate them at build time.
e.error.id !== 'variable-undefined' &&
e.error.id !== 'tag-undefined' &&
(e.error.level === 'error' || e.error.level === 'critical')
);
});
@ -101,8 +169,9 @@ export default function markdocIntegration(legacyConfig?: any): AstroIntegration
}
const res = `import { jsx as h } from 'astro/jsx-runtime';
import { Renderer } from '@astrojs/markdoc/components';
import { collectHeadings, setupConfig, setupConfigSync, Markdoc } from '@astrojs/markdoc/runtime';
import { Renderer } from '@astrojs/markdoc/components';
import { tagConfig } from ${JSON.stringify(embedsVirtualModId)};
import { collectHeadings, setupConfig, setupConfigSync, Markdoc } from '@astrojs/markdoc/runtime';
import * as entry from ${JSON.stringify(viteId + '?astroContentCollectionEntry')};
${
markdocConfigResult
@ -134,6 +203,10 @@ export function getHeadings() {
export async function Content (props) {
const config = await setupConfig({
...userConfig,
tags: {
...tagConfig,
...userConfig.tags,
},
variables: { ...userConfig.variables, ...props },
}, entry);

View file

@ -0,0 +1,55 @@
import z from 'zod';
import type { SchemaAttribute } from '@markdoc/markdoc';
type PropFields = Record<string, ReturnType<(typeof field)[keyof typeof field]>>;
export function markdocAttributesFromZodProps(
zodProps: PropFields
): Record<string, SchemaAttribute> {
let attributes: Record<string, SchemaAttribute> = {};
for (const [key, wrappedVal] of Object.entries(zodProps)) {
let val = wrappedVal;
attributes[key] = {
required: true,
};
if (wrappedVal instanceof z.ZodOptional) {
attributes[key].required = false;
val = wrappedVal.unwrap();
}
if (val instanceof z.ZodString) {
attributes[key].type = 'String';
}
if (val instanceof z.ZodEnum) {
if (!isStrArray(val.options)) throw new Error('Enum values must be strings');
attributes[key].type = 'String';
attributes[key].matches = val.options;
}
}
return attributes;
}
function isStrArray(val: any): val is string[] {
return Array.isArray(val) && val.every((v) => typeof v === 'string');
}
export const field = {
boolean: z.boolean,
string: z.string,
enum: z.enum,
};
export const usedDefinePropsSymbol = Symbol.for('usedDefineProps');
export function isPropsDef(props: unknown): props is ReturnType<typeof defineProps> {
return typeof props === 'object' && props != null && usedDefinePropsSymbol in props;
}
export function defineProps(props: PropFields): PropFields {
return Object.assign(props, {
// Used to check that `.props.js` files use our helper to define.
// Cheapest type check you can have!
[usedDefinePropsSymbol]: true,
});
}

13
pnpm-lock.yaml generated
View file

@ -3982,6 +3982,9 @@ importers:
esbuild:
specifier: ^0.17.12
version: 0.17.12
fast-glob:
specifier: ^3.2.11
version: 3.2.12
github-slugger:
specifier: ^2.0.0
version: 2.0.0
@ -3995,7 +3998,7 @@ importers:
specifier: ^0.14.1
version: 0.14.1
zod:
specifier: ^3.17.3
specifier: ^3.20.6
version: 3.20.6
devDependencies:
'@astrojs/markdown-remark':
@ -12400,7 +12403,7 @@ packages:
'@types/glob': 7.2.0
array-union: 2.1.0
dir-glob: 3.0.1
fast-glob: 3.2.11
fast-glob: 3.2.12
glob: 7.2.3
ignore: 5.2.4
merge2: 1.4.1
@ -12413,7 +12416,7 @@ packages:
dependencies:
array-union: 2.1.0
dir-glob: 3.0.1
fast-glob: 3.2.11
fast-glob: 3.2.12
ignore: 5.2.4
merge2: 1.4.1
slash: 3.0.0
@ -12425,7 +12428,7 @@ packages:
dependencies:
array-union: 3.0.1
dir-glob: 3.0.1
fast-glob: 3.2.11
fast-glob: 3.2.12
ignore: 5.2.4
merge2: 1.4.1
slash: 4.0.0
@ -12436,7 +12439,7 @@ packages:
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
dir-glob: 3.0.1
fast-glob: 3.2.11
fast-glob: 3.2.12
ignore: 5.2.4
merge2: 1.4.1
slash: 4.0.0