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, type Parser, recognize } from "./_shared.ts";
|
2024-05-28 01:14:52 +00:00
|
|
|
import { parse as parseYaml } from "@std/yaml/parse";
|
|
|
|
import { parse as parseToml } from "@std/toml/parse";
|
2024-07-06 11:12:43 +00:00
|
|
|
import type { Extract } from "./types.ts";
|
2024-07-11 06:43:36 +00:00
|
|
|
import type { Format } from "./test.ts";
|
|
|
|
import { EXTRACT_REGEXP_MAP } from "./_formats.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-07-11 06:43:36 +00:00
|
|
|
function getParserForFormat(format: Format): Parser {
|
|
|
|
switch (format) {
|
|
|
|
case "yaml":
|
|
|
|
return parseYaml as Parser;
|
|
|
|
case "toml":
|
|
|
|
return parseToml as Parser;
|
|
|
|
case "json":
|
|
|
|
return JSON.parse;
|
|
|
|
}
|
|
|
|
}
|
2023-03-14 08:09:10 +00:00
|
|
|
|
2024-03-20 01:38:07 +00:00
|
|
|
/**
|
|
|
|
* Extracts and parses {@link https://yaml.org | YAML}, {@link https://toml.io |
|
|
|
|
* TOML}, or {@link https://www.json.org/ | JSON} from the metadata of front
|
|
|
|
* matter content, depending on the format.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { extract } from "@std/front-matter/any";
|
2024-03-20 01:38:07 +00:00
|
|
|
*
|
|
|
|
* const output = `---json
|
|
|
|
* {
|
|
|
|
* "title": "Three dashes marks the spot"
|
|
|
|
* }
|
|
|
|
* ---
|
|
|
|
* Hello, world!`;
|
|
|
|
* const result = extract(output);
|
|
|
|
*
|
|
|
|
* result.frontMatter; // '{\n "title": "Three dashes marks the spot"\n}'
|
|
|
|
* result.body; // "Hello, world!"
|
|
|
|
* result.attrs; // { title: "Three dashes marks the spot" }
|
|
|
|
* ```
|
2024-07-05 11:40:06 +00:00
|
|
|
*
|
|
|
|
* @typeParam T The type of the parsed front matter.
|
|
|
|
* @param text The text to extract front matter from.
|
|
|
|
* @returns The extracted 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
|
|
|
const formats = [...EXTRACT_REGEXP_MAP.keys()] as Format[];
|
|
|
|
const format = recognize(text, formats);
|
|
|
|
const regexp = EXTRACT_REGEXP_MAP.get(format) as RegExp;
|
|
|
|
const parser = getParserForFormat(format);
|
|
|
|
return extractAndParse(text, regexp, parser);
|
2024-07-05 11:40:06 +00:00
|
|
|
}
|