markdown.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { NamedError } from "@opencode-ai/util/error"
  2. import matter from "gray-matter"
  3. import { z } from "zod"
  4. export namespace ConfigMarkdown {
  5. export const FILE_REGEX = /(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g
  6. export const SHELL_REGEX = /!`([^`]+)`/g
  7. export function files(template: string) {
  8. return Array.from(template.matchAll(FILE_REGEX))
  9. }
  10. export function shell(template: string) {
  11. return Array.from(template.matchAll(SHELL_REGEX))
  12. }
  13. export async function parse(filePath: string) {
  14. const template = await Bun.file(filePath).text()
  15. try {
  16. const md = matter(template)
  17. return md
  18. } catch (err) {
  19. throw new FrontmatterError(
  20. {
  21. path: filePath,
  22. message: `Failed to parse YAML frontmatter: ${err instanceof Error ? err.message : String(err)}`,
  23. },
  24. { cause: err },
  25. )
  26. }
  27. }
  28. export const FrontmatterError = NamedError.create(
  29. "ConfigFrontmatterError",
  30. z.object({
  31. path: z.string(),
  32. message: z.string(),
  33. }),
  34. )
  35. }