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 } from "./_shared.ts";
|
2024-09-12 09:55:44 +00:00
|
|
|
import { parse } from "@std/yaml/parse";
|
2024-07-06 11:12:43 +00:00
|
|
|
import type { Extract } from "./types.ts";
|
2024-07-11 06:43:36 +00:00
|
|
|
import { EXTRACT_YAML_REGEXP } 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-03-20 01:38:07 +00:00
|
|
|
/**
|
|
|
|
* Extracts and parses {@link https://yaml.org | YAML} from the metadata of
|
|
|
|
* front matter content.
|
|
|
|
*
|
2024-05-28 01:14:52 +00:00
|
|
|
* @example Extract YAML front matter
|
2024-03-20 01:38:07 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { extract } from "@std/front-matter/yaml";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2024-03-20 01:38:07 +00:00
|
|
|
*
|
|
|
|
* const output = `---yaml
|
|
|
|
* title: Three dashes marks the spot
|
|
|
|
* ---
|
|
|
|
* Hello, world!`;
|
|
|
|
* const result = extract(output);
|
|
|
|
*
|
2024-05-28 01:14:52 +00:00
|
|
|
* assertEquals(result, {
|
|
|
|
* frontMatter: "title: Three dashes marks the spot",
|
|
|
|
* body: "Hello, world!",
|
|
|
|
* attrs: { title: "Three dashes marks the spot" },
|
|
|
|
* });
|
2024-03-20 01:38:07 +00:00
|
|
|
* ```
|
2024-07-05 11:40:06 +00:00
|
|
|
*
|
2024-09-12 09:55:44 +00:00
|
|
|
* Note: If you need to pass the options to the yaml parse,
|
|
|
|
* use the new version of this API from `@std/yaml/unstable-yaml`.
|
2024-08-21 06:41:53 +00:00
|
|
|
*
|
|
|
|
* @typeParam T The type of the parsed front matter.
|
|
|
|
* @param text The text to extract YAML front matter from.
|
|
|
|
* @returns The extracted YAML front matter and body content.
|
|
|
|
*/
|
2024-09-12 09:55:44 +00:00
|
|
|
export function extract<T>(text: string): Extract<T> {
|
2024-08-21 06:41:53 +00:00
|
|
|
return extractAndParse(
|
|
|
|
text,
|
|
|
|
EXTRACT_YAML_REGEXP,
|
2024-09-12 09:55:44 +00:00
|
|
|
((s) => parse(s)) as Parser,
|
2024-08-21 06:41:53 +00:00
|
|
|
);
|
2024-07-05 11:40:06 +00:00
|
|
|
}
|