frontmatter.test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { describe, expect, it } from "vitest";
  2. import { parseFrontmatter, stripFrontmatter } from "../src/utils/frontmatter.ts";
  3. describe("parseFrontmatter", () => {
  4. it("parses keys, strips quotes, and returns body", () => {
  5. const input = "---\nname: \"skill-name\"\ndescription: 'A desc'\nfoo-bar: value\n---\n\nBody text";
  6. const { frontmatter, body } = parseFrontmatter<Record<string, string>>(input);
  7. expect(frontmatter.name).toBe("skill-name");
  8. expect(frontmatter.description).toBe("A desc");
  9. expect(frontmatter["foo-bar"]).toBe("value");
  10. expect(body).toBe("Body text");
  11. });
  12. it("normalizes newlines and handles CRLF", () => {
  13. const input = "---\r\nname: test\r\n---\r\nLine one\r\nLine two";
  14. const { body } = parseFrontmatter<Record<string, string>>(input);
  15. expect(body).toBe("Line one\nLine two");
  16. });
  17. it("throws on invalid YAML frontmatter", () => {
  18. const input = "---\nfoo: [bar\n---\nBody";
  19. expect(() => parseFrontmatter<Record<string, string>>(input)).toThrow(/at line 1, column 10/);
  20. });
  21. it("parses | multiline yaml syntax", () => {
  22. const input = "---\ndescription: |\n Line one\n Line two\n---\n\nBody";
  23. const { frontmatter, body } = parseFrontmatter<Record<string, string>>(input);
  24. expect(frontmatter.description).toBe("Line one\nLine two\n");
  25. expect(body).toBe("Body");
  26. });
  27. it("returns original content when frontmatter is missing or unterminated", () => {
  28. const noFrontmatter = "Just text\nsecond line";
  29. const missingEnd = "---\nname: test\nBody without terminator";
  30. const resultNoFrontmatter = parseFrontmatter<Record<string, string>>(noFrontmatter);
  31. const resultMissingEnd = parseFrontmatter<Record<string, string>>(missingEnd);
  32. expect(resultNoFrontmatter.body).toBe("Just text\nsecond line");
  33. expect(resultMissingEnd.body).toBe(
  34. "---\nname: test\nBody without terminator".replace(/\r\n/g, "\n").replace(/\r/g, "\n"),
  35. );
  36. });
  37. it("returns empty object for empty or comment-only frontmatter", () => {
  38. const input = "---\n# just a comment\n---\nBody";
  39. const { frontmatter } = parseFrontmatter(input);
  40. expect(frontmatter).toEqual({});
  41. });
  42. });
  43. describe("stripFrontmatter", () => {
  44. it("removes frontmatter and trims body", () => {
  45. const input = "---\nkey: value\n---\n\nBody\n";
  46. expect(stripFrontmatter(input)).toBe("Body");
  47. });
  48. it("returns body when no frontmatter present", () => {
  49. const input = "\n No frontmatter body \n";
  50. expect(stripFrontmatter(input)).toBe("\n No frontmatter body \n");
  51. });
  52. });