diff options
author | 2023-01-03 16:31:19 -0500 | |
---|---|---|
committer | 2023-01-03 16:31:19 -0500 | |
commit | e2019be6ffa46fa33d92cfd346f9ecbe51bb7144 (patch) | |
tree | 413c13945ae992c26111e78314a567f5c0136c67 /packages/markdown/remark/src/frontmatter-injection.ts | |
parent | 16c7d0bfd49d2b9bfae45385f506bcd642f9444a (diff) | |
download | astro-e2019be6ffa46fa33d92cfd346f9ecbe51bb7144.tar.gz astro-e2019be6ffa46fa33d92cfd346f9ecbe51bb7144.tar.zst astro-e2019be6ffa46fa33d92cfd346f9ecbe51bb7144.zip |
Change frontmatter injection ordering (#5687)
* feat: make user frontmatter accessible in md
* test: new frontmatter injection
* refactor: move injection utils to remark pkg
* fix: add dist/internal to remark exports
* feat: update frontmater injection in mdx
* tests: new mdx injection
* chore: changeset
* chore: simplify frontmatter destructuring
* fix: remove old _internal references
* refactor: injectedFrontmatter -> remarkPluginFrontmatter
* docs: add content collections change
* chore: changeset heading levels
Diffstat (limited to 'packages/markdown/remark/src/frontmatter-injection.ts')
-rw-r--r-- | packages/markdown/remark/src/frontmatter-injection.ts | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/packages/markdown/remark/src/frontmatter-injection.ts b/packages/markdown/remark/src/frontmatter-injection.ts new file mode 100644 index 000000000..921d01297 --- /dev/null +++ b/packages/markdown/remark/src/frontmatter-injection.ts @@ -0,0 +1,41 @@ +import type { Data, VFile } from 'vfile'; +import type { MarkdownAstroData } from './types.js'; + +function isValidAstroData(obj: unknown): obj is MarkdownAstroData { + if (typeof obj === 'object' && obj !== null && obj.hasOwnProperty('frontmatter')) { + const { frontmatter } = obj as any; + try { + // ensure frontmatter is JSON-serializable + JSON.stringify(frontmatter); + } catch { + return false; + } + return typeof frontmatter === 'object' && frontmatter !== null; + } + return false; +} + +export class InvalidAstroDataError extends TypeError {} + +export function safelyGetAstroData(vfileData: Data): MarkdownAstroData | InvalidAstroDataError { + const { astro } = vfileData; + + if (!astro || !isValidAstroData(astro)) { + return new InvalidAstroDataError(); + } + + return astro; +} + +export function toRemarkInitializeAstroData({ + userFrontmatter, +}: { + userFrontmatter: Record<string, any>; +}) { + return () => + function (tree: any, vfile: VFile) { + if (!vfile.data.astro) { + vfile.data.astro = { frontmatter: userFrontmatter }; + } + }; +} |