2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-03-14 08:09:10 +00:00
|
|
|
|
2024-07-11 06:43:36 +00:00
|
|
|
import { extractAndParse } from "./_shared.ts";
|
|
|
|
import { EXTRACT_JSON_REGEXP } from "./_formats.ts";
|
2024-07-06 11:12:43 +00:00
|
|
|
import type { Extract } from "./types.ts";
|
2024-07-03 07:53:55 +00:00
|
|
|
|
2024-07-06 11:12:43 +00:00
|
|
|
export type { Extract };
|
2024-07-05 11:40:06 +00:00
|
|
|
|
2024-03-20 01:38:07 +00:00
|
|
|
/**
|
|
|
|
* Extracts and parses {@link https://www.json.org/ | JSON } from the metadata
|
|
|
|
* of front matter content.
|
2024-07-05 11:40:06 +00:00
|
|
|
*
|
|
|
|
* @example Extract JSON front matter
|
|
|
|
* ```ts
|
|
|
|
* import { extract } from "@std/front-matter/json";
|
|
|
|
* import { assertEquals } from "@std/assert";
|
|
|
|
*
|
|
|
|
* const output = `---json
|
|
|
|
* { "title": "Three dashes marks the spot" }
|
|
|
|
* ---
|
|
|
|
* Hello, world!`;
|
|
|
|
* const result = extract(output);
|
|
|
|
*
|
|
|
|
* assertEquals(result, {
|
|
|
|
* frontMatter: '{ "title": "Three dashes marks the spot" }',
|
|
|
|
* body: "Hello, world!",
|
|
|
|
* attrs: { title: "Three dashes marks the spot" },
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @typeParam T The type of the parsed front matter.
|
|
|
|
* @param text The text to extract JSON front matter from.
|
|
|
|
* @returns The extracted JSON front matter and body content.
|
2024-03-20 01:38:07 +00:00
|
|
|
*/
|
2024-07-05 11:40:06 +00:00
|
|
|
export function extract<T>(text: string): Extract<T> {
|
2024-07-11 06:43:36 +00:00
|
|
|
return extractAndParse(text, EXTRACT_JSON_REGEXP, JSON.parse);
|
2024-07-05 11:40:06 +00:00
|
|
|
}
|